AlgoMaster Logo

Average of Array Elements

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

Add up every element, then divide the total by the count. The math is trivial, so the real work is handling the numeric details.

Two details matter. First, the sum can grow large. With up to 10^5 elements that can each reach 10^9, the total can reach 10^14, which overflows a 32-bit integer. Second, the answer is a floating-point number, so the division has to keep the fractional part. An array like [1, 2] averages to 1.5, not 1.

The array is guaranteed non-empty, so there is no empty-input case and no division by zero.

Key Constraints:

  • 1 <= nums.length <= 10^5 and -10^9 <= nums[i] <= 10^9 → The sum can reach about 10^14 in magnitude, which is far beyond the 32-bit signed range of roughly 2.1 * 10^9. Accumulate the total in a wide integer type such as long, long long, int64, or i64 so the addition never overflows.
  • The result is a floating-point number → Integer division truncates toward zero, so 3 / 2 would give 1 instead of 1.5. Cast the sum (or the length) to a floating-point type before dividing so the fractional part survives.

Approach 1: Sum then Divide

Intuition

A single pass accumulates the sum, and one division at the end produces the mean. The care is in the types: keep the running sum in a wide integer so it never overflows, then convert to floating point for the final division so the result can hold a fraction.

Algorithm

  1. Initialize a wide integer accumulator sum to 0.
  2. Iterate over every element in nums and add it to sum.
  3. Cast sum to a floating-point type and divide by nums.length.
  4. Return the resulting floating-point value.

Example Walkthrough

Input:

0
1
1
2
nums

Walk through the array once. Start with sum = 0. Add the first element: sum = 0 + 1 = 1. Add the second element: sum = 1 + 2 = 3. The array has 2 elements, so divide. Casting to floating point first, 3.0 / 2 = 1.5. Without the cast, integer division would have produced 1, dropping the fractional part.

1.5
result

Code