#1608
Easy Algorithms Special array with x elements greater than or equal x
Array Binary Search Sorting
66.8% acceptance
Feb 25, 2026
2338
468
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.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn special_array(mut nums: Vec<i32>) -> i32 {
nums.sort();
let n = nums.len() as i32;
for x in 0..=n {
// count elements >= x
let cnt = nums.partition_point(|&v| v < x) as i32;
let ge = n - cnt;
if ge == x {
return x;
}
}
-1
}
}