The pigeonhole principle
Put n + 1 items into n boxes and some box gets two. It's why an array of n+1 numbers from 1..n must contain a duplicate.
The idea
If there are more items than places, at least two items share a place. Simple, but it guarantees answers exist and points to clever solutions.
Find the Duplicate Number has n + 1 values in the range 1..n, so a duplicate must exist. First Missing Positive uses the reverse: n numbers can fill at most 1..n, so the answer is in 1..n + 1.
Worked example
First Missing Positive on [3, 4, -1, 1]
- 4 numbers can cover at most 1..4, so the answer is between 1 and 5.
- Place each value v in 1..4 at index v − 1: [1, -1, 3, 4].
- Index 1 doesn't hold 2 → the answer is 2.
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
nums = [3, 4, -1, 1]
Solution · Pythonline 2
def first_missing_positive(nums):n = len(nums)for i in range(n):while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:j = nums[i] - 1nums[i], nums[j] = nums[j], nums[i]for i in range(n):if nums[i] != i + 1:return i + 1return n + 1Step 1 of 6· line 2
Pigeonhole: 4 numbers can fill at most the 4 slots 1…4, so the answer is between 1 and 5. Put each value v from 1…4 in its own slot, index v − 1.
time, .
How to spot it
- Values limited to 1..n (or 0..n) in an array of about n items: the range itself is a hint.
Common mistakes
- Sorting to find the answer () when the range allows O(n).
- Swapping without the nums[j] != nums[i] check, which loops forever on duplicates.
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
- Second-largest distinct elementIndexing and walking through an arrayPractise ✎
- Count how often each number appearsCounting with a hash mapPractise ✎
- Remove duplicate characters, keep the firstA set for “have I seen this?”Practise ✎
- Reverse the order of wordsBuilding a new string or array as the answerPractise ✎
Where it comes up
Go further
Up next for you · Beginner
“Have I seen this?” is a set →