Special Array With X Elements Greater Than or Equal X - Problem

You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.

Notice that x does not have to be an element in nums.

Return x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.

Input & Output

Example 1 — Basic Special Array
$ Input: nums = [3,5]
Output: 2
💡 Note: There are exactly 2 numbers greater than or equal to 2: both 3 and 5. So x = 2 makes this a special array.
Example 2 — Not Special Array
$ Input: nums = [0,0]
Output: -1
💡 Note: For x=0: 2 elements ≥ 0 (2≠0). For x=1: 0 elements ≥ 1 (0≠1). For x=2: 0 elements ≥ 2 (0≠2). No valid x exists.
Example 3 — Edge Case with Zero
$ Input: nums = [0,4,3,0,4]
Output: 3
💡 Note: There are exactly 3 numbers greater than or equal to 3: [4,3,4]. So x = 3 makes this a special array.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Special Array: Find x where exactly x elements ≥ xInput: [3, 5]35Check x = 2:Elements ≥ 2: count = 2count = x ✓ Special!3 ≥ 2 ✓5 ≥ 2 ✓Output: 22Why x = 2 works:• Exactly 2 elements (3 and 5) are greater than or equal to 2• This matches our target: x = 2• Therefore, the array is special with x = 2
Understanding the Visualization
1
Input Array
Given array of non-negative integers
2
Find Special X
Look for x where count(elements ≥ x) = x
3
Output Result
Return x if found, otherwise -1
Key Takeaway
🎯 Key Insight: The special value x must satisfy the exact balance: x elements are ≥ x
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen