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

TanishiTanishi
2 min read

๐Ÿ—“๏ธ 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 size m + n, where the last n elements are zeros for space.

  • nums2 of size n.

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

0
Subscribe to my newsletter

Read articles from Tanishi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tanishi
Tanishi