EasyArraysTwo PointersSorting

Merge Sorted Array

LeetCode
2 approaches, code in all languages

Two integer arrays are given in non-decreasing order. The first array has spare room at its tail sized to hold the second array's contents: its real length is m, followed by n zero placeholders, while the second array has length n.

Merge the two so the first array ends up holding all m + n values in non-decreasing order, and do the work in place rather than returning a new array.

Example 1

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3

Output: [1,2,2,3,5,6]

The placeholder zeros in nums1 get overwritten by the merged order.

Example 2

Input: nums1 = [1], m = 1, nums2 = [], n = 0

Output: [1]

Constraints

  • nums1.length == m + n
  • 0 ≤ m, n ≤ 200
  • -10^9 ≤ nums1[i], nums2[j] ≤ 10^9
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now