Python 0260.py
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
all = 0
for n in nums:
all ^= n
# x^x = 0
# "all" is result1 ^ result2
# the lowest set bit in "all" is the first difference between result1 and result2
# partition all numbers based on that bit
# there will be two groups with one unique number each
# repeat the XOR trick to get that number
mask = 1
while (all & mask) == 0:
mask <<= 1
a = b = 0
for n in nums:
if n & mask:
a ^= n
else:
b ^= n
return a, b
Difficulty
and has an acceptance rate of about 70% (800k+ submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation solves the classic “single number III” problem: given an integer array where every element appears exactly twice except for two distinct numbers, it returns those two unique values. The algorithm relies on the properties of the XOR operation to isolate the two outliers without auxiliary data structures.
Step 1 - Compute the XOR of the entire collection
The first loop iterates through the input list and accumulates the XOR of every element into a variable named all. Because XOR cancels identical values (x ^ x = 0), the resulting value is the XOR of the two unique numbers only.
all = 0
for n in nums:
all ^= n
At this point all equals result1 ^ result2. The bits that are set in all indicate positions where the two unique numbers differ.
Step 2 - Identify a distinguishing bit mask
To separate the two unique numbers, the algorithm needs a bit that is set in exactly one of them. It finds the least-significant set bit of all by left-shifting a mask until the bitwise AND with all becomes non-zero.
mask = 1
while (all & mask) == 0:
mask <<= 1
The chosen mask isolates the first position where the two unique numbers diverge, guaranteeing that one of the numbers will have this bit set while the other will not.
Step 3 - Partition the array and recover each unique value
With the distinguishing mask, the algorithm performs a second pass over the array. It groups numbers based on whether the mask bit is set, applying XOR within each group. Because duplicate numbers fall into the same group, they cancel out, leaving only the unique member of that group.
a = b = 0
for n in nums:
if n & mask:
a ^= n
else:
b ^= n
After the loop, a and b hold the two numbers that appear only once. The function returns them as a tuple.
Edge Cases Handled
The code naturally accommodates negative integers because the XOR operation works uniformly on two’s-complement representations. When the input contains the minimum or maximum 32-bit values, the bitwise logic still functions correctly, as the mask search examines each bit position independently of the numeric magnitude.
If the two unique numbers differ only in higher-order bits, the while-loop will shift the mask until it reaches the appropriate position, ensuring that the partitioning step still separates them correctly. The algorithm also tolerates arrays where the duplicate elements are interleaved with the unique ones; the grouping relies solely on the mask bit, not on element order.
Performance Optimizations
The solution processes the input list twice, each pass performing only simple arithmetic and bitwise operations. This minimal traversal reduces cache pressure and keeps the runtime low even for large inputs. All auxiliary variables (all, mask, a, b) are scalar integers, so the memory footprint stays constant regardless of input size. The mask discovery loop stops as soon as the first differing bit is found, avoiding unnecessary work. By leveraging XOR’s cancellation property, the algorithm eliminates the need for hash tables or sorting, which would introduce additional overhead.
ELI5 - Simplified Explanation
Imagine holding a big pile of toys where almost every toy has an exact twin, but there are two special toys hiding in the pile that do not have any friends. The goal is to find those two special lonely toys.
First, the code uses a neat math trick by mixing all the toy numbers together. When two identical toys meet, the math makes them vanish. After mixing everyone, only the two lonely toys are left blended together.
Next, the code looks for a tiny clue to tell the two lonely toys apart. It zooms in on a specific spot in their numbers where they are different. It uses a mask, which is like a tiny flashlight, to peek at that specific spot for every single toy in the pile.
Finally, the code splits all the toys into two crates. One crate gets all the toys that have a light on in that spot, and the other crate gets the toys that have the light off. By mixing the toys in each crate separately using the same trick as before, the friends disappear and only the two lonely toys remain, one standing proud in each crate.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Rust | Python | JS | C# | Go | TS | ||
| LeetcodeHelp | C++ | Java | Python | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Java | Python | |||||||
| github | aylei | Rust | ||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | C++ | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| luangong | C++ | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 136: Single Number
- problem 137: Single Number II
- problem 2433: Find The Original Array of Prefix Xor
- problem 3158: Find the XOR of Numbers Which Appear Twice
Solved On The Same Day
- problem 292: Nim Game
- problem 572: Subtree of Another Tree
- problem 617: Merge Two Binary Trees
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 213: House Robber II
- problem 237: Delete Node in a Linked List
- problem 416: Partition Equal Subset Sum
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 560: Subarray Sum Equals K
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 655: Print Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 669: Trim a Binary Search Tree
- problem 687: Longest Univalue Path
- problem 1115: Print FooBar Alternately
- problem 1116: Print Zero Even Odd
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality