339. Nested List Weight Sum
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 us to compute the weighted sum of all integers in a nested list structure. The weight for each integer is its "depth," which is defined as the number of lists it is enclosed within. For example, in [1, [2]], 1 is at depth 1, and 2 is at depth 2. The task is to traverse this nested structure, identify each integer, determine its depth, and sum up the products of each integer's value and its depth.
Solution
Nested List Weight Sum 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
# The result is undefined 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
# The result is undefined if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class Solution:
def depthSum(self, nestedList: List[NestedInteger]) -> int:
def dfs(current_list: List[NestedInteger], depth: int) -> int:
total_sum = 0
# Iterate through each element in the current list
for item in current_list:
if item.isInteger():
# If it's an integer, add its value multiplied by its depth to the sum
total_sum += item.getInteger() * depth
else:
# If it's a list, make a recursive call with the nested list
# and increased depth
total_sum += dfs(item.getList(), depth + 1)
return total_sum
# Start the recursion with the initial list and depth 1
return dfs(nestedList, 1)
Nested List Weight Sum 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
* // The result is undefined 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
* // The result is undefined if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
class Solution {
public int depthSum(List<NestedInteger> nestedList) {
// Start the recursive process with the initial list and depth 1.
return dfs(nestedList, 1);
}
private int dfs(List<NestedInteger> list, int depth) {
int totalSum = 0;
// Iterate through each element in the list.
for (NestedInteger ni : list) {
if (ni.isInteger()) {
// If the element is an integer, add its value multiplied by the current depth.
totalSum += ni.getInteger() * depth;
} else {
// If the element is a list, make a recursive call for the sublist
// with an incremented depth.
totalSum += dfs(ni.getList(), depth + 1);
}
}
return totalSum;
}
}
Nested List Weight Sum 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 depthSum(vector<NestedInteger>& nestedList) {
// Start the recursive process from depth 1.
return dfs(nestedList, 1);
}
private:
int dfs(const vector<NestedInteger>& list, int depth) {
int sum = 0;
// Iterate over each element in the list.
for (const auto& ni : list) {
if (ni.isInteger()) {
// If it's an integer, add its value times depth to the sum.
sum += ni.getInteger() * depth;
} else {
// If it's a list, recursively call dfs on the sublist with increased depth.
sum += dfs(ni.getList(), depth + 1);
}
}
return sum;
}
};
Nested List Weight Sum 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
* The result is undefined 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
* The result is undefined if this NestedInteger holds a single integer
* getList(): NestedInteger[] {
* ...
* };
* };
*/
function depthSum(nestedList: NestedInteger[]): number {
// Helper function to perform DFS traversal
const dfs = (list: NestedInteger[], depth: number): number => {
let totalSum = 0;
// Iterate over each element in the list
for (const item of list) {
if (item.isInteger()) {
// If it's an integer, add its value * depth to the sum.
// The non-null assertion `!` is safe because `isInteger()` check ensures it's a number.
totalSum += item.getInteger()! * depth;
} else {
// If it's a list, make a recursive call for the sublist with increased depth.
totalSum += dfs(item.getList(), depth + 1);
}
}
return totalSum;
};
// Initial call to start the recursion at depth 1.
return dfs(nestedList, 1);
};
More Medium LeetCode answers
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.