TryBugHunt
cppOtherEasy

Shortest name finder returns the first name alphabetically

BugFind the bug and fix the code

What it should do

shortestName(names) returns the shortest name in a non-empty list. Example: shortestName({"Charlotte", "Bo", "Alexander"}) → "Bo"

What happens instead

shortestName({"Charlotte", "Bo", "Alexander"}) returns "Alexander".

#include <algorithm>
#include <string>
#include <vector>

std::string shortestName(std::vector<std::string> names) {
    return *std::min_element(names.begin(), names.end());
}

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 mutation and copying bugs pattern

Copies where you meant references, references where you meant copies, and shallow copies of pointers.

What you'll practise

An easy C++ debugging exercise about mutation and copying bugs: copies where you meant references, references where you meant copies, and shallow copies of pointers.

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: Without a comparator, std::min_element uses < on the strings, and < on std::string compares alphabetically. "Alexander" comes first in the alphabet, so it is the "smallest".

The fix: Pass a comparator that compares lengths: [](const std::string& a, const std::string& b) { return a.size() < b.size(); }

Remember: min_element, max_element and sort all use < unless you say otherwise. For strings that means dictionary order, not length.

The pattern behind it: mutation and copying bugs.

More mutation and copying bugs 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/afed02a8-9db4-4a50-bcf4-f06530ae8dea" title="Debugging challenge: Shortest name finder returns the first name alphabetically" 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/afed02a8-9db4-4a50-bcf4-f06530ae8dea">TryBugHunt</a></p>