Python Program to Find the Total Sum of a Nested List Using Recursion
A nested list is given. The task is to print the sum of this list using recursion. A nested list is a list whose elements can also be a list.
Input: [1,2,] Output: 6 Input: [[4,5],[7,8,],100] Output: 144 Input: [[1,2,3],[4,[5,6]],7] Output: 28
Recursion: In recursion, a function calls itself repeatedly. This technique is generally used when a problem can be divided into smaller subproblems of the same form.
Iterate through the list and whenever we find that an element of the list is also a list that means we have to do the same task of finding the sum with this element list (which can be nested) as well. So we have found a subproblem and, we can call the same function to perform this task and just change the argument to this sublist. And when the element is not a list, then simply add its value to the global total variable.
Time Complexity: O(N), Where N is the total number of elements in the list.
Auxiliary Space: O(1)