简体   繁体   中英

Time complexity of Merging k linked lists is O(nk log (k))

I know there are several questions regarding this, but I haven't got the solution of my question.

Question is simple: Merge k n-length sorted linked lists.

Many answers are there, using k length priority queue with complexity O(n log(k))

Didn't know how. Here is the link Merging K- Sorted Lists using Priority Queue

It makes me think that I am wrong. So mine solution is:

To merge two n-length lists we require O(2n) time.

  1. merge lists in a pair of two ==== k/2 merge * 2n time in merging each pair left with k/2 , 2n-length lists
  2. repeat the step 1, until you left with 1 array of n*k size.

So time complexity would be.

k/2 * 2n = k*n

k/4 * 4n = k*n

.

.

.

k/2^x * 2^x n = k n

last term would be k*n with 2^x = k or x = log (k)

so total log(k) iterations with k * n comparisons in each iteration. So time complexity would be O( k * n * log(k) )

Can someone tell where am I wrong?

Thanks for your time.

Unless otherwise specified, when the complexity of an algorithm is given in terms of N , that N is the size of the input. So when we cay "merging k linked lists is O(N log k)", we mean that N is the total number of elements in all the lists.

As you say, merging k m-length lists is O(km log k). Here the size of the input is km (the total number of elements), so this is consistent with the statement above.

Your statement is not as strong, though, because it only covers k lists of equal length. "merging k linked lists is O(N log k)" is true regardless of how those N elements are distributed among the lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM