Technique
Ordered Set / Balanced BST (TreeMap, multiset)
A balanced BST supporting insert, delete, and predecessor/successor/floor/ceiling in O(log n).
0/13 solved
Recognise it
The signal
nearest value >= x among a changing set
1Brute force
Sorted array with O(n) insertion, or linear scans.
2The observation
O(n) insert/delete in sorted arrays: a balanced tree keeps order with log-time updates.
3Why it works
The structure is always sorted; lower_bound returns the first element >= x.
Reach for it when
- +online interval booking
- +sliding window with order queries
- +assign each customer the best remaining item
Not when
- ×only the min/max is needed (heap is simpler)
- ×k-th element queries in C++ without pb_ds (use BIT over compressed values)
Practice
- My Calendar IGoogle, StripeMedium
- Room AllocationCSESMedium
- Movie Festival IICSESMedium
- Concert TicketsCSESMedium
- Traffic LightsCSESMedium
- TowersCSESMedium
- Sliding Window MedianCSESMedium
- Minimize Manhattan DistancesHard
- Range ModuleHard
- Count Integers in IntervalsHard
- Data Stream as Disjoint IntervalsHard
- Sliding Window MedianHard
- Josephus Problem IICSESHard
Pitfalls
Misconceptions
- !multiset.erase(value) removes ALL copies; erase an iterator instead
Go deepervariants and techniques · 3 combinations · resources
Combinations
Greedy+Ordered Set / Balanced BST (TreeMap, multiset)
match customers to the highest ticket <= budget; assign k members to movies
- Greedy:
- assigns each request the best remaining resource
- Ordered Set / Balanced BST (TreeMap, multiset):
- finds the floor/ceiling resource and removes it
Manhattan <-> Chebyshev Rotation+Ordered Set / Balanced BST (TreeMap, multiset)
remove exactly one point to minimise the max Manhattan distance
- Manhattan <-> Chebyshev Rotation:
- max distance = max(range of u, range of v)
- Ordered Set / Balanced BST (TreeMap, multiset):
- multisets of u and v support removing one point and reading the new extremes
Merge Intervals+Ordered Set / Balanced BST (TreeMap, multiset)
add/remove/query ranges online (range module, count covered integers)
- Merge Intervals:
- the merge/split logic for overlapping ranges
- Ordered Set / Balanced BST (TreeMap, multiset):
- a TreeMap from start to end holds disjoint intervals with O(log n) neighbour lookup
Range ModuleCount Integers in IntervalsData Stream as Disjoint Intervals