Code Logo

Compute Mean

Published at25 Jul 2026
Statistics Easy 2 views
Like0

Given an array of integers, compute the arithmetic mean (average). The mean is calculated by summing all elements and dividing by the total count. Return the result as a floating-point number.

For example, the mean of [1, 2, 3, 4, 5] is (1+2+3+4+5) / 5 = 15 / 5 = 3.0. The mean of [10, 20, 30] is 60 / 3 = 20.0. If the array is empty, return 0.

The mean is one of the three main measures of central tendency in statistics, alongside the median and mode. It represents the typical value of a dataset and is used everywhere from grade averaging to financial forecasting to scientific data analysis. Understanding how to compute a mean programmatically is essential for data processing workflows.

To compute the mean, first iterate through the array and accumulate the sum of all elements. Then divide the sum by the length of the array. Because the result may not be an integer even if all inputs are integers, the division must use floating-point arithmetic to preserve the fractional part.

Edge cases include an empty array (return 0 to avoid division by zero) and single-element arrays (the mean equals that element). The array can contain negative numbers, which lower the mean accordingly.

Example Input & Output

Example 1
Input
[5]
Output
5.0
Explanation

Single element

Example 2
Input
[1,2,3,4,5]
Output
3.0
Explanation

Mean of 1..5 is 3

Example 3
Input
[1,1,1,1]
Output
1.0
Explanation

All same

Example 4
Input
[10,20,30]
Output
20.0
Explanation

Mean of 10,20,30 is 20

Example 5
Input
[1,2,3,4]
Output
2.5
Explanation

Mean is 2.5

Algorithm Flow

Recommendation Algorithm Flow for Compute Mean
Recommendation Algorithm Flow for Compute Mean

Solution Approach

Sum all elements, then divide by the array length using floating-point division.

function solution(arr) {
  if (arr.length === 0) return 0;
  var sum = 0;
  for (var i = 0; i < arr.length; i++) sum += arr[i];
  return sum / arr.length;
}

First check for an empty array and return 0 immediately. Then iterate through the array to compute the sum. Finally, divide the sum by the length. The division automatically produces a float in most languages when the operands are integers (JavaScript, Python 3) or can be forced by casting (Java: (double) sum / arr.length).

The time complexity is O(n) where n is the array length, since every element must be summed. The space complexity is O(1), using only two variables regardless of input size.

Best Answers

java
class Solution {
    public double solution(int[] nums) {
        if(nums.length==0)return 0;double s=0;for(int n:nums)s+=n;return s/nums.length;
    }
}