Count stable server segments
I was asked this
No reports yet. Sign in to say where you were asked it.
A row of n machines has integer capacities capacity[0..n-1]. A contiguous segment [l, r] is stable when all of these hold:
- It contains at least 3 machines (
r - l >= 2). - The two end machines have the same capacity:
capacity[l] == capacity[r]. - 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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
