oneby7

Two Pointers Merging sorted arrays

169. Merge Two Sorted Arrays Without Extra Space

Hard

You are given two arrays of integers, nums1 with n elements and nums2 with m elements. Each one is sorted in non-decreasing order.

Move values between the two arrays so that nums1 followed by nums2 reads as one sorted sequence. In the end nums1 holds the n smallest values in non-decreasing order, and nums2 holds the other m values in non-decreasing order. Neither array changes its length.

Change both arrays in place, using only O(1) extra memory: no third array. The function returns nothing. The output shows both arrays after the call, as [nums1,nums2].

Example 1

Input: nums1 = [1, 4, 8, 10], nums2 = [2, 3, 9]

Output: [[1,2,3,4],[8,9,10]]

Explanation: Together the arrays hold 1, 2, 3, 4, 8, 9 and 10. The four smallest stay in nums1, so 2 and 3 move in and 8 and 10 move out to nums2.

Example 2

Input: nums1 = [-5, 0, 0], nums2 = [-7, 0]

Output: [[-7,-5,0],[0,0]]

Explanation: −7 is the smallest value, so it moves to the front of nums1, and one 0 moves to nums2. The 0s are equal, so it does not matter which one moves.

Example 3

Input: nums1 = [2, 3], nums2 = [3, 7, 11]

Output: [[2,3],[3,7,11]]

Explanation: No value of nums1 is bigger than any value of nums2, so nothing moves.

Check your understanding

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

nums1 = [2, 6, 7], nums2 = [1, 6]

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 105
  • -109 ≤ nums1[i], nums2[i] ≤ 109
  • nums1 and nums2 are each sorted in non-decreasing order.

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.