Tutorialspoint
Problem
Solution
Submissions

Merge Two Sorted Arrays

Certification: Basic Level Accuracy: 25% Submissions: 4 Points: 5

Write a JavaScript program to merge two sorted arrays into a single sorted array. The merged array should contain all elements from both input arrays in ascending order. You cannot use built-in sort functions.

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:
    • nums1 has 3 valid elements [1,2,3] and nums2 has 3 elements [2,5,6].
    • Merge process starts from the end of both arrays.
    • Compare elements and place the larger one at the end of nums1.
    • Continue until all elements from nums2 are merged into nums1.
Example 2
  • Input: nums1 = [1], m = 1, nums2 = [], n = 0
  • Output: [1]
  • Explanation:
    • nums1 has 1 element [1] and nums2 is empty.
    • Since nums2 is empty, the result is just nums1.
    • No merging is required.
Constraints
  • nums1.length == m + n
  • nums2.length == n
  • 0 ≤ m, n ≤ 200
  • 1 ≤ m + n ≤ 200
  • -10^9 ≤ nums1[i], nums2[j] ≤ 10^9
  • You must merge in-place with O(1) extra memory space
ArraysGoldman SachsTutorix
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

  • Use three pointers: one for nums1 valid elements, one for nums2, and one for the final position
  • Start merging from the end of both arrays to avoid overwriting elements
  • Compare elements from the end of both arrays and place the larger one at the end
  • Continue until all elements from nums2 are processed
  • Handle remaining elements in nums2 if any
  • The merge should be done in-place in nums1 array

Steps to solve by this approach:

 Step 1: Initialize three pointers - i for valid elements in nums1, j for nums2, and k for final position.
 Step 2: Set i to m-1, j to n-1, and k to m+n-1 to start from the end of arrays.
 Step 3: Compare elements at nums1[i] and nums2[j] and place the larger one at nums1[k].
 Step 4: Move the corresponding pointer (i or j) and k backward after each placement.
 Step 5: Continue the comparison and placement until one of the arrays is exhausted.
 Step 6: Copy any remaining elements from nums2 to nums1 if j >= 0.
 Step 7: The merge is complete as nums1 now contains all elements in sorted order.

Submitted Code :