Finding duplicates is usually done either by Brute force or collections. So, I came up with a solution without using any of those and which is very efficient for sorted array!

Screen Shot 2016-04-15 at 8.12.04 AM

int[] withoutSet(int []in){

       int []val = new int[in.length];    // to Store the value from the input array

       int []count = new int[in.length]; // to count the occurrences of elements in the input array

       int j=0, k=0, index=0, sum=1;

       Arrays.sort(in);   //Sorting the elements of the input array

       for(int i=0; i< in.length-1;i++){

               //since the array is sorted, till we find a new number if loop will run continously

             //For Example: 1,1,1,1,2,3,3,4. It would be running inside the if loop with val[k] = 1 and sum=4

              if(in[i] == in[i+1]) {  //Checking the first and second element of the array

                                 val[k] = in[i];      // to copy the duplicate element from the input array

                                 sum = sum + 1;      // add the total occurrences

                                count[k] = sum;    //  assign the total occurrences to count

                                index= index + 1;  // Index is to track the total length of output array


           //If it comes to Else condition it means we a new number is found, so we are resetting the value of k and sum



                           sum = 1;


          //subtract output array index by 1 if the same number occurs more than once in input array

          if((val[k] !=0) &&(count[k]>2))

          index= index – 1;


  int []out = new int[index];    //Create output array of size index obtained from above steps

  for(k=0;k<count.length;k++){    //Run through a loop till the size of count/val/in array

           if(count[k] > 0)          //Count[k]=0 for unique elements so make a condition to find duplicates

          out[j++] = val[k];    //store values in output array if the occurrences is > 0


  return  out;


Close Bitnami banner