Algorithms · Level 1 Two Pointers

Merging Sorted Lists

Merge two sorted lists of log timestamps into one with two pointers: each item is touched once, and the input lists stay unchanged.

  • one index per list
  • copy the leftovers
  • don't mutate the input (no pop(0))

Two pointers walk two sorted lists at once: compare the fronts, take the smaller, move that pointer. Each item is touched once: O(n + m). Trap: when one list runs out, the rest of the other must still be copied.

i = j = 0          # items in both lists
while i < len(a) and j < len(b):
    if a[i] == b[j]:
        print(a[i]); i += 1; j += 1
    elif a[i] < b[j]:
        i += 1
    else:
        j += 1

Write merge_sorted(a, b): one new sorted list with every timestamp of the sorted lists a and b, without changing them. Example: merge_sorted([1, 4, 9], [2, 3, 10]) → [1, 2, 3, 4, 9, 10].

solution.py
Test Suites Pending
Output