TryBugHunt
goInfinite loopMedium

Counting a word in a sentence never finishes

BugFind the bug and fix the code

What it should do

countOccurrences(text, word) counts non-overlapping occurrences of a non-empty word in text. countOccurrences("banana", "na") returns 2.

What happens instead

countOccurrences("banana", "na") never returns: Time Limit Exceeded (3000ms).

package main

import "strings"

func countOccurrences(text string, word string) int {
    count := 0
    start := 0
    for {
        i := strings.Index(text[start:], word)
        if i == -1 {
            break
        }
        count++
        start = i + len(word)
    }
    return count
}

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 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)

strings.Index(text[start:], word) returns a position inside the slice text[start:], not inside text. To turn it into an absolute position you have to add start. The broken code sets start to that relative position, so the search jumps back to an earlier spot, finds the same match again and bounces between two positions forever. It only works when there is at most one match near the start. Whenever you search a sub-slice, remember that indexes come back relative to the sub-slice.

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/10da55eb-148f-4fc2-a0e5-04ccda420667" title="Debugging challenge: Counting a word in a sentence 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/10da55eb-148f-4fc2-a0e5-04ccda420667">TryBugHunt</a></p>