Kth Missing Positive Number
LeetCode 1539 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
missing(i) = arr[i] − (i + 1); answer = low + k.
నేను Kth Missing Positive Number (LeetCode 1539) ను ఇలా పరిష్కరించాను — Math / Missing Numbers ప్యాటర్న్లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
At index i, the count of missing numbers before arr[i] is arr[i] − (i + 1). Binary search the last index where fewer than k numbers are missing; the answer is then low + k.
Approach
- 1
Linear version: every array value ≤ k pushes the answer up by one.
- 2
Binary search on missing(mid) < k.
- 3
After the loop, return low + k.
నేను ఎలా పరిష్కరించాను · మొదటి ఆలోచన నుంచి చివరి పరిష్కారం వరకు
Bump k past each present number.
Search on the missing count.
Linear shiftPythonO(n) time
class Solution:
def findKthPositive(self, nums: List[int], k: int) -> int:
for num in nums:
if num>k:
break
else:
k=k+1
return kBinary searchPythonO(log n) time
class Solution:
def findKthPositive(self, nums: List[int], k: int) -> int:
low=0
high = len(nums)-1
while low<=high:
mid = (low+high)//2
missing = nums[mid]-(mid+1)
if missing<k:
low = mid+1
else:
high = mid-1
return low+kKth Missing Positive Number — తరచూ అడిగే ప్రశ్నలు
Kth Missing Positive Number వెనుక ఉన్న intuition ఏమిటి?
At index i, the count of missing numbers before arr[i] is arr[i] − (i + 1). Binary search the last index where fewer than k numbers are missing; the answer is then low + k.
Kth Missing Positive Number (LeetCode 1539) ను ఎలా పరిష్కరించాలి?
1. Linear version: every array value ≤ k pushes the answer up by one. 2. Binary search on missing(mid) < k. 3. After the loop, return low + k.
Kth Missing Positive Number యొక్క time, space complexity ఎంత?
Time: O(log n). Space: O(1). (Accepted approach: Binary search.)
Kth Missing Positive Number లో సాధారణ పొరపాట్లు ఏమిటి?
The answer may be beyond the last element.
Kth Missing Positive Number ను పరిష్కరించడానికి ఒకటి కంటే ఎక్కువ మార్గాలు ఉన్నాయా?
Linear shift (O(n) time): Bump k past each present number. Binary search (O(log n) time): Search on the missing count.