k | Function to find kth missing number ; If the total missing number count is equal to k we can iterate backwards for the first missing number and that will be the answer . ; To further optimize we check if the previous element ' s ▁ ▁ missing ▁ number ▁ count ▁ is ▁ equal ▁ ▁ to ▁ k . ▁ Eg : ▁ arr ▁ = ▁ [ 4,5,6,7,8 ] ▁ ▁ If ▁ you ▁ observe ▁ in ▁ the ▁ example ▁ array , ▁ ▁ the ▁ total ▁ count ▁ of ▁ missing ▁ numbers ▁ for ▁ all ▁ ▁ the ▁ indices ▁ are ▁ same , ▁ and ▁ we ▁ are ▁ ▁ aiming ▁ to ▁ narrow ▁ down ▁ the ▁ ▁ search ▁ window ▁ and ▁ achieve ▁ O ( logn ) ▁ ▁ time ▁ complexity ▁ which ▁ ▁ otherwise ▁ would ' ve been O ( n ) . ; Else we return arr [ mid ] - 1. ; Here we appropriately narrow down the search window . ; In case the upper limit is - ve it means the missing number set is 1 , 2 , . . , k and hence we directly return k . ; Else we find the residual count of numbers which we 'd then add to  arr[u] and get the missing kth number. ; Return arr [ u ] + k ; Driver Code ; Function Call
def missingK ( arr , k ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE l = 0 NEW_LINE u = n - 1 NEW_LINE mid = 0 NEW_LINE while ( l <= u ) : NEW_LINE INDENT mid = ( l + u ) // 2 ; NEW_LINE numbers_less_than_mid = arr [ mid ] - ( mid + 1 ) ; NEW_LINE if ( numbers_less_than_mid == k ) : NEW_LINE if ( mid > 0 and ( arr [ mid - 1 ] - ( mid ) ) == k ) : NEW_LINE INDENT u = mid - 1 ; NEW_LINE continue ; NEW_LINE DEDENT return arr [ mid ] - 1 ; NEW_LINE if ( numbers_less_than_mid < k ) : NEW_LINE l = mid + 1 ; NEW_LINE elif ( k < numbers_less_than_mid ) : NEW_LINE u = mid - 1 ; NEW_LINE DEDENT if ( u < 0 ) : NEW_LINE INDENT return k ; NEW_LINE DEDENT less = arr [ u ] - ( u + 1 ) ; NEW_LINE k -= less ; NEW_LINE return arr [ u ] + k ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 7 , 11 ] ; NEW_LINE k = 5 ; NEW_LINE print ( " Missing ▁ kth ▁ number ▁ = ▁ " + str ( missingK ( arr , k ) ) ) NEW_LINE DEDENT