Given an array of integers, compute the sum of all elements. Return the total as an integer.
For example, the sum of [1, 2, 3, 4, 5] is 15. The sum of [-5, 10, -3] is 2. An empty array returns 0. A single-element array [7] returns 7.
Summation is the most fundamental aggregation operation. It is used in calculating totals, averages, financial balances, and statistical measures. The pattern of accumulating a running total by iterating through a collection is essential for all data processing work.
The solution initializes a sum variable to 0 and adds each element during iteration. After the loop, return the sum.
Edge cases include an empty array (return 0), a single element (return that element), negative values (correctly reduce the total), and large arrays where the sum might exceed typical integer ranges.
Example Input & Output
Example 1: Sum of [1, 2, 3, 4] is 10
Example 2: Sum of [10, -2, 5] is 13
Example 3: Sum of [0, 0, 0] is 0
Algorithm Flow
Solution Approach
Iterate through the array and accumulate the sum of all elements into a running total.
Initialize sum to 0. Loop through each element and add it to the running total using the addition operator. After all elements are processed, return the accumulated sum. For an empty array, the loop never executes and sum remains 0.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public int sum_array(int[] nums) {
int sum = 0;
for (int num : nums) sum += num;
return sum;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
