Maintain a running prefix sum and a hash map of prefix sum frequencies:
Initialize: , , hash map with (empty prefix).
For each element, add it to .
Add to (number of valid subarrays ending here).
Increment by .
Return . The hash map tracks "how many times has each prefix sum occurred?" Time: . Space: .