← Questions

Count stable server segments

0
Scale AICoding

A row of n machines has integer capacities capacity[0..n-1]. A contiguous segment [l, r] is stable when all of these hold:

  1. It contains at least 3 machines (r - l >= 2).
  2. The two end machines have the same capacity: capacity[l] == capacity[r].
  3. That capacity equals the total capacity of the machines strictly inside the segment: capacity[l] == capacity[l+1] + ... + capacity[r-1].

Implement count_stable_subarrays(capacity: List[int]) -> int, which returns the number of stable segments.

Constraints

  • 0 <= n <= 10^5
  • -10^9 <= capacity[i] <= 10^9 (values may be zero or negative)
  • Aim for better than O(n^2).

Example 1

capacity = [6, 1, 2, 3, 6]
output: 1

Only [0, 4] is stable: the ends are both 6, and 1 + 2 + 3 = 6.

Example 2

capacity = [7, 3, 4, 7, 2, 5, 7]
output: 2

[0, 3] (3 + 4 = 7) and [3, 6] (2 + 5 = 7) are stable. [0, 6] has equal ends, but its interior sums to 21, so it is not stable.

Be ready for follow-ups: return the segments themselves, process capacities as a stream, or answer how many stable segments lie inside a given range.

Write and test your solution herePython in your browser, the question's tests level by level, saved for you.Sign in to start coding