Count stable server segments
I was asked this
No reports yet. Sign in to say where you were asked it.
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:
- 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.
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 < 3simply zero?
What a strong answer covers
- Rewriting the condition with prefix sums
P(P[i]= sum of the firstivalues):[l, r]is stable whencapacity[l] == capacity[r]andP[r] - P[l + 1] == capacity[l]. - Turning it into a pair lookup: each left end
lcontributes the key(capacity[l], P[l + 1] + capacity[l]), and each right endrasks for(capacity[r], P[r]). - One left-to-right pass with a hash map of key counts, adding the left end
r - 2just before handlingr, 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-forceO(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
±dof the end value.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
