AI News Hub Logo

AI News Hub

Largest Subarray with 0 sum

DEV Community
we_are_broken_compilers

Problem Statement Given an array of integers, find the maximum length of a subarray whose sum is 0. Example Input: Output: The longest subarray with sum 0 is: The first idea that comes to mind is: Fix a starting index i Keep adding elements till index j Check if the sum becomes 0 Track the maximum length class Solution { int maxLength(int arr[]) { int maxLen = 0; for (int i = 0; i map = new HashMap<>(); map.put(0, -1); // to handle subarray starting from index 0 int sum = 0; int maxLen = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; if (map.containsKey(sum)) { maxLen = Math.max(maxLen, i - map.get(sum)); } else { map.put(sum, i); } } return maxLen; } } Why do we store (0, -1) initially? This handles the edge case when the subarray starts from index 0. Example: arr = [1, -1] So -1 represents a virtual index before the array starts. Time Complexity :O(n) Space Complexity : O(n) So this is all about this problem If you found this solution even a bit worst Please make sure to hit like button and also share it your coding fellows