Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2276. Count Integers in Intervals

Explanation

To solve the problem, we can maintain a list of intervals in a sorted manner. When adding a new interval, we can merge it with existing intervals if there is any overlap. This approach allows us to efficiently count the number of integers present in at least one interval by iterating over the merged intervals.

Algorithm:

  1. Initialize an empty list of intervals.
  2. Implement the add method:
    • For each interval in the list:
      • If the new interval overlaps with the current interval, merge them.
      • Otherwise, keep the intervals separate.
    • After merging all possible intervals, add the new interval.
  3. Implement the count method:
    • Initialize a counter for the total count.
    • Iterate through the merged intervals and add the count of integers in each interval.
    • Return the total count.

Time Complexity:

  • Adding an interval: O(n) where n is the number of intervals.
  • Counting the total number of integers: O(n) where n is the number of intervals.

Space Complexity:

  • O(n) where n is the number of intervals.
class CountIntervals {
    List<int[]> intervals;
    
    public CountIntervals() {
        intervals = new ArrayList<>();
    }
    
    public void add(int left, int right) {
        List<int[]> merged = new ArrayList<>();
        boolean inserted = false;
        
        for (int[] interval : intervals) {
            if (interval[1] < left || interval[0] > right) {
                merged.add(interval);
            } else {
                left = Math.min(left, interval[0]);
                right = Math.max(right, interval[1]);
            }
        }
        
        merged.add(new int[]{left, right});
        intervals = merged;
    }
    
    public int count() {
        int totalCount = 0;
        
        for (int[] interval : intervals) {
            totalCount += interval[1] - interval[0] + 1;
        }
        
        return totalCount;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.