Problem Description
A straight street is represented by a number line. Each street lamp is specified by its position and range, and it lights an interval on the street. The brightness at a given point is the number of street lamps that cover that point. Given an array of lamps where each lamp is defined as [position, range], find the position with the maximum brightness. If multiple positions have the same maximum brightness, return the smallest such position.
Key Insights
- Each street lamp creates an interval [position - range, position + range] (inclusive).
- Use a difference array or sweep-line technique by marking the start of an interval with +1 and the position right after the end with -1.
- After sorting these events by coordinate, a single pass accumulates brightness and identifies the maximum brightness along with the smallest coordinate that attains it.
- Handle gaps between events carefully since brightness is constant over these gaps.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting of the 2n events (n is the number of street lamps).
Space Complexity: O(n) for storing the events.
Solution
The problem is solved using a sweep-line (difference array) approach:
- For each street lamp, calculate the left bound (position - range) and the right bound (position + range).
- Create two events: add +1 at the left bound and add -1 at (right bound + 1) to account for the inclusiveness of the interval.
- Sort the events by their coordinate.
- Perform a sweep-line: as you traverse through the sorted events, accumulate the brightness. The brightness remains constant in the intervals between consecutive events.
- Track the maximum brightness seen so far and update the result with the smallest coordinate when a new maximum is found.
- Finally, return the coordinate corresponding to the maximum brightness.