Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Two pointers

Merge two sorted arrays

Easy · Target 10 minutes · Two pointers

Given two integer arrays a and b, each sorted in non-decreasing order, return one array holding all their elements in non-decreasing order. Either array may be empty. Use O(m + n) time.

Examples

InputOutputWhy
a = [1, 4, 7], b = [2, 3, 9][1, 2, 3, 4, 7, 9]
a = [], b = [1, 2][1, 2]
a = [2, 2, 2], b = [2, 2][2, 2, 2, 2, 2]Equal values are all kept.

Constraints

  • 0 ≤ m, n ≤ 10⁴
  • −10⁹ ≤ a[i], b[j] ≤ 10⁹
  • a and b are sorted in non-decreasing order

Hints

Hint 1

Concatenating and sorting is O((m + n) log(m + n)). The inputs are already sorted; use that.

Hint 2

The smallest value overall is the smaller of a[0] and b[0]. What is the next smallest?

Hint 3

Keep a pointer into each array. Take the smaller of the two front values, advance that pointer, and repeat. When one array runs out, copy the rest of the other.

Where people lose marks

  • Forgetting the tail: the loop ends when either array runs out, and the other may still hold values.
  • Using a[i] < b[j] for the tie: the result is still sorted, but the merge is no longer stable.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.