VOOZH about

URL: https://www.geeksforgeeks.org/dsa/average-of-a-stream-of-numbers/

⇱ Average of a Stream of Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Average of a Stream of Numbers

Last Updated : 10 May, 2026

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

Computing Running Sum - O(n) Time

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

  • At 10 -> sum = 10, store 10 / 1 = 10
  • At 20 -> sum = 30, store 30 / 2 = 15
  • At 30 -> sum = 60, store 60 / 3 = 20
  • At 40 -> sum = 100, store 100 / 4 = 25
  • At 50 -> sum = 150, store 150 / 5 = 30

All elements processed. Final array = 10, 15, 20, 25, 30


Output
10 15 20 25 30 

Running Average to Avoid Overflow - O(n) Time

The idea is to avoid overflow by avoiding sum computation.

The idea is to maintain a variable avg to store the running sum and traverse the array from left to right. At each index i, we add the current element to avg, then compute the average as avg / (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

  • 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

Output
10 15 20 25 30 


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

Comment
Article Tags: