CodingNodes / Arrays & Hashing / Merge Sorted Array System design Space play · ←→ step · R restart

Problem

You get two lists of numbers, each already sorted from small to large. The first list nums1 has room for both: its first m entries are real numbers and the last n entries are placeholder zeros. The second list nums2 holds n real numbers.

Merge nums2 into nums1 in place, so that nums1 ends up as one sorted list of all m + n numbers. Nothing is returned.

Constraints

  • nums1.length = m + n, nums2.length = n
  • 0 ≤ m, n and 1 ≤ m + n ≤ 200
  • Both lists are sorted in non-decreasing order
  • -10⁹ ≤ value ≤ 10⁹

Examples: pick one to animate

Solutions

TimeO(m + n) SpaceO(1)

Time: Each step places one number, and there are m + n numbers in total.

Space: Only the three indexes i, j and k are stored. The merge happens inside nums1.

The empty slots are at the end of nums1, so start there. Compare the largest unplaced item of each list and write the bigger one into the last free slot. The write position never catches up with the items still waiting to be read, so nothing is overwritten too early. Once nums2 is used up, the rest of nums1 is already in the right place.