⚡Flashcard Drill➔
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

  1. Sort the array, then for a candidate x the count of elements >= x is n - lower_bound(x).
  2. Check candidates from n down to 1; the first one satisfying count == x is the answer.
  3. Binary search (bisect_left) gives the lower bound in O(log n), so each candidate costs O(log n).
  4. Iterating x from n downward is required because x cannot exceed n (there are only n elements) and the largest valid x is 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 x from 1 upward and returning the first match: that yields the smallest valid x, 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 >= x uses bisect_left(nums, x); bisect_right counts 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 only n elements.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

特殊数组的特征值

给你一个非负整数数组 nums。如果存在一个数 x,使得 nums 中恰好有 x 个元素 大于或者等于 x,那么就称 nums 是一个特殊数组,而 x 是该数组的特征值。注意:x 不必是 nums 的中的元素。如果数组 nums 是一个特殊数组,请返回它的特征值 x;否则,返回 -1。可以证明的是,如果 nums 是特殊数组,那么其特征值 x 是 唯一 的。约束:1 ≤ nums.length ≤ 100;0 ≤ nums[i] ≤ 1000。

核心要点

  • 排序 + 单调性(标准解) :把 nums 降序排序。此时 nums[x-1] 就是第 x 大的元素。
  • 判定条件 :恰好有 x 个元素 ≥ x,等价于 nums[x-1] &gt;= x (至少 x 个元素 ≥ x) 且 x == n 或 nums[x] &lt; x (不存在第 x+1 个元素也 ≥ x)。
  • 为什么特征值唯一 :函数 f(x) = 「≥ x 的元素个数」 关于 x 单调不增,而 g(x) = x 严格递增,两者最多相交一次,因此 x 唯一。
  • 枚举范围 :x 只能取 1 到 n,逐个检查即可,总复杂度 O(n log n)(排序)或 O(n + V)(计数排序)。

常见陷阱

  • 只检查 nums[x-1] &gt;= x :这只说明「至少有 x 个元素 ≥ x」,可能实际有更多个(例如 nums = [5,5,5],x = 2 时 nums[1] = 5 &gt;= 2 成立,但实际有 3 个元素 ≥ 2,不等于 2)。必须同时检查上界条件。
  • 忘记 x == n 的边界 :当 x 等于数组长度时,不存在 nums[x] ,必须短路避免越界。
  • 误以为 x 必须是数组中的元素 :题目明确说明 x 不必是 nums 中的元素。
  • 在升序数组上用 nums[x-1] :升序时 nums[x-1] 是第 x 小 的元素,语义完全不同。必须降序排序。

参考实现

class Solution:
    def specialArray(self, nums: list[int]) -> int:
        nums.sort(reverse=True)          # 降序:nums[x-1] 即第 x 大的元素
        n = len(nums)
        for x in range(1, n + 1):
            # 至少 x 个元素 >= x,且不存在第 x+1 个元素也 >= x
            if nums[x - 1] >= x and (x == n or nums[x] < x):
                return x
        return -1