TryBugHunt
goInfinite loopEasy

Space cleanup hangs on text with double spaces

BugFind the bug and fix the code

What it should do

collapseSpaces(s) replaces every run of spaces with a single space. collapseSpaces("a b") returns "a b".

What happens instead

collapseSpaces("a b") never returns and the runner stops it: Time Limit Exceeded (3000ms).

package main

func collapseSpaces(s string) string {
    out := []byte{}
    i := 0
    for i < len(s) {
        if s[i] == ' ' && len(out) > 0 && out[len(out)-1] == ' ' {
            continue
        }
        out = append(out, s[i])
        i++
    }
    return string(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

An easy Go 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)

This loop moves forward only at the bottom, with i++. The continue for an extra space jumps straight back to the condition and skips that i++, so i stays on the same space forever, and the same check sends it back again. Text without double spaces never takes that path, so it works. In a for loop with a manual counter, every path through the body has to advance the counter; a continue is the classic way to miss one. A three-part for loop, or ranging over the string, puts the step where continue cannot skip 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/916261b8-2d17-46da-b848-f1dab65a651e" title="Debugging challenge: Space cleanup hangs on text with double spaces" 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/916261b8-2d17-46da-b848-f1dab65a651e">TryBugHunt</a></p>