Merge Sorted Array
Easy
Topics
You are given two integer arrays a and b, each sorted in non-decreasing order. Return a single array containing all their elements, also sorted in non-decreasing order.
Duplicates are kept: if a value appears twice in a and once in b, it appears three times in the result.
On LeetCode this is posed as an in-place merge: nums1 arrives padded with zeros and you overwrite it from the back. A judge that reads stdin and compares printed output cannot observe a write to an argument, so the statement here returns the merged array instead. The interesting part is unchanged — and the back-to-front trick is still worth knowing, which the editorial covers.
Example 1
Input: a = [1,2,3], b = [2,5,6] Output: [1,2,2,3,5,6] Explanation: The two 2s both survive, one from each array.
Example 2
Input: a = [1], b = [] Output: [1] Explanation: One side can be empty.
Example 3
Input: a = [], b = [1] Output: [1] Explanation: And so can the other.
Constraints
- 0 <= a.length, b.length <= 200
- 1 <= a.length + b.length
- -10^9 <= a[i], b[i] <= 10^9
- Both arrays are sorted in non-decreasing order
Editorial — intuition, approach, complexity and pitfalls
Intuition
Concatenating and sorting works and gets the right answer, and it throws away the one fact that makes this problem easy: both inputs are already sorted. Sorting again costs a log factor to rediscover an order you were handed.
The smallest element of the result has to be the smallest element of one array or the other — there is nowhere else for it to come from. So keep a finger on the front of each array, compare the two values under them, take the smaller, and advance that finger. Each step places exactly one element and never looks back.
The in-place version on LeetCode is the same comparison run backwards, and the reason is worth understanding even here: filling from the front would overwrite elements of nums1 that have not been read yet, while filling from the back writes only into the zero padding, which nobody needs.
Approach
- Keep an index into
aand an index intob, both at 0, and an empty output. - While both indices are in range, append the smaller of the two values under them and advance that index. On a tie, either works — the values are equal, so the result is the same.
- When one array runs out, append the whole remainder of the other. It is already sorted and every value in it is at least as large as everything placed so far.
- Handle an empty input by the same code: the main loop simply never runs and one remainder is appended.
Walkthrough
a = [1, 2, 3]
b = [2, 5, 6]
i j compare take output
0 0 1 vs 2 1 [1]
1 0 2 vs 2 2 (a) [1,2]
2 0 3 vs 2 2 (b) [1,2,2]
2 1 3 vs 5 3 [1,2,2,3]
a exhausted, append the rest of b
[1,2,2,3,5,6]Complexity
- Time — O(m + n): each element is looked at once and placed once. Concatenating and re-sorting would be O((m + n) log(m + n)).
- Space — O(m + n): the output. The in-place variant is O(1) beyond the array it is given, which is the whole reason that variant exists.
Common Pitfalls
- Forgetting the remainder. When the loop ends one array still has elements, and they have to be appended — a solution that stops at the loop silently truncates.
- In the in-place variant, filling from the front. That clobbers unread elements of
nums1; the write has to start at the back. - Treating equal values as a duplicate to drop. Both copies belong in the output.
- Assuming both arrays are non-empty. Either can be empty here, and the shorter-array-first optimisation some solutions add breaks on that.
Full Solution — all languages
class Solution:
def merge(self, a, b):
out = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i])
i += 1
else:
out.append(b[j])
j += 1
out.extend(a[i:])
out.extend(b[j:])
return outimport java.util.*;
class Solution {
public int[] merge(int[] a, int[] b) {
int[] out = new int[a.length + b.length];
int i = 0, j = 0, at = 0;
while (i < a.length && j < b.length) {
out[at++] = a[i] <= b[j] ? a[i++] : b[j++];
}
while (i < a.length) out[at++] = a[i++];
while (j < b.length) out[at++] = b[j++];
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> merge(vector<int>& a, vector<int>& b) {
vector<int> out;
size_t i = 0, j = 0;
while (i < a.size() && j < b.size()) {
if (a[i] <= b[j]) out.push_back(a[i++]);
else out.push_back(b[j++]);
}
while (i < a.size()) out.push_back(a[i++]);
while (j < b.size()) out.push_back(b[j++]);
return out;
}
};/**
* @param {number[]} a
* @param {number[]} b
* @return {number[]}
*/ var merge = function(a, b) {
const out = [];
let i = 0, j = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) out.push(a[i++]);
else out.push(b[j++]);
}
while (i < a.length) out.push(a[i++]);
while (j < b.length) out.push(b[j++]);
return out;
};