Missing Number
Problem Statement
Section titled “Problem Statement”Given an array nums containing n distinct numbers in the range [0, n], return the only number in that range that is missing from the array.
Examples
Section titled “Examples”| Input | Output | Explanation |
|---|---|---|
[3, 0, 1] | 2 | Range 0–3, 2 is missing |
[0, 1] | 2 | Range 0–2, 2 is missing |
[9,6,4,2,3,5,7,0,1] | 8 | Range 0–9, 8 is missing |
Constraints
Section titled “Constraints”n == nums.length1 <= n <= 10^40 <= nums[i] <= n- All numbers in
numsare unique.
Real-World Applications
Section titled “Real-World Applications”Complexity Comparison
Section titled “Complexity Comparison”| Approach | Time | Space | Best When |
|---|---|---|---|
| Hash Set | O(n) | O(n) | Quick to write and easy to understand |
| Gauss Sum | O(n) | O(1) | Memory is constrained; elegant one-liner |
Which approach should you learn first?
Section titled “Which approach should you learn first?”- Learn Gauss Sum first — it demonstrates a beautiful mathematical insight and is O(1) space.
- Use Hash Set as a fallback if you forget the formula; it is correct and the same time complexity.
Approach 1: Gauss Sum (Math)
Section titled “Approach 1: Gauss Sum (Math)”The sum of all integers from 0 to n is given by the Gauss formula: n * (n + 1) / 2. Subtract the actual sum of nums from this expected total. The difference is precisely the missing number.
Step-by-step Example
Section titled “Step-by-step Example”Input: [3, 0, 1], n = 3
| Step | Calculation | Value |
|---|---|---|
| Expected sum (0+1+2+3) | 3 × 4 / 2 | 6 |
| Actual sum (3+0+1) | 3 + 0 + 1 | 4 |
| Missing | 6 − 4 | 2 |
Animated walkthrough
Use Next or Autoplay to see the expected total computed, the actual sum accumulated, and the difference revealed.
Pseudocode
Section titled “Pseudocode”function missingNumber(nums): n = len(nums) expected = n * (n + 1) / 2 return expected - sum(nums)Solution Code
Section titled “Solution Code”from typing import List
def missing_number(nums: List[int]) -> int: n = len(nums) expected = n * (n + 1) // 2 return expected - sum(nums)
print(missing_number([3, 0, 1])) # 2print(missing_number([0, 1])) # 2print(missing_number([9, 6, 4, 2, 3, 5, 7, 0, 1])) # 8#include <numeric>#include <vector>using namespace std;
class Solution {public: int missingNumber(vector<int>& nums) { int n = nums.size(); int expected = n * (n + 1) / 2; return expected - accumulate(nums.begin(), nums.end(), 0); }};class Solution { public int missingNumber(int[] nums) { int n = nums.length; int expected = n * (n + 1) / 2; int actual = 0; for (int num : nums) actual += num; return expected - actual; }}function missingNumber(nums) { const n = nums.length; const expected = n * (n + 1) / 2; const actual = nums.reduce((sum, n) => sum + n, 0); return expected - actual;}impl Solution { pub fn missing_number(nums: Vec<i32>) -> i32 { let n = nums.len() as i32; let expected = n * (n + 1) / 2; let actual: i32 = nums.iter().sum(); expected - actual }}package golangfunc missingNumber(nums []int) int { n := len(nums) expected := n * (n + 1) / 2 actual := 0 for _, num := range nums {
} return expected - actual } actual += numApproach 2: Hash Set
Section titled “Approach 2: Hash Set”Build a set from nums, then iterate 0 through n and return the first value that is not in the set.
Step-by-step Example
Section titled “Step-by-step Example”Input: [3, 0, 1]
| Check | In set? |
|---|---|
| 0 | Yes |
| 1 | Yes |
| 2 | No → return 2 |
Pseudocode
Section titled “Pseudocode”function missingNumber(nums): seen = set(nums) for value in range(len(nums) + 1): if value not in seen: return valueSolution Code
Section titled “Solution Code”from typing import List
def missing_number(nums: List[int]) -> int: seen = set(nums) for value in range(len(nums) + 1): if value not in seen: return value return -1#include <unordered_set>#include <vector>using namespace std;
class Solution {public: int missingNumber(vector<int>& nums) { unordered_set<int> seen(nums.begin(), nums.end()); for (int value = 0; value <= nums.size(); value++) { if (!seen.count(value)) return value; } return -1; }};import java.util.HashSet;import java.util.Set;
class Solution { public int missingNumber(int[] nums) { Set<Integer> seen = new HashSet<>(); for (int num : nums) seen.add(num); for (int value = 0; value <= nums.length; value++) { if (!seen.contains(value)) return value; } return -1; }}function missingNumber(nums) { const seen = new Set(nums); for (let value = 0; value <= nums.length; value++) { if (!seen.has(value)) return value; } return -1;}use std::collections::HashSet;
impl Solution { pub fn missing_number(nums: Vec<i32>) -> i32 { let seen: HashSet<i32> = nums.iter().copied().collect(); for value in 0..=(nums.len() as i32) { if !seen.contains(&value) { return value; } } -1 }}func missingNumber(nums []int) int { seen := map[int]bool{} for _, num := range nums { seen[num] = true } for value := 0; value <= len(nums); value++ { if !seen[value] { return value } } return -1}Approach 3: Space-Optimized Variant
Section titled “Approach 3: Space-Optimized Variant”A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.
Pseudocode
Section titled “Pseudocode”function approach3(): // Implementation approach goes hereSolution Code
Section titled “Solution Code”"""Solution for Missing Number"""
def solve(): """Implementation for approach 3 of Missing Number""" pass
if __name__ == "__main__": print("Solution ready")#include <bits/stdc++.h>using namespace std;
// Solution for Missing Number// Approach 3: Implementation
int main() {{ // Main implementation goes here return 0;}}/** * Solution for Missing Number * Approach 3 */public class MissingNumberSpaceOptimized {{
public static void main(String[] args) {{ // Implementation goes here }}}}/** * Solution for Missing Number * Approach 3 */
function solve() {{ // Implementation goes here}}
module.exports = solve;/// Solution for Missing Number/// Approach 3
fn main() {{ println!("Solution implementation");}}package main
import "fmt"
// Solution for Missing Number// Approach 3
func main() {{ fmt.Println("Solution implementation")}}