Arrays
Episode 12 First Missing Positive
▶ This video is coming to YouTube soon.
LeetCode 41, First Missing Positive, solved on screen. Three examples show the cases: every number from 1 up is there, there's a gap in the middle, and 1 itself is missing. A HashSet solves it in O(n) time, but the problem allows only O(1) extra memory. So we use the array itself as the set: swap every value v into slot v − 1, then the first slot i that doesn't hold i + 1 gives the answer. O(n) time, O(1) space.
What you'll learn
- What First Missing Positive asks, through three worked examples
- The HashSet solution: O(n) time, but O(n) space
- The key idea: the answer is always between 1 and n + 1
- Cyclic placement: swap every value into its own seat, in place
- Why the swaps add up to O(n), even with a loop inside a loop
Chapters
- 0:00The problem
- 0:17Examples
- 0:57HashSet check, visualized
- 1:26HashSet check: the code
- 1:41HashSet check, line by line
- 2:16Swap into place: the idea
- 2:37Swap into place, visualized
- 3:41Swap into place: the code
- 3:57Swap into place, line by line
- 5:05Comparing the approaches