Find the bug · #3 · Off by one Medium C++
The newest point is missing from the chart
A sales chart draws a moving average, and the line always stops one day early.
On this page
The report
A sales dashboard draws a moving average: the average of every run of k days in a row. The newest point is always missing, so the line on the chart stops a day early.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// The average of every run of k days in a row.
vector<double> movingAverage(const vector<int>& sales, int k) {
vector<double> out;
int n = sales.size();
for (int i = 0; i + k < n; i++) {
double sum = 0;
for (int j = i; j < i + k; j++) sum += sales[j];
out.push_back(sum / k);
}
return out;
}Read it, then pick a line.
With 4 days and windows of 2, how many windows are there, and where does the last one start?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
vector<int> sales = {10, 20, 30, 40};
vector<double> avg = movingAverage(sales, 2);
cout << avg.size() << " windows:";
for (double a : avg) cout << " " << a;
cout << endl;It prints
2 windows: 15 25
It should print
3 windows: 15 25 35
Show the answer: the bug, the fix, and how you’d find it
The bug (line 5)
Line 5 keeps going while i + k < n. The last window starts at n - k, where i + k equals n, so the loop stops one window early and the newest average is never computed. It should be i + k <= n.
The fix
2vector<double> movingAverage(const vector<int>& sales, int k) {3 vector<double> out;4 int n = sales.size();5 for (int i = 0; i + k < n; i++) {5 for (int i = 0; i + k <= n; i++) {6 double sum = 0;7 for (int j = i; j < i + k; j++) sum += sales[j];8 out.push_back(sum / k);How you’d find it
- Reproduce small: 4 values, window 2. The windows are [10, 20], [20, 30] and [30, 40]: three. The code returns two.
- The missing one is the last window. Its start is
n - k = 2. Put that into the loop condition:2 + 2 < 4is false, so it never runs. - Check the other edge too: the first window starts at 0, which is fine. Only the end is wrong.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
vector<double> a = movingAverage({10, 20, 30, 40}, 2);
CHECK(a.size() == 3);
CHECK(a.back() == 35);
CHECK(movingAverage({5, 7}, 2).size() == 1);Where else this bites
- Sliding-window problems in DSA: the last window is the classic miss.
- Sending in batches: the final, partial batch never goes out.