Merging sorted arrays in-place with two pointers

🚀 Day 35 of #100DaysOfCode — LeetCode + HackerRank Edition! Today’s challenge was all about merging two sorted arrays in-place — no extra space allowed, just clean pointer logic. 📌 Challenge: Merge nums2 into nums1, assuming nums1 has enough trailing space. The final array must be sorted — and the merge must happen in-place. 🔍 Approach: → Used a two-pointer strategy from the back to avoid overwriting values in nums1 → Compared the largest elements from both arrays and placed them at the end → Moved pointers backward (p1, p2, p) until all elements were merged → Handled edge cases like empty nums2 or all elements being smaller than nums1 → Avoided sorting after merge — the logic itself ensures order 💡 What made it click: → Realized that merging from the front causes overwrites — merging from the back preserves data → Visualized the pointer movement with a dry run — that helped me catch off-by-one bugs → Learned that in-place algorithms often rely on reverse traversal and smart indexing 📚 What I learned: ✅ Two-pointer techniques are powerful for in-place operations ✅ Always think about overwrite risks when merging arrays ✅ Dry runs and visual walkthroughs are key to debugging pointer logic Have you tried merging sorted arrays in-place before? Did you use reverse traversal or a different trick? Let’s swap strategies 💬 #Day35 #LeetCode #ArrayProblems #TwoPointerTechnique #ProblemSolving #Python #DebuggingJourney #CleanCode #LearnToCode #CodeNewbie #SoftwareEngineering #TechJourney #100DaysOfCode

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories