TryBugHunt
rustScope errorMedium

Login streak never goes above 1

BugFind the bug and fix the code

What it should do

longest_streak(days) returns the longest run of days in a row where the user logged in (true). Example: longest_streak(vec![true, true, false, true]) → 2

What happens instead

longest_streak(vec![true, true, true]) returns 1 instead of 3.

fn longest_streak(days: Vec<bool>) -> i32 {
    let mut best = 0;
    for active in days {
        let mut streak = 0;
        if active {
            streak += 1;
            if streak > best {
                best = streak;
            }
        } else {
            streak = 0;
        }
    }
    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 shadowed binding, or a value borrowed after the scope that owned it has ended.

What you'll practise

A medium Rust debugging exercise about scope and closure bugs: a shadowed binding, or a value borrowed after the scope that owned it has ended.

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)

What went wrong: streak is declared inside the loop body, so a fresh streak of 0 is created on every pass. Whatever was counted on the previous day is lost. The counter can only ever reach 1.

The fix: Declare let mut streak = 0; before the loop, next to best, so it lives across iterations.

Remember: a variable declared inside a loop body is created again on every iteration. Anything that has to remember earlier iterations, such as a total, a count or a streak, must be declared before the loop.

The pattern behind it: scope and closure bugs.

More scope and closure bugs to practise

Related errors

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/2cbcf6c1-a817-4b97-888e-e749a837d443" title="Debugging challenge: Login streak never goes above 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/2cbcf6c1-a817-4b97-888e-e749a837d443">TryBugHunt</a></p>