Combine Two Sorted Sequences
Linked ListsAuto-graded · 22 test casesLast updated
Merge two non-decreasing sequences into a single sorted sequence, maintaining stable order on equal values.
Given two non-decreasingly ordered integer sequences l1 and l2, combine all elements into a single non-decreasing sequence.
Whenever an element from l1 is equal to an element from l2, the element from l1 must appear earlier in the resulting sequence.
Constraints
- The length of both
l1andl2is between0and50. - Element values range between
-100and100. - Both inputs are sorted in non-decreasing order.
Examples
Example 1
Input: merge_two_lists([1, 2, 4], [1, 3, 4])
Output: [1, 1, 2, 3, 4, 4]
Example 2
Input: merge_two_lists([], [0])
Output: [0]
Hints
Hint 1
Use two pointers to track your current index in each input list.
Hint 2
At each step, compare the current elements of both lists and choose the smaller one.
Hint 3
Use a non-strict inequality (<=) to ensure elements from l1 take precedence when values are equal.
Hint 4
Once one list is exhausted, append all remaining elements from the other list.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since both input lists are already sorted in non-decreasing order, we can construct the output list using a two-pointer technique:
- Maintain two index variables,
iforl1andjforl2. - Compare
l1[i]andl2[j]. Append the smaller value to our result and increment the corresponding pointer. - When
l1[i] == l2[j], prioritizel1[i]by using a<=comparison. This preserves stability between the two inputs. - When one pointer reaches the end of its respective list, append the remaining elements of the other list directly to the result.
Complexity Analysis
- Time Complexity: $O(n + m)$, where $n$ and $m$ are the lengths of
l1andl2. Each element is processed and appended exactly once. - Space Complexity: $O(n + m)$ to construct and return the combined output sequence.
Python Reference Solution
from typing import List
def merge_two_lists(l1: List[int], l2: List[int]) -> List[int]:
i = j = 0
merged = []
while i < len(l1) and j < len(l2):
if l1[i] <= l2[j]:
merged.append(l1[i])
i += 1
else:
merged.append(l2[j])
j += 1
merged.extend(l1[i:])
merged.extend(l2[j:])
return merged