← Questions

Merge two sorted arrays in place

0
AmazonMetaCodingLast asked Feb 2026

A coding interview question asked in Amazon's technical phone screen and at Meta, last asked Feb 2026. It tests arrays, two pointers and sorting.

Two integer arrays are each sorted in ascending order. arr1 has room at its end for all of arr2's values. Merge arr2 into arr1 so arr1 holds every value in ascending order, without using another array.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • merge(arr1: list[int], m: int, arr2: list[int], n: int) -> None — the first m slots of arr1 hold its values and the last n are free (zeros); len(arr1) == m + n.

Example

arr1 = [1, 2, 3, 0, 0, 0], m = 3, arr2 = [2, 5, 6], n = 3
merge(...)  ->  arr1 is [1, 2, 2, 3, 5, 6]

arr1 = [4, 5, 0, 0], m = 2, arr2 = [1, 2], n = 2
merge(...)  ->  arr1 is [1, 2, 4, 5]

arr1 = [0], m = 0, arr2 = [1], n = 1
merge(...)  ->  arr1 is [1]

Constraints

  • 0 <= m, n <= 200, 1 <= m + n; values fit in 32-bit integers.

Clarifying questions

  • Does arr1 already have the free space at its end?
  • What does "without another array" allow: O(1) extra space?
  • Are duplicates possible?

What a strong answer covers

  • Filling from the back: compare the largest remaining values of both arrays and write into the last free slot, so nothing in arr1 is overwritten before it is read.
  • Stopping when arr2 is used up; what is left of arr1 is already in place.
  • O(m + n) time, O(1) extra space.
  • Tests: m = 0, n = 0, all of arr2 smaller, all larger.

Follow-ups

  • Both arrays are sorted in descending order: fill from the back with the smallest values instead.
  • The arrays are not sorted at all: sort first, or merge in place with no free space (gap method, O((m + n) log(m + n))).
  • arr1 has no free space and the result must span both arrays in place.

Where it's asked

  • Amazon · Technical phone screen · Last asked Feb 202660 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI
  • Meta · Technical phone screen · Last asked Sep 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted

What it tests

arrays · two pointers · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding