Special Array With X Elements Greater Than or Equal X

Easy · Binary Search · Explanation and code example

Counting Sort

How it works

We can use a counting array to track how many elements have each value. Since any element greater than n is effectively the same as n for our purposes (they all contribute to counts for candidates 1 through n), we cap values at n. By iterating from the largest possible candidate down to 0 and accumulating counts, we can efficiently find when the running total equals the current index.

Steps

  1. Create a count array of size n + 1.
  2. For each element, increment count[min(num, n)].
  3. Traverse from index n down to 0, accumulating the count in totalRight.
  4. If at any index i, totalRight equals i, return i as the special value.
  5. Return -1 if no match is found.

Complexity

  • Time complexity: O(n)
  • Space complexity: O(n)

Things to watch for

Searching Beyond Array Length

The special value x cannot exceed n (the array length) since there are at most n elements. Searching for values greater than n is unnecessary and can lead to incorrect results or wasted computation.

Using Strict Greater Than Instead of Greater Than or Equal

The problem requires counting elements greater than or equal to x, not strictly greater than. Using the wrong comparison operator will lead to incorrect counts and potentially return -1 when a valid answer exists, or return an incorrect special value.

Python code example

from typing import List

class Solution:
    def specialArray(self, nums: List[int]) -> int:
        count = [0] * (len(nums) + 1)
        for num in nums:
            index = min(num, len(nums))
            count[index] += 1

        total_right = 0
        for i in range(len(nums), -1, -1):
            total_right += count[i]
            if i == total_right:
                return total_right
        return -1

C++ code example

class Solution {
public:
    int specialArray(vector<int>& nums) {
        vector<int> count(nums.size() + 1, 0);
        for (int num : nums) {
            int index = min(num, (int)nums.size());
            count[index]++;
        }

        int totalRight = 0;
        for (int i = nums.size(); i >= 0; --i) {
            totalRight += count[i];
            if (i == totalRight) {
                return totalRight;
            }
        }
        return -1;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations