Count in Ranges
Write count_in_ranges(sorted_numbers, queries). sorted_numbers is a list sorted from smallest to largest (it may contain repeats). queries is a list of (low, high) pairs. Return a list with, for each query, how many numbers x satisfy low <= x <= high, both ends included.
The tests have 200,000 numbers and 200,000 queries.
Understand the problem
Do one query by hand.
In [1, 2, 2, 5, 8], how many numbers lie between 2 and 5, both ends included?
The numbers 2, 2 and 5 qualify: three. Both ends are included, and repeats count each time.
A sorted list has 200,000 numbers. For one query, how many items does a loop examine?
- About 18
- All 200,000
- About 400
A plain loop (or sum(1 for x in numbers if low <= x <= high)) looks at every item: 200,000 steps. With 200,000 queries that is 40 billion steps.
Write the brute force
Write the simplest version that is correct, even if it is slow. Then you have something to test against and something to improve.
def count_in_ranges(sorted_numbers, queries):
# Write the simple version here. It only has to be correct, not fast.
pass
Hint 1: a question to ask yourself
For one query, how do you count the numbers that fit?
Hint 2: the shape of the answer
For each (low, high), count with a loop or sum(1 for x in sorted_numbers if low <= x <= high).
Find the bottleneck
The list is sorted. How can that help?
In a sorted list, the numbers that satisfy low <= x <= high are...
- Scattered everywhere
- One block of neighbours
- Only at the ends
Because the list is sorted, all the qualifying numbers sit next to each other in one block. The count is the position where the block ends minus the position where it starts.
Which function finds the position where low would be inserted, in O(log n) steps, by halving the list?
list.indexbisect.bisect_leftlist.count
bisect_left(a, x) returns the first position where x could be inserted, which is the number of items smaller than x. bisect_right(a, x) returns the position after the last x: the number of items less than or equal to x.
Make it faster
Use binary search for both boundaries.
def count_in_ranges(sorted_numbers, queries):
# Write the faster version here.
pass
Hint 1: a question to ask yourself
How many numbers are smaller than low, and how many are less than or equal to high?
Hint 2: the pattern
Answer = bisect_right(numbers, high) - bisect_left(numbers, low).
Hint 3: pseudocode
result = []
for low, high in queries:
start = bisect_left(numbers, low) # items < low
end = bisect_right(numbers, high) # items <= high
result.append(end - start)
return result
Reflect
Brute force: O(n) per query
def count_in_ranges(sorted_numbers, queries):
return [sum(1 for x in sorted_numbers if low <= x <= high) for low, high in queries]
Improved: binary search, O(log n) per query
from bisect import bisect_left, bisect_right
def count_in_ranges(sorted_numbers, queries):
return [bisect_right(sorted_numbers, high) - bisect_left(sorted_numbers, low)
for low, high in queries]
What this tests: the bisect module, binary search, bisect_left versus bisect_right, and using the fact that data is sorted.
bisect_left versus bisect_right: with repeats, bisect_left(a, 2) is the position of the first 2 and bisect_right(a, 2) is the position after the last 2. Using the right one for high and the left one for low includes both ends. Swapping them is the classic off-by-one.
Binary search: halve the search range each step. 200,000 items need at most 18 steps.
Empty ranges: if low > high the formula can give a negative number; the tests never ask for that, and a real function should return 0 (use max(0, ...)).
Cost:
| Version | Time |
|---|---|
| Loop per query | O(n x q) |
bisect |
O(q log n) |
What an interviewer might ask next: The list changes between queries (items are added). What structure supports that? (A sorted container such as sortedcontainers.SortedList, or a Fenwick tree.)
import random
VISIBLE = 3
CASES = [
(([1, 2, 2, 5, 8], [(2, 5)]), [3], 'a normal range'),
(([1, 2, 2, 5, 8], [(0, 100), (3, 4), (8, 8)]), [5, 0, 1], 'several queries'),
(([], [(1, 5)]), [0], 'an empty list'),
(([5, 5, 5], [(5, 5)]), [3], 'all equal to both ends'),
(([1, 2, 3], []), [], 'no queries'),
(([1, 3, 5, 7], [(2, 6)]), [2], 'ends between the numbers'),
(([-5, -1, 0, 4], [(-5, -1), (0, 0)]), [2, 1], 'negative numbers'),
(([1, 2, 3], [(4, 9), (-3, 0)]), [0, 0], 'ranges outside the list'),
]
def REFERENCE(numbers, queries):
from bisect import bisect_left, bisect_right
return [bisect_right(numbers, high) - bisect_left(numbers, low) for low, high in queries]
LIMIT = 2.0
def PERF():
rng = random.Random(8)
numbers = sorted(rng.randint(0, 10 ** 6) for _ in range(200000))
queries = []
for _ in range(200000):
a, b = rng.randint(0, 10 ** 6), rng.randint(0, 10 ** 6)
queries.append((min(a, b), max(a, b)))
return [('200000 numbers, 200000 queries', (numbers, queries))]