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
Nested List Weight Sum II in Python
The Nested List Weight Sum II problem calculates the weighted sum of integers in a nested list structure, where weights increase from bottom to top. Unlike the regular version where deeper elements have higher weights, here the deepest elements have weight 1, and shallower elements have progressively higher weights.
For example, given [[1,1],2,[1,1]], the structure has:
Four 1's at depth 2 (weight 1 each) = 4 × 1 = 4
One 2 at depth 1 (weight 2) = 1 × 2 = 2
Total sum = 4 + 2 = 6
Algorithm Steps
The solution follows these key steps:
Flatten the nested structure while tracking depth
Find the maximum depth in the structure
Calculate weights as
(max_depth + 1 - current_depth)Sum all weighted values
Implementation
class Solution:
def depthSumInverse(self, nestedList):
flats = []
self.maxd = 0
def flatten(nlst, dist):
if isinstance(nlst, list):
dist += 1
self.maxd = max(self.maxd, dist)
for node in nlst:
if isinstance(node, int):
flats.append((node, dist))
else:
flatten(node, dist)
flatten(nestedList, 0)
summ = 0
for v, d in flats:
summ += v * (self.maxd + 1 - d)
return summ
# Example usage
ob = Solution()
result = ob.depthSumInverse([[1,1],2,[1,1]])
print(f"Input: [[1,1],2,[1,1]]")
print(f"Output: {result}")
Input: [[1,1],2,[1,1]] Output: 8
How It Works
The algorithm works by:
Flattening: The
flatten()function recursively traverses the nested structure, storing each integer with its depthWeight Calculation: For each integer at depth
d, the weight becomesmax_depth + 1 - dSummation: Each value is multiplied by its calculated weight and added to the total
Step-by-Step Example
For input [[1,1],2,[1,1]]:
# Visualization of the process
nested_list = [[1,1],2,[1,1]]
# After flattening with depths:
# flats = [(1,2), (1,2), (2,1), (1,2), (1,2)]
# maxd = 2
# Weight calculation:
# For integers at depth 2: weight = 2+1-2 = 1
# For integers at depth 1: weight = 2+1-1 = 2
# Final calculation:
# 1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 1+1+4+1+1 = 8
solution = Solution()
flats = []
solution.maxd = 0
def debug_flatten(nlst, dist, indent=""):
if isinstance(nlst, list):
dist += 1
solution.maxd = max(solution.maxd, dist)
print(f"{indent}Depth {dist}: {nlst}")
for node in nlst:
if isinstance(node, int):
flats.append((node, dist))
print(f"{indent} Integer {node} at depth {dist}")
else:
debug_flatten(node, dist, indent + " ")
debug_flatten(nested_list, 0)
print(f"\nMax depth: {solution.maxd}")
print(f"Flattened: {flats}")
total = sum(v * (solution.maxd + 1 - d) for v, d in flats)
print(f"Weighted sum: {total}")
Depth 1: [[1, 1], 2, [1, 1]]
Depth 2: [1, 1]
Integer 1 at depth 2
Integer 1 at depth 2
Integer 2 at depth 1
Depth 2: [1, 1]
Integer 1 at depth 2
Integer 1 at depth 2
Max depth: 2
Flattened: [(1, 2), (1, 2), (2, 1), (1, 2), (1, 2)]
Weighted sum: 8
Conclusion
The Nested List Weight Sum II uses recursive traversal to flatten the structure while tracking depths, then applies inverse weighting where deeper elements have smaller weights. This approach efficiently handles arbitrary nesting levels with O(n) time complexity.
