Sum of Array Elements
Pattern: Traversal and in-place tricks
Add up every element in one pass with a running total.
The problem
You are given an array of between 1 and 100,000 whole numbers, each between -10,000 and 10,000. Return their sum. For
example, the sum of [3, 1, 4] is 8.
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 are this guide's own. With these limits the sum always fits in 32 bits (at most
10⁹ in size). The recursive version of this problem is in Recursion basics.
Think first
- What one number do you need to remember while you walk along the array?
- What should it start at, so that adding the first element gives the right value?
- Could the sum overflow a 32-bit integer with these limits? What if each value could be 10⁹?
Hints
Brute force, and why it fails
There is nothing slower to compare with: every element must be read at least once, so one pass is already the best
possible. Built-in helpers such as sum(nums) in Python do exactly this pass.
The key insight
A running total turns "add everything" into one pass with one variable. Almost every traversal problem in this pattern is this loop with a different variable and a different update.
Dry run
| total | 0 |
|---|
nums = [3, 1, 4]. Start the running total at 0, the sum of nothing.
The plan
total = 0
for x in nums:
total = total + x
return total
Complexity
- Time
O(n)- Space
O(1)
Each element is read once, and only the total is stored.
Edge cases
- One element: the sum is that element.
- Negative values and zeros need no special handling.
- Watch the limits: if values could reach 10⁹, use a 64-bit total.
I've built my logic, show the code
Java
class Solution {
public int arraySum(int[] nums) {
int total = 0;
for (int x : nums) {
total += x;
}
return total;
}
}C++
class Solution {
public:
int arraySum(vector<int>& nums) {
int total = 0;
for (int x : nums) {
total += x;
}
return total;
}
};Python
class Solution:
def arraySum(self, nums):
total = 0
for x in nums:
total += x
return totalCommon mistakes
- Starting the total at the first element and then adding the first element again.
- Using a 32-bit total when the limits allow a larger sum.
- Looping to
n - 1with<and so skipping the last element.