Python 0268.py
class Solution:
def missingNumber(self, nums: List[int]) -> int:
# the old XOR trick ...
xor = 0
for i in nums:
xor = xor ^ i
for i in range(1, len(nums)+1):
xor = xor ^ i
return xor
Difficulty
and has an acceptance rate of about 72% (5+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Bit Manipulation
- Hash Table
- Math
- Sorting
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 provided implementation solves the classic “missing number” problem using the XOR (exclusive-or) property. Given an array nums that contains all integers from 0 to n except one, the method computes the absent value in linear time while using only a single integer variable for storage. The algorithm relies on the fact that a number XOR-ed with itself yields zero and that XOR is both associative and commutative. By XOR-ing all elements of the input and then XOR-ing the complete range of expected values, the duplicate cancellations leave only the missing integer.
Key Steps
Accumulating XOR of the input array
The first loop iterates over each element in nums and folds it into the variable xor using the XOR operator. This step builds the cumulative XOR of all present numbers.
xor = 0
for i in nums:
xor = xor ^ i
Folding in the full range of expected numbers
The second loop generates the sequence 1 through len(nums) (which equals n because the array length is one less than the full range) and XOR-s each value into the same accumulator. The inclusion of the full range ensures that every number that should appear in the complete set participates exactly once.
for i in range(1, len(nums) + 1):
xor = xor ^ i
Returning the result
After both passes, the accumulator holds the XOR of the missing number with zero (since all other numbers have cancelled out). The method returns this final value.
return xor
Edge Cases Handled
The algorithm gracefully handles the situation where the input list is empty. In that case len(nums) is 0, the second loop does not execute, and the accumulator remains 0. Returning 0 correctly identifies the missing number when the only expected element is 0.
Another implicit edge case is when the missing number is 0. Because the second loop starts at 1, the value 0 is never XOR-ed into the accumulator from the range side. Consequently, the XOR of all present numbers (which excludes 0) remains unchanged, and the final result is 0, correctly indicating the missing element.
The code also works when the missing number is the maximum value n. The range loop includes n, while the input array lacks it, so the final XOR yields n.
Performance Optimizations
The implementation achieves optimal performance for this problem class by:
- Using a single integer variable (
xor) to store intermediate results, thereby keeping auxiliary memory usage constant regardless of input size. - Performing exactly two linear passes over the data: one over the input list and one over a generated range. Both passes are simple arithmetic operations without any branching, which benefits from CPU pipeline efficiency.
- Avoiding the creation of auxiliary data structures such as hash sets or additional arrays, eliminating overhead associated with dynamic memory allocation and garbage collection.
- Leveraging the bitwise XOR operation, which is a single-cycle instruction on most modern processors, to perform cancellation of matching values efficiently.
These choices ensure that the method runs in linear time with minimal overhead, making it well-suited for large input sizes.
ELI5 - Simplified Explanation
Imagine a group of friends standing in a line. Each friend is wearing a shirt with a number on it. Some numbers are there, but one number is hiding and missing from the group.
To find the missing number, start by holding a magic box that begins empty, which is like the number zero. First, look at every friend in the line and combine their numbers one by one into the magic box using a special secret rule. This rule is like a dance where numbers swap places and cancel each other out if they appear twice.
Next, think about all the numbers that should have been there, starting from one all the way up to the total count of friends. Take these full numbers and put them into the same magic box using the same secret dance. Because the numbers that were already present will cancel out their partners, the only thing left inside the magic box at the end will be the one secret number that was missing all along.
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++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Rust | JS | Go | PHP | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| 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++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| muhammadfarhankt | Go | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 41: First Missing Positive
- problem 136: Single Number
- problem 287: Find the Duplicate Number
- problem 765: Couples Holding Hands
- problem 1980: Find Unique Binary String
Solved On The Same Day
- problem 231: Power of Two
- problem 232: Implement Queue using Stacks
- problem 258: Add Digits
- problem 326: Power of Three
- problem 338: Counting Bits
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