KatInterview

364. Nested List Weight Sum II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for a weighted sum of all integers in a nested list structure. The weight is defined as maxDepth - depth + 1, where depth is the nesting level of an integer and maxDepth is the maximum depth of any integer in the list. This weighting scheme is the inverse of the one in "Nested List Weight Sum I", where integers at deeper levels have higher weights. Here, integers closer to the root (shallower depth) have higher weights.

Solution

Nested List Weight Sum II in 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:
        total_sum = 0
        unweighted_sum = 0
        current_level = nestedList

        # BFS level by level
        while current_level:
            next_level = []
            # Process all elements in the current level
            for ni in current_level:
                if ni.isInteger():
                    # If it's an integer, add its value to the unweighted sum
                    unweighted_sum += ni.getInteger()
                else:
                    # If it's a list, collect its elements for the next level
                    next_level.extend(ni.getList())
            
            # Add the sum of integers from all levels processed so far to the total sum
            total_sum += unweighted_sum
            # Move to the next level
            current_level = next_level

        return total_sum

Nested List Weight Sum II in Java

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *     // Constructor initializes an empty nested list.
 *     public NestedInteger();
 *
 *     // Constructor initializes a single integer.
 *     public NestedInteger(int value);
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // Set this NestedInteger to hold a single integer.
 *     public void setInteger(int value);
 *
 *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
 *     public void add(NestedInteger ni);
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return empty list if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
class Solution {
    public int depthSumInverse(List<NestedInteger> nestedList) {
        int totalSum = 0;
        int unweightedSum = 0;
        List<NestedInteger> currentLevel = nestedList;

        // BFS level by level
        while (!currentLevel.isEmpty()) {
            List<NestedInteger> nextLevel = new ArrayList<>();
            // Process all elements in the current level
            for (NestedInteger ni : currentLevel) {
                if (ni.isInteger()) {
                    // If it's an integer, add its value to the unweighted sum
                    unweightedSum += ni.getInteger();
                } else {
                    // If it's a list, collect its elements for the next level
                    nextLevel.addAll(ni.getList());
                }
            }
            // Add the sum of integers from all levels processed so far to the total sum
            totalSum += unweightedSum;
            // Move to the next level
            currentLevel = nextLevel;
        }

        return totalSum;
    }
}

Nested List Weight Sum II in C++

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class NestedInteger {
 *   public:
 *     // Constructor initializes an empty nested list.
 *     NestedInteger();
 *
 *     // Constructor initializes a single integer.
 *     NestedInteger(int value);
 *
 *     // Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     bool isInteger() const;
 *
 *     // Return the single integer that this NestedInteger holds, if it holds a single integer
 *     // The result is undefined if this NestedInteger holds a nested list
 *     int getInteger() const;
 *
 *     // Set this NestedInteger to hold a single integer.
 *     void setInteger(int value);
 *
 *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
 *     void add(const NestedInteger &ni);
 *
 *     // Return the nested list that this NestedInteger holds, if it holds a nested list
 *     // The result is undefined if this NestedInteger holds a single integer
 *     const vector<NestedInteger> &getList() const;
 * };
 */
class Solution {
public:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int totalSum = 0;
        int unweightedSum = 0;
        vector<NestedInteger> currentLevel = nestedList;

        // BFS level by level
        while (!currentLevel.empty()) {
            vector<NestedInteger> nextLevel;
            // Process all elements in the current level
            for (const auto& ni : currentLevel) {
                if (ni.isInteger()) {
                    // If it's an integer, add its value to the unweighted sum for this level
                    unweightedSum += ni.getInteger();
                } else {
                    // If it's a list, collect its elements for the next level
                    const auto& subList = ni.getList();
                    nextLevel.insert(nextLevel.end(), subList.begin(), subList.end());
                }
            }
            // Add the sum of integers from all levels processed so far to the total sum
            totalSum += unweightedSum;
            // Move to the next level
            currentLevel = move(nextLevel);
        }

        return totalSum;
    }
};

Nested List Weight Sum II in TypeScript

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * class NestedInteger {
 *     If value is provided, then it holds a single integer
 *     Otherwise it holds an empty nested list
 *     constructor(value?: number) {
 *         ...
 *     };
 *
 *     Return true if this NestedInteger holds a single integer, rather than a nested list.
 *     isInteger(): boolean {
 *         ...
 *     };
 *
 *     Return the single integer that this NestedInteger holds, if it holds a single integer
 *     Return null if this NestedInteger holds a nested list
 *     getInteger(): number | null {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a single integer equal to value.
 *     setInteger(value: number) {
 *         ...
 *     };
 *
 *     Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
 *     add(elem: NestedInteger) {
 *         ...
 *     };
 *
 *     Return the nested list that this NestedInteger holds,
 *     or an empty list if this NestedInteger holds a single integer
 *     getList(): NestedInteger[] {
 *         ...
 *     };
 * };
 */

function depthSumInverse(nestedList: NestedInteger[]): number {
    let totalSum = 0;
    let unweightedSum = 0;
    let currentLevel = nestedList;

    // BFS level by level
    while (currentLevel.length > 0) {
        const nextLevel: NestedInteger[] = [];
        // Process all elements in the current level
        for (const ni of currentLevel) {
            if (ni.isInteger()) {
                // If it's an integer, add its value to the unweighted sum
                unweightedSum += ni.getInteger()!;
            } else {
                // If it's a list, collect its elements for the next level
                nextLevel.push(...ni.getList());
            }
        }
        // Add the sum of integers from all levels processed so far to the total sum
        totalSum += unweightedSum;
        // Move to the next level
        currentLevel = nextLevel;
    }

    return totalSum;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.