Merge Sorted Array

25 min · merge()

Two teams have already sorted their score lists. Your job isn't to sort them again; it's to weave them into one correctly ordered leaderboard.

Given integer arrays nums1 and nums2, each sorted in non-decreasing order, meaning each value is at least the value before it, return one sorted array containing every value from both inputs.

Both inputs contain only their real values. nums1 has no padded placeholder slots. The returned array has length nums1.length + nums2.length.

A useful way to picture the merge is from the back: compare the largest unused value in each input, write the larger one into the last open result slot, then move that input's pointer left.

Constraints

  • 0 <= nums1.length, nums2.length <= 100_000
  • 1 <= nums1.length + nums2.length
  • -1_000_000_000 <= nums1[i], nums2[i] <= 1_000_000_000
  • Both inputs are sorted in non-decreasing order.

Hints

A correct baseline

Concatenate the arrays and sort the result. It works, but it throws away the ordering work both inputs have already done.

Compare the largest survivors

Place one pointer at the end of each input and one at the end of the result. The larger pointed-to value must be the largest value still unwritten.

One side may finish early

If either pointer moves before index 0, copy the remaining prefix from the other array. Those values are already in the order the open result slots need.

Follow-up

Why does filling from the back avoid overwriting unread values when the destination is a preallocated buffer?

Visible cases

Examples

Example 1

ready
Input
nums1 = [
  1,
  2,
  3
]
nums2 = [
  2,
  5,
  6
]
Expected
[
  1,
  2,
  2,
  3,
  5,
  6
]
Why
the two 2s are both kept while the lists interleave

Example 2

ready
Input
nums1 = []
nums2 = [
  -4,
  -1,
  3
]
Expected
[
  -4,
  -1,
  3
]
Why
with the first input empty, the second is already the answer

Example 3

ready
Input
nums1 = [
  -2,
  0,
  7
]
nums2 = []
Expected
[
  -2,
  0,
  7
]
Why
with the second input empty, the first is already the answer

Interview signal

Asked at

AmazonMicrosoftAdobe
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite