Community

Start a Thread


Notifications
Subscribe You’re not receiving notifications from this thread.

Merge Sorted Array (Main Thread)

Here is the interview question prompt, presented for reference.

Merge Sorted Arrays

Let's tackle a problem where we need to merge two sorted arrays into one larger sorted array.

Problem Statement

We are given two integer arrays, nums1 and nums2, that are both sorted in non-decreasing order.

We are also given the number of elements in each array, m and n.

Our goal is to:

  1. Merge the two arrays into a single array
  2. Ensure the merged array is also sorted

The catch is that instead of creating a new array, we need to do the merge in-place into nums1.

nums1 has extra space at the end to fit all the elements. We should:

  • Merge nums2 into the end of nums1
  • Sort the final result in nums1

Example

nums1 = [1, 2, 3, _, _, _],  m = 3
nums2 = [2, 5, 6], n = 3

Result: nums1 = [1, 2, 2, 3, 5, 6]

We merged the sorted arrays [1, 2, 3] and [2, 5, 6] into the sorted result [1, 2, 2, 3, 5, 6].

![Problem](https://storage.googleapis.com/algodailyrandomassets/curriculum/merge-sorted-array/ProblemStatement.png)

Constraints

  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • -109 <= nums1[i], nums2[j] <= 109

You can see the full challenge with visuals at this link.

Challenges • Asked over 1 year ago by Jake from AlgoDaily

Jake from AlgoDaily Commented on Aug 23, 2022:

This is the main discussion thread generated for Merge Sorted Array (Main Thread).