DEV Community

King coder
King coder

Posted on

Day 40 of DSA Problem Solving

1 Sum of all numbers

Write a function sum(n) that calculates the sum of all numbers in an array arr using recursion. It sums from index 0 to n

Example:


Input: [5, 2, 6, 1, 3]

Process: 5 + 2 + 6 + 1 + 3 = 17

Output: 17
Enter fullscreen mode Exit fullscreen mode

Approach:

  • Create a Sum Function and pass the Total Number Of Element Inside Array
  • Check If n == 0, return arr[0].
  • Otherwise, return arr[n] + sum(n - 1).

Time & Space Complexity:

  • Time Complexity: O(n) one recursive call per element.

  • Space Complexity: O(n) Due to call stack.

Example Code

let arr = [5, 2, 6, 1, 3];

    function sum(n) {
    if (n === 0) return arr[0];
    return arr[n] + sum(n - 1);
    }
console.log(sum(arr.length - 1)); // 17

Enter fullscreen mode Exit fullscreen mode

Top comments (0)