Meta Interview Question

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

Interview Answers

Anonymous

Nov 13, 2019

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)

Anonymous

Mar 3, 2020

The input is strictly [Any]. Solution if you can't adjust param(Swift): func nestedSum(_ array : [Any]) -> Int { var sum = 0 var multiplier : CGFloat = 1 var flexibleArray = array if let prevMultiplier = array[0] as? CGFloat { multiplier = prevMultiplier flexibleArray.remove(at: 0) } for eachValue in flexibleArray { if eachValue is Int { sum += eachValue as! Int } else if eachValue is [Any] { multiplier += 1 var newArray = eachValue as! [Any] newArray.insert(multiplier, at: 0) sum += Int(multiplier) * nestedSum(newArray) } } return total }