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;
}
};
Difficulty
and has an acceptance rate of about 63% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
AI Disclaimer
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.
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;
}
gaprepresents the count of missing numbers strictly betweenarr[i-1]andarr[i].- If adding this gap to the accumulated
missingreaches or exceedsk, the k-th missing integer resides inside the current interval. The exact value is derived by offsetting fromarr[i-1]. - Otherwise, the gap is added to
missingand 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
kthat 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 + gapequalsk, the condition>= ktriggers 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
kduring 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 2195: Append K Integers With Minimal Sum
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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