algorythms
Cyclic Sort
LC #41Hard

First Missing Positive

Cyclic Sort
AmazonGoogleMeta

Problem

Find the smallest missing positive integer in an unsorted array. Must be O(n) time and O(1) space.

arrayhash-mapcyclic-sort

Constraints

  • 1 ≤ n ≤ 10⁵
  • -2³¹ ≤ nums[i] ≤ 2³¹ − 1
  • O(n) time and O(1) space required

Example

Inputnums = [3, 4, -1, 1]
Output2
Why

1 is present, 2 is missing. Negatives and out-of-range are irrelevant

Hints — reveal one at a time