
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)
Editorial
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. |
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.