Missing Number
LeetCode 268 · Easy · solution, intuition & step-by-step walkthrough
missing = n(n+1)/2 − sum(nums).
This is how I solved Missing Number (LeetCode 268), an easy problem from the Hashing / Anagram pattern. Below: the intuition, the approach step by step, my accepted Python code and the 2 versions I wrote on the way, animated test cases and a line-by-line debugger.
Intuition
The numbers 0..n should all be present except one. You can mark which ones you see, or use arithmetic: the sum of 0..n is n(n+1)/2, and subtracting the actual sum leaves exactly the missing number.
Approach
- 1
Frequency version: mark each number, return the first unmarked index.
- 2
Math version: compute the expected total of 0..n.
- 3
Subtract the actual sum — the difference is the missing number.
How I solved it · from first idea to final
Mark what you see.
Expected sum minus actual.
Frequency tablePythonO(n) time · O(n) space
class Solution:
def missingNumber(self, nums: list[int]) -> int:
n = len(nums)
freq_table = [0]*(n+1)
for num in nums:
freq_table[num]+=1
for i in range(n+1):
if freq_table[i]==0:
return i
return -1
"""
[0,1,2,3] - 6
[3,0,1] - 4
"""Gauss sumPythonO(n) time · O(1) space
class Solution:
def missingNumber(self, nums: list[int]) -> int:
n = len(nums)
total_sum = n*(n+1)//2
cur_sum = sum(nums)
return total_sum-cur_sumMissing Number — FAQ
What is the intuition behind Missing Number?
The numbers 0..n should all be present except one. You can mark which ones you see, or use arithmetic: the sum of 0..n is n(n+1)/2, and subtracting the actual sum leaves exactly the missing number.
How do you solve Missing Number (LeetCode 268)?
1. Frequency version: mark each number, return the first unmarked index. 2. Math version: compute the expected total of 0..n. 3. Subtract the actual sum — the difference is the missing number.
What is the time and space complexity of Missing Number?
Time: O(n). Space: O(1). (Accepted approach: Gauss sum.)
What are common mistakes in Missing Number?
The range is 0..n inclusive (n+1 values), not 1..n.
Is there more than one way to solve Missing Number?
Frequency table (O(n) time · O(n) space): Mark what you see. Gauss sum (O(n) time · O(1) space): Expected sum minus actual.