Given a nested list of integers, each element is either an integer or a nested list. The depth of an integer is the number of lists it's nested within. The weight of an integer is maxDepth - depth + 1
, where maxDepth
is the maximum depth of any integer in the nested list. The problem asks to calculate the sum of each integer multiplied by its weight.
This solution uses a Depth-First Search (DFS) approach to traverse the nested list. It leverages the observation that the final weighted sum can be calculated efficiently using the total sum of integers (s
) and the weighted sum of integers (ws
), where the weight is the depth.
The algorithm works as follows:
Initialization: Initialize maxDepth
, s
(sum of integers), and ws
(weighted sum of integers) to 0.
DFS Function (dfs
): This recursive function takes a NestedInteger
element x
and its current depth d
as input.
maxDepth
to track the maximum depth encountered.x
is an integer, it adds x
to s
and adds x * d
to ws
.x
is a nested list, it recursively calls dfs
on each element of the list, incrementing the depth d
.Main Loop: Iterate through the input nestedList
. For each element, call dfs
with an initial depth of 1.
Result Calculation: After traversing the entire list, the weighted sum is calculated as (maxDepth + 1) * s - ws
.
class Solution:
def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
maxDepth = s = ws = 0
def dfs(x, d):
nonlocal maxDepth, s, ws
maxDepth = max(maxDepth, d)
if x.isInteger():
s += x.getInteger()
ws += x.getInteger() * d
else:
for y in x.getList():
dfs(y, d + 1)
for x in nestedList:
dfs(x, 1)
return (maxDepth + 1) * s - ws
The same algorithm can be implemented in other languages like Java, C++, JavaScript, and Go with minor syntactic changes. The core logic remains consistent across all languages. (See the provided solution for examples in these languages).