Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1
Input: [2,2,1]
Output: 1
Example 2
Input: [4,1,2,1,2]
Output: 4
Solution
A simple approach using extra space is to use a HashMap of the integers as keys and counts as value. Then iterate over the HashMap to find the key with value 1. That will give us a time complexity of O(n) and space complexity of O(n), n being the size of the array.
Another more simple approach is to use XOR (bit manipulation). Given two numbers, a and b, as we know an XOR a is 0 and 0 ^ b is b. So we can iterate over the array and keep XORing the elements with one another, similar ones will cancel out and we will get the unique one.
/**
* SingleNumber.java
* Purpose: Find maximum sum contiguous subarray
*
* @author Megha Rastogi
* @version 1.0 07/13/2020
*/
class SingleNumber {
/**
* Find unique number in an array of duplicates
*
* @param Array, nums
* @return integer, ans
*/
public int singleNumber(int[] nums) {
int ans = 0;
// looping through the array and using XOR
// as a ^ a is 0 and 0 ^ b is b
for(int i = 0; i < nums.length; i++){
ans ^= nums[i];
}
return ans;
}
}
Source – leetcode
Code – SingleNumber.java