AlgoMaster Logo

Sum of All Elements

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

Add every integer in the array together. A single pass that adds each element to a running total produces the answer.

Two edge cases need attention. An empty array has nothing to add, so the answer is 0, which falls out if the total starts at 0 and never enters the loop. The second is the size of the numbers. The array can be long and each value close to the 32-bit limit, so the running total can grow past what a 32-bit integer holds even though every individual element fits.

Key Constraints:

  • 0 <= nums.length <= 10^5 → The array can be empty. Starting the total at 0 means an empty array returns 0 without any special case.
  • -2^31 <= nums[i] <= 2^31 - 1 → Each element fits in a 32-bit integer, but the sum may not. With up to 10^5 elements near 2^31 - 1, the total can reach roughly 2 * 10^14, far beyond the 32-bit maximum of about 2.1 * 10^9. Accumulate into a wide integer type such as long, long long, or int64 to avoid overflow.

Approach 1: Linear Scan

Intuition

Adding up every element requires visiting every element, so the solution is a single loop over the array.

Keep one running total, started at 0. Walk through the array and add each element to that total. When the loop finishes, the total holds the sum. An empty array skips the loop and the total stays 0.

One detail matters: the type of the running total. Each element fits in a 32-bit integer, but their sum might not, so the accumulator uses a wider type.

Algorithm

  1. Initialize a running total sum to 0, using a wide integer type.
  2. Loop over each element num in nums.
  3. Add num to sum.
  4. After the loop ends, return sum.

Example Walkthrough

Input:

0
3
1
9
2
5
nums

Start with sum = 0. Visit the first element, 3, and add it to get sum = 3. Visit the second element, 9, and add it to get sum = 12. Visit the third element, 5, and add it to get sum = 17. The loop ends, and the total is 17.

17
result

Code