Nested List Weight Sum

Updated on 27 June, 2025
Nested List Weight Sum header image

Problem Statement

In this task, you are provided with a nestedList which consists of integers and potentially further nested lists of integers. The challenge requires you to compute the sum of all integers within the list, but with a twist: each integer should be multiplied by its depth within the nested structure. The depth of an integer is determined by the number of layers of lists enclosing it. For instance, an integer located directly within the main list has a depth of 1, while one inside a sublist of that main list has a depth of 2, and so on down the various layers.

Your goal is to devise a method to traverse the nestedList, calculating the depth of each integer and then summing up each integer multiplied by its depth value.

Examples

Example 1

Input:

nestedList = [[1,1],2,[1,1]]

Output:

10

Explanation:

Four 1's at depth 2, one 2 at depth 1. 1*2 + 1*2 + 2*1 + 1*2 + 1*2 = 10.

Example 2

Input:

nestedList = [1,[4,[6]]]

Output:

27

Explanation:

One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3. 1*1 + 4*2 + 6*3 = 27.

Example 3

Input:

nestedList = [0]

Output:

0

Constraints

  • 1 <= nestedList.length <= 50
  • The values of the integers in the nested list is in the range [-100, 100].
  • The maximum depth of any integer is less than or equal to 50.

Approach and Intuition

The task is to uniquely process a nested data structure which isn't just a straightforward iteration over list items. Given that each integer can potentially be nested within multiple layers of lists, a recursive or a stack-based approach are sensible methods to address this problem. Here's a detailed breakdown of the strategy:

  1. Initiate a recursive function to handle the nested nature of the list:

    • The function should accept the current nested item and depth as parameters. The depth parameter helps keep track of the level of nesting.
  2. For each element in the nestedList:

    • If it is an integer, calculate its contribution to the sum as integer_value * depth.
    • If it is a nested list, recursively call the function for that sublist and increase the depth by 1.
  3. Accumulate the results computed for all integers and return the total sum.

Illustrations based on examples:

  • Example 1: nestedList = [[1,1],2,[1,1]]

    • The list contains multiple sublists of varying depths.
    • Calculating: (1*2 + 1*2) + (2*1) + (1*2 + 1*2) = 10
  • Example 2: nestedList = [1,[4,[6]]]

    • Here, the list has three levels of depth.
    • Calculating: (1*1) + (4*2) + (6*3) = 27

In practice, either a depth-first search using recursion or explicit stack management is used to solve the problem effectively within the given constraints. This type of structured traversal ensures each element is processed correctly according to its depth in the list hierarchy.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int calculateDepthSum(vector<NestedInteger>& nestedList) {
        queue<NestedInteger> elementsQueue;
        for (NestedInteger item : nestedList) {
            elementsQueue.push(item);
        }

        int currentDepth = 1;
        int accumulatedSum = 0;

        while (!elementsQueue.empty()) {
            size_t queueLength = elementsQueue.size();
            for (size_t index = 0; index < queueLength; index++) {
                NestedInteger currentItem = elementsQueue.front();
                elementsQueue.pop();
                if (currentItem.isInteger()) {
                    accumulatedSum += currentItem.getInteger() * currentDepth;
                } else {
                    for (NestedInteger deeperItem : currentItem.getList()) {
                        elementsQueue.push(deeperItem);
                    }
                }
            }
            currentDepth++;
        }
        return accumulatedSum;
    }
};

The provided C++ solution calculates the sum of a nested list where each integer is multiplied by its depth level. A class Solution is defined, which includes the calculateDepthSum function to compute this deep sum. Here's a breakdown of the approach:

  • A queue of type NestedInteger is used to store the elements of the nested list and handle them in a first-in, first-out manner. This supports depth-wise traversal.

  • Initiate looping over the entire nestedList provided and each element is pushed to the queue.

  • Initialize variables currentDepth to track the current depth of integers, and accumulatedSum to store the result.

  • Use a while loop to process elements in the queue until it's empty. Inside this loop:

    • Determine the current size of the queue.

    • For each element at the current depth, dequeued elements are either directly added to the accumulatedSum if they are integers (multiplied by their depth), or their list items are added back to the queue if they aren't simple integers, for further processing in subsequent depths.

  • Increment currentDepth with each complete iteration over one depth of integers.

  • Finally, the function returns the accumulatedSum which is the total sum calculated based on the weighted depth criteria.

The solution effectively handles various nested structures by using a queue mechanism, ensuring every integer at each depth level is processed and appropriately multiplied by its depth, and accumulates the results.

java
class Solution {
    public int sumOfDepths(List<NestedInteger> nestedList) {
        Queue<NestedInteger> processingQueue = new LinkedList<>();
        processingQueue.addAll(nestedList);

        int currentDepth = 1;
        int accumulatedSum = 0;

        while (!processingQueue.isEmpty()) {
            int levelSize = processingQueue.size();
            for (int index = 0; index < levelSize; index++) {
                NestedInteger currentItem = processingQueue.poll();
                if (currentItem.isInteger()) {
                    accumulatedSum += currentItem.getInteger() * currentDepth;
                } else {
                    processingQueue.addAll(currentItem.getList());
                }
            }
            currentDepth++;
        }
        return accumulatedSum;
    }
}

The given solution in Java addresses the problem where the objective is to calculate the weight sum of a list of nested integers. Each integer is multiplied by its depth in the list to get its weighted sum, and the overall output is the cumulative sum of these weighted values.

The process involves utilizing a FIFO queue to manage the nested elements and exploring them level by level (similar to a Breadth-First Search technique on trees):

  • Initially, all elements from the input list are added to a queue.
  • The algorithm enters a loop that processes elements until the queue is empty.
  • During each iteration:
    • The size of the current level (i.e., the number of elements at a certain depth) is determined.
    • For each element at this level, if it's an integer, the product of this integer and its depth is added to the cumulative sum.
    • If the element is a list of nested integers, these nested integers are added to the queue for further processing.
    • After processing all elements at the current depth, the depth counter is incremented.
  • After the loop, the cumulative sum, which now holds the weighted sum of all integers, is returned as the result.

This approach ensures that all nested integers are processed accurately according to their depth, without missing any nested structures. Additionally, the usage of a queue helps in managing the breadth-first traversal effectively, ensuring every node and nested list is processed fully.

python
class Solution:
    def nestedIntegerWeightSum(self, nestedIntegers: List[NestedInteger]) -> int:
        bfsQueue = deque(nestedIntegers)

        level = 1
        sumWeights = 0

        while bfsQueue:
            for _ in range(len(bfsQueue)):
                current = bfsQueue.pop()
                if current.isInteger():
                    sumWeights += current.getInteger() * level
                else:
                    bfsQueue.extendleft(current.getList())
            level += 1

        return sumWeights

This solution provides a method to calculate the weighted sum of a nested list, where each integer is multiplied by its depth level. The provided code defines a function nestedIntegerWeightSum within a Solution class, which accepts a list of NestedInteger objects.

The approach utilizes a breadth-first search (BFS) technique to traverse the nested list:

  • Initialize a deque bfsQueue with the list of nested integers.
  • Set the initial level to 1 and initialize sumWeights to hold the resulting weighted sum.
  • While there are items in the queue:
    • Iterate over each item in the queue:
      • If an item is an integer, compute its weighted value by multiplying it by the current level and add the result to sumWeights.
      • If an item is a nested list, extend the deque with the items from this list.
    • Increment the level after processing all items at the current level.
  • Return the computed sumWeights.

This algorithm efficiently handles the nested structures by ensuring each integer's depth reflects correctly in its weighted sum, updating and processing levels iteratively from shallow to deep. The use of deque facilitates efficient operations for both accessing and adding new items.

Comments

No comments yet.