LeetCode 339: Nested List Weight Sum Solution
Master LeetCode problem 339 (Nested List Weight Sum), 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.
339. Nested List Weight Sum
Problem Explanation
Explanation
This problem asks us to find the sum of all nested list values weighted by their depth. We can achieve this by performing a depth-first search on the nested list structure. At each level of recursion, we update the sum by adding the values multiplied by their depth. If we encounter a nested list, we recursively call the function with the nested list and increment the depth.
Algorithm
- Initialize a variable
sumto store the weighted sum. - Define a recursive function
calculateWeightSumthat takes the nested list, current depth, and current sum as parameters. - Iterate through each element in the nested list:
- If the element is an integer, add the product of the integer and the current depth to the sum.
- If the element is a nested list, recursively call
calculateWeightSumwith the nested list and increment the depth.
- Return the final
sum.
Time Complexity: O(N), where N is the total number of integers in the nested list. Space Complexity: O(D), where D is the maximum depth of the nested list.
Java
Solution Code
public int depthSum(List<NestedInteger> nestedList) {
return calculateWeightSum(nestedList, 1, 0);
}
private int calculateWeightSum(List<NestedInteger> nestedList, int depth, int sum) {
for (NestedInteger ni : nestedList) {
if (ni.isInteger()) {
sum += ni.getInteger() * depth;
} else {
sum = calculateWeightSum(ni.getList(), depth + 1, sum);
}
}
return sum;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 339 (Nested List Weight Sum)?
This page provides optimized solutions for LeetCode problem 339 (Nested List Weight Sum) 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 339 (Nested List Weight Sum)?
The time complexity for LeetCode 339 (Nested List Weight Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 339 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 339 in Java, C++, or Python.