Problem 268

Abstract / Summary

Find the number missing from an array of consecutive integers starting from zero.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
11 lines | 264 bytes | submitted August 12, 2023 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.59 | σ = 1.25

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
60 links | 43 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Missing Number | Multiple Approaches | Leetcode 268'
codestorywithMIK 25 mins
Missing Number | Multiple Approaches | Leetcode 268
YouTube video 'Missing Number (#Leetcode 268) - Easy (Hindi)'
Engineering Digest 8 mins
Missing Number (#Leetcode 268) - Easy (Hindi)
YouTube video 'Missing Number - LeetCode 268 - Python [O(n) time and O(1) space]'
Deepti Talesra 7 mins
Missing Number - LeetCode 268 - Python [O(n) time and O(1) space]
YouTube video '7. Missing Number | Arrays - Easy | Learn DSA | Leetcode 268'
Ayushi Sharma 10 mins
7. Missing Number | Arrays - Easy | Learn DSA | Leetcode 268
YouTube video 'Can You Detect the Missing Number? (LeetCode 268: Missing Number)'
Code With Zi 4 mins
Can You Detect the Missing Number? (LeetCode 268: Missing Number)
YouTube video 'Google Interview Question - Missing Number - LeetCode 268'
AlgoJS 5 mins
Google Interview Question - Missing Number - LeetCode 268
YouTube video 'Missing Number - LeetCode 268 - Blind 75 - Coding Interview'
One Code Man 6 mins
Missing Number - LeetCode 268 - Blind 75 - Coding Interview
YouTube video '268. Missing Number | Leetcode | Math based | Fundamentals'
Coding with Tamilarasan 4 mins
268. Missing Number | Leetcode | Math based | Fundamentals
YouTube video 'Missing Number - LeetCode 268 - Java'
LeetCode University 9 mins
Missing Number - LeetCode 268 - Java
YouTube video 'Leetcode | 268. Missing Number | Easy | Java Solution'
Developer Docs 4 mins
Leetcode | 268. Missing Number | Easy | Java Solution
YouTube video 'Missing Number | LeetCode 268 | Xor | Sum | Amazon Facebook Apple'
Naresh Gupta 8 mins
Missing Number | LeetCode 268 | Xor | Sum | Amazon Facebook Apple
YouTube video 'How to Solve "268 Missing Number" on LeetCode? - Javascript'
Becoming A Better Dev (with David) 5 mins
How to Solve "268 Missing Number" on LeetCode? - Javascript
YouTube video 'Missing Number - Leetcode 268 | Intuitive 7 Methods'
Code With K5KC 15 mins
Missing Number - Leetcode 268 | Intuitive 7 Methods
YouTube video '268. Missing Number | February | Java | C++'
Mayur Programming Club 8 mins
268. Missing Number | February | Java | C++
YouTube video 'Missing Number - LeetCode #268 - C++'
Sean Chuah 6 mins
Missing Number - LeetCode #268 - C++
YouTube video 'FIND Missing Number - Leetcode 268'
Lit Code 6 mins
FIND Missing Number - Leetcode 268
YouTube video 'Missing Number - Leetcode 268 | JavaScript Solution Explained'
Web Coder Abhishek 4 mins
Missing Number - Leetcode 268 | JavaScript Solution Explained
YouTube video 'Leetcode 268: Missing Number | XOR | Python DSA | srkcodes'
Srk Codes 10 mins
Leetcode 268: Missing Number | XOR | Python DSA | srkcodes
YouTube video '268. Missing Number || Easy || Bit Manipulation || Hashing || Sorting  || Math || Cpp'
Komal Pal 19 mins
268. Missing Number || Easy || Bit Manipulation || Hashing || Sorting || Math || Cpp
YouTube video 'Daily Leetcode #788: May 28, 2022 - 268. Missing Number'
Programming Live with Larry 6 mins
Daily Leetcode #788: May 28, 2022 - 268. Missing Number
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

5 easy
6 solutions   August 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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