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
INPUTRECURSIVE CALLSRESULT3142Array: [3, 1, 4, 2]Need to find sumusing recursion only1sum([3,1,4,2])= 3 + sum([1,4,2])2sum([1,4,2])= 1 + sum([4,2])3sum([4,2])= 4 + sum([2])4sum([2]) = 2 + sum([])sum([]) = 0 (base case)10Final Sum3 + 1 + 4 + 2 = 10Each recursive callhandles one elementand delegates the restKey Insight:Recursion naturally breaks the problem into smaller pieces - each call handles one element and trusts the next call to handle the rest.TutorialsPoint - Recursive Sum of Array | Index-Based Approach
Asked in
Microsoft 25 Amazon 20 Google 15
31.2K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen