Problem 41

Abstract / Summary

Find the smallest missing positive integer from a list of integers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0041.cpp

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        // n log n
        sort(nums.begin(), nums.end());
        auto last = unique(nums.begin(), nums.end());
        nums.erase(last, nums.end());

        auto pos = upper_bound(nums.begin(), nums.end(), 0);

        int result = 1;
        while (pos != nums.end() && *pos == result)
        {
            pos++;
            result++;
        }

        return result;
    }
};
20 lines | 479 bytes | submitted August 8, 2023 | GitHub   6% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 43% (4+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “first missing positive” problem by first normalizing the input array, then scanning for the smallest positive integer that does not appear. The algorithm proceeds in three logical phases: sorting and deduplication, locating the start of the positive segment, and sequentially checking for the missing value. Each phase is expressed with standard library calls that contribute to both clarity and efficiency.

Sorting and Deduplication

The initial step orders the elements in non-decreasing order.

sort(nums.begin(), nums.end());

Sorting guarantees that any subsequent linear scan will encounter numbers in ascending order, which simplifies the detection of gaps. After sorting, duplicate entries are removed to avoid redundant comparisons later.

auto last = unique(nums.begin(), nums.end());
nums.erase(last, nums.end());

The combination of unique and erase yields a compact container that contains each distinct value exactly once, reducing the number of iterations required in later phases.

Finding the First Positive

Once the array is sorted and deduplicated, the algorithm isolates the sub-range that contains positive numbers.

auto pos = upper_bound(nums.begin(), nums.end(), 0);

upper_bound performs a binary search to locate the first element greater than zero, effectively skipping all non-positive entries. This step ensures that the subsequent loop works only with relevant data, eliminating unnecessary checks for negative numbers or zero.

Linear Scan for the Missing Positive

The core of the solution is a simple while-loop that walks through the positive segment, comparing each element to an expected counter.

int result = 1;
while (pos != nums.end() && *pos == result)
{
    pos++;
    result++;
}

The loop starts with the candidate answer 1. As long as the current element matches the expected value, both the iterator and the candidate are advanced. The moment a mismatch occurs, the loop terminates, and the current value of result is the smallest missing positive integer. If the iterator reaches the end of the container without a mismatch, result will be one greater than the largest positive number present, which correctly represents the missing value.

Edge Cases Handled

When the input consists solely of non-positive numbers, upper_bound returns an iterator equal to nums.end(). The while-loop condition fails immediately, and the function returns 1, which is the correct answer because no positive integers are present.

If the array contains a contiguous sequence of positive integers starting from 1, the loop will consume the entire positive range, and result will be set to one more than the largest element, correctly identifying the next missing positive.

Duplicate positive numbers are eliminated by the deduplication step, so the loop does not get stalled by repeated values that could otherwise cause an infinite iteration.

Performance Optimizations

The use of the standard library’s sort function leverages highly tuned introsort implementations, providing fast ordering even for large inputs. By invoking unique immediately after sorting, the algorithm reduces the effective size of the container before the linear scan, minimizing the number of comparisons in the while-loop.

Locating the first positive element with upper_bound is a logarithmic operation, which is more efficient than a linear scan that would examine every element. This early narrowing of the search space means that the subsequent while-loop processes only the relevant positive segment, avoiding work on negative or zero values.

Overall, the combination of sorting, deduplication, binary search, and a single linear pass yields a solution that balances simplicity with the performance benefits of well-optimized library routines.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big jumbled pile of numbered blocks. Some blocks have big numbers, some have negative numbers, and some might even be duplicates. The goal is to find the very first small number that is missing, starting from the number one.

First, the code lines up all the blocks in order from smallest to biggest, just like putting your toys in a neat row. Then, it looks at the row and throws away any extra copies so that every number appears only once. If there are any blocks with grumpy negative numbers, the code ignores them and focuses only on the positive ones.

Now the code starts a little game. It keeps a tiny counter that starts at one. It looks at the row of blocks to see if the number one is there. If it finds the one, it moves to the next spot in the row and increases the counter to two to see if that is there too. It keeps doing this, checking each spot for the next number, until it finds a hole where a number should be but is not. When it hits that empty space or reaches the end of the row, it knows it has found the smallest number that was hiding from the set.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 28 | median = 6 | μ = 5.96 | σ = 1.55

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# Java C Rust TS Go PHP
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns Python
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++ TS
martianoff Scala
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fpdjsns Python
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++, TypeScript
martianoff Scala
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
YuriSpiridonov Python
zfang399 C++
60 links | 41 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'First Missing Positive - Leetcode 41 - Python'
NeetCode 22 mins
First Missing Positive - Leetcode 41 - Python
YouTube video 'Amazon Coding Interview Question - First Missing Positive (LeetCode)'
AlgosWithMichael 21 mins
Amazon Coding Interview Question - First Missing Positive (LeetCode)
YouTube video 'First Missing Positive | LeetCode 41 | C++, Java, Python | BITWISE operation'
Knowledge Center 17 mins
First Missing Positive | LeetCode 41 | C++, Java, Python | BITWISE operation
YouTube video 'First Missing Positive | In Depth Intuition | Clean Code | Leetcode 41 | codestorywithMIK'
codestorywithMIK 34 mins
First Missing Positive | In Depth Intuition | Clean Code | Leetcode 41 | codestorywithMIK
YouTube video 'first missing positive | first missing positive leetcode | leetcode 41 |  array'
Naresh Gupta 11 mins
first missing positive | first missing positive leetcode | leetcode 41 | array
YouTube video 'First Missing Positive Leetcode'
Pratiksha Bakrola 4 mins
First Missing Positive Leetcode
YouTube video '41. First Missing Positive | Cycle Sort | Using Array as Hash | HashMap | 5 Approaches'
Aryan Mittal 42 mins
41. First Missing Positive | Cycle Sort | Using Array as Hash | HashMap | 5 Approaches
YouTube video 'Leetcode | 41. First Missing Positive | Hard | Java Solution'
Developer Docs 8 mins
Leetcode | 41. First Missing Positive | Hard | Java Solution
YouTube video 'Leetcode 41 First Missing Positive (Java)'
TheAnalyticGuy 6 mins
Leetcode 41 First Missing Positive (Java)
YouTube video 'First missing positive leetcode solution'
InterviewNest 21 mins
First missing positive leetcode solution
YouTube video 'First Missing Positive | Leet code 41 | Theory explained + Python code'
Sai Anish Malla 15 mins
First Missing Positive | Leet code 41 | Theory explained + Python code
YouTube video 'FIRST MISSING POSITIVE | LEETCODE # 41 | PYTHON SOLUTION'
Cracking FAANG 25 mins
FIRST MISSING POSITIVE | LEETCODE # 41 | PYTHON SOLUTION
YouTube video 'First Missing Positive | Leetcode 41 | DSA using python (telugu) | srkcodes'
Srk Codes 16 mins
First Missing Positive | Leetcode 41 | DSA using python (telugu) | srkcodes
YouTube video 'First Missing Positive (LeetCode 41) — Forget HashMap. Use the Array Itself | O(1) Space Trick'
Nikhil Lohia 18 mins
First Missing Positive (LeetCode 41) — Forget HashMap. Use the Array Itself | O(1) Space Trick
YouTube video 'Daily Leetcode #1456: Mar 26, 2024 - 41. First Missing Positive'
Programming Live with Larry 12 mins
Daily Leetcode #1456: Mar 26, 2024 - 41. First Missing Positive
YouTube video '41. First Missing Positive | March | Java | C++'
Mayur Programming Club 16 mins
41. First Missing Positive | March | Java | C++
YouTube video 'First Missing Positive Python Solution - LeetCode #41'
Professor Oakes 5 mins
First Missing Positive Python Solution - LeetCode #41
YouTube video 'LeetCode 41. First Missing Positive'
Happy Coding 11 mins
LeetCode 41. First Missing Positive
YouTube video 'Daily Leetcode #183: Sep 30, 2020 - 41. First Missing Positive'
Programming Live with Larry 18 mins
Daily Leetcode #183: Sep 30, 2020 - 41. First Missing Positive
YouTube video 'Leetcode Question 41 "First Missing Positive" in Javascript'
Ghumman Tech 6 mins
Leetcode Question 41 "First Missing Positive" in Javascript
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

8 similar problems

Solved On The Same Day

19 easy 43 medium 1 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality