Standard Bar Sliding Window · Medium Problems O(n) · O(n)
A datacenter logs rack activations as 1s and idle slots as 0s across a duty cycle. Facilities wants to know how many contiguous stretches of the cycle drew exactly a target amount of power. Each stretch is identified by its start and end position, so identical stretches at different positions count separately.
Input: A binary array nums and an integer goal.
Output: Return the number of non-empty contiguous subarrays whose elements sum to goal.
1 <= nums.length <= 3 * 10^4nums[i] is 0 or 10 <= goal <= nums.lengthInput: {"nums":[1,0,1,0,1],"goal":2}
Output: 4
The qualifying stretches are [1,0,1], [1,0,1,0], [0,1,0,1] and [1,0,1] again at a later start.
Input: {"nums":[0,0,0,0,0],"goal":0}
Output: 15
Every one of the 15 contiguous stretches sums to zero.