## Facebook Interview Question for SDE-3s

• 0

Country: United States

Comment hidden because of low score. Click to expand.
2
of 2 vote

average' = average + (new_value - average)/(n+1)

Comment hidden because of low score. Click to expand.
1
of 3 vote

double sum=0;
int n=0;
sum+=new_num;
n++;
return sum/n;
}

Comment hidden because of low score. Click to expand.
0
of 0 vote

Average is easy, because you can just use math to compute the new average, no need to use all the previous elements, just use your current average to get the new one.
Calculate the median is more difficult though.

Comment hidden because of low score. Click to expand.
0
of 0 vote

Can you share a sample code

Comment hidden because of low score. Click to expand.
0
of 0 vote

Can u please share ur code :) I want to see the handling of overflow mainly

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````class StreamAverageCalculator {

private Double average = 0.0;
AtomicInteger count = new AtomicInteger();

Double number = new Double (count.incrementAndGet());
Double delta = (num - average) / number;
average += delta;
}

StreamAverageCalculator (Stream<Double> streamOfNumbers) {
if (streamOfNumbers == null) {
// throw Exception
} else {
}
}

public Double getAverage() {
return average;
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public class AverageStream {

private long[] stream;

private double average = 0;

// constructor
AverageStream(long[] input) {
stream = input;
}

// calculate average
void setAverage() {
long sum = 0;
for (int i = 0; i < stream.length; i++) {
// in case of overflow, set zero
if (isOverflow(sum)) {
sum = 0;
average = 0;
return;
}

sum += stream[i];
}

average = (sum/stream.length);
}

double getAverage() {
return average;
}

boolean isOverflow(long in) {
if (in >= -0x7FFFFFFF && in <= 0x7FFFFFFF)
return false;
else
return true;
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````public BigDecimal getAverage(Stream<BigDecimal> numberStream) {
return numberStream.reduce(BigDecimal.ZERO, (bd1, bd2) -> bd1.add(bd2).divide(new BigDecimal(2)));
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````class AvgCalc {
double avg;
int count;
public:
AvgCalc(): avg(0), count(0){}

double x = i - avg;
double y = x/++count;
avg += y;
}

double getAvg() { return avg; };
};``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.