Single Number (easy)
We'll cover the following
Solution #
One straight forward solution can be to use a HashMap kind of data structure and iterate through the input:
- If number is already present in HashMap, remove it.
- If number is not present in HashMap, add it.
- In the end, only number left in the HashMap is our required single number.
Time and space complexity Time Complexity of the above solution will be and space complexity will also be .
Can we do better than this using the XOR Pattern?
Solution with XOR #
Recall the following two properties of XOR:
- It returns zero if we take XOR of two same numbers.
- It returns the same number if we XOR with zero.
So we can XOR all the numbers in the input; duplicate numbers will zero out each other and we will be left with the single number.
Code #
Here is what our algorithm will look like:
Time Complexity: Time complexity of this solution is as we iterate through all numbers of the input once.
Space Complexity: The algorithm runs in constant space O(1).