From 69ee8198b0d2bd21a4c21112220e3bf8e9791266 Mon Sep 17 00:00:00 2001 From: Samir Paul <77569653+SamirPaulb@users.noreply.github.com> Date: Sun, 1 Dec 2024 11:40:42 +0530 Subject: [PATCH] Update 11. Kth Missing Positive Number.py --- .../11. Kth Missing Positive Number.py | 39 +++++++++++++------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/11_Binary-Search/11. Kth Missing Positive Number.py b/11_Binary-Search/11. Kth Missing Positive Number.py index 95ca2f3c..a0c11727 100644 --- a/11_Binary-Search/11. Kth Missing Positive Number.py +++ b/11_Binary-Search/11. Kth Missing Positive Number.py @@ -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