The "Count Integers in Intervals" interview question asks you to design a data structure that can dynamically add intervals and return the total number of unique integers covered by all added intervals. Intervals can overlap, so you must ensure that each integer is only counted once, regardless of how many intervals cover it.
This "Hard" difficulty problem is popular at Databricks, Uber, and Google because it tests efficiency in managing dynamic ranges. It evaluates a candidate's ability to handle overlapping intervals and maintain a global count without re-calculating everything from scratch. It is a classic example of where naive list storage fails, requiring more sophisticated data structures like a Balanced BST or a Segment Tree.
This problem is best approached using the Disjoint Intervals or Ordered Set pattern. By maintaining a set of non-overlapping intervals, you can efficiently add a new interval by merging any existing intervals that overlap with it. Alternatively, a Dynamic Segment Tree with lazy propagation can be used to handle the range updates and queries in time, where is the range of possible values ().
Suppose we perform the following operations:
add(2, 5): Intervals: [[2, 5]]. Count: 4 (integers 2, 3, 4, 5).add(7, 10): Intervals: [[2, 5], [7, 10]]. Count: 4 + 4 = 8.add(4, 8): The interval [4, 8] overlaps with both.
[2, 5] to become [2, 8].[7, 10] to become [2, 10].[[2, 10]]. Count: 9 (integers 2 through 10).One major pitfall is trying to store every integer in a Hash Set, which will consume massive amounts of memory ( integers). Another mistake is failing to remove old intervals from the data structure when they are merged into a larger one, leading to redundant checks. Some also struggle with the boundary conditions—for instance, forgetting that an interval covers integers.
When dealing with "Count" or "Sum" queries over potentially overlapping ranges, always think about merging intervals. Mastering the "merge intervals" logic—specifically how to find and remove overlapping segments in a sorted structure—is a key skill for high-level technical interviews.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Range Module | Hard | Solve | |
| My Calendar III | Hard | Solve | |
| My Calendar I | Medium | Solve | |
| Amount of New Area Painted Each Day | Hard | Solve | |
| Data Stream as Disjoint Intervals | Hard | Solve |