Merge Sorted Array – Solution & Complexity
Solution Walkthrough
Step 1: Warm up with extra space and sorting
- Copy the meaningful part of
nums1usingnums1[:m](or its language equivalent), then append all ofnums2. - Sort the combined values and return them.
- This is easy to write and reason about, but it spends extra memory and relies on a general sort, so it is not the optimal interview answer.
- Copy the meaningful part of
Step 2: Fill from the end with three pointers
- Keep
iat the last meaningful value innums1,jat the last value innums2, andwriteat the final slot ofnums1. - Compare
nums1[i]andnums2[j], writing the larger one intonums1[write], then move that pointer backward. - Writing from the end prevents you from overwriting unfinished values in the front of
nums1. - When one array runs out, copy any remaining
nums2values. Ifnums1still has leftovers, they are already in the correct place. - This achieves the optimal
O(m + n)time andO(1)extra space.
- Keep