XOR all
Time O(n) Space O(1)Fold the array with ^.
class Solution {
public int singleNumber(int[] nums) {
int x = 0;
for (int v : nums) x ^= v;
return x;
}
}Verdict: A hash set works but uses O(n) memory.
Search for a command to run...
What it teaches: XOR cancels pairs in O(1) space.
Practise it on judges as “Single Number”.
Every element appears twice except one. Find it in O(n) time and O(1) extra space.
Example 1
Input: nums = [4, 1, 2, 1, 2] Output: 4
Constraints
Pattern clues in the wording
These clues point to Bit Manipulation: Use XOR, AND, OR and shifts to test, set and cancel bits, often in O(1) space.
Stuck? Take one hint at a time
class Solution {
public int singleNumber(int[] nums) {
return 0;
}
}Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Test cases
| # | Input | Expected |
|---|---|---|
| 1 | nums = [2,2,1] | 1 |
| 2 | nums = [4,1,2,1,2] | 4 |
+ 1 hidden test the code runner will check
From slow to fast
Fold the array with ^.
class Solution {
public int singleNumber(int[] nums) {
int x = 0;
for (int v : nums) x ^= v;
return x;
}
}Verdict: A hash set works but uses O(n) memory.
Before you submit
Test these inputs
Mistakes people make
Interview
What if every other element appears three times?