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 INPUT Operations: CountIntervals add count add count Number Line: 1 2 3 4 5 Intervals to Add: [2, 3] [4, 5] Values: [[], [2,3], [], [4,5], []] Empty set initially ALGORITHM STEPS 1 Initialize Empty set, count = 0 2 Add [2,3] No overlap, insert directly 2--3 count: 2 3 Add [4,5] No overlap with [2,3] 2-3 4-5 count: 4 4 Merge Logic Find overlapping intervals Merge Overlapping: 1. Find intervals that overlap 2. Remove old, insert merged 3. Update count accordingly FINAL RESULT Final Interval Set: 2 3 4 5 Integers Covered: 2, 3, 4, 5 = 4 integers Output: [null, null, 2, null, 4] OK - Correct result! Execution Trace: CountIntervals() --> null add(2,3) --> null count() --> 2 add(4,5) --> null count() --> 4 Key Insight: Use a TreeMap/sorted structure to store non-overlapping intervals. When adding a new interval, find and merge all overlapping intervals. Maintain a running count that updates during merges: subtract old intervals' lengths, add the merged interval's length. Time: O(n) add, O(1) count. TutorialsPoint - Count Integers in Intervals | Merge Overlapping Intervals Approach
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