TryBugHunt
rustInfinite loopMedium

Removing double spaces never finishes

BugFind the bug and fix the code

What it should do

squeeze_spaces(text) replaces every run of spaces with a single space. Example: squeeze_spaces("one two") → "one two"

What happens instead

squeeze_spaces("a b") never returns. The run is stopped by the time limit. Text without double spaces, like "plain", works.

fn squeeze_spaces(text: &str) -> String {
    let mut s = text.to_string();
    while s.contains("  ") {
        let s = s.replace("  ", " ");
    }
    s
}

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 infinite loops pattern

The loop condition never becomes false, so the program runs until it is stopped.

What you'll practise

A medium Rust debugging exercise about infinite loops: the loop condition never becomes false, so the program runs until it is stopped.

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: let s = ... inside the loop creates a new s that lives only for one pass of the loop body. The replaced text is stored in that new variable and thrown away. The while condition checks the outer s, which never changes, so it always still contains two spaces and the loop never ends.

The fix: Assign to the outer variable without let: s = s.replace(" ", " ");.

Remember: a while loop ends only when something its condition reads changes. If the loop body uses let on the same name, it is changing a different variable. The compiler's "unused variable" warning points right at it.

The pattern behind it: infinite loops.

More infinite loops 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/520e814e-25c7-403d-a8d7-cedb2d2c25cc" title="Debugging challenge: Removing double spaces never finishes" 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/520e814e-25c7-403d-a8d7-cedb2d2c25cc">TryBugHunt</a></p>