TryBugHunt
rustOff-by-oneMedium

Rising readings counter misses the last rise

BugFind the bug and fix the code

What it should do

count_increases(readings) counts how many readings are higher than the one before. The list always has at least one reading. Example: count_increases(&[1, 2, 3, 4]) → 3

What happens instead

count_increases(&[1, 2, 3, 4]) returns 2 instead of 3, and count_increases(&[10, 12]) returns 0.

fn count_increases(readings: &[i32]) -> i32 {
    let mut count = 0;
    for i in 1..readings.len() - 1 {
        if readings[i] > readings[i - 1] {
            count += 1;
        }
    }
    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 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

A medium Rust 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)

What went wrong: Each step compares readings[i] with readings[i - 1], so i must run from 1 to the last index, len() - 1, inclusive. The range 1..len() - 1 stops one step early because the end of a range is never included. The last pair is never compared.

The fix: Use 1..readings.len(). Its last value is len() - 1, the last valid index.

Remember: when you compare with the previous element, start at 1 and end at len(). Subtracting 1 from the end of a half-open range removes the last element twice.

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

More off-by-one errors 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/d4090803-f80f-4711-9532-4a06193ca47e" title="Debugging challenge: Rising readings counter misses the last rise" 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/d4090803-f80f-4711-9532-4a06193ca47e">TryBugHunt</a></p>