Merge two sorted arrays in-place
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: Merge two sorted arrays in-place evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- nums1.length == m + n
- nums2.length == n
- 0 <= m, n <= 200
- 1 <= m + n <= 400
- -10^9 <= nums1[i], nums2[j] <= 10^9
- The first m elements of nums1 and all of nums2 are sorted non-decreasing
Examples
Input: ([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3)
Expected Output: [1, 2, 2, 3, 5, 6]
Explanation: Standard interleave: merging [1,2,3] and [2,5,6] yields [1,2,2,3,5,6].
Input: ([1], 1, [], 0)
Expected Output: [1]
Explanation: nums2 is empty (n=0); nums1 is already complete and unchanged.
Input: ([0], 0, [1], 1)
Expected Output: [1]
Explanation: nums1 has no real elements (m=0); the i>=0 guard prevents reading the placeholder, and nums2 fills the slot.
Input: ([2, 2, 2, 0, 0, 0], 3, [2, 2, 2], 3)
Expected Output: [2, 2, 2, 2, 2, 2]
Explanation: All elements equal; ties are handled consistently and the result stays sorted.
Input: ([4, 5, 6, 0, 0, 0], 3, [1, 2, 3], 3)
Expected Output: [1, 2, 3, 4, 5, 6]
Explanation: Every element of nums2 is smaller, so nums1's data is pushed entirely to the back first.
Input: ([1, 2, 3, 0, 0, 0], 3, [4, 5, 6], 3)
Expected Output: [1, 2, 3, 4, 5, 6]
Explanation: Every element of nums2 is larger; nums2 fills the tail while the nums1 prefix needs no movement.
Input: ([-5, -3, 0, 0, 0], 2, [-10, -2, 7], 3)
Expected Output: [-10, -5, -3, -2, 7]
Explanation: Negative values merge correctly across both arrays.
Hints
- A forward merge into nums1[0] would overwrite elements of nums1 you have not yet compared. Which direction avoids that?
- Use three pointers: i at the last real element of nums1 (index m-1), j at the last element of nums2 (index n-1), and k at the last slot of nums1 (index m+n-1). Write the larger of nums1[i] and nums2[j] into position k.
- Loop only while j >= 0. Once nums2 is exhausted, any remaining nums1 prefix is already in its correct place, so no extra copying is needed. Guard the read with i >= 0 to handle the m = 0 case.