Missing or Duplicate Number in an Array

Write a function that will find a missing or duplicated number in an array.

💡Strategies for Solving This Problem

Multiple Solutions, Different Trade-offs

I've gotten variants of this at Amazon and Microsoft. The problem: array of n numbers from 1 to n, one is missing or duplicated. Find it.

Approach 1: Math Formula (Cleanest)

Sum of 1 to n is: n(n+1)/2

Expected sum - actual sum = missing number (or duplicate with negative)

This is O(n) time, O(1) space. My go-to solution.

Approach 2: XOR Bit Manipulation (Clever)

XOR has cool properties:

  • a ⊕ a = 0
  • a ⊕ 0 = a
  • XOR is commutative and associative

XOR all numbers 1 to n, then XOR with array elements. Result is the missing/duplicate number.

Also O(n) time, O(1) space, but shows you know bit tricks.

Approach 3: Hash Set (Straightforward)

Put all numbers in a Set, then check which from 1 to n is missing.

O(n) time, O(n) space. Works but uses extra space.

Approach 4: In-Place Marking (Tricky)

Use array indices as a hash. For each number, mark array[number] as negative. The index that stays positive (or goes negative twice) is your answer.

O(n) time, O(1) space, but modifies the array.

Which to Use?

I usually start with the math approach (it's cleanest). If interviewer asks to optimize or show another method, I'll do XOR. Hash set is the fallback if I'm blanking.

Scroll to Top