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

Problem: Find the smallest missing positive integer using cyclic placement.

Problem: Find the smallest missing positive integer using cyclic placement.
def first_missing(a):
    n = len(a)
    for i in range(n):
        while 1 <= a[i] <= n and a[a[i] - 1] != a[i]:
            j = a[i] - 1
            a[i], a[j] = a[j], a[i]
    for i in range(n):
        if a[i] != i + 1: return i + 1
    return n + 1
print(first_missing([3, 4, -1, 1]), first_missing([7, 8, 9]), first_missing([1, 2, 3]), first_missing([1, 1]))
What is printed?
  1. A. 2 1 3 2
  2. B. 2 10 4 2
  3. C. 2 1 4 1
  4. D. 2 1 4 2

Correct answer: D. 2 1 4 2

After placing every value v in 1..n at index v − 1, the first position not holding i + 1 is the answer. [1, 2, 3] → 4 (n + 1). The condition a[a[i] − 1] != a[i] (not a[i] != i + 1) stops infinite swapping on duplicates like [1, 1]. Note the swap order: j is computed before swapping. O(n), O(1).

More Coding Interview Problems questions

Exams that ask this topic