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 With X Elements Greater Than or Equal X INPUT Array nums: 3 index 0 5 index 1 nums = [3, 5] Length: 2 Find special x value Need: exactly x numbers that are >= x ALGORITHM STEPS 1 Sort Array [3,5] --> [3,5] 2 Try x = 1 to n x can be 1 or 2 3 Count nums >= x Binary search or scan 4 Check if count == x Return x if match Verification: x=1: count(>=1)=2, 2!=1 FAIL x=2: count(>=2)=2, 2==2 OK Found x = 2! FINAL RESULT Special value found: x = 2 Verification: Elements >= 2: [3, 5] Count = 2 2 == 2 -- OK! Output: 2 Key Insight: The value x must satisfy: exactly x elements in the array are >= x. Since array length is n, x can only be in range [0, n]. Sort the array and use binary search for O(n log n) solution. TutorialsPoint - Special Array With X Elements Greater Than or Equal X | Optimal Solution
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