Moh Ramjan’s Post

🚀 Day 25 of My DSA Journey – Mastering In-Place Array Manipulation Today I solved an interesting problem on LeetCode: 👉 Remove Duplicates from Sorted Array II 🔍 Problem Understanding Given a sorted array, the goal is to remove duplicates in-place such that each element appears at most twice, and return the new length. ⚠️ Constraint: No extra space allowed Modify array in-place 🧠 Brute Force Approach Use extra space (like ArrayList) Track frequency and rebuild array ❌ Not optimal due to O(n) space complexity ⚡ Optimized Approach (Two Pointer Technique) 💡 Key Idea: Since array is sorted, duplicates are adjacent. We can compare current element with the element 2 steps back. 🪜 Steps Start pointer i = 2 (since first 2 elements are always valid) Traverse from j = 2 → n-1 Check: If nums[j] != nums[i-2] → valid element Place it at index i and increment i 🧾 Code Snippet (Java) class Solution { public int removeDuplicates(int[] nums) { int i = 2; for(int j = 2; j < nums.length; j++) { if(nums[j] != nums[i-2]) { nums[i] = nums[j]; i++; } } return i; } } 🧪 Example Walkthrough Input: [1,1,1,2,2,3] Process: Allow only 2 occurrences Final array becomes: [1,1,2,2,3] Output: 5 ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) ✅ (In-place) 💡 Key Learning Sorted array → powerful advantage Two-pointer technique = must-know for interviews Comparing with i-2 is the trick 🔥 🙏 Gratitude Grateful for the consistency and learning curve. Every problem sharpens my logic a bit more! 📈 Consistency Note Showing up daily > being perfect occasionally 💯 #DSA #LeetCode #Java #CodingJourney #100DaysOfCode #SoftwareEngineering #ProblemSolving #InterviewPrep #TechLearning

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories