12. Calculate the Average of Array Elements

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

Given an array of numbers, calculate the average of all elements.

How It Works & Algorithmic Design

The average is calculated as sum / count:

  1. Initialize a sum variable to 0.
  2. Traverse every element and add it to sum.
  3. After traversal, divide sum by the number of elements.
  4. Handle an empty array separately because division by zero is invalid.

Why This Approach Works Best

The array only needs to be traversed once. The algorithm requires $O(n)$ time and $O(1)$ auxiliary space.

Example Walkthrough
Input: [10, 20, 30, 40]
Four numerical values are provided.
Sum: 10 + 20 + 30 + 40 = 100
All values are accumulated.
Output: 25
Average = 100 / 4 = 25.

Answer: Calculate array average

function average(arr) {
  if (arr.length === 0) return null;
  let sum = 0;
  for (const value of arr) {
    sum += value;
  }
  return sum / arr.length;
}
💡 First calculate the total sum and then divide it by the number of elements.
Key Takeaways
  • Average is calculated as total sum divided by number of elements.
  • Always handle an empty array before dividing.
  • The algorithm runs in O(n) time and O(1) space.