Introduction
Sum of Array Elements means:
- adding all values
- present inside an array
The task is to:
- traverse array
- calculate total sum
- return final answer
Example:
Input:
1 2 3 4 5
Output:15
Explanation:
1 + 2 + 3 + 4 + 5 = 15 This problem is one of the most important applications of:
Recursion on Arrays Constraints
1 <= Array Size <= 10^5 Approach 1 : Iterative Solution
Explanations:
Explanation:
The idea is:
- traverse array
- add every element
Steps:
- Initialize sum as 0.
- Traverse array.
- Add elements one by one.
- Print final sum.
This approach:
- is simple
- avoids recursion
Dry Run
Array:
1 2 3 4 5
sum = 0
0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6 + 4 = 1010 + 5 = 15
Practice :
Complexity Analysis
Time Complexity:- O(n)Explanation :
Array is traversed once.
Space Complexity:- O(1) Explanation :
No extra space is used.
Approach 2 : Recursive Solution
Explanations:
Explanation:
This is the most important recursion-based solution.
The idea is:
- current element
- recursive sum of remaining array
Base Case:
- when index reaches end
Recursive Case:
- add current element
- recurse for next index
Dry Run
Array:
1 2 3 4 5
1 + sum(2 3 4 5) 1 + 2 + sum(3 4 5) 1 + 2 + 3 + sum(4 5) 1 + 2 + 3 + 4 + 5 = 15
Practice :
Complexity Analysis :
Time Complexity:- O(n)Explanation : Recursive calls run n times.
Space Complexity:- O(n) Explanation :
Recursion stack is used.
Why This Problem is Important