VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-average-array-iterative-recursive/

⇱ Mean of an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Mean of an Array

Last Updated : 8 May, 2026

Given an unsorted array arr[], the task is to find the mean of the array.

Note: Return the floor value of the mean.

Examples :

Input: arr[] = [1, 3, 4, 2, 6, 5, 8, 7]
Output: 4
Explanation: Sum of the elements is 1 + 3 + 4 + 2 + 6 + 5 + 8 + 7 = 36, 
Mean = 36/8 = 4.5. 
Floor(4.5) = 4.

Input: arr[] = [4, 4, 4, 4, 4]
Output: 4
Explanation: Sum of the elements is 4 + 4 + 4 + 4 + 4 = 20, 
Mean = 20/5 = 4

Naive Approach - O(n) Time O(1) Space

The idea is to traverse the array to compute the sum, then divide it by n to get the average. Since the return type is int, the result is the floor of the mean.


Output
4

Time Complexity: O(n)
Auxiliary Space: O(1)

Handling Overflow - O(n) Time O(1) Space

Instead of computing the total sum (which may cause overflow), update the average incrementally while traversing the array. For each element, adjust the current average using the difference between the element and the current average, divided by its position. This avoids large intermediate sums and is numerically stable.

Let us understand with an example:

Input: arr[] = [1, 3, 4, 2, 6, 5, 8, 7]
Start traversal: Initialize avg = 0

  • At 1 -> avg = 1
  • At 3 -> avg = 1 + (3 - 1)/2 = 2
  • At 4 -> avg = 2 + (4 - 2)/3 = 2.67
  • At 2 -> avg = 2.67 + (2 - 2.67)/4 = 2.5
  • At 6 -> avg = 3.2
  • At 5 -> avg = 3.5
  • At 8 -> avg ≈ 4.14
  • At 7 -> avg = 4.5

All elements processed. Final value = floor(4.5) = 4


Output
4

Time Complexity: O(n)
Auxiliary Space: O(1)

Comment