Sum of Array Elements II
Pattern: Recursion basics
Sum an array recursively by passing an index along, which makes "the rest of the array" a smaller problem without copying anything.
The problem
You are given an array of whole numbers with between 1 and 500 elements, each between -10,000 and 10,000. Return the sum
of all its elements, using recursion. For example, the sum of [5, 3, 8] is 16.
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name arraySum and the limits above are this guide's own. With these limits the sum always fits in 32 bits.
Think first
- How is the sum of
[5, 3, 8]related to the sum of[3, 8]? - To recurse on "the rest of the array", do you need to make a new, shorter array? What could you pass instead?
- What is the sum of an empty part of the array?
Hints
Brute force, and why it fails
A simple loop is the everyday answer, with O(1) extra memory. A recursive version that slices the array (arr[1:] in
Python, or a copied sub-array in Java) is also correct, but each slice copies the remaining elements, so it does about
n²/2 copying in total. Passing an index avoids every copy.
The key insight
A recursive call does not need a smaller copy of the input, only a smaller description of it. An index i that means
"from here to the end" shrinks the problem by one each call, and costs nothing.
Dry run
| waiting | 5 + ? |
|---|
arr = [5, 3, 8]. Call sumFrom(arr, 0). Index 0 is inside the array, so it needs 5 + sumFrom(arr, 1) and waits.
The plan
function arraySum(arr):
return sumFrom(arr, 0)
function sumFrom(arr, i):
if i == length(arr):
return 0 # nothing left to add
return arr[i] + sumFrom(arr, i + 1) # this element plus the rest
Complexity
- Time
O(n)- Space
O(n)
One call per element, each doing constant work. The deepest point has n + 1 calls open on the stack.
Edge cases
- A single element returns itself plus the base case's 0.
- Negative numbers and zeros need no special handling.
- 500 elements of 10,000 sum to 5,000,000, which fits easily in 32 bits.
I've built my logic, show the code
Java
class Solution {
public int arraySum(int[] arr) {
return sumFrom(arr, 0);
}
private int sumFrom(int[] arr, int i) {
if (i == arr.length) {
return 0; // base case: no elements left
}
return arr[i] + sumFrom(arr, i + 1); // this element plus the rest
}
}C++
class Solution {
public:
int arraySum(vector<int>& arr) {
return sumFrom(arr, 0);
}
int sumFrom(vector<int>& arr, int i) {
if (i == static_cast<int>(arr.size())) {
return 0; // base case: no elements left
}
return arr[i] + sumFrom(arr, i + 1); // this element plus the rest
}
};Python
class Solution:
def arraySum(self, arr):
return self.sumFrom(arr, 0)
def sumFrom(self, arr, i):
if i == len(arr):
return 0 # base case: no elements left
return arr[i] + self.sumFrom(arr, i + 1) # this element plus the restCommon mistakes
- Stopping at
i == length - 1and returningarr[i], which crashes on an empty part. - Slicing or copying the array on every call, which turns O(n) into O(n²).
- Forgetting to move
iforward, which recurses forever.