Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1608. Special Array With X Elements Greater Than or Equal X - Leetcode Solution

Code Implementation

class Solution:
    def specialArray(self, nums):
        nums.sort()
        n = len(nums)
        for x in range(1, n + 1):
            # Count how many elements are >= x
            idx = 0
            while idx < n and nums[idx] < x:
                idx += 1
            if n - idx == x:
                return x
        return -1
      
class Solution {
public:
    int specialArray(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int n = nums.size();
        for (int x = 1; x <= n; ++x) {
            int idx = 0;
            while (idx < n && nums[idx] < x) {
                ++idx;
            }
            if (n - idx == x) {
                return x;
            }
        }
        return -1;
    }
};
      
class Solution {
    public int specialArray(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        for (int x = 1; x <= n; ++x) {
            int idx = 0;
            while (idx < n && nums[idx] < x) {
                ++idx;
            }
            if (n - idx == x) {
                return x;
            }
        }
        return -1;
    }
}
      
var specialArray = function(nums) {
    nums.sort((a, b) => a - b);
    let n = nums.length;
    for (let x = 1; x <= n; ++x) {
        let idx = 0;
        while (idx < n && nums[idx] < x) {
            idx++;
        }
        if (n - idx === x) {
            return x;
        }
    }
    return -1;
};
      

Problem Description

Given an array of non-negative integers nums, you are asked to find a special integer x such that there are exactly x elements in nums that are greater than or equal to x. If such an x exists, return it; otherwise, return -1.

  • Each element in nums can be used only once when counting.
  • There is at most one valid x for any input.
  • The array nums may contain duplicate values.

Thought Process

The problem asks for a value x such that exactly x numbers in the array are at least x. At first glance, it might seem like we need to check every possible x from 1 up to the array length and count how many numbers are greater than or equal to x for each. This brute-force approach is simple but could be slow for large arrays.

To optimize, we can sort the array, so that for a given x, we can quickly determine how many elements are greater than or equal to x by looking for the first position where the value is at least x. This reduces repeated work and makes the counting step much faster.

Solution Approach

  • Step 1: Sort the Array
    • Sorting helps us efficiently count, for any x, how many elements are greater than or equal to x.
  • Step 2: Try All Possible x
    • Loop x from 1 up to the length of the array (since you can't have more than n elements in nums).
  • Step 3: Count Elements ≥ x
    • For each x, find the first index where nums[index] ≥ x. The count is then n - index.
    • If this count equals x, we've found our answer.
  • Step 4: Return Result
    • If no such x is found after checking all possibilities, return -1.

The sorting step ensures that the counting for each x is efficient, and we never double-count or miss elements.

Example Walkthrough

Let's use the sample input nums = [3,5,6,7,1].

  1. Sort the array: [1,3,5,6,7].
  2. Try x = 1: There are 5 numbers ≥ 1. Since 5 ≠ 1, continue.
  3. Try x = 2: There are 4 numbers ≥ 2 (3,5,6,7). 4 ≠ 2, continue.
  4. Try x = 3: There are 4 numbers ≥ 3 (3,5,6,7). 4 ≠ 3, continue.
  5. Try x = 4: There are 3 numbers ≥ 4 (5,6,7). 3 ≠ 4, continue.
  6. Try x = 5: There are 3 numbers ≥ 5 (5,6,7). 3 ≠ 5, continue.
  7. No x satisfies the condition, so return -1.

For an input like nums = [0,4,3,0,4]:

  1. Sort: [0,0,3,4,4].
  2. Try x = 1: 4 numbers ≥ 1. 4 ≠ 1.
  3. Try x = 2: 3 numbers ≥ 2. 3 ≠ 2.
  4. Try x = 3: 3 numbers ≥ 3. 3 = 3. Return 3.

Time and Space Complexity

  • Brute-force Approach:
    • For each possible x (up to n), count how many numbers are ≥ x (O(n) per check).
    • Total time: O(n2).
  • Optimized Approach:
    • Sorting takes O(n log n).
    • For each x, finding the index where nums[index] ≥ x can be O(n) (with a simple loop), or O(log n) (with binary search). The provided code uses a linear scan for clarity, but a binary search would make it O(n log n) overall.
    • Total time: O(n log n) (with binary search), or O(n2) (with linear scan).
    • Space: O(1) extra (in-place sorting or O(n) if sorting not in-place).

Summary

The problem asks us to find a unique x such that exactly x elements in nums are at least x. Sorting the array enables efficient counting for each candidate x, making the solution both clear and efficient. The approach leverages the properties of sorted arrays to avoid unnecessary repeated work, and ensures we never double-count or miss a possible solution.