Solution: Merge Two Sorted Arrays
Let’s solve the Merge Two Sorted Arrays problem.
Statement
Given two integer arrays, nums1
and nums2
, of size nums1
and nums2
into a single array sorted in nondecreasing order.
Constraints:
nums1[i]
,nums2[i]
Solution 1: Creating a new array and using three pointers
Since we have two arrays, nums1
and nums2
, to merge, we start by creating a new empty array result
of length equal to the sum of the length of nums1
and nums2
. This array will be filled with all the elements of both arrays in sorted order and returned. The following are the further steps of the algorithm:
Initialize three pointers,
p1
,p2
, andp3
, pointing to the start ofnums1
,nums2
, andresult
, respectively.Traverse both arrays until the end of either
nums1
andnums2
is reached.While traversing, compare the elements of
nums1
andnums2
, pointed byp1
andp2
, respectively. Check whether the element pointed byp1
orp2
is smaller.If the element pointed by
p1
is smaller, store this element at the position pointed byp3
. Also, incrementp1
andp3
by 1.Otherwise, if the element pointed by
p2
is smaller, store this element at the position pointed byp3
. Also, incrementp2
andp3
by 1.
After the traversal, append the rest of the elements in any of the arrays to
result
.
The following illustrations demonstrate the algorithm:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.