Hi friends, we are going to solve a leetcode problem called Merge Sorted Array. Iam to to write a series of posts regarding solving the problem on leet code on wards. Let's check the problem
Description of the problem:
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Our task is to merge nums1 and nums2 into a single array sorted in the non-decreasing order. The final sorted array should not be returned by the function but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Example
Input:nums1 = [1,2,3,0,0,0], m = 3nums2 = [2,5,6], n = 3Output:[1,2,2,3,5,6]
Approach
To solve this problem efficiently, we can use a two-pointer technique. This approach allows us to avoid the need for extra space and directly merge the arrays in place.
Steps:
- Initialise pointers
- Initialize Pointers:
- One pointer (i) for traversing nums1 starting from the end of its valid elements.
- Another pointer (j) for traversing nums2 from the end.
- A third pointer (last) for placing elements in their correct positions starting from the end of nums1.
- Declaration of pointers
- Merge in Reverse Order:
- Compare elements pointed by i and j.
- Place the larger element at the position pointed by last.
- Move the respective pointers (i, j, last) accordingly.
- Continue this until all elements from nums2 are placed in nums1
last=m+n-1i=m-1j=n-1
Python
def merge(self, nums1, m, nums2, n):
last=m+n-1
i=m-1
j=n-1
while j>=0:
if i>=0 and nums1[i]>nums2[j]:
nums1[last]=nums1[i]
i-=1
else:
nums1[last]=nums2[j]
j-=1