The best answer has already been given (XOR-ing), this will be an alternative, more general way.
If the input array is sorted (we can sort it), we could just iterate over the elements in pairs (step by step 2), and if the elements of the โpairโ are different, we do the following:
public static int findSingle(int[] arr) { Arrays.sort(arr); for (int i = 0, max = arr.length - 1; i < max; i += 2) if (arr[i] != arr[i + 1]) return arr[i]; return arr[arr.length - 1];
Note. . This solution sorts the input array; if this is undesirable or not permitted, it may be cloned first:
arr = arr.clone();
If the input array is sorted, a call to Arrays.sort(arr) can be left, of course.
Generalization
The advantage of this solution is that it can be applied to all types that are comparable and therefore can be sorted (types that implement Comparable ), such as String or Date . The XOR solution XOR limited only by numbers.
Here is a slightly modified version that takes an input array of any type of element that is comparable:
public static <E extends Comparable<E>> E findSingle(E[] arr) { Arrays.sort(arr); for (int i = 0, max = arr.length - 1; i < max; i += 2) if (arr[i].compareTo(arr[i + 1]) != 0) return arr[i]; return arr[arr.length - 1];
Note. In most cases, you can also use arr[i].equals(arr[i + 1]) to compare items instead of Comparable.compareTo() . Read the related javadoc for details. Quoting the relevant part:
It is highly recommended, but not necessary, that (x.compareTo(y)==0) == (x.equals(y)) . Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. Recommended language: "Note: this class has a natural order that is incompatible with peers."
Now you can call this with String[] , for example:
System.out.println(findSingle(new String[] { "1", "2", "3", "1", "3" }));
Output:
2
Concluding remarks:
Starting with the problem statement, it does not check if there are more than two occurrences of elements, and if the length of the array is odd. In addition, the second example does not check for null values; they should be added if necessary.