Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

You maintain a live leaderboard of players in a TreeSet<Player> ordered by score descending, then id. Scores update often. Users report players appearing twice or not being found. What is wrong and how would you design it correctly?

The bug is changing a player's score while the Player is inside the TreeSet: the tree placed the player by its old score, so after the change searches go the wrong way, remove fails, and re-adding creates a second copy. The correct update removes the player, changes the score, and re-inserts it, all under one lock if threads share the set. A sound design uses immutable entries, such as a record of (score, id), plus a HashMap from id to the current entry so we can find the old one; ConcurrentSkipListSet works for concurrent access with the same remove-then-add discipline, accepting that the two steps are not atomic together, and very large boards may belong in a sorted store such as a Redis sorted set.

Why this question is asked

Leaderboards, priority queues and schedules all keep objects sorted by a value that changes. It is very tempting to keep mutable objects in a TreeSet and update them in place, and it works in a quick test. Then under real traffic, players appear twice, disappear from searches, or cannot be removed. Interviewers ask this scenario because it combines two ideas, how sorted collections locate elements and why their keys must not change, with concurrency and system design. In this answer, we will recap how TreeSet finds elements, reproduce the corruption, design the correct update, make it thread-safe, and decide when the leaderboard should move out of the JVM.

1A Quick Recap of How TreeSet Finds an Element

A TreeSet is a red-black tree ordered by its comparator, here score descending, then id. To find, remove or insert an element, it starts at the root and compares: if the element sorts before the node, it goes left; if after, right; if equal, it has found it. Each decision assumes that the elements already in the tree are still where their ordering says they should be.

The tree computes an element's position once, when it is inserted. It has no way to know that an element's fields changed later, so it does not move it. If the fields used by the comparator change, the element stays at a position that is now wrong, and every search that passes through that part of the tree may take a wrong turn.

2Reproducing the Corruption

Here is the mutable version, with a few players and one in-place update.

Java
class Player {
final String id;
int score;
Player(String id, int score) { this.id = id; this.score = score; }
}
Comparator<Player> byScoreDescThenId =
Comparator.comparingInt((Player p) -> p.score).reversed().thenComparing(p -> p.id);
TreeSet<Player> board = new TreeSet<>(byScoreDescThenId);
Player ann = new Player("ann", 50), bob = new Player("bob", 40), cat = new Player("cat", 30);
board.addAll(List.of(ann, bob, cat)); // order: ann 50, bob 40, cat 30
cat.score = 90; // changed while inside the tree
board.contains(cat); // false: search for 90 goes left of bob, never reaches cat
board.remove(cat); // false: cannot find it
board.add(cat); // true: inserted again at the 90 position
board.size(); // 4: cat appears twice
Board state after cat.score = 90 and add(cat)
Position in treeNodeComparator says it belongs
1cat (90), new nodehere, correct
2ann (50)here, correct
3bob (40)here, correct
4cat (90), old nodeat position 1, stranded
The old node keeps its stale position and the tree cannot find it again.

Notice that every result is consistent with the tree's rules. The search for cat with score 90 starts at the root, which sorts below 90 in descending order, so it goes towards the high scores and never reaches cat's old node among the low scores. remove fails for the same reason, and add, finding no match on the new path, inserts a second node. Iteration then shows cat twice, and the old node may never be removable. Exactly the symptoms the users report.

3The Correct Update: Remove, Change, Re-insert

The rule for any sorted or hashed collection is that fields used for ordering or hashing must not change while the element is inside. So an update has three steps: remove the element while its fields still match its position, change the fields, and insert it again so the tree places it correctly. If several threads share the board, all three steps must run under one lock; otherwise a reader may miss the player between remove and add, or two updates may interleave.

Step throughUpdating a player's score safely
  1. Acquire the board lock
  2. Look up the current entry by idHashMap<String, Entry>
  3. Remove the old entry from the TreeSetfields still match its position
  4. Create a new entry with the new score
  5. Add the new entry and update the map
  6. Release the lock

6 steps in order. Play them, or step through them one at a time.

4A Design With Immutable Entries

Rather than relying on discipline with a mutable Player, we make it impossible to change an entry in place. Each entry is an immutable record of score and id, and a HashMap from id to the current entry lets us find the old one without a search by value.

Java
record Entry(int score, String id) {}
final class Leaderboard {
private static final Comparator<Entry> ORDER =
Comparator.comparingInt(Entry::score).reversed().thenComparing(Entry::id);
private final TreeSet<Entry> ranking = new TreeSet<>(ORDER);
private final Map<String, Entry> byId = new HashMap<>();
synchronized void setScore(String id, int score) {
Entry old = byId.get(id);
if (old != null) ranking.remove(old); // old entry still sorted correctly
Entry now = new Entry(score, id);
ranking.add(now);
byId.put(id, now);
}
synchronized List<Entry> top(int n) {
return ranking.stream().limit(n).toList(); // a snapshot copy for the caller
}
}
board.setScore("cat", 30);
board.setScore("cat", 90);
board.top(3); // [Entry[score=90, id=cat], ...]: one cat, in the right place

Notice that the id tie-breaker in the comparator also matters: without it, two players with the same score would compare as equal, and the TreeSet would silently drop one of them. Because entries are records with final fields, no code can corrupt the tree by mutating an entry. And because top returns a copy, callers never iterate the live set while another thread changes it.

5Concurrent Access With ConcurrentSkipListSet

A single lock is simple and is fine for many thousands of updates per second. If contention becomes a problem, ConcurrentSkipListSet offers the same NavigableSet operations with lock-free reads and concurrent writes, and a ConcurrentHashMap can replace the id map. We keep the same remove-then-add discipline, but must accept that the remove and the add are now two separate atomic operations, not one. For a brief moment the player is absent from the ranking, and a reader computing ranks may miss them; two concurrent updates of the same player could also interleave unless we serialise updates per id, for example with ConcurrentHashMap.compute on the id map wrapping both steps. For a game leaderboard, that brief gap is usually acceptable; for anything financial, it is not, and we would keep the lock.

6When the Board Outgrows the JVM

An in-memory TreeSet works for a single instance and a board of perhaps a few million players. When many service instances must share one board, or the board must survive restarts, a dedicated sorted store is a better fit. A Redis sorted set keeps members ordered by a score, updates with ZADD in O(log n), and answers rank and top-N queries with commands such as ZREVRANK and ZREVRANGE, atomically on the server. It solves the update problem by design, because the score is the sort key and changing it is a single operation that moves the member. The trade-offs are a network hop per operation and another system to operate.

7Follow-up questions

How would you return a player's rank efficiently?

TreeSet does not track subtree sizes, so headSet(entry).size() walks the elements and is O(n). For frequent rank queries, an order-statistic tree, a skip list with span counts, or a Redis sorted set with ZREVRANK, which is O(log n), is the right tool.

Why not simply re-sort a list of players on each read?

For small boards, that can be perfectly fine and avoids all of these problems. Sorting 10,000 players takes about a millisecond. It becomes a problem when reads are frequent and the board is large, which is when a structure that keeps the order incrementally pays off.

8Conclusion

In this answer, we saw that changing a player's score while it sits in a TreeSet leaves its node at a stale position, so lookups and removal fail and a re-add creates a duplicate. The correct update removes the entry, changes the score and re-inserts it under one lock, and immutable (score, id) records with a HashMap from id to the current entry make that design hard to break. ConcurrentSkipListSet supports concurrent access with the same discipline but without atomicity across the two steps, and a Redis sorted set suits very large or shared boards.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is that scores are updated while players are inside the TreeSet. A TreeSet places an element by its comparator once, when it is inserted, and never re-sorts it.

Then, if they want more

When a score changes in place, the node stays at its old position, so a search for the new score goes down a different path and never finds it. remove fails, contains fails, and adding the player again inserts a second node at the new position, so the player appears twice and the old node can never be removed.

The fix is the rule for any sorted or hashed collection: fields used for ordering must not change while the element is inside. An update must remove the player, change the score and re-insert it, and if threads share the board, all three steps happen under one lock.

I would design it with immutable entries, a record of score and id, ordered by score descending and then id, so equal scores do not collapse, plus a HashMap from id to the current entry so I can find the old one to remove.

For more concurrency, ConcurrentSkipListSet and ConcurrentHashMap work with the same remove-then-add steps, accepting that the two steps are not atomic together. For very large or shared boards, I would use a Redis sorted set, where ZADD updates the score atomically and ZREVRANGE gives the top N.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "You maintain a live leaderboard of players in a TreeSet<Player> ordered by score...": https://scrivio-interview-library.netlify.app/java/sets/3d6025a830/