VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-nested-list-weight-sum-ii/

⇱ Find Nested List Weight Sum II - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Nested List Weight Sum II

Last Updated : 9 May, 2024

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 = 8

Input: 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:

  • Initialize an empty list flats to store the flattened elements along with their depth.
  • Initialize max_depth to store the maximum depth encountered.
  • Define a function flatten that takes the nested list, current depth, flats list, and max_depth.
  • Iterate through each element of the nested list:
    • If the element is an integer, append it to flats with its corresponding depth.
    • If the element is a nested list, recursively call flatten with the nested list, incremented depth, flats, and max_depth.
    • Update max_depth to the maximum of current depth and max_depth.
  • Define a function depth_sum_inverse that takes the nested list and returns the depth sum inverse.
  • Call the flatten function with the nested list, initial depth 0, flats list, and max_depth.
  • Calculate the depth sum inverse by iterating through flats, summing the product of each element and (max_depth + 1 - depth).
  • Return the calculated depth sum inverse.

Below is the implementation of the algorithm:


Output
8
14

Time Complexity : O(N), where is the total number of elements in the nested list.
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: