Merge Two Sorted Array
š Problem Statement
Given two sorted integer arrays arr1 and arr2, return a new array that contains all elements from both arrays in sorted order.
Input: arr1 = [1, 3, 5, 7], arr2 = [2, 4, 6, 8] -> Output: [1, 2, 3, 4, 5, 6, 7, 8].
Constraint: You must achieve time complexity. You cannot simply concatenate the arrays and call sort().
š” Intuition
Since both arrays are already sorted, we can think of them like two separate lines of people arranged by height. If we want to merge them into a single sorted line, we just need to compare the person at the front of line A with the person at the front of line B. The shorter person steps into the new line, and the next person in their original line steps up. We repeat this "zipper" motion until one line is empty, and then simply append everyone remaining in the other line.
š§ Approach
- Initialize an empty
resultarray to store the merged elements. - Initialize two pointers, and , to track the current index in
arr1andarr2, respectively. - Use a
whileloop that continues as long as both and are within the bounds of their respective arrays. - Compare
arr1[i]andarr2[j]. Append the smaller value toresultand increment the corresponding pointer. - Once the loop terminates (meaning one array has been fully traversed), there may be remaining elements in the other array. Since the original arrays are already sorted, we can safely append the entire remaining portion directly to
result.
ā” Complexity Analysis
ā We iterate through each element in both arrays exactly once, where is the length of arr1 and is the length of arr2.
ā We create a new result array that holds all elements from both input arrays.
ā ļø Common Mistakes
- Forgetting to handle the "leftovers" after the main
whileloop finishes. One array will always run out before the other (unless they are exactly identical in length and values). - Trying to modify one of the arrays in-place instead of returning a new array. While in-place merging is possible, it is significantly more complex and usually requires time unless advanced techniques are used.
- Using
arr.pop(0)instead of pointers.pop(0)on a Python list is an operation, which would destroy the time complexity and make the algorithm .
šÆ Final Thoughts
This "zipper" technique is the exact logic that powers the "Merge" step of the classic Merge Sort algorithm. Mastering this pointer manipulation is crucial because it proves you can evaluate and combine multiple datasets linearly without resorting to brute-force comparisons or lazy built-in functions.