Skip to main content

7. Missing Number

easyAsked at Confluent

Find the missing number in [0..n] — Confluent uses it to probe whether you reach for sum-formula or XOR before they extend to detecting missing offsets in a Kafka log.

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

Problem

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

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. Sort then scan

Sort and return the first index where nums[i] !== i, else n.

Time
O(n log n)
Space
O(1)
nums.sort((a,b)=>a-b);
for (let i=0;i<nums.length;i++) if (nums[i]!==i) return i;
return nums.length;

Tradeoff:

2. Sum formula

Expected sum is n*(n+1)/2; subtract the actual sum to find the missing value in linear time and constant space.

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:

Confluent-specific tips

Confluent will reframe this as gap-detection in a Kafka offset stream — show you'd use the same sum/XOR trick over a sliding offset window so consumer-group rebalance keeps the running gap state warm.

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 Confluent interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →