TRT
Sign in
easyFoundationscoding

Merge two sorted arrays when the first has room for both

Merge in O(m + n) time and O(1) extra space by filling from the back, and explain why the front doesn't work.

TRT practice prompt — not a verified question from a named employer.

The Runtime Theory Team1 min read
Learn it firstTwo pointers on arraysTwo indexes moving through one array can reverse it, test a palindrome, compact it or merge into it, in one pass and with O(1) extra memory.

A strong answer

a holds m sorted values followed by n empty slots; b holds n sorted values. The standard merge compares the front elements of both arrays and takes the smaller, but writing to the front of a would overwrite, so fill from the back values that haven't been compared yet.

So merge from the back. Keep i = m − 1 at the last real value of a, j = n − 1 at the last value of b, and w = m + n − 1 at the last slot. While j ≥ 0, write the larger of a[i] and b[j] to a[w] (treating a as exhausted when i < 0), and move that index and w back by one. When b runs out, the remaining elements of a are already in place, so the loop can stop.

Why it is safe: before each write, w = i + j + 1, so w > i as long as any element of b remains, and the write never lands on an unread element of a. Each step places one element, so the total is O(m + n) time with O(1) extra space.

Taking from a when the two values are equal keeps equal elements from a before those from b in the result, which makes the merge stable, a property merge sort relies on.

What the interviewer is listening for

  • Recognizing why the front fails and the back works.
  • The loop invariant w = i + j + 1, or an equivalent argument.
  • Correct handling of one array running out.
  • O(m + n) time and O(1) extra space.

Common mistakes

  • Merging into a new array and copying back, which works but uses O(m + n) extra space.
  • Forgetting the remaining elements of b when a runs out first.
  • Off-by-one errors in the starting indexes.

This answer walks

Practice follow-ups

  1. 01Why can't the write index overtake the unread part of the first array?
  2. 02What happens when the second array runs out first? And the first?
  3. 03How would you merge k sorted arrays?
  4. 04Is your merge stable? Why might that matter?

Not started

Sign in to save your learning progress.

Sign in to save