1. Hash Set Lookup (Brute Force)
Intuition
Add all elements to a hash set, then check for the presence of 1, 2, 3, ... up to N + 1.
Algorithm
- 1. Insert all numbers from nums into a HashSet.
- 2. Loop target from 1 to N+1: - If target not in set, return target.
- 3. Return N + 1.
Brute Force Successive Positive Integer Membership Scans
2 of 2 questions left todayPhase 1 — 1 is present Advance candidate to 2: Step 1: Smallest positive integer is 1
Phase 1 — 1 is present Advance candidate to 2: Step 1: Smallest positive integer is 1. Scan array for 1: found at index 3. Increment candidate to 2.
#include <iostream>#include <vector>#include <unordered_set>using namespace std; // Brute Force Approach: Hash Set Lookupint firstMissingPositive(const vector<int>& nums) { unordered_set<int> seen(nums.begin(), nums.end()); int n = nums.size(); for (int i = 1; i <= n + 1; i++) { if (seen.find(i) == seen.end()) { return i; } } return n + 1;} int main() { vector<int> nums = {3, 4, -1, 1}; int result = firstMissingPositive(nums); cout << "Output: " << result << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Inserting N items takes O(N). Checking 1..N+1 takes at most N+1 lookups of O(1) each. - Space complexity:
O(N)— Hash set requires O(N) auxiliary memory.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.