← Arrays & Strings

Drill #6 — Merge two sorted arrays

Easy Two Pointers Arrays & Strings

In plain English: Combine two already-sorted lists into a single sorted list.

Both arrays are sorted, so the smallest unprocessed element is always at one of the two front pointers — just pick the smaller one.

Prompt

Given sorted arrays a and b, return a single merged sorted array.

Try to write it from scratch before scrolling down.

Solution

def merge(a, b):
    res, i, j = [], 0, 0
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:  # always pick the smaller front
            res.append(a[i]); i += 1
        else:
            res.append(b[j]); j += 1
    res.extend(a[i:])
    res.extend(b[j:])
    return res

# Test: merge([1,3,5], [2,4,6]) == [1,2,3,4,5,6]
O(n+m) time · O(n+m) space

Related Micro Drills

← Drill #5 Drill #7 →