Program to find k where k elements have value at least k in Python

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 value, 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].

Algorithm

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 break from loop

    • Otherwise when i > nums[i], then return i

  • Return -1 if no valid k is found

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]
result = solve(nums)
print(f"Input: {[6, 4, 0, 8, 2, 9]}")
print(f"Output: {result}")
Input: [6, 4, 0, 8, 2, 9]
Output: 4

How It Works

After sorting [6, 4, 0, 8, 2, 9] in reverse order, we get [9, 8, 6, 4, 2, 0]. The algorithm checks each position i:

  • At i=1: 1 elements ? 8? No (only 9), continue

  • At i=2: 2 elements ? 6? No (9, 8), continue

  • At i=3: 3 elements ? 4? No (9, 8, 6), continue

  • At i=4: 4 elements ? 2? Yes (9, 8, 6, 4), and i > nums[4] (4 > 2), so return 4

Additional Examples

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

# Test case 1: Valid k exists
nums1 = [3, 5, 3, 0, 1, 5]
print(f"nums1 = {nums1}, k = {solve(nums1)}")

# Test case 2: No valid k exists  
nums2 = [0, 1, 2]
print(f"nums2 = {nums2}, k = {solve(nums2)}")
nums1 = [3, 5, 3, 0, 1, 5], k = 3
nums2 = [0, 1, 2], k = -1

Conclusion

This algorithm efficiently finds the value k where exactly k elements are greater than or equal to k by sorting the array in descending order and checking each position. The time complexity is O(n log n) due to sorting.

Updated on: 2026-03-26T15:15:25+05:30

385 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements