Merge Two Sorted Arrays in-place with Two Pointers

🚀 DSA Day — Merge Two Sorted Arrays (LeetCode 88) Today I worked on a classic problem that looks simple but teaches an important optimization technique 👇 🔹 Problem Statement You are given two sorted arrays and need to merge them into one sorted array in-place. Example: nums1 = [1, 7, 8, 0, 0, 0], m = 3 nums2 = [2, 5, 6], n = 3 ✅ Output: [1, 2, 5, 6, 7, 8] 🔸 Approach 1: Brute Force ✔ Copy nums2 into nums1 ✔ Sort the entire array ⏱ Time Complexity: O((m+n) log(m+n)) 👉 Simple but not efficient 🔸 Approach 2: Optimized (Two Pointers) 💡 Key Idea: Start filling from the end ✔ Compare last elements of both arrays ✔ Place the larger one at the end ✔ Move pointers accordingly ⏱ Time Complexity: O(m+n) 📦 Space Complexity: O(1) 🔥 Why this works? Because nums1 already has extra space at the end — we use it smartly without shifting elements. 💻 Code Snippet (Optimized) https://lnkd.in/g9Z7yf3d def merge(nums1, m, nums2, n): i = m - 1 j = n - 1 k = m + n - 1 while i >= 0 and j >= 0: if nums1[i] > nums2[j]: nums1[k] = nums1[i] i -= 1 else: nums1[k] = nums2[j] j -= 1 k -= 1 while j >= 0: nums1[k] = nums2[j] j -= 1 k -= 1 🎯 Key Takeaway 👉 Always think from the end when dealing with in-place array problems. #DSA #Python #CodingInterview #LeetCode #ProblemSolving #SoftwareEngineering #LearnInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories