← Questions

Count stable server segments

0
Scale AICoding

A coding interview question asked at Scale AI. It tests arrays, prefix sums and hash map.

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.

Clarifying questions

  • With zeros, [0, 0, 0] is stable (ends 0, interior sum 0); confirm that counts.
  • Is the answer possibly larger than 2**31, so it needs a 64-bit count?
  • Do overlapping or nested stable segments each count separately?
  • Is n < 3 simply zero?

What a strong answer covers

  • Rewriting the condition with prefix sums P (P[i] = sum of the first i values): [l, r] is stable when capacity[l] == capacity[r] and P[r] - P[l + 1] == capacity[l].
  • Turning it into a pair lookup: each left end l contributes the key (capacity[l], P[l + 1] + capacity[l]), and each right end r asks for (capacity[r], P[r]).
  • One left-to-right pass with a hash map of key counts, adding the left end r - 2 just before handling r, which enforces the minimum length of 3. O(n) time and space.
  • Negative values and zeros work unchanged because the map matches exact sums, not a two-pointer window.
  • Tests: both examples, all zeros (every length-3+ segment), n < 3, negatives, and a brute-force O(n^3) check on random small arrays.

Follow-ups

  • Return the segments themselves, and what that costs when there are many.
  • Process capacities as a stream, answering the count so far after each one.
  • Answer how many stable segments lie inside a range [a, b] for many queries.
  • Relax the rule: interior sum within ±d of the end value.

Where it's asked

What it tests

arrays · prefix sums · hash map

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