Remove Duplicates from Sorted Array in O(n) Time Complexity

🚀 Day 23 of My DSA Journey – Clean & Efficient Deduplication Today I solved a classic and very important problem: 👉 Remove Duplicates from Sorted Array 🔍 Problem Understanding Given a sorted array, we need to remove duplicates in-place such that each element appears only once and return the new length. ⚠️ Constraints: No extra space allowed Maintain relative order 🧠 Brute Force Approach Use a Set or ArrayList to store unique elements Copy back to array ❌ Not optimal due to O(n) extra space ⚡ Optimized Approach (Two Pointer Technique) 💡 Key Idea: Since the array is sorted, duplicates are adjacent. We can maintain a pointer j to track the position of unique elements. 🪜 Steps Initialize j = 0 Traverse array using i If nums[j] != nums[i] Increment j Assign nums[j] = nums[i] Return j + 1 🧪 Example Walkthrough Input: [0,0,1,1,1,2,2,3,3,4] Process: Keep only unique elements Final array: [0,1,2,3,4] Output: 5 ⏱️ Complexity Analysis Time Complexity: O(n) Space Complexity: O(1) ✅ 💡 Key Learning Sorted arrays simplify many problems Two-pointer approach is 🔑 for in-place operations Writing clean and minimal code matters in interviews 🙏 Gratitude Consistency is paying off. Small daily wins are building strong fundamentals 💪 📈 Consistency Note Discipline > Motivation. Showing up daily 🚀 #DSA #LeetCode #Java #CodingJourney #100DaysOfCode #ProblemSolving #TechJourney #InterviewPreparation

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories