Merge Two Sorted Arrays
WhatnotSoftware Engineer · Technical ScreenLast updated
Implement a linear-time merge of two sorted arrays into a new sorted array using two pointers, preserving duplicates without modifying the input arrays.
Merge Two Sorted Arrays
You are given two integer arrays, nums1 and nums2, both sorted in non-decreasing order.
Write a function merge_sorted_arrays(nums1: list[int], nums2: list[int]) -> list[int] that combines all elements from both arrays into a single, newly allocated array sorted in non-decreasing order. Every duplicate element from both input arrays must be preserved in the output.
You must not mutate either nums1 or nums2.
Function Signature
def merge_sorted_arrays(nums1: list[int], nums2: list[int]) -> list[int]:
pass
Constraints
0 <= len(nums1), len(nums2) <= 10^6-10^9 <= nums1[i], nums2[j] <= 10^9nums1andnums2are sorted in non-decreasing order.- Expected time complexity:
O(m + n)wherem = len(nums1)andn = len(nums2). - Expected auxiliary space complexity:
O(1)extra space beyond the memory required for the output array.
Examples
Example 1:
Input: nums1 = [1, 2, 4, 7], nums2 = [2, 3, 5, 7, 8]
Output: [1, 2, 2, 3, 4, 5, 7, 7, 8]
Explanation: Elements 2 and 7 appear in both arrays and are both included twice in sorted order.
Example 2:
Input: nums1 = [], nums2 = [0, 5]
Output: [0, 5]
Explanation: An empty input array returns a copy of the non-empty array.
Edge Cases to Consider
- One or both input arrays are empty.
- All elements of one array are strictly smaller or larger than all elements of the other.
- Multiple identical elements exist across both arrays.
- Negative numbers and zero.
Hints
Hint 1
Initialize two index pointers, one at the beginning of each array.
Hint 2
At each step, compare the elements at the current pointers, append the smaller (or equal) element to your result list, and increment that pointer.
Hint 3
Once one pointer reaches the end of its respective array, append all remaining elements of the other array directly to the output.
Follow-up questions
- How would you optimize the merge if `len(nums1) << len(nums2)` (e.g., using binary search)?
- How would you scale this logic to merge `k` sorted arrays simultaneously in `O(N log k)` time?
- If the inputs were iterator streams that do not fit into memory, how would you design a memory-bounded generator that yields sorted values?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.