LeetCode 364: Nested List Weight Sum II Solution
Master LeetCode problem 364 (Nested List Weight Sum II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
364. Nested List Weight Sum II
Problem Explanation
Explanation:
This problem asks us to find the sum of all nested lists where each element is multiplied by its depth level. However, the depth of each element is defined differently from the previous problem. In this problem, the depth of a nested list is defined as the maximum depth of any nested list within it plus 1.
To solve this problem, we can perform a two-pass approach:
- Calculate the maximum depth of the nested list.
- Calculate the sum of all elements by recursively traversing the nested list and multiplying each element by
maxDepth - currentDepth + 1.
Example:
Consider the nested list [[1,1],2,[1,1]], where the maximum depth is 2. The sum would be calculated as follows:
- For
[1,1], the sum is2*(1+1) = 4. - For
2, the sum is2*2 = 4. - For
[1,1], the sum is2*(1+1) = 4.
Therefore, the total sum is 4 + 4 + 4 = 12.
Time Complexity:
The time complexity of this approach is O(N), where N is the total number of nested elements in the input list.
Space Complexity:
The space complexity is also O(N) due to the recursive stack space used during the traversal.
: :
Solution Code
class Solution {
public int depthSumInverse(List<NestedInteger> nestedList) {
int maxDepth = calculateDepth(nestedList);
return calculateSum(nestedList, maxDepth);
}
private int calculateDepth(List<NestedInteger> nestedList) {
int depth = 0;
for (NestedInteger ni : nestedList) {
if (!ni.isInteger()) {
depth = Math.max(depth, calculateDepth(ni.getList()));
}
}
return depth + 1;
}
private int calculateSum(List<NestedInteger> nestedList, int depth) {
int sum = 0;
for (NestedInteger ni : nestedList) {
if (ni.isInteger()) {
sum += ni.getInteger() * depth;
} else {
sum += calculateSum(ni.getList(), depth - 1);
}
}
return sum;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 364 (Nested List Weight Sum II)?
This page provides optimized solutions for LeetCode problem 364 (Nested List Weight Sum II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 364 (Nested List Weight Sum II)?
The time complexity for LeetCode 364 (Nested List Weight Sum II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 364 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 364 in Java, C++, or Python.