forked from SamirPaulb/DSAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update 11. Kth Missing Positive Number.py
- Loading branch information
1 parent
680456f
commit 69ee819
Showing
1 changed file
with
27 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |