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.