Program to find X for special array with X elements greater than or equal X in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called nums where all elements are either 0 or positive. The nums is considered special array if there exists a number x such that there are exactly x numbers in nums which are larger than or equal to x. And x does not have to be an element in nums. Here we have to find x if the array is special, otherwise, return -1.

So, if the input is like nums = [4,6,7,7,1,0], then the output will be 4 as there are 4 numbers which are greater or equal to 4.

To solve this, we will follow these steps −

  • for i in range 0 to maximum of nums, do

    • count:= 0

    • for each j in nums, do

      • if j >= i, then


      • count := count + 1
    • if count is same as i, then

      • return i

  • return -1

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(nums):
   for i in range(max(nums)+1):
      count=0
      for j in nums:
         if j >= i:
            count+=1
      if count == i:
         return i
      return -1

nums = [4,6,7,7,1,0]
print(solve(nums))

Input

[4,6,7,7,1,0]

Output

-1
raja
Published on 17-May-2021 13:04:42
Advertisements