![]() |
VOOZH | about |
Given an array arr[], find the average or mean of the prefix array at every index.
Examples:
Input: arr[] = [10, 20, 30, 40, 50]
Output: [10, 15, 20, 25, 30]
Explanation: 10 / 1 = 10, (10 + 20) / 2 = 15, (10 + 20 + 30) / 3 = 20 and so on.
Input: arr[] = [12, 1]
Output: [12, 6]
Explanation: 12 / 1 = 12, (12 + 1) / 2 = 6
The idea is to compute sum till every point and compute average at every point. The problem with this solution is, it causes overflow even for small values.
Let us understand with an example:
Input: arr[] = 10, 20, 30, 40, 50
Start traversal: Initialize avg = 0
All elements processed. Final array = 10, 15, 20, 25, 30
10 15 20 25 30
The idea is to avoid overflow by avoiding sum computation.
The idea is to maintain a variable
avgto store the running sum and traverse the array from left to right. At each indexi, we add the current element toavg, then compute the average asavg / (i + 1)and store it in the result array.
Let us understand with an example:
Input: arr[] = [1, 3, 4, 2, 6, 5, 8, 7]
Start traversal: Initialize avg = 0
10 15 20 25 30
Time Complexity: O(n)
Auxiliary Space: O(n)