Showing posts with label merge. Show all posts
Showing posts with label merge. Show all posts

Merging two Binary Search Trees

Describe a method to merge two BSTs.

50
/ \
30 70
/ \ / \
20 40 60 80
/ \ \
10 25 90


30
/ \
15 45
\
20



Answer:

Probably the most efficient:
1. Create two array from the two trees by traversing in inorder: O(n+m) space + O(n+m) time
2. Merge the two arrays: O(n+m) time, O(n+m) space.
3. Create a balanced binary tree from this sorted array 1, O(n+m) time (see related solution)

merging sorted streams

Given k sorted streams where each stream could possibly be infinite in length, describe an efficient algorithm to merge the k streams into a new stream (also in sorted order).

Answer:

Solution I (Divide and Conquer) :

list1
listA /
/ . \
/ . list2
/ . .
Merged / . .
List \ . .
\
\ . listk-1
listC /
\
listk


This solution is not efficient, Complexity is 2k-1 - 1

Solution II (Using buckets)

Use technique similar to Bucket sort, maximum complexity = O(N2)

Solution III (Using Heap)

(credit : The Great Khali)

Step1: Take first element of all k streams and build a min heap of them. => O(k)
Step2: Remove the min element (elem at top of heap) from the heap and put in the new stream. => O(log k)
Step3: Put new element in heap from the stream to which the prev elem belongs (which was at heap min). => O(log k)
Step4: continue above steps till we exhaust all the streams. If all streams in combination have n elements then order is O(n log(k))

Merging two arrays

Given two sorted integer arrays and the larger array has room for the second. Merge the smaller array into the larger one, in O(n) time and O(1) space.

Answer:

l_begin l_end free
| | |
[4][6][8][10][22][ ][ ][ ][ ]

sml_begin small_end
| |
[1][2][3][20]

void InplaceMerge(int * l_up, int * l_down, int* s_up, int* s_down)
{
int* free = l_down + (s_down-s_up);
while(s_end <= s_begin)
{
while(*l_end >= *s_end)
{
*free = *l_end;
--free; --l_end;
}
while (*s_end >= *l_end)
{
*free = *s_end;
--free; --s_end;
}
}
}