KatInterview

Maximum Score Level Backed by Enough Servers

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingcountingh-indexbucket

Last updated

Find the largest k such that at least k scores are k or higher, using counting with capped values to reach linear time.

You are given a list of integer scores, one per server in a fleet. Find the highest level k that the fleet can support.

A level k is supported if at least k servers have a score that is greater than or equal to k. A score exactly equal to k counts toward that level.

Return the largest supported level. If no positive level is supported, return 0.

Rules

  • The level k can never be larger than the number of servers.
  • Scores may be zero or negative. Such scores never count toward any positive level.
  • An empty list has answer 0.

Input and Output

  • Input: scores, a list of integers.
  • Output: a single integer, the largest supported level, or 0 if there is none.

Constraints

  • 0 <= len(scores) <= 10^5
  • Each score is an integer that fits in a 32-bit signed integer (it may be negative, zero, or very large).
  • A solution that runs in O(n) time is achievable and preferred.

Examples

Example 1

Input: max_supported_level([3, 0, 6, 1, 5])

Output: 3

Example 2

Input: max_supported_level([0, 0])

Output: 0

Hints

Hint 1

The answer is always between 0 and n, where n is the number of servers, so you only need to consider those n + 1 levels.

Hint 2

For the purpose of this problem, a score larger than n behaves exactly like a score equal to n. Cap large scores, and ignore negative ones.

Hint 3

Count how many scores land on each value from 0 to n, then walk k downward from n while keeping a running total of scores that are at least k. The first k where the total reaches k is the answer.