Tutorialspoint
Problem
Solution
Submissions

Merge Two Sorted Arrays

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to merge two sorted arrays into a single sorted array. Given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. The final sorted array should be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored.

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]
  • Explanation: The arrays [1,2,3] and [2,5,6] are merged to form [1,2,2,3,5,6].
Example 2
  • Input: nums1 = [1], m = 1, nums2 = [], n = 0
  • Output: [1]
  • Explanation: Since nums2 is empty, nums1 remains unchanged.
Constraints
  • nums1.length == m + n
  • nums2.length == n
  • 0 ≤ m, n ≤ 200
  • 1 ≤ m + n ≤ 200
  • -10^9 ≤ nums1[i], nums2[j] ≤ 10^9
  • Time Complexity: O(m + n)
  • Space Complexity: O(1) - no extra space should be used
ArraysWiproIBM
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • nums1 has enough space at the end, start filling nums1 from the end
  • Use two pointers to track the current positions in the valid portions of nums1 and nums2
  • Compare elements from both arrays and place the larger one at the end of nums1
  • Continue this process until all elements are merged
  • Be careful about handling cases where one array is exhausted before the other
  • Remember that you need to handle any remaining elements in nums2

Steps to solve by this approach:

 Step 1: Initialize three pointers - i pointing to the last element in nums1 array (m-1), j pointing to the last element in nums2 array (n-1), and k pointing to the last position in the merged array (m+n-1).

 Step 2: Compare elements at nums1[i] and nums2[j].
 Step 3: Place the larger element at position nums1[k] and decrement the respective pointers.
 Step 4: Continue this process until we exhaust either nums1 or nums2.
 Step 5: If there are remaining elements in nums2, copy them to the beginning of nums1.
 Step 6: No need to handle remaining elements in nums1 as they are already in the correct position.
 Step 7: The array nums1 now contains the merged result.

Submitted Code :