TryBugHunt
javaLogic errorHard

Tied players listed in reverse alphabetical order

BugFind the bug and fix the code

What it should do

topPlayers(scores, k) returns the names of the k best players, highest score first. Players with the same score are listed alphabetically. So topPlayers({"ann": 50, "bob": 70, "cy": 70, "dee": 40}, 2) returns ["bob", "cy"].

What happens instead

topPlayers({"ann": 50, "bob": 70, "cy": 70, "dee": 40}, 2) returns ["cy", "bob"]. Players with different scores are in the right order.

import java.util.*;

public class Main {
    static List<String> topPlayers(Map<String, Integer> scores, int k) {
        List<String> names = new ArrayList<>(scores.keySet());
        names.sort((a, b) -> {
            int byScore = Integer.compare(scores.get(b), scores.get(a));
            if (byScore != 0) {
                return byScore;
            }
            return b.compareTo(a);
        });
        return names.subList(0, Math.min(k, names.size()));
    }
}

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 Java 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)

A comparator returns a negative number when a should come first. To sort scores from high to low, the code deliberately compares b with a, and that part is right. The tie-break was written the same way, b.compareTo(a), which sorts names from Z to A. Each key in a multi-key comparator has its own direction, and reversing one must not reverse the others. Comparator.comparing(scores::get).reversed().thenComparing(Comparator.naturalOrder()) makes each direction explicit. When a sort is right in general but wrong only for ties, look straight at the tie-break.

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/94b28890-af02-468c-b63d-d2fa684f2f19" title="Debugging challenge: Tied players listed in reverse alphabetical order" 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/94b28890-af02-468c-b63d-d2fa684f2f19">TryBugHunt</a></p>