Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: For n = 10⁶ distinct integers up to 10⁹, find the smallest positive integer missing from the array in O(n) time and O(1) extra space. Which technique achieves this?

  1. A. Cyclic placement: swap each value v in 1..n into index v − 1, then scan for the first index i with a[i] ≠ i + 1
  2. B. Sort, then scan – O(n) time
  3. C. Hash set of values – O(1) extra space
  4. D. Binary search on the answer – O(log n) total

Correct answer: A. Cyclic placement: swap each value v in 1..n into index v − 1, then scan for the first index i with a[i] ≠ i + 1

The answer lies in 1..n + 1, so values outside that range can be ignored, and each swap puts one value in its final slot – at most n swaps overall. Sorting is O(n log n); a hash set needs O(n) space; feasibility is not monotonic in a way binary search can test cheaply.

More Coding Interview Problems questions

Exams that ask this topic