Interview Question
SDE-2sCountry: United States
@koustav.adorable, the input is a list of integers, not a string, please note. I have a solution involving two-pass. First pass is to find the maxDepth of the nested list and the second pass is to sum up the numbers using max-depth. Can probably be done in a clever way using one-pass but I'll have to think about it. Outlining my solution in Python below:
def sumList(l):
if not l:
return 0
max_d = -1
def maxDepth(nums, d=1):
nonlocal max_d
for x in nums:
if type(x) == list:
maxDepth(x, d+1)
else:
max_d = max(max_d, d)
maxDepth(l)
total_sum = 0
def findSum(nums, maxDepth=max_d):
nonlocal total_sum
for x in nums:
if type(x) == list:
total_sum += findSum(x, maxDepth - 1)
else:
total_sum += x
return total_sum
findSum(l)
return total_sum
Can anybody offer a better solution pls ? Please don't change the method signature
- koustav.adorable June 09, 2019