Remove Duplicates from Array in Java

In this tutorial, we’ll see how to remove duplicate elements from an array in Java. This is a common interview question and helps in building problem-solving skills.

🧠 Approach

We'll use a simple loop and create a new array to store only unique elements:

  • Iterate through the array
  • Check if the element already exists in the new array
  • If not, add it to the new array

✅ Java Program


public class RemoveDuplicates {
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 3, 7, 1, 9};
        int n = arr.length;
        int[] unique = new int[n];
        int index = 0;

        for (int i = 0; i < n; i++) {
            boolean isDuplicate = false;
            for (int j = 0; j < index; j++) {
                if (arr[i] == unique[j]) {
                    isDuplicate = true;
                    break;
                }
            }
            if (!isDuplicate) {
                unique[index++] = arr[i];
            }
        }

        System.out.print("Array after removing duplicates: ");
        for (int i = 0; i < index; i++) {
            System.out.print(unique[i] + " ");
        }
    }
}

✅ Output

Array after removing duplicates: 1 3 5 7 9

💡 Tip

This approach can be optimized using Set in Java, but for interview practice, understanding this logic without using built-ins is more valuable.

📌 Conclusion

We learned how to remove duplicates from an array using a simple loop and no built-in collections. Practice this kind of logic to boost your problem-solving confidence.

Another common array operation is to find duplicates and handle them efficiently.