Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Program to find X for special array with X elements greater than or equal X in Python
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 −
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
