DSA AnimatorREVISION VIDEOS
← Back to problems
New

Missing Number — LeetCode 268 video explanation

The array holds n distinct numbers taken from 0 to n. Exactly one number is missing, so return it.

Loading videos…

DSA Animator › DSA Revision › Binary Search › Missing Number

Key moments in the Missing Number video

0:04Problem0:10Example0:16Brute force0:27Key idea0:41Dry run0:53Code1:03Takeaway

What you will learn

Remember: expected sum minus actual sum gives the missing number. XOR of indexes and values is the overflow-safe twin. The video solves Missing Number (LeetCode 268, Easy) with the Math / XOR pattern from the Binary Search topic, and you can replay every step in the interactive Missing Number animation.

Missing Number video transcript

Problem

The array holds n distinct numbers taken from 0 to n. Exactly one number is missing, so return it.

Example

For 3, 0, 1, n is 3, so the numbers should be 0 to 3. The missing one is 2.

Brute force

Sorting and scanning is O of n log n, and a hash set uses O of n space. If the array is already sorted, binary search on whether index equals value also works.

Key idea

The sum of 0 to n is n times n plus 1, over 2. Subtract the actual sum of the array, and what is left is the missing number. An exclusive or of all indexes and values works the same way, without any risk of overflow.

Dry run

n is 3, so the expected sum is 3 times 4 over 2, which is 6. The actual sum is 3 plus 0 plus 1, which is 4. 6 minus 4 is 2. The missing number is 2.

Code

In code, start with n times n plus 1, over 2. Subtract every number in the array. Return what remains, so it's O of n time and O of 1 space.

Takeaway

Remember: expected sum minus actual sum gives the missing number. XOR of indexes and values is the overflow-safe twin.

More Binary Search revision videos

← All 185 DSA revision videos