Missing Number

Solve this Problem
Easy15–20 min
Topics
Companies
Practice:LeetCode ↗GFG ↗
An array nums contains n distinct numbers, each drawn from the range [0, n] — so exactly one value in that range is missing from the array. Find it. Summing 0 through n and subtracting the array's actual sum gets there directly, though the expected-sum formula can overflow for large n before it's ever halved. XOR sidesteps that entirely: XOR together every number from 0 to n with every value actually in the array, and every number that appears in both cancels itself out — the only one left standing is the missing value.

Test Case 1:

Input:nums = [3, 0, 1]
Output:2
Explanation:n=3, so the full range is [0,3]. 2 is the only value missing from the array.

Test Case 2:

Input:nums = [0, 1]
Output:2
Explanation:n=2, range [0,2] — the array only has 0 and 1, so 2 is missing.

Test Case 3:

Input:nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
Output:8
Explanation:n=9, range [0,9] — every value except 8 is present.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 10⁵
  • 0 ≤ nums[i] ≤ n
  • All the numbers in nums are unique
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

Approach & Solutions

Sum Formula

Good

The numbers 0 through n sum to a fixed total, n(n + 1) / 2. Subtract the array's actual sum from that expected total, and whatever's left over is the missing value. This works, though the expected-sum formula computes n(n + 1) before halving it, which can overflow a 32-bit integer for large enough n.

TimeO(n)
SpaceO(1)
1class Solution { 2 public int missingNumber(int[] nums) { 3 int n = nums.length; 4 int expectedSum = n * (n + 1) / 2; 5 int actualSum = 0; 6 for (int num : nums) { 7 actualSum += num; 8 } 9 return expectedSum - actualSum; 10 } 11}

Optimal — XOR Everything

Optimal

XOR together every number from 0 to n with every value actually in the array. Every number that appears in both the full range and the array cancels itself out, since XOR-ing a value with itself gives 0 — the only number left standing is the one that's in the full range but missing from the array. Unlike the sum formula, XOR-ing integers can never overflow.

TimeO(n)
SpaceO(1)
1class Solution { 2 public int missingNumber(int[] nums) { 3 int n = nums.length; 4 int result = n; 5 for (int i = 0; i < n; i++) { 6 result ^= i ^ nums[i]; 7 } 8 return result; 9 } 10}

Related Problems