Problem 1539

Abstract / Summary

Given a positive integer n and a missing positive integer k find the kth missing positive number up to n.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 1539.cpp

class Solution {
public:
    int findKthPositive(vector<int>& arr, int k) {
        // just tired of binary search ...
        if (k < arr[0])
            return k;

        int missing = arr[0] - 1;

        for (int i = 1; i < arr.size(); i++)
        {
            auto gap = arr[i] - arr[i-1] - 1;
            if (missing + gap >= k)
                return arr[i-1] + k - missing;

            missing += gap;
        }

        return arr.back() + k - missing;
    }
};
21 lines | 496 bytes | submitted August 7, 2023 | GitHub   6% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 63% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the k-th missing positive integer from a strictly increasing array arr. It proceeds with a single forward scan, leveraging arithmetic relationships between consecutive elements to determine where the missing numbers lie. The algorithm avoids more complex search structures and returns as soon as the target position is identified.

Approach

The method treats the array as a sequence of intervals. For each interval between arr[i-1] and arr[i] it calculates how many positive integers are absent (gap). By accumulating these gaps in missing, the code can decide whether the k-th missing number falls inside the current interval or lies beyond the array’s end.

Early Return for Small k

If the desired missing count is smaller than the first element, the answer is simply k because all numbers from 1 up to arr[0]-1 are missing.

if (k < arr[0])
    return k;

Initial Missing Count

The variable missing starts with the count of numbers missing before the first array element, which is arr[0] - 1.

int missing = arr[0] - 1;

Scanning Intervals

The loop iterates from the second element to the end, computing the size of each gap:

for (int i = 1; i < arr.size(); i++)
{
    auto gap = arr[i] - arr[i-1] - 1;
    if (missing + gap >= k)
        return arr[i-1] + k - missing;

    missing += gap;
}
  • gap represents the count of missing numbers strictly between arr[i-1] and arr[i].
  • If adding this gap to the accumulated missing reaches or exceeds k, the k-th missing integer resides inside the current interval. The exact value is derived by offsetting from arr[i-1].
  • Otherwise, the gap is added to missing and the scan continues.

Handling the Tail of the Sequence

When the loop finishes without returning, the k-th missing number lies after the last array element. The final expression extends beyond arr.back() by the remaining offset:

return arr.back() + k - missing;

Edge Cases Handled

The algorithm correctly addresses several boundary conditions:

  • Missing numbers before the first element - The early return covers any k that falls within the initial missing segment.
  • Single-element arrays - With only one element, the loop body is skipped, and the tail calculation yields the correct result, whether the missing number is before, between (none), or after the sole element.
  • Exact match at an interval boundary - When missing + gap equals k, the condition >= k triggers a return that lands precisely on the last missing number of the current interval.
  • All missing numbers after the array - If the cumulative missing count never reaches k during the scan, the final return computes the offset beyond the last element, ensuring the answer is always positive and correctly positioned.
  • Large gaps - The arithmetic uses the difference arr[i] - arr[i-1] - 1, which naturally accommodates any size of gap without overflow concerns for typical input ranges.

Performance Optimizations

The implementation achieves efficiency through several deliberate choices:

  • Single pass linear scan - By iterating once over the array, the algorithm avoids the overhead of binary search or auxiliary data structures.
  • Early termination - As soon as the cumulative missing count meets the target, the function returns immediately, preventing unnecessary processing of later elements.
  • Constant extra space - Only a few integer variables (missing, gap, loop index) are used, keeping the memory footprint minimal.
  • Direct arithmetic computation - The calculation of the result inside the interval (arr[i-1] + k - missing) eliminates the need for additional loops or lookups.
  • Avoidance of function calls - All operations are performed inline within the method, reducing call-stack overhead.

These characteristics combine to deliver a solution that runs quickly even for large input arrays while maintaining a straightforward and readable code path.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long line of numbered toy blocks. Some blocks are missing from the line, and you want to find the special one that is the k-th missing toy.

The computer looks at the first block in your line and checks if the missing toy you want comes before that first block. If the count of missing toys is small enough, the computer can tell you exactly what it is right away.

Then, the computer walks along the line block by block. It looks at the space between two neighbors to see how many toys are hiding in that gap. Every time it finds a gap, it adds those hidden toys to a running count to keep track of how many items are missing so far.

If the number of missing toys becomes large enough to include the k-th one, the computer stops walking. It uses a bit of simple counting to figure out which missing number you were looking for. If it reaches the very end of the line and still has not found the k-th missing one, it looks at the last block in the row and counts forward from there to find the answer.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.37 | σ = 0.67

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java
leetcode.ca C++ Java Python Go
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 Java
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
qiyuangong Java
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 Java
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
qiyuangong Java
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
YuriSpiridonov Python
32 links | 23 authors | 9 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality