#2276

Count Integers in Intervals

Hard
DesignSegment TreeOrdered SetInterval MergingDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a list to store intervals and merges overlapping intervals whenever a new interval is added. This way, we maintain a compact representation of the intervals, allowing us to count the total integers efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Maintain a list of non-overlapping intervals.
  2. 2Step 2: When adding a new interval, merge it with any overlapping intervals.
  3. 3Step 3: After merging, calculate the total count of integers covered by the intervals.
solution.py23 lines
1class CountIntervals:
2    def __init__(self):
3        self.intervals = []
4
5    def add(self, left: int, right: int) -> None:
6        new_intervals = []
7        i = 0
8        while i < len(self.intervals) and self.intervals[i][1] < left:
9            new_intervals.append(self.intervals[i])
10            i += 1
11        while i < len(self.intervals) and self.intervals[i][0] <= right:
12            left = min(left, self.intervals[i][0])
13            right = max(right, self.intervals[i][1])
14            i += 1
15        new_intervals.append((left, right))
16        new_intervals.extend(self.intervals[i:])
17        self.intervals = new_intervals
18
19    def count(self) -> int:
20        total = 0
21        for left, right in self.intervals:
22            total += right - left + 1
23        return total

Complexity note: The time complexity is O(n) for adding intervals since we may need to merge existing intervals. The space complexity is O(n) because we store the merged intervals.

  • 1Merging overlapping intervals is crucial for efficiency.
  • 2Using a list to maintain non-overlapping intervals simplifies counting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.