Suppose we have a list of numbers called nums, that contains only non-negative numbers. If there are exactly k number of elements in nums that are greater than or equal to k, find the value k. If we cannot find such, then return -1.
So, if the input is like nums = [6, 4, 0, 8, 2, 9], then the output will be 4, because there are exactly 4 elements that are greater than or equal to 4: [6, 4, 8, 9].
To solve this, we will follow these steps −
sort the list nums in reverse order
for i in range 1 to size of nums - 1, do
if i > nums[i - 1], then
come out from loop
otherwise when i > nums[i], then
return i
return -1
Example
Let us see the following implementation to get better understanding
def solve(nums): nums.sort(reverse=True) for i in range(1, len(nums)): if i >nums[i - 1]: break elif i > nums[i]: return i return -1 nums = [6, 4, 0, 8, 2, 9] print(solve(nums))
Input
[6, 4, 0, 8, 2, 9]
Output
4