LC 268 — Problem

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Input: nums = 301
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range 03. 2 is the missing number.
Input: nums = 0123
Output: 4

Constraints: n = nums.length · 0 ≤ nums[i] ≤ n · All values are unique.

You are given an array of n distinct numbers drawn from the range [0, n]. One number is missing — your job is to find it. The constraint is tight: n numbers occupy n + 1 possible slots, so exactly one slot is empty.

Take 301. The range is 0123, but one number is absent. Before we reveal which one, consider: how would you find a missing number efficiently? Three classical approaches exist, each with a different tradeoff.

Three approaches

Tap each card to see how it works. Every approach finds the answer — the question is which one does it best.