Given a nested list of integers, return the sum of all integers in the list weighted by their depth. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.
So, if the input is like [[1,1],2,[1,1]], then the output will be 8, as four 1's at depth 1, one 2 at depth 2.
To solve this, we will follow these steps −
Define a function depthSumInverse() . This will take nestedList
flats:= a new list
maxd:= 0
Define a function flatten() . This will take nlst,dist
dist := dist + 1
maxd:= maximum of maxd, dist
for each node in nlst, do
if node is an integer is non-zero, then
insert (node,dist) at the end of flats
otherwise,
flatten(node, dist)
flatten(nestedList, 0)
summ:= 0
for each v,d in flats, do
summ := summ + v*(maxd+1-d)
return summ
Example
Let us see the following implementation to get a better understanding −
class Solution(object): def depthSumInverse(self, nestedList): flats=[] self.maxd=0 def flatten(nlst,dist): if isinstance(nlst,list): nlst=nlst 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 ob = Solution() print(ob.depthSumInverse([[1,1],2,[1,1]]))
Input
[[1,1],2,[1,1]]
Output
8