Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the largest zero-sum subarray

Find the length of the longest contiguous subarray whose elements sum to zero using prefix sums and a map.

Python practice30 minHashing & SetsAdvancedLast updated March 26, 2026

Problem statement

Given an integer array arr, return the length of the longest contiguous subarray whose sum is 0. Implement an O(n) approach using a dictionary that maps prefix sums to their earliest index.

Task

Use prefix sums and a hash map to locate repeated prefix sums and compute the maximum zero-sum subarray length in O(n).

Examples

Zero-sum at the start

Input

arr = [1, -1, 3, -3, 5]

Output

4

Prefix sum becomes 0 at index 3, so subarray from index 0 to 3 has sum 0 and length 4.

Input format

Function input: largest_zero_sum_subarray(arr) where arr is a list of integers.

Output format

Return an integer: the length of the longest contiguous subarray with sum zero. Return 0 if none exist.

Constraints

0 <= len(arr) <= 10^5, elements between -10^9 and 10^9. Aim for O(n) time and O(n) space.

Samples

Sample 1

Input

arr = [1, 2, -3, 3]

Output

3

Subarray [1,2,-3] sums to 0 and has length 3.