Skip to content

Commit

Permalink
Update 11. Kth Missing Positive Number.py
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb authored Dec 1, 2024
1 parent 680456f commit 69ee819
Showing 1 changed file with 27 additions and 12 deletions.
39 changes: 27 additions & 12 deletions 11_Binary-Search/11. Kth Missing Positive Number.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,33 @@
# https://leetcode.com/problems/kth-missing-positive-number/
# https://youtu.be/88k8xa-pSrM
# https://www.youtube.com/watch?v=uZ0N_hZpyps

# Brute Force approach
# If there were no elements in arr, then Kth element would be k.
# But for every element of value less than equal to k, will make
# Kth missing value shift to right
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
l, r = 0, len(arr)-1
while l <= r:
mid = l + (r - l) // 2
if arr[mid] < mid+1 + k:
l = mid + 1
for i in arr:
if i <= k: k += 1
else: break
return k
# Time: O(N)
# Space: O(1)


# Binary Search approach => Most Optimised
class Solution:
def findKthPositive(self, arr: List[int], k: int) -> int:
l,r = 0,len(arr)-1
while l<=r:
m = l+(r-l)//2
tmp = m
if arr[m] - m - 1 < k:
l = m+1
else:
r = mid - 1

return l + k


# Time: O(log(n))
r = m-1
# Now r<l and arr[r] to arr[l]: Kth element is in this window
return arr[r] + (k - (arr[r]-r-1))

# Time: O(log(N))
# Space: O(1)

0 comments on commit 69ee819

Please sign in to comment.