Day 6 โ Merge Sorted Array | Two Pointer Approach | LeetCode Challenge


๐๏ธ Date: July 30, 2025
๐ Challenge:
๐งฉ Problem: Merge Sorted Array โ LeetCode #88 (Easy)
๐ป Topic: Arrays, Two Pointers, In-place Merge
โ Problem Statement (Summary):
You are given two sorted arrays:
nums1
of sizem + n
, where the lastn
elements are zeros for space.nums2
of sizen
.
Merge both arrays in-place into nums1
, sorted in non-decreasing order.
Do not return a new array.
Example:
Input:nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output:[1,2,2,3,5,6]
Constraints:
Do it in-place using O(1) space
Can you do it in O(m + n) time?
๐ง What I Learned Today:
Learned how to merge from the end of the arrays to avoid overwriting values in
nums1
.This is a good example of reverse two-pointer approach.
Reduced the need for shifting elements by working backward.
๐งช Code (C++):
class Solution {
public:
void merge(vector<int>& a, int m, vector<int>& b, int n) {
int l = m - 1, r = n - 1, c = m + n - 1;
while (r >= 0 && l >= 0) {
if (a[l] > b[r])
a[c--] = a[l--];
else
a[c--] = b[r--];
}
while (r >= 0)
a[c--] = b[r--];
}
};
๐ Time Complexity: O(m + n)
๐ฆ Space Complexity: O(1)
๐ธ LeetCode Submission Screenshot:
๐ Progress Tracker:
โ Day: 6 / 30
๐งฉ Total Problems Solved: 1
๐งญ Focus Today: Two Pointers (Reverse Merge Strategy)
๐๏ธ Tags:
#leetcode #30DaysChallenge #twopointers #inplace #dsa #c++ #arrays #merge
Subscribe to my newsletter
Read articles from Tanishi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
