1. Check All Subarrays (Brute Force)
Intuition
Iterate with two nested loops: start from 0 to n-1, end from start to n-1. Accumulate elements in currentSum. If currentSum == 0, maxLen = max(maxLen, end - start + 1).
When to apply: Use to understand the baseline search for zero-sum windows.
Brute Force Zero-Sum Subarray Trace
2 of 2 questions left todayArray: [15, -2, 2, -8, 1, 7, 10, 23]
Array: [15, -2, 2, -8, 1, 7, 10, 23]. Initialize maxLen = 0. start = 0.
public class Main { public static class Solution { public int maxLen(int[] arr) { int maxLen = 0; for (int i = 0; i < arr.length; i++) { int sum = 0; for (int j = i; j < arr.length; j++) { sum += arr[j]; if (sum == 0) { maxLen = Math.max(maxLen, j - i + 1); } } } return maxLen; } } public static void main(String[] args) { Solution sol = new Solution(); int[] arr = {15, -2, 2, -8, 1, 7, 10, 23}; System.out.println("Max length: " + sol.maxLen(arr)); }}Time & Space Complexity
- Time complexity:
O(n^2)— Nested loops test all n*(n+1)/2 subarrays. - Space complexity:
O(1)— Only scalar max length tracker is maintained.
Why Brute Force Doesn't Scale:
For N = 100,000, N2 requires 10 billion operations.
Prefix sum hash map does 1 single pass with 100,000 lookups, completing in milliseconds.