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.