← DiffPush

Binary Subarrays With Sum

Standard Bar Sliding Window · Medium Problems O(n) · O(n)

The Server Room Power Ledger

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.

Constraints

Examples

Example 1

Input: {"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.

Example 2

Input: {"nums":[0,0,0,0,0],"goal":0}
Output: 15
Every one of the 15 contiguous stretches sums to zero.

Solve this in your browser →

Also on LeetCode ↗