1. Brute Force — Hash Set / Lookup Table
Intuition
Store all elements of arr in a hash set, then iterate from positive integer 1 upwards, counting missing numbers until the kth is found.
Algorithm
- Insert all elements of
arrinto a hash setpresent. - Initialize
curr = 1andmissingCount = 0. - While
missingCount < k: - If
curris not inpresent: - Increment
missingCount. - If
missingCount == k, returncurr. - Increment
curr. - Return
curr.
Hash Set Lookup
2 of 2 questions left todayPhase 1 — Populate Set: Store elements { 2, 3, 4, 7, 11 } in set
Phase 1 — Populate Set: Store elements { 2, 3, 4, 7, 11 } in set. Initialize candidate = 1, missingCount = 0, target k = 5.
#include <iostream>#include <unordered_set>#include <vector>using namespace std; // Brute Force: Hash Set checking positive integers from 1 upwardsint findKthPositive(vector<int>& arr, int k) { unordered_set<int> present(arr.begin(), arr.end()); int curr = 1; int missingCount = 0; while (true) { if (present.find(curr) == present.end()) { missingCount++; if (missingCount == k) { return curr; } } curr++; }} int main() { vector<int> arr = {2, 3, 4, 7, 11}; int k = 5; cout << "Output: " << findKthPositive(arr, k) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Approach 1: Brute Force — Hash Set / Lookup Table. - Space complexity:
O(1)— Space complexity for Approach 1: Brute Force — Hash Set / Lookup Table.
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.