Product Sum

Given an array (that can have nested arrays) - return the sum of all the numbers in the array. If nested array is encountered, recursively add the numbers in the nested array multiplied by the depth of the nested array.

Product Sums solutions

This is a classic case of recursion since we are asked to multiply the nested arrays with their depths.

The solution is straightforward - as and when we encounter a nested array, we multiply the array sum with the respective depth (increment it when we loop through the nested array).

  1. Declare a sum variable that will keep track of the local sum values. Pass in a depth parameter that will help us to know what the current depth of the array is during recursion.
  2. Run a for loop for the entire array from 0 to length.
  3. IF the current element, i.e. arr[i] is NOT AN ARRAY, we add it to the cummulative sum and at the end return sum * depth.
  4. Otherwise, we recurse and call the productSum() method again by passing depth +1 - Since we are going into a nested array, the depth will increase.
  5. Return sum * depth at the end.
Solve Product Sum on Algochurn

Practice all the solutions below

Practice the most popular front-end questions asked in coding interviews with   Frontend Churn