Prefix sum · Medium
A ledger records signed adjustments over time. An analyst wants the number of continuous periods whose net adjustment is divisible by a batch size. Negative changes and repeated zero balances are valid and must not be discarded.
Count all non-empty contiguous segments whose sum is evenly divisible by the positive divisor.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], divisor: integer }
Fields
- nums is an array of signed integers. Repeated values at different positions are separate entries.
- divisor is a positive integer. A sum of zero is divisible by every allowed divisor.
Output
Return value
- Return the count of index ranges, not the number of distinct sums.
- Negative divisible sums count. Empty input returns 0.
Constraints
- 0 <= nums.length <= 100000; -1000000000 <= nums[i] <= 1000000000.
- All totals and counts fit exactly in a safe JSON integer.
- 1 <= divisor <= 1000000000.
Examples
Example 1
{
"divisor": 3,
"nums": [
-1,
2,
4
]
}Returns
1Example 2
{
"divisor": 5,
"nums": [
0,
0
]
}Returns
3Required complexity
O(n) expected time and O(min(n + 1, divisor)) auxiliary space