20Merge two sorted arrays
easyAbout 15 minutesCodingarraystwo-pointerssorting
Problem
Implement merge(nums1, m, nums2, n). nums1 and nums2 are sorted in ascending order. nums1 has a length of m + n: the first m items are real values and the last n are placeholders (0). Merge nums2 into nums1 in place so nums1 ends up sorted.
const nums1 = [1, 2, 3, 0, 0, 0];
merge(nums1, 3, [2, 5, 6], 3);
nums1; // [1, 2, 2, 3, 5, 6]Requirements
- Change
nums1in place; do not return a new array. - Use O(1) extra space.
- Solve it in O(m + n) time.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
solution.jsJavaScript
Press Run or ⌘ Enter to execute your code.
Video walkthrough
Stuck? Watch someone solve it, then try again on your own.
Step-by-step
Filling nums1 from the front would overwrite values you have not placed yet. The placeholders are at the back, so fill from the back.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 4 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.