Combine Two Ordered Lists
Arrays & HashingAuto-graded · 21 test casesLast updated
Tests the ability to implement the classic two-pointer merge algorithm in linear time.
You receive two integer lists, first and second, each already arranged in non-decreasing order.
Your task is to create a function combine_sorted_lists(first: List[int], second: List[int]) -> List[int] that produces a new list containing every element from both inputs, arranged in non-decreasing order. All duplicate values must appear in the output as many times as they appear across both inputs combined.
Neither input list should be modified by your function.
Constraints
0 <= len(first), len(second) <= 10^6-10^9 <= first[i], second[j] <= 10^9- Both
firstandsecondare sorted in non-decreasing order - Your solution should run in
O(m + n)time wherem = len(first)andn = len(second) - Use
O(1)extra space beyond the output list itself
Examples
Example 1
Input: combine_sorted_lists([1, 2, 4, 7], [2, 3, 5, 7, 8])
Output: [1, 2, 2, 3, 4, 5, 7, 7, 8]
Example 2
Input: combine_sorted_lists([], [0, 5])
Output: [0, 5]
Hints
Hint 1
Maintain a position marker in each list and compare the current elements to decide which one to take next.
Hint 2
When one list is fully consumed, all remaining elements in the other list can be appended in one operation.
Hint 3
Since both lists are pre-sorted, you never need to look backward or re-examine elements.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Two-Pointer Merge
Approach
The core insight is that both input lists are already sorted. This means the smallest unconsumed element must be at the front of one of the two remaining portions. We maintain two index pointers, one for each list, starting at position zero.
At each step, we compare the elements at both pointers and append whichever is smaller to our output list, then advance that pointer by one. When we've exhausted all elements from one list, everything left in the other list is already sorted and larger than everything we've already added, so we can append it all at once.
This technique is the merge step from merge sort and is a fundamental pattern for combining sorted sequences.
Why It Works
We maintain an invariant: before each iteration, our result list contains the smallest i + j elements from both inputs combined, in sorted order.
- Initially, when both pointers are at zero, the result is empty and the invariant holds trivially
- During each iteration, because both lists are sorted,
first[i]is the minimum of all remaining elements infirst, andsecond[j]is the minimum of all remaining elements insecond. Therefore, the smaller of these two is the global minimum of all unconsumed elements. Appending it maintains sorted order - When one list runs out, the remaining portion of the other list is already sorted and all its elements are at least as large as our last appended element, so extending with it completes the sorted result
Duplicates are naturally preserved because we process every element exactly once. When elements are equal, using <= ensures we take from the first list before the second, which maintains stability (though this doesn't affect the correctness for plain integers).
Complexity
Time: O(m + n) where m and n are the lengths of the two input lists. Each iteration processes exactly one element, and we process every element exactly once. The final extend operations together process all remaining elements, which is still linear.
Space: O(1) auxiliary space beyond the required output list. We only use two integer index variables. (Note: while first[i:] creates a slice, this is part of producing the required output, not auxiliary overhead.)
Implementation
from typing import List
def combine_sorted_lists(first: List[int], second: List[int]) -> List[int]:
result = []
i = j = 0
while i < len(first) and j < len(second):
if first[i] <= second[j]:
result.append(first[i])
i += 1
else:
result.append(second[j])
j += 1
result.extend(first[i:])
result.extend(second[j:])
return result