Sub topic 5
Range queries and sub-range views
This chapter assumes you know basic map and set use, Big-O notation, and binary search. You also need the navigation operations from the previous chapter, such as floorEntry and ceilingEntry.
What a range query asks
A range query returns every key between a lower bound and an upper bound. Examples are "all orders placed between 9:00 and 10:00" or "all scores from 70 up to but not including 90".
A hash map cannot answer this without scanning every entry. An ordered map can. It finds the lower bound, then walks forward in key order until it passes the upper bound.
The cost is O(log n) to find the start, plus O(k) to visit the k results.
Inclusive and exclusive bounds
Each bound is either inclusive (the bound itself is included) or exclusive (it is left out). Most libraries use a half-open range: the lower bound is inclusive and the upper bound is exclusive. Java's subMap(from, to) follows this rule.
import java.util.SortedMap;
import java.util.TreeMap;
TreeMap<Integer, String> grades = new TreeMap<>();
grades.put(60, "D");
grades.put(70, "C");
grades.put(80, "B");
grades.put(90, "A");
SortedMap<Integer, String> middle = grades.subMap(70, 90);
System.out.println(middle); // {70=C, 80=B}Key 70 is in the result and key 90 is not. TreeMap also has a four-argument form, subMap(from, fromInclusive, to, toInclusive), when you need different bounds.
Views, not copies
subMap does not copy entries. It returns a view, which is a window onto the original map. This has three effects:
- Creating the view is cheap, because no entries are copied.
- Changes to the original map show up in the view.
- Changes made through the view write to the original map.
A view also enforces its range. Putting a key outside the bounds into the view throws an IllegalArgumentException.
middle.put(85, "B+"); // allowed, 85 is inside [70, 90)
System.out.println(grades); // {60=D, 70=C, 80=B, 85=B+, 90=A}
// middle.put(95, "A+"); // would throw IllegalArgumentExceptionIf you need a snapshot that will not change, copy the view: new TreeMap<>(middle).
TreeMap offers related views: headMap(to) for keys below a bound, tailMap(from) for keys at or above a bound, and descendingMap() for reverse order.
Range queries on a sorted array
You can build the same behavior on a sorted array. Find both boundaries with binary search, then slice between them. Python's bisect module supplies the searches.
from bisect import bisect_left, bisect_right, insort
scores = []
for s in [50, 20, 40, 20, 30]:
insort(scores, s)
print(scores) # [20, 20, 30, 40, 50]
lo = bisect_left(scores, 20) # 0
hi = bisect_right(scores, 40) # 4
print(scores[lo:hi]) # [20, 20, 30, 40]The two functions treat duplicates differently:
| Function | Returns | Use it for |
|---|---|---|
| `bisect_left(a, x)` | Index of the first element `>= x` | An inclusive lower bound |
| `bisect_right(a, x)` | Index just after the last element `<= x` | An inclusive upper bound |
Swap them to get exclusive bounds. Use bisect_right for an exclusive lower bound and bisect_left for an exclusive upper bound.
A Python slice is a copy, not a view, and insort costs O(n) because later elements must shift.
Common errors
- Off-by-one bounds. Check whether your library treats each end as inclusive or exclusive.
- Reversed bounds.
subMap(90, 70)throwsIllegalArgumentExceptionbecause the lower bound is above the upper bound. - Assuming a view is a snapshot. Modifying the map while holding a view changes what the view shows.
Exercise
A TreeMap<Integer, String> holds keys 10, 20, 30, 40, 50. What does subMap(20, true, 40, true) contain, and what happens if you then call remove(30) on the original map?
Show answer
It contains keys 20, 30 and 40. After remove(30) on the original map, the view contains only 20 and 40, because the view reflects changes to the underlying map.
Exercise
A sorted Python list is [10, 20, 20, 20, 30]. Which two bisect calls give the slice of all values from 20 to 30, both inclusive, and what slice do they produce?
Show answer
lo = bisectleft(a, 20) is 1 and hi = bisectright(a, 30) is 5. The slice a[1:5] is [20, 20, 20, 30].