File: special-array-with-x-elements-greater-than-or-equal-x/solution.py

Date: 2026-06-06

Time: 19:13

Purpose

This file solves LeetCode 1608: Special Array With X Elements Greater Than or Equal to X. It determines whether there exists a value x such that exactly x elements in the array are greater than or equal to x. If such a value exists, it returns x; otherwise it returns -1.

It follows the repo's convention: one solution.py per problem directory, exporting a single function matching the LeetCode signature.

Key Components

specialArray(nums: list[int]) -> int

Contract: Given a list of non-negative integers, return the unique special value x or -1 if none exists.

The function uses a sort-then-scan approach rather than brute-force counting:

1. Sort descendingnums.sort(reverse=True) places the largest values first.

2. Iterate candidate valuesx ranges from 1 to n (inclusive). For each x, the element at index x-1 is the x-th largest value.

3. Two-condition check:

Patterns

Dependencies

Imports: None — pure stdlib, no external dependencies.

Imported by: The corresponding test_solution.py in the same directory. The "Imported By" list in the prompt is misleading — those are test files for *other* problems that share a common test harness importing from their own solution.py, not from this file.

Flow


Input: [3, 5]

1. Sort descending:  [5, 3]
2. x=1: nums[0]=5 >= 1 ✓, nums[1]=3 >= 1 → not < 1 ✗ → skip
3. x=2: nums[1]=3 >= 2 ✓, x==n (2==2) ✓ → return 2

Output: 2

The key insight: after descending sort, nums[x-1] >= x means "the x-th largest value is big enough," and nums[x] < x means "the (x+1)-th largest value is too small," so exactly x values qualify.

Invariants

Error Handling

None. The function assumes valid input per LeetCode constraints (non-negative integers, non-empty list). Returns -1 as the "not found" sentinel — no exceptions are raised.

Topics to Explore

Beliefs