Merge Two Sorted Arrays

viaGlassdoor

Problem: Given two sorted arrays, merge them into a single sorted array.

Constraints: Arrays can be of different lengths; may need to merge in-place into the first array if it has enough trailing capacity.

Example: Input: nums1=[1,2,3,0,0,0], m=3, nums2=[2,5,6], n=3 Output: [1,2,2,3,5,6]

Approach: Use two pointers starting at the end of each array's valid elements and fill the combined array from the back, always placing the larger of the two current elements at the current end position. This avoids overwriting unprocessed elements in nums1 and runs in O(m+n) time, O(1) extra space.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account