ExamAdda Logo

First Missing Positive

Easy

Given an unsorted integer array nums, find the smallest positive integer that does not appear in the array.

You must solve the problem in O(n) time and use O(1) extra space.

Example 1

Input

n = 3
nums = [1, 2, 0]

Output

3

Explanation

The positive integers start from 1.

1 and 2 are present, but 3 is missing.

Therefore, the answer is 3.

Example 2

Input

n = 4
nums = [3, 4, -1, 1]

Output

2

Explanation

1 is present, but 2 is missing.

Therefore, the smallest missing positive integer is 2.

Constraints

1 <= n <= 10^5
-10^9 <= nums[i] <= 10^9
The solution must run in O(n) time.
Use O(1) extra space.

Hints:

Hint 1

The answer must be between 1 and n + 1.

Hint 2

Try placing every positive number x in the position x - 1.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 27, 2026

Last updated

Aug 28, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output