Count Active Ranges at Query Points
Greedy & IntervalsAuto-graded · 17 test casesLast updated
Tests whether a candidate can efficiently count how many inclusive ranges cover each of a set of query values using binary search decomposition.
Problem Statement
A monitoring system tracks a collection of active windows, each defined by a lower and upper bound. Every window is inclusive on both ends, meaning a value x falls inside window [lo, hi] whenever lo <= x <= hi.
Given a list of such windows and a separate list of probe values, determine how many windows are active at each probe value.
Write a function count_active_ranges(ranges, probes) that accepts:
ranges: a list of pairs[lo, hi], each describing one inclusive window wherelo <= hi.probes: a list of integers representing the values to evaluate.
Return a list of integers the same length as probes, where position i holds the number of windows that contain probes[i].
Constraints
0 <= len(ranges) <= 10^50 <= len(probes) <= 10^5- Each element of
rangeshas exactly 2 values:-10^9 <= lo <= hi <= 10^9 -10^9 <= probes[j] <= 10^9- If
probesis empty, return an empty list. - If
rangesis empty, return a list of zeros with the same length asprobes. - Duplicate ranges and duplicate probe values are both permitted and must be handled correctly.
- Point windows where
lo == hiare valid; a probe equal to that value is considered inside the window.
Examples
Example 1
Input: count_active_ranges([[1, 4], [2, 6], [7, 9], [3, 5]], [2, 3, 5, 7, 10])
Output: [2, 3, 2, 1, 0]
Example 2
Input: count_active_ranges([[5, 5], [1, 10]], [5, 4, 11])
Output: [2, 1, 0]
Hints
Hint 1
Checking every range against every probe is O(N·Q) — around 10^10 operations at the given limits. Think about whether you can preprocess the ranges to answer each probe faster.
Hint 2
A probe `q` lies inside `[lo, hi]` when two independent conditions hold: `lo <= q` AND `hi >= q`. Try counting each condition separately using sorted arrays and binary search.
Hint 3
Once you have a sorted list of all `lo` values and a sorted list of all `hi` values, one `bisect_right` and one `bisect_left` call per probe gives you the answer. Pay close attention to which variant you use for each list — the inclusive boundary rule makes this matter.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why brute force is too slow
Checking every range against every probe costs O(N · Q). At the maximum input sizes that is up to 10^10 comparisons, which is far too slow.
Decomposing the containment condition
A probe q sits inside [lo, hi] when two things are true at the same time: lo <= q and hi >= q. Counting ranges where both hold simultaneously is hard. Counting ranges where each holds individually is easy — and the two counts can be combined.
The key identity is:
active(q) = #{ranges with lo <= q} − #{ranges with hi < q}
This works because of a subset relationship. Any range with hi < q also has lo <= hi < q, so it is already included in the first count. Subtracting the second count removes exactly those ranges that ended before q, leaving only ranges still open at q.
Using binary search
Extract all lower bounds into one sorted list and all upper bounds into a separate sorted list. The pairing between a lower bound and its upper bound no longer matters.
For each probe q:
bisect_right(lower, q)counts lower bounds<= q(inclusive, so ranges that have started byq).bisect_left(upper, q)counts upper bounds< q(strictly less, so ranges that ended beforeq).
The choice between bisect_right and bisect_left is deliberate. A range whose lower bound equals q does contain q, so it must be counted — bisect_right includes it. A range whose upper bound equals q also contains q, so it must not be subtracted — bisect_left excludes equal values from the "already closed" count.
Swapping either bisect function would miscount point windows where lo == hi == q.
Worked trace
For ranges = [[1,4],[2,6],[7,9],[3,5]]:
lower = [1, 2, 3, 7]
upper = [4, 5, 6, 9]
| q | lo ≤ q | hi < q | answer |
|---|---|---|---|
| 2 | 2 | 0 | 2 |
| 3 | 3 | 0 | 3 |
| 5 | 3 | 1 | 2 |
| 7 | 4 | 3 | 1 |
| 10 | 4 | 4 | 0 |
Output: [2, 3, 2, 1, 0].
Edge cases
- Empty
ranges: both sorted lists are empty, every bisect returns 0, and the output is all zeros. - Empty
probes: the list comprehension produces[]. - Point windows (
lo == hi): handled correctly by the right/left bisect asymmetry. - Duplicate ranges: each copy contributes its own entries to both lists, so duplicates are counted with full multiplicity.
- Duplicate probes: each probe is evaluated independently.
- Extreme coordinates (±10^9): only comparisons are used, so there are no overflow issues.
Complexity
- Time: O(N log N + Q log N) — sorting both lists is O(N log N); each of the Q probes makes two O(log N) binary searches.
- Space: O(N) for the two sorted lists, plus O(Q) for the output.
Reference solution
from bisect import bisect_left, bisect_right
from typing import List
def count_active_ranges(ranges: List[List[int]], probes: List[int]) -> List[int]:
# Decompose each range into independent sorted arrays of lower and upper bounds.
# The pairing between lo and hi is irrelevant for pure counting.
lower = sorted(lo for lo, hi in ranges)
upper = sorted(hi for lo, hi in ranges)
# For a probe q:
# bisect_right(lower, q) -> number of ranges whose lo <= q
# bisect_left(upper, q) -> number of ranges whose hi < q
# Subtracting removes ranges that closed before reaching q.
return [bisect_right(lower, q) - bisect_left(upper, q) for q in probes]