I recently began to learn a Python
I downloaded a basic exercise file from https://developers.google.com/edu/python/exercises/basic
and I wrote the code for following exercise.
Given two lists sorted in increasing order, create and return a merged list of all the elements in sorted order. You may modify the passed in lists. Ideally, the solution should work in "linear" time, making a single pass of both lists.
My code was
def linear_merge(list1, list2):
result = sorted(list1 + list2)
return result
However, solution provided is
def linear_merge(list1, list2):
result = []
while len(list1) and len(list2):
if list1[0] < list2[0]:
result.append(list1.pop(0))
else:
result.append(list2.pop(0))
result.extend(list1)
result.extend(list2)
return result
I ran sample example with my code and It worked.
However, I don't know why the solution is quite longer than mine.
Is there an actual difference between two codes? Do I misunderstood the problem?
p.s. Also, what is the meaning of the last sentence in the question which is saying 'linear' time?