TryBugHunt
javaOff-by-oneMedium

Rolling sales total crashes on its final window

BugFind the bug and fix the code

What it should do

movingSum(values, window) returns the sum of every run of window consecutive days, so movingSum([1, 2, 3, 4], 2) returns [3, 5, 7].

What happens instead

movingSum([1, 2, 3, 4], 2) throws java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2.

public class Main {
    static int[] movingSum(int[] values, int window) {
        int[] sums = new int[values.length - window];
        for (int i = 0; i <= values.length - window; i++) {
            int s = 0;
            for (int j = i; j < i + window; j++) {
                s += values[j];
            }
            sums[i] = s;
        }
        return sums;
    }
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the off-by-one errors pattern

The loop that runs one time too many, the slice that drops the last item, the index that starts in the wrong place.

What you'll practise

A medium Java debugging exercise about off-by-one errors: the loop that runs one time too many, the slice that drops the last item, the index that starts in the wrong place.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

With 4 values and a window of 2 there are three windows, starting at 0, 1 and 2. In general there are n - window + 1 windows. The loop is right, it visits every start from 0 to n - window inclusive, but the result array was sized n - window, one slot too small, so writing the last window's sum goes out of bounds. When a loop and an array size are computed separately, they have to agree. Count the windows on a tiny example (here 4 values, 2 per window) and check that the array length matches the number of loop passes. A window as wide as the whole input is a good test: it must give exactly one sum.

The pattern behind it: off-by-one errors.

More off-by-one errors to practise

Seen this error in your own code?

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/225f4ee5-b230-4b0e-9664-c53fc7270400" title="Debugging challenge: Rolling sales total crashes on its final window" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/225f4ee5-b230-4b0e-9664-c53fc7270400">TryBugHunt</a></p>