Skip to content

Instantly share code, notes, and snippets.

@ankit167
Created May 9, 2021 09:56
Show Gist options
  • Save ankit167/089e6907e2ad6aab5151832483e2e53e to your computer and use it in GitHub Desktop.
Save ankit167/089e6907e2ad6aab5151832483e2e53e to your computer and use it in GitHub Desktop.
Find two elements in the array that are not repeated
// Input: 2 1 7 4 5 4 7 1
// Output: 2 5
public void findTwoElements(int[] a) {
int xor = 0, x = 0, y = 0, rsb;
for (int i = 0; i < a.length; i++) {
xor = xor ^ a[i]
}
rsb = xor & ~(xor-1);
for (int i = 0; i < a.length; i++) {
if (a[i] & rsb == 0) {
x = x ^ a[i];
} else {
y = y ^ a[i];
}
}
System.out.println(x);
System.out.println(y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment