Merge Sorted Array

Easy

Topics
ArrayTwo PointersSorting

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

a123
b256
merged102122335465
came from acame from b
Both inputs are already sorted, and the merged row is their 6 values in one sorted sequence — the shading shows which input each came from. Equal values from the two sides both survive; nothing is deduplicated.
The two rows are the two input arrays; they have independent lengths.
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

a1
b
empty array
merged10
came from a
Input:  a = [1], b = []
Output: [1]
Explanation: One side can be empty.

Example 3

a1
b
empty array
merged10
came from a
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

  1. Keep an index into a and an index into b, both at 0, and an empty output.
  2. 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.
  3. 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.
  4. 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 out
SensAI
Beta
Tap the mic to stop voice mode