⚡ TL;DR
Solve Missing Number in Python with working code. Sum formula approach with O(n) time, plus complexity analysis and interview tips.
Missing Number (#268 — Easy): Given an array nums containing n distinct numbers taken from the range [0, n], return the only number in that range that is missing from the array.
Problem Statement
Given an array nums containing n distinct numbers taken from the range [0, n], return the only number in that range that is missing from the array.
Example:
Input: nums = [3,0,1]
Output: 2
Explanation: n = 3, the range is [0,3]; 2 is the only value absent.Approach: Sum Formula (Gauss)
Time: O(n) | Space: O(1)
The sum of 0..n is n(n+1)/2. Subtracting the actual sum of the array from that expected sum leaves exactly the missing value — one pass, one integer.
def missing_number(nums):
n = len(nums)
return n * (n + 1) // 2 - sum(nums)
nums = [3, 0, 1]
print("Missing number:", missing_number(nums))Approach: XOR Trick
Time: O(n) | Space: O(1)
XOR every index 0..n with every value in the array. Paired values cancel out (x ^ x = 0), so only the missing number survives — and it never overflows, unlike the sum on huge arrays.
def missing_number_xor(nums):
n = len(nums)
result = n
for i in range(n):
result ^= i ^ nums[i]
return result
nums = [3, 0, 1]
print("Missing number:", missing_number_xor(nums))Key Takeaways
- The sum formula is the fastest to write: expected − actual is the whole algorithm
- The XOR variant avoids overflow on huge arrays because it never adds — only cancels
- Both run in a single O(n) pass with O(1) extra space
FAQ
What is the best approach to solve Missing Number in Python?
The recommended approach is Sum Formula (Gauss), which runs in O(n) time with O(1) space. The full Python implementation is shown above.
What is the time complexity of Missing Number in Python?
Using Sum Formula (Gauss), the time complexity is O(n) and the space complexity is O(1); XOR Trick runs in O(n) time with O(1) space.
Happy coding!

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →