![]() |
VOOZH | about |
Given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. The depth of an integer is the number of lists that it is inside of. For example, the nested list [1,[2,2],[[3],2],1] has each integer's value set to its depth.
Let maxDepth be the maximum depth of any integer. The weight of an integer is maxDepth - (the depth of the integer) + 1.
Your task is to find the sum of each integer in nestedList multiplied by its weight.
Examples:
Input: nestedList = [[1, 1], 2, [1, 1]]
Output: 8
Explanation: Four 1's with a weight of 1, one 2 with a weight of 2. 1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8Input: nestedList = [1, [3, [5]]]
Output: 14
Explanation: One 1 at depth 3, one 3 at depth 2, and one 5 at depth 1; 1*3 + 3*2 + 5*1 = 14)
Algorithm: To solve the problem, follow the below idea:
We can solve this problem by recursively flattening the nested list while tracking each element's depth and calculating the maximum depth encountered. Then, iterating through the flattened list, it computes the depth sum inverse for each element using the maximum depth and the element's depth. Finally, it returns the sum of these depth sum inverses.
Step-by-step algorithm:
flats to store the flattened elements along with their depth.max_depth to store the maximum depth encountered. flatten that takes the nested list, current depth, flats list, and max_depth.flats with its corresponding depth.flatten with the nested list, incremented depth, flats, and max_depth.max_depth to the maximum of current depth and max_depth.depth_sum_inverse that takes the nested list and returns the depth sum inverse.flatten function with the nested list, initial depth 0, flats list, and max_depth.flats, summing the product of each element and (max_depth + 1 - depth).Below is the implementation of the algorithm:
8 14
Time Complexity : O(N), where N is the total number of elements in the nested list.
Auxiliary Space: O(N)