Given nested array calculate the depth sum and provide time and space complexity. Input: [1, 2, [4, 5, [7], 8], 9] Output: 1 + 2 + 2*(4 + 5 + 3*7 + 8) + 9 = 88
Anonymous
My answer in Swift: let nestedArray = [1 , 2, [4, 5, [7], 8], 9] as [Any] func calculateArray(array : [Any], level : Int)->Int { print(array) print(level) var sum = 0 for i in array { if i is Int { sum += i as! Int } if i is [Any] { sum += calculateArray(array: i as! [Any], level: level + 1) } } return level * sum } calculateArray(array: nestedArray, level: 1)
Check out your Company Bowl for anonymous work chats.