Recursive Sum of Array - Problem
Write a recursive function to calculate the sum of all elements in an array. You are not allowed to use loops (for, while, forEach, etc.).
The function should handle arrays containing integers (positive, negative, or zero). For an empty array, return 0.
Example:
- Input:
[1, 2, 3, 4, 5]→ Output:15 - Input:
[-1, -2, 3]→ Output:0 - Input:
[]→ Output:0
Input & Output
Example 1 — Basic Case
$
Input:
arr = [3, 1, 4, 2]
›
Output:
10
💡 Note:
Sum: 3 + 1 + 4 + 2 = 10. Recursion breaks down as: 3 + sum([1,4,2]) = 3 + (1 + sum([4,2])) = 3 + 1 + (4 + sum([2])) = 3 + 1 + 4 + (2 + sum([])) = 3 + 1 + 4 + 2 + 0 = 10
Example 2 — Negative Numbers
$
Input:
arr = [-1, -2, 3]
›
Output:
0
💡 Note:
Sum: (-1) + (-2) + 3 = 0. Recursion handles negative numbers normally.
Example 3 — Empty Array
$
Input:
arr = []
›
Output:
0
💡 Note:
Base case: empty array returns 0 immediately, no recursive calls needed.
Constraints
- 0 ≤ arr.length ≤ 1000
- -106 ≤ arr[i] ≤ 106
- No loops allowed (must use recursion)
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code