TryBugHunt
cppOff-by-oneEasy

Last two scores come back as just one score

BugFind the bug and fix the code

What it should do

lastN(scores, n) returns the last n scores in their original order. Example: lastN({10, 20, 30, 40}, 2) → {30, 40}

What happens instead

lastN({10, 20, 30, 40}, 2) returns [40] instead of [30, 40].

#include <vector>

std::vector<int> lastN(std::vector<int> scores, int n) {
    std::vector<int> out;
    for (size_t i = scores.size() - n + 1; i < scores.size(); i++) {
        out.push_back(scores[i]);
    }
    return out;
}

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 C++ 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: The loop starts at scores.size() - n + 1. For 4 scores and n = 2 that is index 3, so only the very last score is copied.

The fix: Start at scores.size() - n. Indexes run from 0 to size - 1, so the last n items start at size - n.

Remember: When you count back from the end, check the start index with a tiny example. With 4 items and n = 2 you want indexes 2 and 3, and 4 - 2 = 2 is the first one.

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/09042cf6-709c-4e12-9938-4600cd898529" title="Debugging challenge: Last two scores come back as just one score" 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/09042cf6-709c-4e12-9938-4600cd898529">TryBugHunt</a></p>