Leo Leo - 6 months ago 24
Java Question

Finding non duplicate element in an array

I am stuck in the following program:

I have an input integer array which has only one non duplicate number, say {1,1,3,2,3}. The output should show the non duplicate element i.e. 2.

So far I did the following:

public class Solution {

public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];

for(int i=0;i<size;i++){
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j)
//System.out.println("Match found for "+temp);
flag = false;
return result;

public static void main(String[] args) {

int[] a = {1,1,3,2,3};
Solution sol = new Solution();

System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));

Restricting the solution in array is preferable. Avoid using collections,maps.


Since this is almost certainly a learning exercise, and because you are very close to completing it right, here are the things that you need to change to make it work:

  • Move the declaration of flag inside the outer loop - the flag needs to be set to true every iteration of the outer loop, and it is not used anywhere outside the outer loop.
  • Check the flag when the inner loop completes - if the flag remains true, you have found a unique number; return it.