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.