Merge Sorted Arrays
Company: Fora Travel
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates competency in implementing and generalizing merge operations on sorted arrays, exercising algorithmic problem-solving, array manipulation, handling of edge cases (empty arrays, negative numbers, duplicates), and analysis of time and space complexity.
Part 1: Merge Two Sorted Arrays
Constraints
- 0 <= len(a), len(b) <= 100000
- -1000000000 <= a[i], b[i] <= 1000000000
- Both input arrays are already sorted in nondecreasing order
- The solution must return a new array rather than modifying the inputs
Examples
Input: ([1, 3, 5], [2, 4, 6])
Expected Output: [1, 2, 3, 4, 5, 6]
Explanation: A standard merge of two equal-length sorted arrays.
Input: ([-3, -1, 2], [-2, 2, 2, 7])
Expected Output: [-3, -2, -1, 2, 2, 2, 7]
Explanation: Handles negative values, duplicates, and different lengths.
Input: ([], [1, 2, 3])
Expected Output: [1, 2, 3]
Explanation: If one array is empty, the result is the other array.
Input: ([], [])
Expected Output: []
Explanation: Edge case where both arrays are empty.
Input: ([5], [5])
Expected Output: [5, 5]
Explanation: Single-element arrays with equal values must preserve duplicates.
Hints
- Keep one pointer in each array and compare the current elements.
- After one array is exhausted, append the remaining elements from the other array.
Part 2: Merge K Sorted Arrays
Constraints
- 0 <= K <= 10000, where K is the number of arrays
- 0 <= total number of elements across all arrays <= 200000
- -1000000000 <= arrays[i][j] <= 1000000000
- Each inner array is already sorted in nondecreasing order
- The solution must return a new array rather than modifying the inputs
Examples
Input: ([[1, 4, 5], [1, 3, 4], [2, 6]],)
Expected Output: [1, 1, 2, 3, 4, 4, 5, 6]
Explanation: A classic example with three sorted arrays.
Input: ([[], [-2, -1, 3], [0, 0, 2]],)
Expected Output: [-2, -1, 0, 0, 2, 3]
Explanation: Handles empty inner arrays, negative numbers, and duplicates.
Input: ([[1, 2, 3]],)
Expected Output: [1, 2, 3]
Explanation: If there is only one array, the result is that array copied into a new list.
Input: ([],)
Expected Output: []
Explanation: Edge case where there are no arrays at all.
Input: ([[], [], []],)
Expected Output: []
Explanation: Edge case where every array is empty.
Hints
- At any moment, you only need to know the smallest current unused element from each array.
- A min-heap can help you repeatedly extract the next smallest element in better than O(K) per step.