← Questions

Count intervals covering a point

0
GoogleNetflixAppleCodingLast asked Nov 2025

A coding interview question asked in Apple's technical phone screen and at Google and Netflix, last asked Nov 2025. It tests intervals, binary-search and sweep line.

Build a data structure over a fixed list of closed intervals on the integer number line that answers many point queries quickly.

An interval [l, r] covers a point x when l <= x <= r. Both endpoints count.

Implement IntervalCounter:

  • IntervalCounter(intervals: list[tuple[int, int]]): store the intervals. Each has l <= r. Intervals can repeat, and coordinates can be negative or very large.
  • count(x: int) -> int: return how many stored intervals cover x.

count is called many times, so it should be faster than scanning every interval.

Constraints

  • 0 <= len(intervals) <= 10^5
  • -10^9 <= l <= r <= 10^9
  • Up to 10^5 calls to count

Example 1

c = IntervalCounter([(3, 7), (5, 9), (12, 12)])
c.count(2)   # 0
c.count(5)   # 2  -> [3,7] and [5,9]
c.count(9)   # 1  -> [5,9]; the right endpoint is included
c.count(12)  # 1  -> [12,12]

Example 2

c = IntervalCounter([(-4, 0), (-4, 0), (-1, 6)])
c.count(-4)  # 2
c.count(0)   # 3
c.count(7)   # 0

Be ready to extend it: intervals added and removed after construction, and the point covered by the most intervals.

Clarifying questions

  • Are the intervals fixed after construction?
  • Are the endpoints always integers, so r < x is the same as r <= x - 1?
  • Is a query outside every interval allowed, returning 0?
  • How many intervals and queries should I plan for, and are the queries known in advance?

What a strong answer covers

  • Sorts the starts and the ends into two separate lists at construction. A query's answer is the number of starts <= x minus the number of ends < x, each found with a binary search.
  • O(n log n) to build and O(log n) per query, O(n) space, with no dependence on the coordinate range.
  • Gets the closed endpoints right: an interval ending at x still covers x, so only ends strictly below x are subtracted.
  • Mentions the offline alternative: sort the queries with the endpoints and sweep once.
  • Tests: both examples, an empty list, repeated intervals, a point interval, queries at every endpoint, and a brute-force count on random inputs.

Follow-ups

  • Intervals are added and removed after construction: a Fenwick tree over compressed coordinates, or a balanced tree.
  • Find the point covered by the most intervals (a sweep line).
  • Return the intervals that cover x, not just the count (an interval tree).
  • Count intervals that overlap a query range [a, b].

Where it's asked

What it tests

intervals · binary-search · sweep line · fenwick tree

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding