➜ ~

Playing Hacks and Stuffs!


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

Special Array With X Elements Greater Than or Equal X

image image

We are given an array nums of non negative integers. We can say nums is special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x

The idea is simple we just need to find a number x such that there are exactly x numbers in the array nums that are greater than or equal to x

Let’s take a example:

nums = [3, 5]

I’ll take x as 1:

If x == 1 --> is there any single number in the nums array that is greater than or equal to one?

In this case it returns True because there are two various numbers that meets the condition

Let’s take x as 2:

If x == 2 --> are there any two numbers in the nums array that are greater than or equal to two?

Looking at the condition we can tell that there are two numbers in the array that meet the condition

So the answer we would return is 2 and not 1 because it kinda takes the highest value

From this first case I was able to conclude that the value of x doesn’t essentially need to be in the array but it must be less than or equal to the length of the array i.e x <= len(nums)

Let us take another example:

nums = [0, 4, 3, 0, 4]

I’ll take x as 1:

If x == 1 --> is there any single value in the nums array that is greater than or equal to one? --> True

When x is 2:

If x == 2 --> are there any two numbers in the nums array that are greater than or equal to two? --> True

When x is 3:

If x == 3 --> are there any three numbers in the num array that are greater than or equal to three --> True

When x is 4:

If x == 4 --> are there are four numbers in the num array that are greater than or equal to four --> False

This case returned False this means that the previous result is what will be returned as it returns True so the answer is 3

After I understood that I was able to come up with an idea I can use to implement this and find the value of x:

Solve Script: link image

My approach is Ok but not well optimized

Anyways after looking at others solution I found this approach which made use of Binary Search

Here’s the way it was used:

Here’s the script implementation:

def specialArray(nums):
    left, right = 0, len(nums) - 1

    while left <= right:
        mid = left + (right - left) // 2
        count = sum(1 for num in nums if num >= mid)

        if count == mid:
            return mid
        elif count > mid:
            left = mid + 1
        else:
            right = mid - 1

    return -1

nums = [0,4,3,0,4]
r = specialArray(nums)

print(r)

It works pretty well image