1

Im trying to figure out the time complexity of the following code. lst_of_lsts contains m lists whose lengths are at most n.

This is what I think: all runs in O(m*n), minimum = O(m*n), remove = O(m*n).

Overall O(m*n)*O(m*n) = O(m^2*n^2)

Am I right?

 def multi_merge_v1(lst_of_lsts): 
      all = [e for lst in lst_of_lsts for e in lst] 
      merged = [] 
      while all != []: 
          minimum = min(all) 
          merged += [minimum] 
          all.remove(minimum) 
      return merged 
1
  • 1
    Isn't this code review? Commented Apr 6, 2014 at 14:52

1 Answer 1

1
def multi_merge_v1(lst_of_lsts): # M lists of N
  all = [e for lst in lst_of_lsts for e in lst]
  # this is messy. Enumerate all N*M list items --> O(nm)

  merged = [] # O(1)
  while all != []: # n*m items initially, decreases in size by 1 each iteration.
    minimum = min(all) # O(|all|).
    # |all| diminishes linearly from (nm) items, so this is O(nm).
    # can re-use work here. Should use a sorted data structure or heap

    merged += [minimum] # O(1) amortized due to table doubling
    all.remove(minimum) # O(|all|)
  return merged # O(1)

The overall complexity appears to be O(nm + nm*nm + 1) = O(n^2m^2+1). Yikes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.