First solution:
Use Hashmap like data structure Map
performance : O(n) + O(n) = O(n)
Problem : extra space & data structure
Second solution:
Sort the array & start skipping the pair e.g. [2,2,3,3,9,9,11,11,11,12,12,34,34] : 11 cannot be skipped as it’s not a pair.
performance: O (nlog(n)) + O(n)
problem: bad performance
Trick solution:
We know X XOR X = 0, therefore start with 0 as result and XOR all the elements with result.
performace : O(n)
problem: none, let me know if you see any
public static void main(String[] args){
int[] arr = {2,3,6,9,20,2,4,6,9,20,3};
int result = 0;
for(int i: arr){
result ^= i;
}
System.out.println(result); //prints 4
}
No comments:
Post a Comment