Modified version of summing an array with recursion in JavaScript

Let’s say, we are required to write a recursive function that sums all the elements of an array of Numbers but with a twist and the twist is that the recursive function we write cannot initialize any extra variable (memory).

Like we cannot use a variable to store the sum or to keep a count of the index of the array, it all has to be using what we already have.

Here’s the solution −

We already have an array and can use its first element (i.e., the element at zeroth index to hold the recursive sum).

The approach is that we repeatedly pop one element from the array and add it to the first element of the array until we are left with only one element.

When we are left with only one element, it will be the cumulative sum of the array and we return that. The code for this approach will be −

Example

const recursiveSum = arr => {
if(arr.length > 1){
arr[0] += arr.pop();
return recursiveSum(arr);
};
return arr[0];
};
console.log(recursiveSum([1,2,3,4]));
console.log(recursiveSum([1,2,3,4,3,6,3,32,7,9,5]));
console.log(recursiveSum([]));

Output

The output in the console will be −

10
75
undefined

Updated on: 28-Aug-2020

225 Views