Count Subarrays with Zero Sum
Problem Statement
You are given an array of integers arr. The numbers can be positive, negative or zero.
Count how many contiguous, non-empty subarrays add up to exactly 0.
Write long long findSubarray(vector<int>& arr) that returns this count. Two subarrays are different if they start or end at a different index, even if they hold the same values.
An integer array arr of length n. Values may be negative.
The number of non-empty contiguous subarrays whose sum is 0 (as a 64-bit integer).
The zero-sum subarrays are [0] (index 0), [0] (index 1), [0, 0] (0..1), [0] (index 4), [0] (index 5) and [0, 0] (4..5).
They are [-1, -3, 4] (1..3), [-2, 2] (4..5), [-1, -3, 4, -2, 2] (1..5) and [-2, 2, 4, 6, -12] (4..8).
The single element is a subarray with sum 0.
- • 1 ≤ n ≤ 10^6
- • −10^9 ≤ arr[i] ≤ 10^9
- • Prefix sums and the count can both exceed the int range — use 64-bit types.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Fix each start, grow the end with a running sum, count every sum of 0
count += how many earlier prefixes have the same total; seed seen[0] = 1
For every start, walk the end to the right while keeping a running sum of arr[start..end]. Each time the sum is 0, add one to the count.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Prefix Sum translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.