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.