2,899 views
2 votes
2 votes
Consider n elements that are equally distributed in k stacks. In each stack, elements of it are arranged in ascending order (min is at the top in each of the stack and then increasing downwards). Given a queue of size n in which we have to put all n elements in increasing order. What will be the time complexity of the best known algorithm?

3 Answers

Best answer
5 votes
5 votes
N elements are equally distributed over k Stacks means each stack will have $\left ( \frac{n}{k} \right )$ elements.

Now, apply pop operation to get top element from each stack and construct Min Heap.

we will have k elements from each stack and time complexity to construct Min heap will be $O(k)$.

Now apply deletion to root node and insert it into Queue and Heapify remaining heap and repeat this procedure untill we remove all elements from heap. This operation with heapify operation will take total of time $O(k log k)$.

So, now we have k sorted elements in Queue.

we have to repeat this whole procedure $\left ( \frac{n}{k} \right )$ times because in each step we have k elements from each stack.

so Total time complexity will be $= \left ( \frac{n}{k} \right ) \cdot (klogk) = n log k$.
selected by
2 votes
2 votes

The algorithm should be like this

  • All k stacks contain k pointer
  • k pointers are pointing to the top element of the stack
  • Now, all these elements are compared and the smallest one is popped and put inside the queue
  • Now, which stack is popped one element, it points to the second element of that stack, and all other stack points to the first elements to the stack
  • Again comparison done with the top element of the stack
  • Like this all kn elements are compared and pushed into the queue

So, time complexity will be O(kn)

1 votes
1 votes
1)let us construct a min heap with all the top elements of k stacks.==>O(k)

2)extract min and add it to queue, then insert the next element of stack into min heap ==>O(logk)+O(1)+O(logk)

so total n extract-mins,n insertions into queue, n-k insertions into min heap.

total complexity: O(k)+O(nlogk)+O(n)+O((n-k)*logk)

i.e O(nlogk)