TryBugHunt
cppInfinite loopHard

Squeezing double spaces freezes the program

BugFind the bug and fix the code

What it should do

squeezeSpaces(text) turns every run of spaces into a single space. Example: squeezeSpaces("a b c") → "a b c"

What happens instead

squeezeSpaces("a b c") never returns and the run times out, while squeezeSpaces("a b") returns "a b".

#include <string>

std::string squeezeSpaces(std::string text) {
    std::string out;
    size_t i = 0;
    while (i < text.size()) {
        if (text[i] == ' ' && i + 1 < text.size() && text[i + 1] == ' ') {
            continue;
        }
        out += text[i];
        i++;
    }
    return out;
}

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 hard C++ 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: When a space is followed by another space, the code skips it with continue. But i++ is at the bottom of the loop, after the continue, so i never moves and the same space is checked forever.

The fix: Advance i before continue.

Remember: continue jumps straight back to the condition and skips the rest of the body. In a while loop, where the update is written by hand, every path through the body (including each continue) must move the index forward. A for loop's update part runs even after continue.

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/c326584b-2bd8-488e-9d32-0ff71c9dcbd1" title="Debugging challenge: Squeezing double spaces freezes the program" 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/c326584b-2bd8-488e-9d32-0ff71c9dcbd1">TryBugHunt</a></p>