Skip to main content
CodeOath
← All problems

Problem

Missing Number

Easy
  • arrays
  • math

nums holds all but one of the integers from 0 to n, where n is the length of nums, and no integer appears twice. Return the integer that is not there.

Example 1
Input
nums = [4, 0, 2, 1]
Output
3
Explanation

n is 4, so the integers are 0, 1, 2, 3 and 4. Only 3 is absent from the array.

Example 2
Input
nums = [1, 2, 3]
Output
0
Explanation

n is 3, so the integers are 0, 1, 2 and 3. The array has no 0.

Example 3
Input
nums = [0, 1, 2]
Output
3
Explanation

n is 3, so the integers are 0, 1, 2 and 3. Everything below 3 is present, which makes n itself the missing one.

Constraints:

  • 1 <= nums.length <= 10^5
  • the values are distinct integers in [0, nums.length]

Follow-up: sorting the array or using a set will work. Can you do it in O(n) time with O(1) extra space?

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.