TryBugHunt
goOff-by-oneEasy

Lowest price ignores the last item in the list

BugFind the bug and fix the code

What it should do

cheapestPrice(prices) returns the smallest price in a non-empty list. cheapestPrice([5, 3, 1]) returns 1.

What happens instead

cheapestPrice([5, 3, 1]) returns 3 even though 1 is in the list.

package main

func cheapestPrice(prices []int) int {
    lowest := prices[0]
    for i := 0; i < len(prices)-1; i++ {
        if prices[i] < lowest {
            lowest = prices[i]
        }
    }
    return lowest
}

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 off-by-one errors pattern

The loop that runs one time too many, the slice that drops the last item, the index that starts in the wrong place.

What you'll practise

An easy Go debugging exercise about off-by-one errors: the loop that runs one time too many, the slice that drops the last item, the index that starts in the wrong place.

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)

i < len(prices) - 1 stops one index early, so the final element is never compared. The bug only shows when the cheapest item happens to be last, which is why it can survive a few quick tests. The - 1 often sneaks in from loops that compare prices[i] with prices[i+1], where stopping early is needed to stay in bounds. Here each pass reads only prices[i], so the plain i < len(prices) is right. Better still, range over the slice and let Go handle the bounds.

The pattern behind it: off-by-one errors.

More off-by-one errors to practise

Related errors

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/1123281f-6b6f-4079-ad70-db7bace83d87" title="Debugging challenge: Lowest price ignores the last item in the list" 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/1123281f-6b6f-4079-ad70-db7bace83d87">TryBugHunt</a></p>