Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find length of longest sublist whose sum is 0 in Python
Suppose we have a list with only two values 1 and −1. We have to find the length of the longest sublist whose sum is 0.
So, if the input is like nums = [1, 1, −1, 1, 1, −1, 1, −1, 1, −1], then the output will be 8, as the longest sublist is [−1, 1, 1, −1, 1, −1, 1, −1] whose sum is 0.
Algorithm
To solve this, we will follow these steps −
Create an empty hash map to store cumulative sum positions
Initialize cumulative sum (cs) = 0 and max_diff = 0
-
For each element at index i:
Add nums[i] to cumulative sum
If cumulative sum is 0, update max_diff to max(i + 1, max_diff)
If cumulative sum exists in hash map, update max_diff
Otherwise, store the cumulative sum with its index
Return max_diff
How It Works
The key insight is that if two positions have the same cumulative sum, then the sublist between them has sum 0. We use a hash map to track the first occurrence of each cumulative sum value ?
Example
class Solution:
def solve(self, nums):
table = {}
cs = 0
max_diff = 0
for i in range(len(nums)):
cs += nums[i]
if cs == 0:
max_diff = max(i + 1, max_diff)
if cs in table:
max_diff = max(max_diff, i - table[cs])
else:
table[cs] = i
return max_diff
# Test the solution
ob = Solution()
nums = [1, 1, -1, 1, 1, -1, 1, -1, 1, -1]
result = ob.solve(nums)
print(f"Length of longest sublist with sum 0: {result}")
Length of longest sublist with sum 0: 8
Step-by-Step Trace
Let's trace through the algorithm with nums = [1, 1, −1, 1, 1, −1, 1, −1, 1, −1] ?
def solve_with_trace(nums):
table = {}
cs = 0
max_diff = 0
print("Index | Element | Cumulative Sum | Action")
print("------|---------|----------------|--------")
for i in range(len(nums)):
cs += nums[i]
action = ""
if cs == 0:
max_diff = max(i + 1, max_diff)
action = f"Sum=0, max_diff={max_diff}"
elif cs in table:
old_max = max_diff
max_diff = max(max_diff, i - table[cs])
action = f"Found at {table[cs]}, length={i - table[cs]}, max_diff={max_diff}"
else:
table[cs] = i
action = f"Store position {i}"
print(f"{i:5} | {nums[i]:7} | {cs:14} | {action}")
return max_diff
nums = [1, 1, -1, 1, 1, -1, 1, -1, 1, -1]
result = solve_with_trace(nums)
print(f"\nFinal result: {result}")
Index | Element | Cumulative Sum | Action
------|---------|----------------|--------
0 | 1 | 1 | Store position 0
1 | 1 | 2 | Store position 1
2 | -1 | 1 | Found at 0, length=2, max_diff=2
3 | 1 | 2 | Found at 1, length=2, max_diff=2
4 | 1 | 3 | Store position 4
5 | -1 | 2 | Found at 1, length=4, max_diff=4
6 | 1 | 3 | Found at 4, length=2, max_diff=4
7 | -1 | 2 | Found at 1, length=6, max_diff=6
8 | 1 | 3 | Found at 4, length=4, max_diff=6
9 | -1 | 2 | Found at 1, length=8, max_diff=8
Final result: 8
Alternative Approach
Here's a simpler function-based approach ?
def longest_zero_sum_sublist(nums):
"""Find length of longest sublist with sum 0"""
sum_positions = {}
cumulative_sum = 0
max_length = 0
for i, num in enumerate(nums):
cumulative_sum += num
# If cumulative sum is 0, sublist from start to current position has sum 0
if cumulative_sum == 0:
max_length = i + 1
# If we've seen this sum before, sublist between positions has sum 0
elif cumulative_sum in sum_positions:
length = i - sum_positions[cumulative_sum]
max_length = max(max_length, length)
# Store first occurrence of this cumulative sum
else:
sum_positions[cumulative_sum] = i
return max_length
# Test cases
test_cases = [
[1, 1, -1, 1, 1, -1, 1, -1, 1, -1],
[1, -1, 1, -1],
[1, 1, 1],
[-1, -1, -1]
]
for nums in test_cases:
result = longest_zero_sum_sublist(nums)
print(f"nums = {nums}")
print(f"Longest zero-sum sublist length: {result}\n")
nums = [1, 1, -1, 1, 1, -1, 1, -1, 1, -1] Longest zero-sum sublist length: 8 nums = [1, -1, 1, -1] Longest zero-sum sublist length: 4 nums = [1, 1, 1] Longest zero-sum sublist length: 0 nums = [-1, -1, -1] Longest zero-sum sublist length: 0
Conclusion
The algorithm uses cumulative sums and hash maps to efficiently find the longest zero-sum sublist in O(n) time. When two positions have the same cumulative sum, the sublist between them sums to zero.
