A quiz app stores bonus rounds inside rounds: a round is an array whose items are either points (integers) or another, nested round. A value's depth is the number of arrays it sits inside, so values in the outer array have depth 1.
Write two functions that take such a nested array list:
depthSum(list) returns the sum of every integer multiplied by its depth.
inverseDepthSum(list) returns the sum of every integer multiplied by maxDepth - depth + 1, where maxDepth is the greatest depth of any integer in list. The deepest integers count once, and integers in the outer array count the most.
Rules:
An item is either a safe integer (Number.isSafeInteger) or an array. If list is not an array, or any item at any depth is something else (a string, a fraction, null, a hole in a sparse array), throw a TypeError.
Empty arrays are allowed. They hold no integers, so they never change maxDepth. A list without integers sums to 0.
Nesting can be 100,000 levels deep, and a list can hold 200,000 integers. A recursive walk overflows the call stack on the deep input, so traverse with your own stack or queue.
depthSum([[1, 1], 2, [1, 1]]); // 10: four 1s at depth 2, one 2 at depth 1inverseDepthSum([[1, 1], 2, [1, 1]]); // 8: the 1s weigh 1, the 2 weighs 2depthSum([1, [4, [6]]]); // 27: 1×1 + 4×2 + 6×3inverseDepthSum([1, [4, [6]]]); // 17: 1×3 + 4×2 + 6×1inverseDepthSum([3, [[]]]); // 3: the empty arrays do not count as depth
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
5
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.