Leetcode 364. Nested List Weight Sum II

Problem Explanation

In this problem, you are given a nested list of integers and required to calculate the weighted sum, where the weights are determined by the depth of the integers in the structure. However, the weights are assigned in a bottom-up manner, meaning that the leaf level elements (at the lowest depth) gets the weight of 1, whereas the elements at the root level (with no nested lists inside it) gets the highest weight.

Let's walk through an example to understand it better. Consider the example - [1,[4,[6]]]. Here, 6 is a leaf level element at depth 1, 4 is at depth 2 and 1 is at the root level at a depth of 3. The weighted sum would therefore be calculated as 13 + 42 + 6*1 = 17.

To solve this problem, we'll be using a Breadth-First Search Algorithm (BFS). BFS algorithm traverses the list in a level by level manner where each level corresponds to the depth of the integers. We'll take the level by level sum of integer values, while also keep adding the previous levels' sum to the current level's sum, and append the result each time to our final answer.

To visualize this, for the above example:

First, the queue would fetch 1 with a sum of 1.

Then it would fetch [4,[6]] with a sum of 5 (4 + previous sum of 1 = 5)

Lastly, it would fetch 6 as the last leaf. Now, the sum grows to 11 (6 + previous sum of 5 = 11)

As you see, at each level, we have been adding the previous sum to the current sum and this will help us in calculating the weighted sum eventually.

Python Solution

1
2python
3class Solution(object):
4    def depthSumInverse(self, nestedList):
5        result, prevSum = 0, 0
6        while nestedList:
7            nextNestedList = []
8            for i in nestedList:
9                if isinstance(i, int):
10                    prevSum += i
11                else:
12                    for j in i:
13                        nextNestedList.append(j)
14            result += prevSum
15            nestedList = nextNestedList
16        return result

Java Solution

1
2java
3public class Solution {
4    public int depthSumInverse(List<NestedInteger> nestedList) {
5        int unweighted = 0, weighted = 0;
6        while (!nestedList.isEmpty()) {
7            List<NestedInteger> nextLevel = new ArrayList<>();
8            for (NestedInteger ni : nestedList) {
9                if (ni.isInteger())
10                    unweighted += ni.getInteger();
11                else
12                    nextLevel.addAll(ni.getList());
13            }
14            weighted += unweighted;
15            nestedList = nextLevel;
16        }
17        return weighted;
18    }
19}

C++ Solution

1
2c++
3class Solution {
4public:
5    int depthSumInverse(vector<NestedInteger>& nestedList) {
6        int res = 0, previousSum = 0;
7        while (!nestedList.empty()) {
8            int sz = nestedList.size();
9            vector<NestedInteger> tmp;
10            for (int i = 0; i < sz; ++i) {
11                if (nestedList[i].isInteger()) {
12                    previousSum += nestedList[i].getInteger();
13                } else {
14                    for (auto a : nestedList[i].getList()) {
15                        tmp.push_back(a);
16                    }
17                }
18            }
19            nestedList = tmp;
20            res += previousSum;
21        }
22        return res;
23    }
24};

JavaScript Solution

1
2javascript
3var depthSumInverse = function(nestedList) {
4  let unweighted = 0, weighted = 0, nlist;
5
6  while(nestedList.length){
7    nlist = [];
8    for(let ni of nestedList){
9      if(ni.isInteger()){
10        unweighted += ni.getInteger();
11      }
12      else{
13        nlist = nlist.concat(ni.getList());
14      }
15    }
16    weighted += unweighted;
17    nestedList = nlist;
18  }
19  return weighted;
20};

C# Solution

1
2csharp
3public class Solution {
4    public int DepthSumInverse(IList<NestedInteger> nestedList) {
5        int ans = 0, prevSum = 0;
6        
7        while (nestedList != null && nestedList.Count != 0) {
8            List<NestedInteger> nextLevel = new List<NestedInteger>();
9            foreach (NestedInteger ni in nestedList) {
10                if (ni.IsInteger()) {
11                    prevSum += ni.GetInteger();
12                } else {
13                    nextLevel.AddRange(ni.GetList());
14                }
15            }
16            nestedList = nextLevel;
17            ans += prevSum;
18        }
19        return ans;
20    }
21}

Please make sure that the functions isInteger(), getInteger(), getList() do correspond to their names in the actual implementation. The functionality assumed is that isInteger() returns a boolean indicating if the item is an integer, getInteger() returns the integer value of the item and getList() returns the nested list of the item, if it is not an integer. The main takeaway from this problem is understanding how to navigate and manipulate nested data structures. The concept of 'depth' or 'height' is important for hierarchically structured data and is widely used in fields such as data science and machine learning. The highest level sometimes referred to as the 'root', usually contains the most aggregated information. In contrast, the leaf nodes or the 'bottom' level of the tree has the most granular, less aggregated information. We leverage this structure to calculate the weighted sum leveraging the concept of 'depth'.

Each of the given solutions uses the BFS approach to traverse the nested list. This approach is advantageous here because it allows us to easily navigate the depth of the structure in a systematic way, which is not easily achievable with other traversal methods like the depth-first search (DFS).

The different language implementations, though written in their own syntax, still follow the same logical structure - traverse the list, add each value encountered to a running total and also keep track of current depth level, multiplying the current level by the aggregated total of previous levels.

In terms of complexity, each of these implementations run in O(n) time, where n is the total number of elements in the structure including the nested lists. This is because, in the worst case, we are visiting each element once. The space complexity is also O(n), considering the extra space needed for the queue. This makes the solutions quite efficient.

Therefore, if you encounter problems involving the depth or height of nested lists or trees, BFS is a good technique to keep in mind. However, always remember to keep track of the current depth or level while traversing as it can be useful in calculations.


Got a question?ย Ask the Teaching Assistantย anything you don't understand.

Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ