Remove Duplicates from Sorted Array in Java

#Coding6 Q: Remove Duplicates from Sorted Array (Java) Example: int[] arr = {1, 1, 2, 2, 3, 4, 4}; Output → {1, 2, 3, 4} Count → 4 I explored 2 different approaches: ✅ 1. Two Pointer Technique (Optimal – O(n), O(1)) static int removeDuplicates(int[] arr) { if(arr.length == 0) return 0; int j = 1; for(int i = 1; i < arr.length; i++) { if(arr[i] != arr[i - 1]) { arr[j++] = arr[i]; } } return j; // number of unique elements } ✅ 2. Using HashSet (Extra Space) Set<Integer> set = new LinkedHashSet<>(); for(int num : arr) set.add(num); int k = 0; for(int num : set) { arr[k++] = num; } Key Learnings: Two-pointer approach is interview preferred (in-place, no extra memory) HashSet approach is simpler but uses extra space Sorted property makes duplicate removal efficient Practicing DSA daily to strengthen problem-solving skills #DSA #Java #Arrays #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic #LinkedInDSA

To view or add a comment, sign in

Explore content categories