Merge Sorted Array solution explained
To merge a second sorted array into a first sorted array that has empty slots at its end, fill the result from the back. Compare the largest remaining value of each array, write the bigger one into the last free slot, and step left. Because the free space is at the end, nothing you still need gets overwritten, and the merge takes O(m + n) time with O(1) extra space.
By Evin JohnPublished 8 min read
The problem, in plain terms
There are two lists of numbers, each sorted from small to large. The first list has room for both: its first m positions hold real values and its last n positions are placeholders. The second list holds n values. Change the first list so that all m + n values are in it, sorted, without allocating a new result list. Nothing is returned.
first = [2, 5, 8, 0, 0, 0] m = 3 (the zeros are placeholders)
second = [1, 5, 9] n = 3
compare 8 and 9 -> write 9 at index 5
compare 8 and 5 -> write 8 at index 4
compare 5 and 5 -> tie, take from second, write 5 at index 3
compare 5 and 1 -> write 5 at index 2
compare 2 and 1 -> write 2 at index 1
first is used up -> write 1 at index 0
first = [1, 2, 5, 5, 8, 9]Useful questions: can m or n be zero, are the placeholder values meaningful (they are not), and must the merge be in place or is a temporary copy acceptable. Interviewers almost always want the in-place version once the basic idea is on the table.
Where this shows up
This is the merge step of merge sort, dressed up with an in-place constraint. It is popular as a first question because the brute force is obvious and the improvement needs one insight rather than a new data structure. Interviewers listen for the moment you notice that writing at the front clobbers data and that the empty space at the back is there for a reason.
Slower starting ideas
The shortest correct answer copies the second array into the placeholder slots and sorts the whole first array. That is O((m + n) log(m + n)) and ignores that both inputs were sorted. A better but still wasteful approach copies the first m values into a temporary list and then merges front to back into the first array, which is linear time but needs O(m) extra memory. A third idea, merging front to back in place and shifting the first array right each time a value from the second array is inserted, keeps O(1) space but costs O(m × n) shifts in the worst case. Naming these quickly shows you understand the trade-off you are about to remove.
The optimal approach: merge from the back
Point i at the last real value of the first array (index m - 1), j at the last value of the second array (index n - 1), and k at the last slot (index m + n - 1). While the second array still has values, write whichever of first[i] and second[j] is larger into first[k], move that pointer left, and move k left. If i runs out first, the remaining values of the second array are copied in order. If j runs out first, stop: the values of the first array that were never moved already sit at the front, in sorted order.
def merge(first, m, second, n):
i, j, k = m - 1, n - 1, m + n - 1
while j >= 0: # once second is used up, first is already in place
if i >= 0 and first[i] > second[j]:
first[k] = first[i]
i -= 1
else:
first[k] = second[j]
j -= 1
k -= 1#include <vector>
// first has m real values followed by n spare slots; second has n values.
void merge(std::vector<int>& first, int m, const std::vector<int>& second, int n) {
int i = m - 1, j = n - 1, k = m + n - 1;
while (j >= 0) {
if (i >= 0 && first[i] > second[j]) {
first[k--] = first[i--];
} else {
first[k--] = second[j--];
}
}
}Why is this safe? At every step the write position k equals i + j + 1, so k is always at least i + 1 while j is non-negative. The slot being written is therefore never one that still holds an unplaced value from the first array. That one-line argument is worth saying out loud, since it is exactly what the front-to-back version gets wrong.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Copy second into the tail, then sort | O((m + n) log(m + n)) | Depends on the sort, often O(m + n) |
| Copy first aside, merge front to back | O(m + n) | O(m) |
| Insert front to back with shifting | O(m × n) worst case | O(1) |
| Merge from the back | O(m + n), and often fewer steps | O(1) |
The back-to-front loop runs at most m + n times and stops early when the second array is exhausted, so if every value of the second array is smaller than every value of the first, it still does m + n moves, but if every value of the second array is larger, it does only n.
Edge cases to test
- n = 0: nothing to merge, and the loop body never runs.
- m = 0: the first array is all placeholders, so the second array is copied in.
- Every value of the second array smaller than every value of the first, which moves the whole first array right.
- Every value of the second array larger, which only fills the tail.
- Equal values across the arrays, to confirm the tie rule does not skip or duplicate anything.
- Negative numbers, in case the placeholder zeros are being treated as real data.
Pitfalls
- Looping while both i and j are non-negative and forgetting to copy what is left of the second array afterward.
- Checking first[i] without checking i >= 0 first. In Python, first[-1] silently reads the last slot instead of failing.
- Merging from the front in place, which overwrites values of the first array before they are compared.
- Treating the placeholder zeros as values, which breaks on inputs that contain negative numbers.
- Returning a new list when the caller expects the first list to be changed.
How to explain it out loud
Fictional example
- Candidate
- If I merge from the front, I'll overwrite values in the first array before I've placed them. But the empty slots are at the end, so I'll fill from the end instead.
- Candidate
- I keep one pointer at the last real value of each array and one at the last slot. I write the larger value and move left. The write pointer always stays ahead of the first array's pointer, so I never overwrite anything I still need.
- Candidate
- I only loop while the second array has values. If the first array has leftovers, they're already in the right place. That's linear time and no extra memory.
Follow-ups you might hear
- Merge k sorted arrays: a min-heap of the current head of each array gives O(total × log k).
- Merge without the spare slots: you either use extra space or reach for a far more intricate in-place merge, and saying so plainly is the honest answer.
- Keep the merge stable when values carry labels: on ties, take from the second array when filling from the back, so equal items from the first array end up first. The code above does exactly this.
- Merge two sorted linked lists: no spare slots are needed, because nodes can be relinked instead of moved.
Related problems
Filling an output from its largest end is also how Squares of a Sorted Array avoids a sort. For another in-place rewrite of a sorted array, see Remove Duplicates from Sorted Array, and for combining two arrays by value rather than by order, see Intersection of Two Arrays.
Natively during practice
The merge itself is short, so an interviewer will judge you largely on how well you justify it. In a practice run on Mac or Windows, Natively can read the prompt from a screenshot, suggest test inputs such as an empty second array, and keep a transcript you can reread to see whether your explanation of the overwrite risk was clear. Read more about the AI interview assistant.
Questions people ask
How do you solve Merge Sorted Array in place?
Start three pointers at the last real value of each array and at the last slot of the first array. Write the larger of the two values into that slot and move left, stopping when the second array is used up.
Why merge from the back instead of the front?
The spare slots are at the end of the first array. Filling from the back writes only into slots that are free or already moved, while filling from the front would overwrite values that have not been placed yet.
What is the time complexity of Merge Sorted Array?
O(m + n) time and O(1) extra space for the back-to-front merge. Copying the second array in and sorting costs O((m + n) log(m + n)).
What happens to leftover values in the first array?
Nothing needs to happen. If the second array runs out first, the remaining values of the first array are already in their sorted positions at the front.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
