TryBugHunt
javaScope errorMedium

Longest block of free seats is never more than 1

BugFind the bug and fix the code

What it should do

seats is a row in a cinema, "." for a free seat and "X" for a taken one. longestFreeBlock(seats) returns the length of the longest run of free seats next to each other, so longestFreeBlock("XX..X...X") returns 3.

What happens instead

longestFreeBlock("XX..X...X") returns 1 instead of 3.

public class Main {
    static int longestFreeBlock(String seats) {
        int best = 0;
        for (int i = 0; i < seats.length(); i++) {
            int run = 0;
            if (seats.charAt(i) == '.') {
                run++;
                best = Math.max(best, run);
            } else {
                run = 0;
            }
        }
        return best;
    }
}

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 scope and closure bugs pattern

A field shadowed by a local or parameter with the same name, so the field never changes.

What you'll practise

A medium Java debugging exercise about scope and closure bugs: a field shadowed by a local or parameter with the same name, so the field never changes.

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)

run is declared inside the loop body, so it is a brand new variable on every pass and starts at 0 each time. It can never be more than 1, because the count from the previous seat is thrown away at the end of each iteration. A variable that must remember something from one iteration to the next has to be declared before the loop. The else branch resetting run to 0 is fine; it is the declaration that resets it too often. When a running count or total seems stuck at its first value, check where it is declared.

The pattern behind it: scope and closure bugs.

More scope and closure bugs to practise

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/48ff9d91-aaa9-4d63-88f2-b019b23b45d4" title="Debugging challenge: Longest block of free seats is never more than 1" 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/48ff9d91-aaa9-4d63-88f2-b019b23b45d4">TryBugHunt</a></p>