Nested List Weight Sum II — LeetCode 364 Python Solution

MediumLeetCode PremiumStackDepth-First SearchBreadth-First Search
Problem
#364
Pattern
Stack
Reading time
10 min

The problem

You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists.

Example

Input
nestedList = [[1,1],2,[1,1]]
Output
8
Explanation
Four 1's with a weight of 1, one 2 with a weight of 2.

Python solution

Python
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
# class NestedInteger:
#    def __init__(self, value=None):
#        """
#        If value is not specified, initializes an empty list.
#        Otherwise initializes a single integer equal to value.
#        """
#
#    def isInteger(self):
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        :rtype bool
#        """
#
#    def add(self, elem):
#        """
#        Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
#        :rtype void
#        """
#
#    def setInteger(self, value):
#        """
#        Set this NestedInteger to hold a single integer equal to value.
#        :rtype void
#        """
#
#    def getInteger(self):
#        """
#        @return the single integer that this NestedInteger holds, if it holds a single integer
#        Return None if this NestedInteger holds a nested list
#        :rtype int
#        """
#
#    def getList(self):
#        """
#        @return the nested list that this NestedInteger holds, if it holds a nested list
#        Return None if this NestedInteger holds a single integer
#        :rtype List[NestedInteger]
#        """
class Solution:
    def depthSumInverse(self, nestedList: List[NestedInteger]) -> int:
        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)

        maxDepth = s = ws = 0
        for x in nestedList:
            dfs(x, 1)
        return (maxDepth + 1) * s - ws

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 364. Nested List Weight Sum II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 364. Nested List Weight Sum II?
LeetCode 364. Nested List Weight Sum II is rated Medium on LeetCode.
What is the time complexity of LeetCode 364. Nested List Weight Sum II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 364. Nested List Weight Sum II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 364. Nested List Weight Sum II cover?
LeetCode 364. Nested List Weight Sum II is tagged Stack, Depth-First Search and Breadth-First Search on LeetCode.
Is LeetCode 364. Nested List Weight Sum II a premium problem?
Yes. LeetCode 364. Nested List Weight Sum II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview