TreeMap in problem solving
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Java TreeMap provides powerful navigation and range views that solve interval and scheduling problems cleanly.
Key navigation methods: floorKey, ceilingKey and subMap
Standard maps only check whether an exact key exists in constant expected time. Java TreeMap implements NavigableMap, offering nearest-neighbor and range lookups.
Example 1 · NavigableMap Methods Demonstration
import java.util.TreeMap;
public class Main { public static void main(String[] args) { TreeMap<Integer, String> map = new TreeMap<>(); map.put(10, "Ten"); map.put(20, "Twenty"); map.put(30, "Thirty");
System.out.println("floorKey(25): " + map.floorKey(25)); System.out.println("ceilingKey(25): " + map.ceilingKey(25)); System.out.println("lowerKey(20): " + map.lowerKey(20)); System.out.println("higherKey(20): " + map.higherKey(20)); }}floorKey(25): 20 ceilingKey(25): 30 lowerKey(20): 10 higherKey(20): 30
What this code does
- floorKey and ceilingKey permit equal matches while lowerKey and higherKey require strict inequality.
- Lookups navigate the internal Red-Black tree in O(log n) time.
- Absent candidates return null when boundaries are exceeded.
The floorKey method returns the greatest key less than or equal to a target. The ceilingKey method returns the smallest key greater than or equal to a target. The lowerKey and higherKey methods provide strict inequalities. The subMap method creates a dynamic sub-range view between two key bounds. All these navigation methods execute in guaranteed O(log n) logarithmic time.
Calendar booking and interval overlap detection
The calendar booking problem schedules events without overlapping existing bookings. A brute-force check tests the new interval [start, end) against all existing events. With n booked events, checking each new request takes linear O(n) time.
Example 2 · Calendar Booking System
import java.util.TreeMap;
public class Main { static class MyCalendar { private TreeMap<Integer, Integer> calendar = new TreeMap<>();
public boolean book(int start, int end) { Integer prevStart = calendar.floorKey(start); if (prevStart != null && calendar.get(prevStart) > start) { return false; } Integer nextStart = calendar.ceilingKey(start); if (nextStart != null && nextStart < end) { return false; } calendar.put(start, end); return true; } }
public static void main(String[] args) { MyCalendar cal = new MyCalendar(); System.out.println("Book 10-20: " + cal.book(10, 20)); System.out.println("Book 15-25: " + cal.book(15, 25)); System.out.println("Book 20-30: " + cal.book(20, 30)); }}Book 10-20: true Book 15-25: false Book 20-30: true
What this code does
- Map stores interval start times as keys and end times as values.
- Floor check detects overlap with the immediately preceding event.
- Ceiling check detects collision with the immediately following event.
Using a TreeMap keyed by interval start times optimizes booking to O(log n). To check a new interval [start, end), look up the event starting just before it with floorKey. Verify that the previous event ends on or before the new start time. Next check the event starting on or after the new start time with ceilingKey. Verify that the new interval ends on or before that next event start time. If both checks pass, insert the booking in O(log n) time.
Real-world applications: price ladders and time series
Financial exchanges maintain limit order books using price ladders. A TreeMap groups pending orders by price level, keeping best bids and asks at extremes.
Example 3 · Order Book Price Ladder
import java.util.TreeMap;
public class Main { static class OrderBook { private TreeMap<Double, Integer> bids = new TreeMap<>();
public void addOrder(double price, int qty) { bids.put(price, bids.getOrDefault(price, 0) + qty); }
public double getBestBid() { return bids.lastKey(); }
public void printTopLevels() { System.out.println("Best Bid: $" + getBestBid() + " (Qty: " + bids.get(getBestBid()) + ")"); } }
public static void main(String[] args) { OrderBook book = new OrderBook(); book.addOrder(100.50, 10); book.addOrder(101.00, 5); book.addOrder(99.75, 20);
book.printTopLevels(); }}Best Bid: $101.0 (Qty: 5)
What this code does
- TreeMap maintains sorted order book prices automatically.
- The highest bid price corresponds to lastKey in O(log n) time.
- Quantities accumulate at each specific price tick level.
Time series monitoring systems store sensor readings keyed by timestamp. Querying values across time windows uses subMap to extract data slices without re-sorting. Rate limiters and sliding window algorithms use TreeMap to track sliding expiration windows efficiently.
Next step
Check your understanding
10 quick questions