JavaScriptMediumTwo Pointers20 min
Merge two sorted arrays
Merge two nondecreasing integer arrays into one nondecreasing array, retaining duplicates. All input is valid JSON satisfying the constraints; do not mutate the meaning of values through type coercion. Interviewers use this problem to assess advance the pointer with the smaller current value.
Input
A JSON array [firstArray, secondArray].
Output
Print one compact JSON value: the merged array.
Constraints
Each array has at most 10000 integers between -1000000 and 1000000.
Example
Input
[[1,3],[2,4]]
Output
[1,2,3,4]
Example 2 input
[[3],[]]
Output
[3]
Boundary case: Append the untouched suffix after one array is exhausted
Public test cases (2)
Input
[[1,3],[2,4]]
Expected output
[1,2,3,4]
Input
[[1,1],[1]]
Expected output
[1,1,1]
Hints (2)
- Neither input needs to be sorted again
- Append the untouched suffix after one array is exhausted
Target complexity: time O(n+m) · space O(n+m)
