Interview Question
Country: United States
Use fix size queue (size = n), and push the data from one end pop the data from the other end when the queue is full. We want to maintain the total and update total as well so that it takes constant time to compute the average
if the average value is required everytime new element come (in the streamming applications)
template<typename T>
class AvgQueue {
queue q;
T total;
public:
AvgQueue(): total(0);
void push(T v) {
T old = 0;
if (q.size() == n) {
old = q.front();
q.pop();
}
q.push(v);
total += v - old;
}
T get() {
return (q.empty()) ? 0 : total / q.size();
}
}
Use stack for best perorformance. The last n values would be basically the the first n values in stack.. just pop..
The question apparently is not very clear here. If it is a static data, you just take the last n element and compute the average.
If the data is coming in a stream, and you always want to know the avg of the last n elements, you need to use a queue as eugene mentioned.
Once you have computed the avg of the n numbers, when a new number comes in:
1. De-queue the first element and compute the new average as: ((n*avg - value of first element) + value of new element)/n
2. En-queue the new element.
I think the best data structure is simple an Array. Say the array is A.
public void printAvg(int N, in[] A) {
int[] temp = new int[N];
int sum = 0;
int i = -1;
for(i = 0; i < N && i < A.length; ++i) {
temp[i] = A[i];
sum += A[i];
}
if(i < N) {
System.out.println((sum*1.0)/A.length);
return;
}
else {
System.out.println((sum*1.0)/N);
}
int idx = 0;
for(int j = N; j < A.length; ++j) {
sum = sum-temp[idx]+A[j];
System.out.println((sum*1.0)/N);
temp[idx++] = A[j];
if(idx == N)
idx = 0;
}
}
We can use a circular queue (size of n) with some modification. Modification is:
- Rudra July 18, 2013When the overflow condition arise we will remove the first element from the queue and put the newly come element in the queue. When the input stream ends the queue will contain just only last n elements. This will give O(n) time complexity.