Last Updated: June 7, 2026
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.
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.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.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.
sum to 0.nums and add it to sum.sum to a floating-point type and divide by nums.length.Input:
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.
n elements once, followed by a single division.