Remove Duplicates in Java: Solution, Explanation & Practice
Remove duplicate elements from array
Problem summary
Write a program that removes duplicates from a sorted array and prints unique elements.
Starter code
public class Main {
public static void main(String[] args) {
int[] arr = {1, 1, 2, 2, 3, 4, 4, 5}; // Test case 1
// Remove duplicates and print unique elements
// Print space-separated
}
}Expected output and test cases
- Unique from sorted array
1 2 3 4 5
- From [1,1,1,2,2,3]
1 2 3
- From [5,5,5,5]
5
Hints
- Since sorted, duplicates are adjacent
- Compare current with previous
- Only print if different from last printed
Validated solution
Reveal Java solution
public class Main {
static int uniqueLength(int[] sorted) {
if (sorted.length == 0) return 0;
int write = 1;
for (int read = 1; read < sorted.length; read++) {
if (sorted[read] != sorted[write - 1]) sorted[write++] = sorted[read];
}
return write;
}
public static void main(String[] args) {
int[] values = {1, 1, 2, 2, 3, 4, 4, 5};
int length = uniqueLength(values);
for (int i = 0; i < length; i++) System.out.print(values[i] + (i + 1 == length ? "" : " "));
}
}How to approach the problem
Because the array is sorted, equal values are adjacent. Keep a write position for the compacted prefix and copy a value only when it differs from the last unique value written.
Approach
- Return zero for an empty array.
- Keep index zero as the first unique value.
- Advance write only after copying a new value.
Time and space complexity
Time: O(n). Space: O(1).
Edge cases to test
- All duplicates compact to one value.
- This contract requires sorted input; unsorted input needs a Set or sorting.
Common mistakes
- Comparing to sorted[read - 1] after the array has been overwritten.
- Printing the whole backing array instead of only the returned prefix.
Follow-up challenge
Preserve order while removing duplicates from an unsorted array with LinkedHashSet.
Related Arrays exercises
Practice all Arrays exercises · Run this idea in the Java compiler