← Questions
Merge two sorted arrays in place
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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 firstmslots ofarr1hold its values and the lastnare 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
arr1already 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
arr1is overwritten before it is read. - Stopping when
arr2is used up; what is left ofarr1is already in place. - O(m + n) time, O(1) extra space.
- Tests:
m = 0,n = 0, all ofarr2smaller, 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))).
-
arr1has 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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

