Skip to content

Practice Count Integers in Intervals

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#2276
LeetCode Problem

Count Integers in Intervals

Problem Statement

CountIntervals starts with no covered integers. add(left,right) covers every integer in the inclusive interval [left,right]. count() returns the number covered by at least one interval, without counting overlaps twice. Practice approach: Maintain disjoint sorted intervals and their total length. When adding a range, subtract lengths of merged intervals and add the merged length right - left + 1. A dynamic segment tree is another option for the 10^9 coordinate range. Unlike RangeModule, these intervals include the right endpoint and count integers rather than real-valued coverage.

Source: Count Integers in Intervals on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["CountIntervals","add","add","count","add","count"]
[[],[4,6],[8,9],[],[6,8],[]]
Output
[null,null,null,5,null,6]
Explanation

Initially five integers are covered; filling the gap merges coverage into integers 4 through 9.

Constraints

1 <= left <= right <= 10^9
At most 10^5 total calls; at least one count call.

Related LeetCode Problems

Practice more problems similar to Count Integers in Intervals.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.