Merging two sorted lists is one of the popular problems in Leetcode. It is asked in coding interviews by companies like FAANG many times. Here you need to return a sorted list by merging two sorted lists. So, if you want to learn how to solve the problem of Merging two sorted lists, this article is for you. In this article, I will take you through how to merge two sorted lists using Python.
Merge Two Sorted Lists using Python
To solve the problem of merging two sorted lists, you need to combine two sorted lists in a way that the final combined list is also in a sorted manner. For example, look at the two lists mentioned below:
- ist1 = [1, 3, 5, 7, 9]
- list2 = [2, 4, 6, 8, 10]
After merging both the lists, the output list must be [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
I hope you now have understood what merging two sorted lists means. Now here’s how to solve this problem using the Python programming language:
def merge2Lists(i, j): mergedlist = [] while (i and j): if (i[0] <= j[0]): item = i.pop(0) mergedlist.append(item) else: item = j.pop(0) mergedlist.append(item) mergedlist.extend(i if i else j) return mergedlist list1 = [1, 3, 5, 7, 9] list2 = [2, 4, 6, 8, 10] print(merge2Lists(list1, list2))
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
So this is how you can merge two sorted lists using Python. You can find many more practice questions to improve your problem-solving skills using Python here.
Summary
To solve the problem of merging two sorted lists, you need to combine two sorted lists in a way that the final combined list is also in a sorted manner. I hope you liked this article on merging two sorted lists using Python. Feel free to ask valuable questions in the comments section below.