![]() |
VOOZH | about |
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
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.
4
Time Complexity: O(n)
Auxiliary Space: O(1)
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
All elements processed. Final value = floor(4.5) = 4
4
Time Complexity: O(n)
Auxiliary Space: O(1)