Problem Description
Given a list of buildings represented as [start, end, height] describing a half-closed interval [start, end) and a constant height for that building, partition the street (i.e., the number line) into the minimum number of non-overlapping segments such that in each segment the average height of all active buildings (using integer division) is constant. Segments where there are no buildings are omitted, and contiguous segments with the same average height must be merged.
Key Insights
- Use a sweep line algorithm to handle events (building starts and ends) along the number line.
- Treat each building’s start as an addition event and its end as a removal event.
- For events at the same coordinate, process removal events before addition events to correctly implement the half-open interval [start, end).
- Maintain variables to track the current sum of heights and the count of active buildings.
- Compute the average using integer division (sum // count) whenever there is a change in the set of active buildings.
- Merge contiguous segments if they have the same computed average height.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the events, where n is the number of buildings.
Space Complexity: O(n) for storing the events.
Solution
We use a sweep line algorithm for this problem. First, we convert each building into two events: one for the start (addition) event and one for the end (removal) event. We then sort these events by coordinate, ensuring that removals come before additions when they share the same coordinate. As we sweep through the events along the number line, we update the active set of buildings by maintaining the total height and the count of buildings. On any change of coordinate, if there is at least one active building, we compute the current average using integer division and record the segment. Finally, we merge adjacent segments with the same average value to achieve the minimum segmentation required.