Count Integers in Intervals - Problem

Given an empty set of intervals, implement a data structure that can:

  • Add an interval to the set of intervals
  • Count the number of integers that are present in at least one interval

Implement the CountIntervals class:

  • CountIntervals() Initializes the object with an empty set of intervals
  • void add(int left, int right) Adds the interval [left, right] to the set of intervals
  • int count() Returns the number of integers that are present in at least one interval

Note that an interval [left, right] denotes all the integers x where left <= x <= right.

Input & Output

Example 1 — Basic Operations
$ Input: operations = ["CountIntervals", "add", "count", "add", "count"], values = [[], [2, 3], [], [4, 5], []]
Output: [null, null, 2, null, 4]
💡 Note: Initialize empty intervals, add [2,3] (count=2), add [4,5] (count=4 total)
Example 2 — Overlapping Intervals
$ Input: operations = ["CountIntervals", "add", "add", "count"], values = [[], [2, 3], [4, 5], []]
Output: [null, null, null, 4]
💡 Note: Add [2,3] and [4,5], total unique integers: 2,3,4,5 = 4 numbers
Example 3 — Merging Intervals
$ Input: operations = ["CountIntervals", "add", "add", "count"], values = [[], [1, 3], [2, 4], []]
Output: [null, null, null, 4]
💡 Note: Intervals [1,3] and [2,4] overlap, merge to [1,4] covering 4 integers

Constraints

  • 1 ≤ left ≤ right ≤ 109
  • At most 105 calls in total to add and count

Visualization

Tap to expand
Count Integers in Intervals - Data Structure DesignOperations:add(2, 3)add(4, 5)count()Intervals stored:[2, 3][4, 5]Integers covered: {2, 3, 4, 5}Total Count = 4
Understanding the Visualization
1
Input Operations
Sequence of add() and count() operations on intervals
2
Merge Process
Overlapping intervals are merged to avoid double counting
3
Count Result
Return total unique integers covered by all intervals
Key Takeaway
🎯 Key Insight: Merge overlapping intervals to efficiently count unique integers without duplication
Asked in
Google 25 Amazon 18 Microsoft 15
28.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen