Merge Sorted Arrays
An easy Arrays problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Arrays
- Sheets
- 3
- Core for
- 25 roles
- Platform
- LeetCode
The problem
Given two sorted integer arrays, merge them into a single sorted array.
Example 1
- Input
- nums1=[1,3,5], nums2=[2,4,6]
- Output
- [1,2,3,4,5,6]
Example 2
- Input
- nums1=[1,2], nums2=[3,4]
- Output
- [1,2,3,4]
Example 3
- Input
- nums1=[], nums2=[1]
- Output
- [1]
Constraints
- 0 <= nums1.length, nums2.length <= 10^3
- -10^6 <= arr[i] <= 10^6
How to think about it
Updated 2026-09-09Because both sources are ordered, the absolute smallest remaining candidate is always standing at one of the two heads. Comparing those two values allows you to stream the merged output directly without sorting, and filling into spare buffer capacity from right to left prevents overwriting unprocessed items.
Approaches, worst first
Concatenate and sort
time O((n + m) log(n + m)) · space O(1)
Append all elements from the second array into the first (or an allocated slice) and invoke standard sorting. Ignores the sorted precondition completely and spends extra time re-evaluating already ordered sequences.
Linear merge passWrite this one
time O(n + m) · space O(1)
Maintain read pointers at the boundaries of nums1 and nums2, writing into a new array or working backwards from index n + m - 1 if nums1 provides trailing buffer capacity. Chooses the larger element each time to place values cleanly in a single pass.
Where people lose marks · 3
- Handling the remaining items of nums2 after nums1 is exhausted: if nums2 has items left, they must be copied over; if nums1 has items left in an in-place merge, they already sit in their correct spots.
- Either input array can be empty (length 0), which can cause immediate negative indexing if bounds are not checked before dereferencing pointers.
- Advancing the wrong pointer after a comparison duplicate, dropping matching elements.
Full solution
Linear merge pass: two read pointers, always emit the smaller head, then copy whichever tail is left — O(n + m) time in one pass, using the sorted precondition that concatenate-and-sort throws away.
Python
from typing import List
def merge_sorted_arrays(nums1: List[int], nums2: List[int]) -> List[int]:
merged = []
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
# smallest remaining value always sits at one of the two heads
if nums1[i] <= nums2[j]:
merged.append(nums1[i])
i += 1
else:
merged.append(nums2[j])
j += 1
merged.extend(nums1[i:]) # at most one of these tails is non-empty
merged.extend(nums2[j:])
return merged
JavaScript
function mergeSortedArrays(nums1, nums2) {
const merged = [];
let i = 0;
let j = 0;
while (i < nums1.length && j < nums2.length) {
// smallest remaining value always sits at one of the two heads
if (nums1[i] <= nums2[j]) {
merged.push(nums1[i++]);
} else {
merged.push(nums2[j++]);
}
}
// at most one of these tails is non-empty
for (; i < nums1.length; i++) merged.push(nums1[i]);
for (; j < nums2.length; j++) merged.push(nums2[j]);
return merged;
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
What each operation costs
| Operation | Time |
|---|---|
| look up element by index | O(1) |
| insert or delete at the start | O(n) |
| search an unsorted collection for a value | O(n) |
What usually goes wrong with Arrays
- Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
- Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
- Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.
Which roles need this problem
Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Arrays problems
Problem set and role mapping as of .