sortedcontainers: The Balanced Tree Python Was Missing
A sorted list, a sorted set, and a sorted dict - with
O(log n)insert, delete, k-th element, and count queries.
Python’s standard library gives you a hash map (dict), a hash set (set), a binary heap (heapq), binary search over sorted lists (bisect), and a double-ended queue (collections.deque). What it does not give you is a balanced binary search tree - a container that stays sorted while you add and remove elements, and that can answer ordered queries (k-th element, rank, and counts) in O(log n).
That container is sortedcontainers - a pure-Python library that is pre-installed on LeetCode’s Python judge, so you can import it in a submission without a second thought.
1 | |
What sortedcontainers provides
The library ships three classes, and each one answers the same three questions: k-th smallest, insert / delete, and how many elements are less than v. The only differences are whether duplicates are kept and whether you store bare values or key-value pairs.
SortedList - a sorted multiset (duplicates kept)
1 | |
k-th smallest - just index it. S[k] is the (k+1)-th smallest element, and duplicates each occupy a position:
1 | |
add / remove / pop - order is preserved. add slots an element in for you; remove deletes a single occurrence; pop(k) removes and returns the element at index k:
1 | |
bisect - how many elements are less than v? bisect_left(v) and bisect_right(v) both return a count:
bisect_left(v): number of elements strictly less than vbisect_right(v): number of elements less than or equal to v
1 | |
SortedSet - a sorted set (duplicates collapsed)
Same three operations, but duplicates collapse into one, so [2, 5, 5, 8, 11] becomes [2, 5, 8, 11]:
1 | |
SortedDict - sorted keys mapped to values
A map stores key-value pairs, not bare values, so you build it from pairs. The same three operations answer questions about keys:
1 | |