DevPath

← All problems

Merge Two Sorted Lists

Easy linked-list · two-pointers

Description

Merge two sorted arrays into one sorted array.

Constraints

0 <= n, m <= 100000

Examples

Input: a = [1,2,4], b = [1,3,4]

Output: [1,1,2,3,4,4]

Hints (1)
  • Advance two pointers, always taking the smaller head.

Solutions

Two-pointer merge. · Time O(n+m) · Space O(n+m)

func mergeSorted(a, b []int) []int {
    out := []int{}
    i, j := 0, 0
    for i < len(a) && j < len(b) {
        if a[i] <= b[j] {
            out = append(out, a[i]); i++
        } else {
            out = append(out, b[j]); j++
        }
    }
    out = append(out, a[i:]...)
    out = append(out, b[j:]...)
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account