LeetCode Problem Workspace

Special Array With X Elements Greater Than or Equal X

Determine if an array has exactly x elements greater than or equal to x using binary search over the answer space.

category

3

Topics

code_blocks

6

Code langs

hub

3

Related

Practice Focus

Easy · Binary search over the valid answer space

bolt

Answer-first summary

Determine if an array has exactly x elements greater than or equal to x using binary search over the answer space.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Binary search over the valid answer space

Try AiBox Copilotarrow_forward

This problem requires finding a number x such that exactly x elements in nums are greater than or equal to x. By counting elements for each potential x from 0 to nums.length, we can efficiently identify the valid x or return -1 if none exists. Using a sorted array can simplify comparisons and ensures the solution runs in linear time.

Problem Statement

You are given an array nums of non-negative integers. The array is considered special if there exists a number x such that exactly x elements in nums are greater than or equal to x. Your task is to determine this x efficiently using binary search principles over the possible answer space.

If such a number exists, return it. Otherwise, return -1. The number x does not need to be an element in the array, and it can be proven that if a valid x exists, it is unique.

Examples

Example 1

Input: nums = [3,5]

Output: 2

There are 2 values (3 and 5) that are greater than or equal to 2.

Example 2

Input: nums = [0,0]

Output: -1

No numbers fit the criteria for x. If x = 0, there should be 0 numbers >= x, but there are 2. If x = 1, there should be 1 number >= x, but there are 0. If x = 2, there should be 2 numbers >= x, but there are 0. x cannot be greater since there are only 2 numbers in nums.

Example 3

Input: nums = [0,4,3,0,4]

Output: 3

There are 3 values that are greater than or equal to 3.

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 1000

Solution Approach

Sort the Array

Begin by sorting nums. Sorting allows us to count the number of elements greater than or equal to each candidate x in O(1) per check using the array's indices.

Binary Search over x

Instead of checking all numbers, iterate x from 0 to nums.length. For each x, count how many numbers in nums are >= x. If count equals x, return x. This approach leverages the pattern of binary search over the valid answer space.

Handle Edge Cases

Ensure to handle cases like all zeros or arrays with repeated values. If no x satisfies the condition, return -1. Edge cases often fail when ignoring counts beyond array length or miscounting equal elements.

Complexity Analysis

Metric Value
Time O(N)
Space O(N)

Sorting takes O(N log N) but checking counts can be done in O(N). Overall, the approach is O(N log N) time and O(1) extra space if counting in-place, or O(N) space if creating auxiliary arrays.

What Interviewers Usually Probe

  • Check if candidate x can exceed array length.
  • Watch out for off-by-one errors when counting >= x.
  • Consider using sorting to simplify counting elements efficiently.

Common Pitfalls or Variants

Common pitfalls

  • Assuming x must be an element of nums instead of any integer in [0, nums.length].
  • Miscounting elements equal to x, leading to incorrect results.
  • Ignoring edge cases where all elements are zeros or duplicates.

Follow-up variants

  • Find x where at least x elements are greater than or equal to x.
  • Return all possible x values instead of a unique one.
  • Apply the pattern to multidimensional arrays counting elements in each row.

FAQ

What does 'Special Array With X Elements Greater Than or Equal X' mean?

It means finding a number x such that exactly x elements in nums are greater than or equal to x.

Do I need x to be an element of the array?

No, x can be any integer between 0 and nums.length, not necessarily present in nums.

Can duplicates in nums affect the solution?

Duplicates are counted normally. Only the count of elements >= x matters, so duplicates do not break the logic.

Is sorting necessary for the solution?

Sorting simplifies counting elements greater than or equal to x, but a direct count over the array without sorting also works.

How does binary search over the valid answer space help?

It restricts checks to candidate x values from 0 to nums.length, avoiding unnecessary iterations beyond possible x.

terminal

Solution

Solution 1: Brute Force Enumeration

We enumerate $x$ in the range of $[1..n]$, and then count the number of elements in the array that are greater than or equal to $x$, denoted as $cnt$. If there exists $cnt$ equal to $x$, return $x$ directly.

1
2
3
4
5
6
7
class Solution:
    def specialArray(self, nums: List[int]) -> int:
        for x in range(1, len(nums) + 1):
            cnt = sum(v >= x for v in nums)
            if cnt == x:
                return x
        return -1

Solution 2: Sorting + Binary Search

We can also sort `nums` first.

1
2
3
4
5
6
7
class Solution:
    def specialArray(self, nums: List[int]) -> int:
        for x in range(1, len(nums) + 1):
            cnt = sum(v >= x for v in nums)
            if cnt == x:
                return x
        return -1
Special Array With X Elements Greater Than or Equal X Solution: Binary search over the valid answer s… | LeetCode #1608 Easy