Algorithm-Day17-First-Missing-Positive-lc-41
π§© Problem Description
Given an unsorted integer array nums
, return the smallest missing positive integer.
You must implement an algorithm that runs in O(n) time and uses constant extra space.
Example:
1 | Input: nums = [3,4,-1,1] |
π‘ Brute Force (Not Acceptable)
- Sort the array β O(n log n)
- Check for the first missing positive
- β Not allowed by problem constraints
π‘ Optimal Approach: Index Placement (Cyclic Sort Pattern)
β¨ Key Idea
- If
nums[i]
is in range[1, n]
, ideally it should be placed atnums[nums[i] - 1]
. - Swap elements until every number is placed correctly.
- Then scan once to find the first index
i
wherenums[i] != i + 1
.
π’ Java Code
1 | class Solution { |
β± Time and Space Complexity
- Time Complexity: O(n)
Each number is swapped at most once. - Space Complexity: O(1)
In-place swaps only.
βοΈ Summary
- This is a textbook application of the cyclic sort pattern.
- Focus on the fact that only numbers within
[1, n]
matter. - Understand why O(n) solutions are possible by leveraging in-place swaps.
Problems like this appear often in data structure interviews where array indexing and in-place manipulation are tested.