Special Array With X Elements Greater Than or Equal X

easy search sorting counting

Problem

Given an array nums of non-negative integers, the array is special if there exists a value x such that exactly x elements of nums are greater than or equal to x. The value x need not appear in nums. Return that unique x if it exists, otherwise return -1.

Inputnums = [0,4,3,0,4]
Output3
Exactly 3 values (4, 3, 4) are greater than or equal to 3, so x = 3.
Inputnums = [0,0]
Output-1
No x works: x = 1 needs 1 element ≥ 1 but there are 0, x = 2 needs 2 but there are 0.

def special_array(nums):
    nums.sort(reverse=True)
    n = len(nums)
    for i in range(n):
        x = i + 1
        if nums[i] >= x and (i == n - 1 or nums[i + 1] < x):
            return x
    return -1
function specialArray(nums) {
  nums.sort((a, b) => b - a);
  const n = nums.length;
  for (let i = 0; i < n; i++) {
    const x = i + 1;
    if (nums[i] >= x && (i === n - 1 || nums[i + 1] < x)) {
      return x;
    }
  }
  return -1;
}
int specialArray(int[] nums) {
    Arrays.sort(nums);
    int n = nums.length;
    for (int i = 0; i < n; i++) {
        int x = i + 1;
        int v = nums[n - 1 - i];
        if (v >= x && (i == n - 1 || nums[n - 2 - i] < x)) {
            return x;
        }
    }
    return -1;
}
int specialArray(vector<int>& nums) {
    sort(nums.rbegin(), nums.rend());
    int n = nums.size();
    for (int i = 0; i < n; i++) {
        int x = i + 1;
        if (nums[i] >= x && (i == n - 1 || nums[i + 1] < x)) {
            return x;
        }
    }
    return -1;
}
Time: O(n log n) Space: O(1)