⬅ Previous Topic
4 Sum ProblemNext Topic ⮕
Find Maximum Product Subarray⬅ Previous Topic
4 Sum ProblemNext Topic ⮕
Find Maximum Product SubarrayTopic Contents
Given an array of integers (which may contain both positive and negative numbers), your task is to find the length of the longest contiguous subarray whose elements sum up to 0.
0
.arr
of size n
.max_len = 0
and prefix_sum = 0
.prefix_sum
.prefix_sum == 0
, update max_len = current index + 1
.prefix_sum
already exists in the map, update max_len
as the maximum of current max_len
and current index - first occurrence index
.prefix_sum
with the current index in the map.max_len
.def max_len_zero_sum_subarray(arr):
prefix_sum = 0
max_len = 0
prefix_map = {}
for i, num in enumerate(arr):
prefix_sum += num
if prefix_sum == 0:
max_len = i + 1
elif prefix_sum in prefix_map:
max_len = max(max_len, i - prefix_map[prefix_sum])
else:
prefix_map[prefix_sum] = i
return max_len
# Sample Input
arr = [15, -2, 2, -8, 1, 7, 10, 23]
print("Length of Largest Subarray with 0 Sum:", max_len_zero_sum_subarray(arr))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | In the best case, we traverse the array once and find subarrays summing to 0 early, updating the maximum length efficiently. |
Average Case | O(n) | The algorithm runs in linear time by computing the prefix sum and checking/recording it in the hash map in constant time for each element. |
Worst Case | O(n) | Even in the worst case, we perform a single pass through the array, and all hash map operations (insertion, lookup) are constant time on average. |
O(n)
Explanation: In the worst case, all prefix sums may be unique, requiring storage of each sum and its index in the hash map.
⬅ Previous Topic
4 Sum ProblemNext Topic ⮕
Find Maximum Product SubarrayYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.