Workspace Missing Number
0d
DSA Problem Sheet

Missing Number

The input has distinct values from zero through n inclusive, with one number missing. Identify that number.

EXECUTION LAB

The input has distinct values from zero through n inclusive, with one number missing. Identify that number.

Input and constraints
  • Use distinct values from 0 through n inclusive.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
result = len(values)
i = 0
while (i < len(values)):
result = ((result ^ i) ^ values[i])
i = (i + 1)
return result

Visualizer

Step 1 of 4
03i
10
21

Inspect the current state

Cancel the expected index and supplied value together.

Variable watch

i 0result 3

Step explanation

Cancel the expected index and supplied value together.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(1) space

Worked explanation

Pair expected roll-call cards with attended cards; the unmatched card remains.

Guided solution

XOR every expected number and every supplied number. All values present in both groups cancel.

O(n) time · O(1) auxiliary space

Examples

Worked example · {"values":[3,0,1],"target":0} ⇒ 2

Edge case 1 · {"values":[],"target":0} ⇒ 0

Edge case 2 · {"values":[0],"target":0} ⇒ 1

Progressive hints

Hint 1Pair expected roll-call cards with attended cards; the unmatched card remains.
Hint 2XOR every expected number and every supplied number. All values present in both groups cancel.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

The inclusive upper endpoint n also belongs to the expected set.

Interview follow-up

Would an arithmetic sum also work for this bounded input?