Just [[currentUser.getNumFreeQuestionsLeft()]] No more free questions left!Upgrade Now
In order to win the prize for most cookies sold, my friend Alice and I are going to merge our Girl Scout Cookies orders and enter as one unit.
Each order is represented by an "order id" (an integer).
We have our lists of orders sorted numerically already, in lists. Write a function to merge our lists of orders into one sorted list.
We can do this in time and space.
If you're running a built-in sorting function, your algorithm probably takes time for that sort.
Think about edge cases! What happens when we've merged in all of the elements from one of our lists but we still have elements to merge in from our other list?
time and additional space, where n is the number of items in the merged list.
The added space comes from allocating the merged_list. There's no way to do this "in-place" because neither of our input lists are necessarily big enough to hold the merged list.
But if our inputs were linked lists, we could avoid allocating a new structure and do the merge by simply adjusting the next pointers in the list nodes!
In our implementation above, we could avoid tracking current_index_merged and just compute it on the fly by adding current_index_mine and current_index_alices. This would only save us one integer of space though, which is hardly anything. It's probably not worth the added code complexity.
Trivia! Python's native sorting algorithm is called Timsort. It's actually optimized for sorting lists where subsections of the lists are already sorted. For this reason, a more naive algorithm:
is actually faster until n gets pretty big. Like 1,000,000.
Also, in Python 2.6+, there's a built-in function for merging sorted lists into one sorted list: heapq.merge.
What if we wanted to merge several sorted lists? Write a function that takes as an input a list of sorted lists and outputs a single sorted list with all the items from each list.