Calculate the Sum of All Elements in an Array
Brute Force Approach
Idea
The brute force method is to loop through the array and accumulate the sum of all the elements.
Steps
- Initialize a variable
sum
to 0.
- Traverse the array and add each element to the
sum
.
- Return the
sum
at the end.
Time Complexity
- O(n) where
n
is the size of the array, as each element needs to be processed once.
Space Complexity
- O(1) since we are only using a single variable to hold the sum.
Example Code
Dry Run
For array [1, 2, 3, 4, 5]
:
- Start with
sum = 0
.
- Add each element:
sum = 0 + 1 = 1
sum = 1 + 2 = 3
sum = 3 + 3 = 6
sum = 6 + 4 = 10
sum = 10 + 5 = 15
- Return
15
.
Efficient Approach (Using Built-in Function)
Idea
JavaScript provides a built-in method reduce()
which can be used to accumulate the sum of array elements in a more concise manner.
Steps
- Use the
reduce()
method to sum up the elements of the array.
Time Complexity
- O(n) since we are iterating over the array once.
Space Complexity
- O(1) as the operation is performed in place.
Example Code
Dry Run
For array [1, 2, 3, 4, 5]
:
reduce()
starts with an initial value of 0
.
- Add each element:
sum = 0 + 1 = 1
sum = 1 + 2 = 3
sum = 3 + 3 = 6
sum = 6 + 4 = 10
sum = 10 + 5 = 15
- Return
15
.
Example Test Cases
Test Case 1
Input: [1, 2, 3, 4, 5]
Output: 15
Test Case 2
Input: [10, -2, 8, 4]
Output: 20
Test Case 3
Input: []
Output: 0
(Empty array)
Complexity Analysis
Brute Force Approach
- Time Complexity:
O(n)
(due to traversal)
- Space Complexity:
O(1)
(only a single variable for sum)
Efficient Approach
- Time Complexity:
O(n)
(due to traversal)
- Space Complexity:
O(1)
(single accumulator for reduce)
Conclusion
Both approaches solve the problem in linear time, but the built-in reduce()
method provides a cleaner and more concise solution for calculating the sum of elements in an array.