Java Program to Remove Duplicates from Array
LinkedHashSet to keep elements unique and preserve order, then convert it back to an array, like this: Set set = new LinkedHashSet<>(Arrays.asList(array)); Integer[] unique = set.toArray(new Integer[0]); .Examples
How to Think About It
Algorithm
Code
import java.util.*; public class RemoveDuplicates { public static void main(String[] args) { Integer[] array = {1, 2, 2, 3, 4, 4, 5}; Set<Integer> set = new LinkedHashSet<>(Arrays.asList(array)); Integer[] unique = set.toArray(new Integer[0]); System.out.println(Arrays.toString(unique)); } }
Dry Run
Let's trace the example array [1, 2, 2, 3, 4, 4, 5] through the code
Input array
[1, 2, 2, 3, 4, 4, 5]
Create LinkedHashSet and add elements
Set after adding elements: [1, 2, 3, 4, 5] (duplicates ignored)
Convert set back to array
Unique array: [1, 2, 3, 4, 5]
Print result
[1, 2, 3, 4, 5]
| Iteration | Element Added | Set Content |
|---|---|---|
| 1 | 1 | [1] |
| 2 | 2 | [1, 2] |
| 3 | 2 | [1, 2] |
| 4 | 3 | [1, 2, 3] |
| 5 | 4 | [1, 2, 3, 4] |
| 6 | 4 | [1, 2, 3, 4] |
| 7 | 5 | [1, 2, 3, 4, 5] |
Why This Works
Step 1: Using LinkedHashSet
A LinkedHashSet stores unique elements and keeps their original order, so duplicates are automatically removed.
Step 2: Converting array to list
We convert the array to a list with Arrays.asList() so we can pass it to the set constructor easily.
Step 3: Converting set back to array
After duplicates are removed, we convert the set back to an array using toArray(new Integer[0]) to get the final result.
Alternative Approaches
import java.util.*; public class RemoveDuplicates { public static void main(String[] args) { int[] array = {1, 2, 2, 3, 4, 4, 5}; boolean[] seen = new boolean[100]; // assuming max value < 100 List<Integer> uniqueList = new ArrayList<>(); for (int num : array) { if (!seen[num]) { uniqueList.add(num); seen[num] = true; } } System.out.println(uniqueList); } }
import java.util.*; public class RemoveDuplicates { public static void main(String[] args) { int[] array = {1, 2, 2, 3, 4, 4, 5}; Arrays.sort(array); int j = 0; for (int i = 1; i < array.length; i++) { if (array[i] != array[j]) { j++; array[j] = array[i]; } } int[] unique = Arrays.copyOf(array, j + 1); System.out.println(Arrays.toString(unique)); } }
Complexity: O(n) time, O(n) space
Time Complexity
Adding elements to a LinkedHashSet takes O(1) on average, so for n elements it is O(n).
Space Complexity
The set stores up to n unique elements, so space is O(n).
Which Approach is Fastest?
Using LinkedHashSet is usually fastest and simplest; sorting is slower due to O(n log n) time but uses less extra space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| LinkedHashSet | O(n) | O(n) | Preserving order, general use |
| Boolean array | O(n) | O(k) | Small integer ranges, fast |
| Sorting + in-place | O(n log n) | O(1) | When order doesn't matter, space efficient |