Find the First K Missing Positive Numbers

curriculum-track — return the first k positive integers missing from `nums` using cyclic sort then post-scan.

Easy
Time O(n + k) Space O(k)
4 min read
cyclic-sort

Problem#

(curriculum variant.) Given nums and k, return the first k smallest positive integers missing from nums.

Examples#

  • nums = [3, -1, 4, 5, 5], k = 3[1, 2, 6]

Constraints#

  • 1 <= n, k <= 10^5.

Approach#

Cyclic sort over indices 1..n. Then scan [1..n]; each i where nums[i] != i + 1 contributes a missing number i + 1. Track the “extra” displaced values in a set to avoid re-listing them when continuing past n. Append n + 1, n + 2, … until k are collected.

Solution#

First K Missing Positives
vector<int> firstKMissing(vector<int> nums, int k) {
int n = nums.size();
for (int i = 0; i < n; ) {
if (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) swap(nums[i], nums[nums[i] - 1]);
else ++i;
}
vector<int> out;
unordered_set<int> displaced;
for (int i = 0; i < n && (int)out.size() < k; ++i) {
if (nums[i] != i + 1) {
out.push_back(i + 1);
displaced.insert(nums[i]);
}
}
int extra = n + 1;
while ((int)out.size() < k) {
if (!displaced.count(extra)) out.push_back(extra);
++extra;
}
return out;
}

Editorial#

Cyclic sort identifies the missing positions within [1, n]. Beyond n, candidates are n + 1, n + 2, …; we must skip values displaced out of [1, n] that appeared in the input (e.g., n + 2 if it sat in the original input).

Complexity#

  • Time: O(n + k).
  • Space: O(k).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.