Simple Java program for Removing duplicates from sorted array


Definition

A data structure consisting of a collection of elements (values or variables), each identified by an index or key is called an Array. The position of each element in an array can be computed from its index.

Syntax

Data_type[] Variable_name = new Data_type[Length];

Removing duplicates from sorted array Program

public class RemoveDuplicatesFromSortedArray {
    public static int[] removeDuplicates(int[] input){
        int j = 0;
        int i = 1;
        
        if(input.length<2){
            return input;
        }
        while (i<input.length) {            
            if(input[i] == input[j]){
                i++;
            }else{
                input[++j] = input[i++];
            }
        }
        int[] output = new int[j+1];
        for( int k = 0 ; k < output.length; k++){
            output[k] = input[k];
        }
        return output;
    }
    
    public static void main(String[] args) {
        int[] input = {2,3,66,6,8,9,10,10};
        int[] output = removeDuplicates(input);
        for(int i : output){
            System.out.println(i+" ");
        }
    }
}

Sample Output

2 
3 
66 
6 
8 
9 
10