Contiguous subarrays with sum k

Write codeMedium16 min

Your task

A water tank logs one signed flow value per minute: positive means water in, negative means water out. An auditor wants to know how many contiguous stretches of minutes had a net flow of exactly k liters. Count every such stretch (non-empty, any length, any starting minute). Flows and k may be zero or negative, so stretches can overlap and shorter stretches inside longer ones count separately. Example: flows = [2, -2, 2, -2], k = 0 gives 4.

Examples

count_net_stretches(flows: list[int], k: int) -> int
Example 1
Inputcount_net_stretches([2, -2, 2, -2], 0)
Output4