Sub topic 8
Ordered structures: sorted data, ranges and neighbors
This chapter assumes you know Python lists and dictionaries, can read Big-O notation, and have seen how hash tables work. A hash table answers "is this key present?" very quickly. It cannot answer "what is the next key after this one?" or "which keys fall between 20 and 40?". Ordered structures answer those questions.
What a hash table cannot do
A hash table scatters keys by their hash value, so it keeps no useful order. To find the smallest key greater than 25, you would have to scan every key. That costs O(n).
You need an ordered structure when a problem asks for any of these:
- The successor or predecessor of a value (the nearest larger or smaller one).
- All items inside a range, such as ids from 20 to 40.
- The minimum, the maximum, or the k-th smallest item at any time.
- Items visited in sorted order.
Sorted list with binary search
The simplest ordered structure is a Python list kept in sorted order. Binary search repeatedly halves the search range, so a lookup costs O(log n). The bisect module does this for you.
import bisect
sorted_ids = [10, 20, 30, 40]
i = bisect.bisect_left(sorted_ids, 25)
print(i, sorted_ids[i]) # 2 30
bisect.insort(sorted_ids, 25)
print(sorted_ids) # [10, 20, 25, 30, 40]bisect_left returns the index where the value would be inserted. That index points at the successor, the first element that is 25 or larger. If no such element exists, the index equals len(sorted_ids), so check it before you read the list.
A range query is two binary searches and a slice:
import bisect
ids = [10, 20, 25, 30, 40, 55]
low = bisect.bisect_left(ids, 20) # first index with value >= 20
high = bisect.bisect_right(ids, 40) # first index with value > 40
print(ids[low:high]) # [20, 25, 30, 40]The cost is O(log n) to find both ends, plus O(k) to copy the k results.
The cost of insertion
Finding the position is cheap, but insort still has to shift every element after it. Insertion and deletion in the middle of a list are O(n). The shifting is a fast memory copy, so a sorted list works well for thousands or even hundreds of thousands of items. It becomes slow when you do many inserts into a very large collection.
Balanced search trees
A balanced search tree keeps items in order and rebalances itself on every change. Search, insert, delete, successor and predecessor all cost O(log n). Range queries cost O(log n + k).
Python's standard library has no balanced tree. Languages such as Java (TreeMap) and C++ (std::map) include one. In Python, the usual choices are a sorted list for read-heavy data, or a third-party package such as sortedcontainers when you need frequent inserts.
Comparing the options
| Structure | Lookup | Insert | Successor | Range query |
|---|---|---|---|---|
| Hash table | O(1) average | O(1) average | O(n) | O(n) |
| Sorted list | O(log n) | O(n) | O(log n) | O(log n + k) |
| Balanced tree | O(log n) | O(log n) | O(log n) | O(log n + k) |
Common errors
- Reading
sorted_ids[i]without checking thati < len(sorted_ids). - Using
bisecton a list that is not sorted. It returns a wrong answer and raises no error. - Choosing an ordered structure when you only need membership tests. A set is simpler and faster.
- Choosing a heap when you need ranges. A heap only gives you the smallest item cheaply.
Exercise
A service stores 100,000 timestamps in a sorted list and must return every timestamp between two given times, many times per second. New timestamps arrive occasionally. Which operations do you use, and what does one query cost?
Show answer
Use bisect.bisectleft for the start time and bisect.bisectright for the end time, then slice between the two indexes. One query costs O(log n + k), where k is the number of results. Occasional arrivals can use bisect.insort at O(n) each, which is acceptable because inserts are rare. If inserts became frequent, switch to a balanced tree or sortedcontainers.