KatInterview

Count Active Ranges at Query Points

Greedy & IntervalsAuto-graded · 17 test cases
MediumAuto-gradedGreedy & Intervalsbinary-searchintervalssorting

Last 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 where lo <= 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^5
  • 0 <= len(probes) <= 10^5
  • Each element of ranges has exactly 2 values: -10^9 <= lo <= hi <= 10^9
  • -10^9 <= probes[j] <= 10^9
  • If probes is empty, return an empty list.
  • If ranges is empty, return a list of zeros with the same length as probes.
  • Duplicate ranges and duplicate probe values are both permitted and must be handled correctly.
  • Point windows where lo == hi are 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.