Problem Description
Given a list of intervals nums where each interval represents the starting and ending points of a car parked on a number line, return the total number of distinct integer points that are covered by one or more intervals.
Key Insights
- The problem is essentially about finding the union of all given intervals.
- Merging overlapping intervals avoids double-counting integer points.
- Given the constraint (points up to 100), even a brute force counting would work, but merging intervals is a cleaner approach.
- Sorting intervals by their start value simplifies the merging process.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the intervals. Space Complexity: O(n) for storing the merged intervals.
Solution
The solution uses the following approach:
- Sort the intervals based on the start value.
- Iterate through the sorted intervals and merge them if they overlap (i.e., the current interval's start is less than or equal to the previous interval's end).
- For each merged interval, calculate the number of integer points it covers by using the formula (end - start + 1).
- Sum up the counts from all merged intervals to get the final result.
Data structures used:
- An array (or list) to store the merged intervals.
- Sorting simplifies the identification of overlapping intervals.
This approach ensures that each point is counted only once even if it is covered by multiple intervals.