➜ ~

Playing Hacks and Stuffs!


Project maintained by h4ckyou Hosted on GitHub Pages — Theme by mattgraham

Kth Missing Positive Number

image

We are given an array which is sorted in increasing order with an integer k

Our goal is to return the Kth positive integer that’s missing from the array

Approach

One way we can easily solve this is:

First we can store a list of possible values within a specific range in this case I used 5001 in an array possible[]

Now I can iterate through each values in the possible[i] and see if the iterate isn’t among the array[j]

Is that returns True I’ll save those elements in another array missing then return the kth missing value which we can represent as missing[k]

That said it’s pretty simple but the issue is what if our kth value is more than the value in possible that would return an error!

Also it’s efficiency is bad image

It uses much space and time because we’re storing a large value in memory and iterating through a large array

So let’s optmize that!

Instead of using lot of memory we can optimize that

I’ll keep the current number not in the array in a variable and keep track of when we get the k which would be possible if I make a variable count that increments on each check of currentNumber image

In terms of space complexity I improved it but in terms of time I didn’t :(

Solve Script: link

After looking at other people solution I found this one which implemented Binary Search

Here’s how it’s done:

Script:

def findKthPositive(arr, k):
    left, right = 0, len(arr)-1

    while left <= right:
        mid = left + (right - left) // 2

        missing = arr[mid] - (mid + 1)

        if missing < k:
            left = mid + 1
        
        else:
            right = mid - 1
        
    # arr[mid] + (k - missing) == kth missing number
    return left + k

arr = [2,3,4,7,11]
k = 5

r = findKthPositive(arr, k)
print(r)

Running it works and it’s fast since the time complexity is O(log N) image