LeetCode ยท #268

Missing Number Solution

Given array of n distinct numbers in [0, n], find the missing one.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Easy

๐Ÿ”—

LeetCode

Problem #268

๐Ÿ—๏ธ

Pattern

Math / XOR

Example
Input: nums = [3,0,1] Output: 2 // range [0,3], missing 2
02
Section Two ยท Approach 1

Sort โ€” O(n log n)

Sort and find where nums[i] != i.

Better: Gauss sum: expected = n*(n+1)/2, subtract actual sum. Or XOR: XOR [0..n] with all elements โ€” pairs cancel, missing remains.
03
Section Three ยท Approach 2

Sum Formula or XOR โ€” O(n), O(1)

Sum: n*(n+1)/2 - sum(nums). XOR: XOR all indices [0..n] with all elements. Duplicates cancel, missing remains.

๐Ÿ’ก Mental model (sum): You know the sum of a complete set. The actual sum is less โ€” the difference is the missing piece. Like counting money: expected $55, got $53, missing $2.
๐Ÿ’ก XOR variant: XOR index 0 with nums[0], index 1 with nums[1], ..., index n (the extra index) with nothing. All present numbers pair up (index โŠ• value), leaving the missing one.
04
Section Four ยท Trace

Visual Walkthrough

Missing Number โ€” Sum Formula
nums=[3,0,1]. n=3. expected=3*4/2=6. actual=3+0+1=4. missing=6-4=2. return 2 โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” XOR
class Solution { public int missingNumber(int[] nums) { int xor = nums.length; for (int i = 0; i < nums.length; i++) xor ^= i ^ nums[i]; return xor; } }
Python โ€” Sum formula
class Solution: def missingNumber(self, nums: list[int]) -> int: n = len(nums) return n * (n + 1) // 2 - sum(nums)
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpace
SortO(n log n)O(1)
HashSetO(n)O(n)
Sum / XOR โ† optimalO(n)O(1)
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
Missing 0[1]expected=1, actual=1โ€ฆ wait, n=1, expected=1 โ†’ 1-1=0. Missing 0.
Missing n[0,1,2]n=3, expected=6, actual=3, missing=3.
Single element[0]Missing 1. n=1, 1-0=1.
โš  Common Mistake: Sum formula can overflow for very large n with 32-bit ints. Use long or XOR (no overflow risk). Python has arbitrary precision so no issue there.

โ† Back to Math & Bit problems