Skip to main content

12. Missing Number

easyAsked at Wise

Find the missing value in 0..n with one slot absent — a clean stand-in for the missing-leg detector in a double-entry ledger.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an array nums containing n distinct numbers in the range [0, n], return the one number in the range that is missing from the array. Solve in O(n) time and O(1) extra space.

Constraints

  • n == nums.length
  • 1 <= n <= 10^4
  • All numbers are unique and in [0, n]

Examples

Example 1

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

Example 2

Input
nums=[9,6,4,2,3,5,7,0,1]
Output
8

Approaches

1. Hash set lookup

Put nums in a Set, then probe 0..n until one is missing.

Time
O(n)
Space
O(n)
const s=new Set(nums);
for (let i=0;i<=nums.length;i++)
  if (!s.has(i)) return i;

Tradeoff:

2. Gauss sum difference

Expected sum is n(n+1)/2; subtract the actual sum to reveal the missing entry. Constant space, no hashing.

Time
O(n)
Space
O(1)
function missingNumber(nums){
  const n = nums.length;
  let expected = (n*(n+1))/2;
  for (const x of nums) expected -= x;
  return expected;
}

Tradeoff:

Wise-specific tips

Wise loves the sum-difference trick because their reconciliation job uses the same algebraic shortcut to flag the missing leg of a double-entry post.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Missing Number and other Wise interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →