oneby7

Two Pointers Merging sorted arrays

168. Merge Sorted Array

Easy

You are given two integer arrays, nums1 and nums2, and two integers, m and n.

The values of nums1 are its first m elements. After them, nums1 has n free places, each holding 0, so its length is m + n. nums2 holds exactly n values. The values of each array are sorted in non-decreasing order.

Merge the values of nums2 into nums1, so that nums1 holds all m + n values in non-decreasing order. Change nums1 itself. The function returns nothing; the answer is what nums1 holds after it finishes.

Example 1

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

Output: [1,2,5,5,8,9]

Explanation: The six values in order are 1, 2, 5, 5, 8 and 9. The value 5 is in both arrays, so it appears twice.

Example 2

Input: nums1 = [-4, 0, 0, 0] m = 2 nums2 = [-6, -1] n = 2

Output: [-6,-4,-1,0]

Explanation: The values of nums1 are −4 and 0, and the last two zeros are free places. The 0 that is a value stays in the answer.

Example 3

Input: nums1 = [0, 0], m = 0, nums2 = [3, 7], n = 2

Output: [3,7]

Explanation: nums1 has no values of its own, so the answer is the values of nums2.

Check your understanding

Work out the answer for this input before you write any code.

nums1 = [1, 4, 0, 0], m = 2, nums2 = [2, 3], n = 2

Constraints

  • 0 ≤ m, n ≤ 105
  • 1 ≤ m + n
  • nums1.length = m + n and nums2.length = n
  • -109 ≤ nums1[i], nums2[i] ≤ 109
  • The first m elements of nums1 and all of nums2 are sorted in non-decreasing order.
  • The last n elements of nums1 are 0.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.