How do you merge two sorted lists?
Merging two sorted lists is a common problem in computer science and is often asked in technical interviews. The goal is to create a new list that contains all elements from the two given lists, maintaining the sorted order. This task can be tackled efficiently, and understanding the approach will help improve your algorithmic skills.
Let's start by visualizing the problem. Suppose we have two sorted lists:
- List A: [1, 3, 5, 7]
- List B: [2, 4, 6, 8]
We want to merge these two lists into a single sorted list:
- Merged List: [1, 2, 3, 4, 5, 6, 7, 8]
Approach
The most efficient way to merge two sorted lists is to use a two-pointer technique. We maintain two pointers, one for each list, and compare the elements they point to. Depending on which element is smaller, we will add it to the new list and move the corresponding pointer forward.
Implementation
Here is a Python function that demonstrates this approach:
Python
Explanation
-
Initialization: We initialize an empty list called
merged_list
, and two indices,i
andj
, both set to 0. These indices will keep track of our current position inlist1
andlist2
, respectively. -
Comparing elements: The main while loop runs as long as neither pointer has reached the end of its respective list. Inside the loop, we compare the current elements of both lists:
- If the current element of
list1
(pointed byi
) is smaller, it gets added tomerged_list
, and we move the pointeri
forward. - If the current element of
list2
(pointed byj
) is smaller or equal, we add that element, and move the pointerj
.
- If the current element of
-
Appending remaining elements: After the main loop, we may have remaining elements in either
list1
orlist2
. Two additional while loops handle this by appending any leftover elements tomerged_list
.
Complexity
This algorithm runs in O(n + m) time, where n and m are the lengths of the two lists. This is more efficient than concatenating the lists and then sorting, which would take O((n + m) log(n + m)) time. The space complexity is O(n + m) since we store all elements in the merged list.