Remove Duplicates in Java: 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

  1. Since sorted, duplicates are adjacent
  2. Compare current with previous
  3. Only print if different from last printed

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler