Largest Subarray with 0 Sum
Hard Problems: N-Sum & Hashing DSA practice problem on Onlearn.
Difficulty: medium.
Topics: Finding the Length of the Longest Subarray with Sum Zero in an Array of Integers, Arrays, Subarray, Prefix Sum, Hash Tables, Time Complexity, Space Complexity, Big O Notation, Loops, complexity analysis, brute force, subarray, prefix sum, hash map.
Problem Statement: Given an array containing both positive and negative integers, find the length of the longest subarray whose sum of all elements is equal to zero. Input Format: The first line contains an integer N, the size of the array. The second line contains N space separated integers representing the elements of the array. Output Format: Print a single integer representing the length of the longest subarray with a sum of zero. If no such subarray exists, print 0. Examples: Example 1: Input: 6 9 3 3 1 6 5 Result: 5 Explanation: The following subarrays sum to zero: { 3, 3} (length 2) { 1, 6, 5} (length 3) { 3, 3, 1, 6, 5} (length 5) Since we require the length of the longest subarray, the answer is 5! Example 2: Input: 8 6 2 2 8 1 7 4 10 Result: 8 Explanation: Subarrays with sum 0: { 2, 2} (length 2) { 8, 1, 7} (length 3) { 2, 2, 8, 1, 7} (length 5) {6, 2, 2, 8, 1, 7, 4, 10} (length 8) Length of longest subarray = 8 Example 3: Input: 3 1 0 5 Result: 1 Explanation: Subarray: {0} (length 1) Length of longest subarray = 1 Example 4: Input: 5 1 3 5 6 2 Result: 0 Explanation: There is no subarray that sums to zero.