Ordered Set
A set that stays sorted while you add and remove: O(log n) for every operation, plus the nearest-neighbor and range queries a hash set cannot answer.
Overview
What an ordered set gives you
An ordered set keeps its elements sorted at all times. You can add and remove elements, and you can ask questions that depend on order: the smallest, the largest, the nearest element below or above a value, or how many elements are smaller than a value. Each of these takes O(log n).
It sits between two structures you already know, and the contrast shows what it is for. A hash set adds, removes and checks membership in O(1) on average, but it knows nothing about order. Finding its min or max means a scan, O(n). It cannot answer 'nearest below or above' (floor and ceiling) or 'how many elements are below x' (the rank) at all, and walking it in sorted order means sorting first, O(n log n).
A sorted array is the opposite. Its min or max is O(1), and contains, floor, ceiling and rank are O(log n) by binary search. Walking it in order is O(n). But adding or removing an element is O(n), because the elements after it shift.
The ordered set takes the middle road: add, remove, contains, min, max, floor and ceiling are all O(log n), and so is rank in Python's SortedList. Walking it in sorted order is O(n).
Pick it when the collection changes and you need order. If the collection never changes, sort once and binary search. If you only need the minimum, a heap is simpler.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio