Data Structures & AlgorithmsVery hardProduct company OA

What is the smallest positive integer missing from [3, 4, −1, 1, 7, 2, 2, 9]? (In-place cyclic placement: put each value v with 1 ≤ v ≤ n at index v − 1, then scan.)

  1. A. 6
  2. B. 8
  3. C. 10
  4. D. 5

Correct answer: D. 5

Values in 1..8 are placed at their own index: 1, 2, 3, 4 and 7 find their slots; −1, the duplicate 2 and 9 (> n) are left wherever they land. The first index i with a[i] ≠ i + 1 is i = 4, so 5 is missing. The duplicate check a[v − 1] ≠ v prevents an infinite swap loop on the two 2s. '10' (n + 2) or '8' come from ignoring the gap at 5.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic