Skip to content

1608. Special Array With X Elements Greater Than or Equal X 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int specialArray(vector<int>& nums) {
    ranges::sort(nums);

    if (nums[0] >= nums.size())
      return nums.size();

    for (int i = 1; i < nums.size(); ++i) {
      const int count = nums.size() - i;
      if (nums[i - 1] < count && nums[i] >= count)
        return count;
    }

    return -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int specialArray(int[] nums) {
    Arrays.sort(nums);

    if (nums[0] >= nums.length)
      return nums.length;

    for (int i = 1; i < nums.length; ++i) {
      final int count = nums.length - i;
      if (nums[i - 1] < count && nums[i] >= count)
        return count;
    }

    return -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def specialArray(self, nums: list[int]) -> int:
    nums.sort()

    if nums[0] >= len(nums):
      return len(nums)

    for i, (a, b) in enumerate(itertools.pairwise(nums)):
      count = len(nums) - i - 1
      if a < count and b >= count:
        return count

    return -1