TryBugHunt
rustLogic errorHard

Runner-up score comes back empty for a rising list

BugFind the bug and fix the code

What it should do

second_largest(nums) returns the second highest different value in the list, or None if there is none. Example: second_largest(&[10, 20, 5]) → Some(10)

What happens instead

second_largest(&[1, 2, 3]) returns None (null) instead of Some(2), and second_largest(&[10, 20, 5]) returns Some(5) instead of Some(10).

fn second_largest(nums: &[i32]) -> Option<i32> {
    let mut first: Option<i32> = None;
    let mut second: Option<i32> = None;
    for &n in nums {
        if first.map_or(true, |f| n > f) {
            first = Some(n);
        } else if Some(n) != first && second.map_or(true, |s| n > s) {
            second = Some(n);
        }
    }
    second
}

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 logic errors pattern

The wrong operator, an inverted condition, a formula the right way round but backwards.

What you'll practise

A hard Rust debugging exercise about logic errors: the wrong operator, an inverted condition, a formula the right way round but backwards.

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: When a new highest value arrives, the old highest value becomes the runner-up. The code replaces first but forgets to move the old first into second, so that value is lost. In a list that only rises, every number becomes the new first and second is never set.

The fix: Before first = Some(n);, save the old leader: second = first;.

Remember: when you track the top two (or top N) values, a new leader pushes every other place down by one. Test with input in rising order, falling order and mixed order.

The pattern behind it: logic errors.

More logic 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/9854b685-6638-4250-8312-bd8335f6c008" title="Debugging challenge: Runner-up score comes back empty for a rising 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/9854b685-6638-4250-8312-bd8335f6c008">TryBugHunt</a></p>