To solve this problem, we need to find the length of the longest subarray with a sum of zero. The optimal approach involves using a hash map (dictionary) to track the first occurrence of each prefix sum, which allows us to efficiently determine the longest subarray with a sum of zero.
Approach
- Prefix Sum Concept: The prefix sum up to an index
iis the sum of all elements from the start of the array to indexi. If the prefix sum at indexj(wherej > i) is the same as the prefix sum at indexi, the subarray fromi+1tojhas a sum of zero. - Hash Map Usage: We use a hash map to store the first occurrence of each prefix sum. This helps in calculating the length of the subarray with a sum of zero by subtracting the first occurrence index from the current index.
- Initialization: We start with a prefix sum of
0at index-1to handle cases where the subarray starts from the beginning of the array (sum of elements from index0toiis zero).
Solution Code
def longest_zero_sum_subarray(arr):
prefix_sum = 0
max_length = 0
sum_index_map = {0: -1} # Maps prefix sum to its first occurrence index
for i in range(len(arr)):
prefix_sum += arr[i]
if prefix_sum in sum_index_map:
# Calculate the length of the subarray with sum zero
current_length = i - sum_index_map[prefix_sum]
if current_length > max_length:
max_length = current_length
else:
# Store the first occurrence of this prefix sum
sum_index_map[prefix_sum] = i
return max_length
Explanation
- Initialization: We initialize
prefix_sumto0andmax_lengthto0(since the minimum length of a subarray with sum zero is0if no such subarray exists). Thesum_index_mapstarts with{0: -1}to handle subarrays starting from index0. - Iterate Through Array: For each element in the array, we update the
prefix_sumby adding the current element. - Check Prefix Sum: If the
prefix_sumis already in the map, we calculate the length of the subarray from the first occurrence index to the current index. If this length is greater thanmax_length, we updatemax_length. - Store New Prefix Sum: If the
prefix_sumis not in the map, we store it with the current index (since we want the first occurrence).
Key Points
- Time Complexity: O(n) (we traverse the array once, and each hash map operation is O(1)).
- Space Complexity: O(n) (in the worst case, all prefix sums are unique, so the hash map stores
n+1entries).
This approach efficiently finds the longest subarray with a sum of zero using prefix sums and a hash map, making it optimal for large input sizes.
Example Test Cases:
- Input:
[1, 2, -3, 3]→ Output:3(subarray[1,2,-3]). - Input:
[0,0,0]→ Output:3(entire array). - Input:
[1,-1,2,-2]→ Output:4(entire array). - Input:
[5]→ Output:0(no subarray with sum zero). - Input:
[0]→ Output:1(single element zero).
All these test cases are handled correctly by the solution.


作者声明:本文包含人工智能生成内容。