Solution: Merge Two Sorted Lists
Let's solve the Merge Two Sorted Lists problem.
Statement
Given two integer lists, nums1
and nums2
, of size nums1
and nums2
into a single list sorted in nondecreasing order.
Constraints:
nums1[i]
,nums2[i]
Solution 1: Creating a new list and using three pointers
Since we have two lists, nums1
and nums2
, to merge, we start by creating a new empty list result
of length equal to the sum of the length of nums1
and nums2
. This list will be filled with all the elements of both lists 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 lists 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 lists to
result
.
The following illustrations demonstrate the algorithm:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.