Array Sum
Recursion
📋 Problem Statement
Write a recursive function sum_array(arr) that returns the sum of all elements in an array. Input: [1, 2, 3, 4, 5] → Output: 15. Input: [] → Output: 0. No for or while loops allowed.
💡 Intuition
The recursive insight: . The base case is an empty array with sum 0. This "peel off the first element" pattern is fundamental to recursive array processing.
🔧 Approach
- Base case: if
len(arr) == 0, return 0. - Recursive case: return
arr[0] + sum_of_array(arr[1:]). arr[1:]creates a new sub-array, shrinking the problem by one element each call.
⚡ Complexity Analysis
Time
— one recursive call per element
Space
for the call stack, plus a hidden total cost due to arr[1:] creating a new array copy at each level
⚠️ Common Mistakes
- Forgetting the base case for an empty array, leading to infinite recursion
- Using
arr[0]without checking if the array is empty first (IndexError) - Not realizing
arr[1:]costs per call — hidden total cost is - For production code, Python's built-in
sum()is more efficient
🎯 Final Thoughts
This problem teaches recursive decomposition: process the head, recurse on the tail. While slicing makes it impractical for real use, it builds the recursive thinking needed for merge sort, tree traversals, and divide-and-conquer.