TryBugHunt
goInfinite loopHard

Merging two sorted price lists freezes on matching prices

BugFind the bug and fix the code

What it should do

mergeSorted(a, b) merges two ascending price lists into one ascending list, keeping duplicates. mergeSorted([1, 3], [3, 6]) returns [1, 3, 3, 6].

What happens instead

mergeSorted([1, 3], [3, 6]) never returns: Time Limit Exceeded (3000ms).

package main

func mergeSorted(a []int, b []int) []int {
    merged := []int{}
    i, j := 0, 0
    for i < len(a) || j < len(b) {
        if j >= len(b) || (i < len(a) && a[i] < b[j]) {
            merged = append(merged, a[i])
            i++
        } else if i >= len(a) || b[j] < a[i] {
            merged = append(merged, b[j])
            j++
        }
    }
    return merged
}

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

Each pass must take an element from one of the lists, or the loop makes no progress. The first branch takes from a when a[i] < b[j], the second takes from b when b[j] < a[i], and when the two values are equal neither condition is true. Nothing is appended, neither index moves, and the loop spins forever on the same pair. Lists with no shared values merge correctly, which is why this can pass a quick test. Make the last branch a plain else so every case is covered; ties then go to b, which keeps the result sorted.

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/2fa56ea4-d970-4cc2-a848-227b350d1cf2" title="Debugging challenge: Merging two sorted price lists freezes on matching prices" 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/2fa56ea4-d970-4cc2-a848-227b350d1cf2">TryBugHunt</a></p>