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.