Here's the observation. If , then the subarray from to sums to . Rearrange: . So for each position , you need to count how many earlier prefix sums equal . Use a HashMap to store prefix sum frequencies. As you iterate:
Check if exists in the map. Add that count to your answer.
Add current to the map. One pass. time, space. This pattern appears in many problems.