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;
}
};
Difficulty
and has an acceptance rate of about 43% (4+ million submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 268: Missing Number
- problem 287: Find the Duplicate Number
- problem 448: Find All Numbers Disappeared in an Array
- problem 765: Couples Holding Hands
- problem 2336: Smallest Number in Infinite Set
- problem 2554: Maximum Number of Integers to Choose From a Range I
- problem 2598: Smallest Missing Non-negative Integer After Operations
- problem 2996: Smallest Missing Integer Greater Than Sequential Prefix Sum
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
Extra
- 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