NeetCode #87LC-1608EasyArrays & Hashing
← Back to All Problems#87 · #1608 · Special Array With X Elements Greater Than or Equal X(特殊数组的特征值)
📌 Problem Statement & Constraints
An array is special if there exists a number
x such that exactly x elements in the array are greater than or equal to x. Given nums, return x, or -1 if no such value exists. If multiple x satisfy the condition, the answer is guaranteed unique. Constraints: 1 <= nums.length <= 100, 0 <= nums[i] <= 1000.💡 Core Algorithmic Approaches
- Sort the array, then for a candidate
xthe count of elements>= xisn - lower_bound(x). - Check candidates from
ndown to 1; the first one satisfyingcount == xis the answer. - Binary search (
bisect_left) gives the lower bound in O(log n), so each candidate costs O(log n). - Iterating
xfromndownward is required becausexcannot exceedn(there are onlynelements) and the largest validxis the answer when the statement guarantees uniqueness.
💻 Benchmark Python3 Implementation
class Solution:
def specialArray(self, nums: List[int]) -> int:
from bisect import bisect_left
nums.sort()
n = len(nums)
for x in range(n, 0, -1): # x cannot exceed n
cnt = n - bisect_left(nums, x) # elements >= x
if cnt == x:
return x
return -1
# Linear alternative: sort descending and scan
class Solution2:
def specialArray(self, nums: List[int]) -> int:
nums.sort(reverse=True)
for i in range(len(nums)):
if nums[i] >= i + 1 and (i + 1 == len(nums) or nums[i + 1] < i + 1):
return i + 1
return -1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n log n) for the sort plus O(n log n) for the candidate loop in the first version, or O(n) after sorting in the second.
💾 Space Complexity
O(1) beyond the in-place sort.
⚠️ Interview Pitfalls & Follow-ups
- Iterating
xfrom 1 upward and returning the first match: that yields the smallest validx, but the problem asks for the answer when it is unique -- iterating downward is the safe convention and matches the expected output when several candidates exist. - Using
bisect_right: the count of elements>= xusesbisect_left(nums, x);bisect_rightcounts elements> x. - Considering
x = 0: zero elements greater than or equal to 0 is false whenever the array is non-empty, so 0 is never a valid answer. - Allowing
x > n: impossible, since there are onlynelements.