03. Calculate the Sum of Array Elements

Difficulty:EasyPattern:AccumulatorTime:O(n)Space:O(1)

Compute the sum of all numerical values in a given array.

How It Works & Algorithmic Design

This utilizes the Accumulator Pattern:

  1. State Initialization: Declare an accumulator variable total = 0. Zero acts as the additive identity element ($x + 0 = x$).
  2. Iteration: Walk through the elements one by one.
  3. Accumulation: Add each element's value to total using the addition assignment operator (total += element).
  4. Return: Once the loop completes, return total.

Why This Approach Works Best

It performs a single pass over the array with constant extra space ($O(1)$ memory). For large arrays, integer overflow should be considered depending on the language (e.g., using 64-bit integers like long in Java when working with large numbers).

Example Walkthrough
Input: [1, 2, 3, 4, 5]
Sequential numbers from 1 to 5.
Step-by-Step Calculation: 0 + 1 = 1 | 1 + 2 = 3 | 3 + 3 = 6 | 6 + 4 = 10 | 10 + 5 = 15
Accumulates values step by step.
Output: 15
Total sum of all elements.

Answer: Calculate total sum

function sum(arr) {
  let total = 0;
  for (const value of arr) {
    total += value;
  }
  return total;
}
💡 Iterate through the array and accumulate values into a tracking variable.
Key Takeaways
  • Initialize accumulators with the identity element (0 for sum, 1 for product).
  • Time complexity is $O(n)$ as every element is visited once.
  • In languages like Java or C++, use long to prevent overflow when dealing with large numbers.