In a Rust leaderboard stored as BTreeMap<u32, String> keyed by score, why do tied players vanish, and how do you read the top and bottom?
answer
- one value per key
- what insert returns on a repeat
- make the element unique
- both ends of the order
- stable since 1.66
basics
~20 sEach key holds one value, so inserting a second player with an equal score replaces the first. Store unique (score, player) tuples in a BTreeSet instead, then read last() for the top, first() for the bottom, and pop_first() to evict the lowest.
solid answer
~40 s`BTreeMap::insert` on an existing key overwrites the value and returns `Some(old)`; the key itself is not replaced. Two players on 870 therefore collapse into one entry, and `len()` stays the same. Make the ordering element unique: a `BTreeSet<(u32, String)>` sorts by score, then by name to break ties. The ends are direct calls: `last()` is the top score, `first()` the bottom, and `iter().rev().take(10)` the top ten, because the iterators are double-ended. `pop_first()` and `pop_last()` remove and return an end, which suits a board capped at N entries. On a map the equivalents are `first_key_value`, `last_key_value`, `first_entry`, `last_entry`, `pop_first` and `pop_last`, all stable since Rust 1.66. Updating a score means removing the old tuple and inserting the new one, so keep a second index from player to current score.
code
rust · 25 linesuse std::collections::{BTreeMap, BTreeSet};
fn main() {
// Bug: score as the key, so a tie overwrites the earlier player.
let mut by_score: BTreeMap<u32, &str> = BTreeMap::new();
by_score.insert(870, "ana");
by_score.insert(920, "bo");
let old = by_score.insert(870, "cy"); // same key: value replaced
println!("replaced: {old:?}, len = {}", by_score.len());
// Fix: make each entry unique with (score, player) as the element.
let mut board: BTreeSet<(u32, String)> = BTreeSet::new();
for (s, p) in [(870, "ana"), (920, "bo"), (870, "cy"), (640, "di")] {
board.insert((s, p.to_string()));
}
println!("top: {:?}", board.last());
println!("bottom: {:?}", board.first());
let top3: Vec<_> = board.iter().rev().take(3).collect();
println!("top 3: {top3:?}");
// Drop the lowest entry when the board is over capacity.
let evicted = board.pop_first();
println!("evicted: {evicted:?}, len = {}", board.len());
}go deeper
Recall that a map key holds one value, and that first and last on a BTreeSet return the smallest and largest elements.
Explain insert's Some(old) return, tuple keys that break ties, double-ended iteration for a top N, and pop_first or pop_last for eviction.
Show the full update path: a second index from player to score, then remove and reinsert, and how tie order follows from tuple comparison.
Discuss whether one process-local ordered set is enough or whether a ranking service needs persistence and sharding, which changes which guarantees the API can offer.
## Why tied players vanish A map holds **one value per key**. `BTreeMap::insert(k, v)` on a key that is already present **overwrites the value** and returns `Some(old_value)`. The std docs add that the key itself is not updated. So a leaderboard typed `BTreeMap<u32, String>`, with score as the key, silently loses a player whenever two players tie: - `insert(870, "ana")` returns `None`, and `len()` is 1; - `insert(870, "cy")` returns `Some("ana")`, `len()` is still 1, and Ana is gone. Nothing panics or warns. The bug only shows up as a shorter board, so check the return value of `insert` whenever duplicates are possible. ## Making each entry unique The ordering key has to be unique, while still sorting by score first. The usual options: 1. **`BTreeSet<(u32, String)>`**: tuples compare field by field, so entries sort by score and ties break by name. This is the simplest and most common choice. 2. **`BTreeMap<(u32, PlayerId), Stats>`**: the same idea, when each entry also carries data. 3. **`BTreeMap<u32, Vec<String>>`**: one bucket per score. This works, but every insert and removal must manage the inner `Vec`, including removing the key once its bucket is empty. ## Reading both ends A sorted structure keeps the smallest and largest elements at its two ends, so you never need a full scan with `max_by_key`: | Goal | `BTreeSet<T>` | `BTreeMap<K, V>` | |---|---|---| | Lowest, without removing | `first()` | `first_key_value()` | | Highest, without removing | `last()` | `last_key_value()` | | Remove and return the lowest | `pop_first()` | `pop_first()` | | Remove and return the highest | `pop_last()` | `pop_last()` | | Edit or remove an end in place | (none) | `first_entry()`, `last_entry()` | | Top N, highest first | `iter().rev().take(n)` | `iter().rev().take(n)` | All of these were **stabilised in Rust 1.66**. Older code wrote `iter().next()` and `iter().next_back()` instead. Those still work, and `next_back()` is cheap because the iterators are double-ended, but there was no one-call way to remove an end. `first_entry` returns an `OccupiedEntry`, so you can decrement a value and `remove()` the entry with a single lookup. ## The same calls on an order book The calls are not leaderboard-specific. On the bid side of a book stored as `BTreeMap<u64, u32>`, `last_key_value()` is the best bid and `first_key_value()` the worst. On the ask side, `first_key_value()` is the best ask. Filling an incoming order against the best ask is a loop over `first_entry()`: reduce the quantity through `get_mut`, call `remove()` once the level reaches zero, and move on to the next entry. ## Capping and evicting A board limited to N entries is a short loop: 1. `board.insert((score, name))`, which returns `false` if that exact tuple was already present; 2. if `board.len()` exceeds N, call `board.pop_first()` to evict the lowest entry. `pop_first` on an empty set returns `None` instead of panicking, so the loop is safe on a fresh board. ## Updating a player's score Elements of a `BTreeSet` are only reachable through `&T`, so a stored tuple cannot be edited. Changing its score in place would also break the sorted order. To update a score: - look up the player's current score in a **second index**, such as a `HashMap<String, u32>` from player to score; - `remove(&(old_score, name.clone()))` from the set; - `insert((new_score, name))`, and update the index. Keeping the two structures in step is the price of a leaderboard that answers both "who is top" and "what is Ana's score". ## Ordering ties the way the product wants `iter().rev()` reverses the **whole** tuple, so tied names come out in reverse alphabetical order (`cy` before `ana`). If ties should read alphabetically from the top, store `(Reverse(score), name)` with `std::cmp::Reverse` and iterate forwards: the highest score sorts first, and names stay ascending within a tie. Designing such orderings in general is covered with the comparison traits. ## Mistakes interviewers listen for - Keying by score alone and losing ties without noticing. - Thinking `pop_first` returns the **oldest** entry. It returns the **smallest**. - Scanning with `max_by_key` when `last()` is a direct call. - Trying to mutate a set element in place instead of removing it and inserting it again.
- How do you list a Rust BTreeSet leaderboard's top entries with tied names in alphabetical order?`iter().rev()` reverses the whole `(score, name)` tuple, so tied names come out descending. Store `(Reverse(score), name)` with `std::cmp::Reverse` and iterate forwards instead. The highest score sorts first, and names within a tie stay ascending. `first()` is then the top entry, and `pop_last()` evicts the lowest.
- What does BTreeMap::first_entry give you that first_key_value does not?`first_key_value` returns shared references only. `first_entry` returns an `OccupiedEntry` for the smallest key, so in one lookup you can change the value through `get_mut` or delete the entry with `remove`. That suits an order book where you fill against the best level and drop it once its quantity reaches zero.
- BTreeMap::insert on an existing key keeps the old value and drops the new one.
- BTreeMap stores duplicate keys side by side in insertion order.
- Finding the top score needs a full scan with max_by_key.
- pop_first removes the entry that was inserted first.
- You can update a score by mutating the tuple inside the set.
Assumes Rust 1.99; first_key_value, last_key_value, first_entry, last_entry, pop_first and pop_last on BTreeMap, and first, last, pop_first, pop_last on BTreeSet, are stable since 1.66.