Tutorialspoint
Problem
Solution
Submissions

Merge Two Sorted Arrays

Certification: Basic Level Accuracy: 44.44% Submissions: 27 Points: 5

Write a Java program to merge two sorted arrays into a single sorted array. Given two arrays nums1 and nums2, which are already sorted in non-decreasing order, merge nums2 into nums1 as one sorted array. The number of elements initialized in nums1 and nums2 are m and n respectively.

Example 1
  • Input:
    nums1 = [1,3,5,0,0,0], m = 3
    nums2 = [2,4,6], n = 3
  • Output:
    [1,2,3,4,5,6]
  • Explanation:
    • Compare 1 and 2 → place 1
    • Compare 3 and 2 → place 2
    • Compare 3 and 4 → place 3
    • Compare 5 and 4 → place 4
    • Compare 5 and 6 → place 5
    • Place remaining 6
Example 2
  • Input:
    nums1 = [1,2,3,0,0,0], m = 3
    nums2 = [2,5,6], n = 3
  • Output:
    [1,2,2,3,5,6]
  • Explanation:
    • Insert elements in sorted order using two pointers
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)
ArraysPwCAdobe
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

  • Start filling nums1 from the end to avoid overwriting elements
  • Compare elements from the end of both arrays
  • Place the larger element at the end of nums1
  • Keep moving backward through both arrays
  • If nums2 still has elements after nums1 is exhausted, copy them to nums1

Steps to solve by this approach:

 Step 1: Initialize three pointers - p1 at the end of the filled portion of nums1 (at index m-1), p2 at the end of nums2 (at index n-1), and p at the end of the nums1 array (at index m+n-1).
 Step 2: Compare elements at p1 and p2 positions and place the larger one at position p in nums1.
 Step 3: Decrement the pointer of the array from which the element was taken.
 Step 4: Decrement p to move to the next position in the merged array.
 Step 5: Repeat steps 2-4 until we exhaust one of the arrays.
 Step 6: If there are remaining elements in nums2, copy them to the beginning of nums1.
 Step 7: The array nums1 now contains the merged sorted array.

Submitted Code :