Skip to main content

41. First Missing Positive

hard

Find the smallest missing positive integer in O(n) time and O(1) extra space. The classic in-place cyclic-sort trick — use the array's own indices as a hash map.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an unsorted integer array nums, return the smallest positive integer that is not present in nums. You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.

Constraints

  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1

Examples

Example 1

Input
nums = [1,2,0]
Output
3

Example 2

Input
nums = [3,4,-1,1]
Output
2

Example 3

Input
nums = [7,8,9,11,12]
Output
1

Explanation: 1 is missing because no positive integer in [1, n] appears.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

The answer must lie in [1, n+1] — there are only n elements, so at least one value in [1, n+1] must be missing.

Hint 2

Use the array itself as a hash map. Place each value v in [1, n] at index v - 1 by swapping. After placement, the first index i where nums[i] != i + 1 reveals the answer i + 1.

Hint 3

Be careful with the swap loop: keep swapping while the current value belongs somewhere valid AND its target slot doesn't already hold the right value (avoid infinite loops on duplicates).

Solution approach

Reveal approach

Cyclic sort in place. For each index i, while nums[i] is in [1, n] and nums[nums[i] - 1] != nums[i], swap nums[i] with nums[nums[i] - 1]. This puts each value v in [1, n] at index v - 1. The inner condition prevents infinite loops when duplicates would otherwise endlessly swap. Values outside [1, n] (zeros, negatives, values > n) are simply skipped — they can't be answers and don't need a home. After the placement pass, walk the array: the first index i where nums[i] != i + 1 means i + 1 is missing, so return i + 1. If every slot is correct, the answer is n + 1. The algorithm is O(n) because each swap moves a value into its correct slot, so the total number of swaps is bounded by n. O(1) extra space because we mutate in place.

Complexity

Time
O(n)
Space
O(1)

Related patterns

  • cyclic-sort
  • in-place

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Google
  • Meta
  • Microsoft
  • Apple
  • Bloomberg

Practice these live with InterviewChamp.AI

Drill First Missing Positive and Arrays problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →