Sub topic 16
Applications: leaderboards, time-series windows and scheduling
This chapter assumes you know the navigation operations (floor, ceiling), range views and comparator consistency from earlier chapters. It applies them to three common jobs. In each, a hash map can't answer the question efficiently, because the question depends on order.
Leaderboards
A leaderboard needs the top N players, and scores change constantly. A sorted set ordered by score descending, with the name as a tie-breaker, gives the top N by walking from the first element. Each insert or removal costs O(log n).
import java.util.Comparator;
import java.util.TreeSet;
public class Leaderboard {
record Entry(int score, String name) {}
public static void main(String[] args) {
TreeSet<Entry> board = new TreeSet<>(
Comparator.comparingInt(Entry::score).reversed()
.thenComparing(Entry::name));
board.add(new Entry(120, "ana"));
board.add(new Entry(95, "bo"));
board.add(new Entry(120, "cy"));
// Update bo: remove the old entry, then insert the new one.
board.remove(new Entry(95, "bo"));
board.add(new Entry(130, "bo"));
board.stream().limit(2).forEach(System.out::println);
// Entry[score=130, name=bo]
// Entry[score=120, name=ana]
}
}The tie-breaker matters. Without thenComparing(Entry::name), two players with the same score compare as equal, and the set silently drops one of them. To update a score, remove the old entry first. Changing a key that is already in the set breaks the tree's ordering.
Time-series windows
Events arrive with timestamps, and you often want everything in a time window. A sorted array with two binary searches returns the window as a slice. The half-open interval [start, end) avoids counting a boundary event twice.
from bisect import bisect_left, insort
events = []
for t, label in [(5, "a"), (1, "b"), (9, "c"), (3, "d")]:
insort(events, (t, label))
def window(start, end):
lo = bisect_left(events, (start,))
hi = bisect_left(events, (end,))
return events[lo:hi]
print(window(3, 9)) # [(3, 'd'), (5, 'a')]The one-element tuple (start,) sorts before any (start, label), so bisect_left lands on the first event at or after start. Inserting into the middle of a Python list is O(n), which is fine for modest data. For heavy write loads, use a tree-based structure such as Java's TreeMap.subMap, which returns a view.
Scheduling
A booking calendar must reject overlapping intervals. Store each booking as start mapped to end. A new booking [start, end) conflicts only with its two neighbours: the booking that starts at or before start, and the one that starts next after it.
import java.util.Map;
import java.util.TreeMap;
public class Calendar {
private final TreeMap<Integer, Integer> booked = new TreeMap<>();
boolean book(int start, int end) {
Map.Entry<Integer, Integer> before = booked.floorEntry(start);
if (before != null && before.getValue() > start) return false;
Integer next = booked.ceilingKey(start);
if (next != null && next < end) return false;
booked.put(start, end);
return true;
}
public static void main(String[] args) {
Calendar c = new Calendar();
System.out.println(c.book(10, 20)); // true
System.out.println(c.book(15, 25)); // false
System.out.println(c.book(20, 30)); // true
}
}Each check is two O(log n) lookups, however many bookings exist.
Exercise
In the calendar example, why is checking only floorEntry(start) and ceilingKey(start) enough to detect every overlap?
Show answer
Bookings never overlap each other, so they are ordered by start and by end. Any existing booking that overlaps the new one must either begin at or before the new start, or begin inside the new interval. The first case can only be the closest booking at or before start, which floorEntry finds. The second case can only be the earliest booking after start, which ceilingKey finds. All other bookings are further away and cannot overlap.