
Problem
Solution
Submissions
Merge Two Sorted Arrays
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to merge two sorted arrays into a single sorted array. Given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively. The final sorted array should be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored.
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: The arrays [1,2,3] and [2,5,6] are merged to form [1,2,2,3,5,6].
Example 2
- Input: nums1 = [1], m = 1, nums2 = [], n = 0
- Output: [1]
- Explanation: Since nums2 is empty, nums1 remains unchanged.
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) - no extra space should be used
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
- nums1 has enough space at the end, start filling nums1 from the end
- Use two pointers to track the current positions in the valid portions of nums1 and nums2
- Compare elements from both arrays and place the larger one at the end of nums1
- Continue this process until all elements are merged
- Be careful about handling cases where one array is exhausted before the other
- Remember that you need to handle any remaining elements in nums2