KatInterview

Combine Two Ordered Lists

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingtwo-pointerssortingmerge-algorithm

Last 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 first and second are sorted in non-decreasing order
  • Your solution should run in O(m + n) time where m = len(first) and n = 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.