This is a practice problem from AlgoExpert. Input is a "special" array that is a non-empty array that contains either integers or other "special arrays". The product sum of a "special" array is the sum of its elements, where "special" arrays inside it are summed themselves and then multiplied by their level of depth.
O(n) time, where n is the total number of elements in the array
O(d) space, where d is the greatest depth of "special" arrays in the array
O(d) space
def productSum(array, multiplier=1):
sum = 0
for element in array:
if type(element) is list:
sum += productSum(element, multiplier + 1)
else:
sum += element
return sum * multiplier
I don't understand why the time complexity of this function is O(N)?
If the element you're iterating through in the for statement is another array, then isn't it a for statement within for statement O(N^2)?
Or, I guess the inner for statement, the length of the array is unknown.....
but still I don't understand why it's just O(N). What if you get an input where every single element is an array, and all those inner array lengths are even longer than initial input array length?
Or is this some amortized analysis stuff?
Thanks!