
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.
- nums1 has 3 valid elements [1,2,3] and nums2 has 3 elements [2,5,6].
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.
- nums1 has 1 element [1] and nums2 is empty.
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
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 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