Tutorialspoint
Problem
Solution
Submissions

Merge two sorted arrays.

Certification: Basic Level Accuracy: 60% Submissions: 10 Points: 10

Write a C++ program that merges two sorted arrays into a single sorted array.

Example 1
  • Input: array1 = [1, 3, 5], array2 = [2, 4, 6]
  • Output: [1, 2, 3, 4, 5, 6]
  • Explanation:
    • Step 1: Create a result array of size (array1.length + array2.length).
    • Step 2: Compare elements from both arrays and insert the smaller one into result array.
    • Step 3: Continue until all elements from both arrays are processed.
    • Step 4: Return the merged sorted array.
Example 2
  • Input: array1 = [10, 20, 30], array2 = [15, 25]
  • Output: [10, 15, 20, 25, 30]
  • Explanation:
    • Step 1: Create a result array of size 5 (3 + 2).
    • Step 2: Compare elements from both arrays and insert the smaller one into result array.
    • Step 3: Continue until all elements from both arrays are processed.
    • Step 4: Return the merged sorted array.
Constraints
  • 1 ≤ len(array1), len(array2) ≤ 10^6
  • -10^9 ≤ array1[i], array2[i] ≤ 10^9
  • Time Complexity: O(n + m), where n and m are the lengths of the two arrays
  • Space Complexity: O(n + m)
ArraysPointers and ReferencesIBMLTIMindtree
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 two pointers to traverse both arrays.
  • Compare elements at the current pointers and add the smaller one to the result.
  • If one array is exhausted, add the remaining elements from the other array.

Steps to solve by this approach:

 Step 1: Define a function mergeSortedArrays that takes two constant vectors of integers.
 Step 2: Create a result vector to store the merged array.
 Step 3: Use two pointers to track current positions in both input arrays.
 Step 4: Compare elements at current positions and add the smaller one to the result.
 Step 5: Once one array is exhausted, add remaining elements from the other array.
 Step 6: Return the merged result vector.
 Step 7: In main, call mergeSortedArrays with two vectors and print the result.

Submitted Code :