DSA problem
Sum of Array Elements Using Recursion
Given an array of N integers, compute the sum of all its elements using recursion only.
The key insight: the sum of an array is its first element plus the sum of the rest of the array. The "rest" is represented by passing an index that advances with each call. Base case: when index reaches the array length, return 0. Recursive case: return arr[index] + sumArray(arr, index + 1).
This "handle one element, recurse on the rest" decomposition is the foundation of recursive list processing - how functional languages such as Haskell, Lisp, and Erlang process collections - and it introduces the idea of reducing (folding) a collection to a single value.
Examples
arr = [1, 2, 3, 4, 5]15arr = [-2, 4, 10]12Constraints
- 1 <= N <= 10^4
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.