Merge Sorted Arrays
Given two sorted integer arrays `nums1` and `nums2`, merge `nums1` and `nums2` into a single sorted array in non-decreasing order. The original arrays should not be mutated. The function should return a new array. **Examples:** ```typescript mergeSortedArrays([1, 2, 3], [2, 5, 6]) // [1, 2, 2, 3, 5, 6] mergeSortedArrays([1], []) // [1] mergeSortedArrays([], [0]) // [0] ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(m + n)
- Space complexity: O(m + n)
With two pointers i and j advancing monotonically, each element from nums1 (size m) and nums2 (size n) is inspected exactly once, giving strictly linear O(m + n) time.
Follow-Up Questions Interviewers Ask About Merge Sorted Arrays
- How would you solve this with O(1) extra space if nums1 has enough buffer space at the end (LeetCode 88)?
Iterate backwards from the end using three pointers: place the largest element at nums1[m + n - 1], decrementing the respective pointer. Merging from back to front prevents overwriting elements in nums1. - Why is using nums1.concat(nums2).sort((a,b)=>a-b) suboptimal in an interview?
Concatenating and sorting throws away the pre-sorted property of the inputs and incurs O((m+n) log(m+n)) runtime instead of linear O(m + n). - How does this algorithm relate to Merge Sort?
This exact two-pointer merge subroutine is the core combine phase of the Merge Sort divide-and-conquer sorting algorithm.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.