Skip to content
BytePatterns

Smallest Absent Positive

HardArrays#cyclic-sort#index-as-home~35m

Problem

A ticket machine hands out the smallest positive ticket number that is not already taken. Given an unsorted list of whole numbers, which may include zero, negatives, duplicates and values far larger than the list, return the smallest positive whole number missing from it. Use O(n) time and only constant extra memory, rearranging the list itself if that helps.

Examples

Input:  nums = [5, 3, -1, 1, 2]
Output: 4
Why:    1, 2 and 3 are all present, and 4 is not
Input:  nums = [2, 2, 90]
Output: 1
Why:    1 is missing, whatever else the list holds
Input:  nums = []
Output: 1
Why:    edge case, nothing is taken yet

Hints

0 / 3

Stuck on the idea rather than the code? Cyclic Sort covers it.