Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Find the missing number in an array containing n distinct values from 0..n.

Problem: Find the missing number in an array containing n distinct values from 0..n.
def missing(a):
    x = len(a)
    for i, v in enumerate(a):
        x ^= i ^ v
    return x
print(missing([3, 0, 1]), missing([9, 6, 4, 2, 3, 5, 7, 0, 1]), missing([0]))
What is printed?
  1. A. 2 8 0
  2. B. 2 8 1
  3. C. 2 9 1
  4. D. 4 8 1

Correct answer: B. 2 8 1

XOR all indices 0..n with all values; every present number cancels with its index and the missing one remains. The sum formula n(n+1)/2 − Σa also works but can overflow 32-bit ints for large n in C/Java. O(n), O(1).

More Coding Interview Problems questions

Exams that ask this topic