r/codinginterview • • Aug 11 '18

Facebook telephonic lead software engineer

Can someone answer this in Java plz..

write a class that 1) calculates the average of the stream, 2) provides an API read the average.

Handle overflows because numbers can be very large and not fit in double/long.

Input is a stream of numbers and not array

0 Upvotes

1 comment sorted by

1

u/cantux Sep 15 '18

Hi,

So taking in a stream, you might imagine your "avarage calculation" function to be invocated with a single value similar to a callback.

Ask if any of the numbers we will be taking in will be in min-max integer boundries.

Ask the interviewer if he could giveyou a domain that this algorithm will work on, so that you can further pinpoint some of the possible requirements.

After coming up with those, you have to ask the interviewer about the precision requirement. You might be expected to be aware that floating point operations on binary systems are not precise. So you could define an epsilon(double d = .00001 for example). Or try to find out about the capacity requirement. For example if you will be processing 10000 integers you could use .00001 as your epsilon.

Here is a sample class:

class StreamProcessor {
  double avarage;
  int count;
  public StreamProcessor(int capacity) {
    epsilon = 1 / capacity;
    // go crazy, keep the capacity state, throw exceptions if exceeded
  }
  

  void processNext(double d) {
    double oldWeight = count / (count + 1);
    double normalizedOldAverage = floorToNearestEpsilon(average * oldWeight);

    count++; // increment count
    double newValueToAddToAverage = floorToNearestEpsilon(d / count);
    average = newValueToAddToAverage + normalizedOldAverage;
  }

  double floorToNearestEpsilon(double d) {
    double temp = epsilon * d;
    return temp / epsilon;
  }
}