Brightest Position on Street Problem
Description
LeetCode Problem 2021.
A perfectly straight street is represented by a number line. The street has street lamp(s) on it and is represented by a 2D integer array lights. Each lights[i] = [position_i, range_i] indicates that there is a street lamp at position position_i that lights up the area from [position_i - range_i, position_i + range_i] (inclusive).
The brightness of a position p is defined as the number of street lamp that light up the position p.
Given lights, return the brightest position on the street. If there are multiple brightest positions, return the smallest one.
Example 1:

Input: lights = [[-3,2],[1,2],[3,3]]
Output: -1
Explanation:
The first street lamp lights up the area from [(-3) - 2, (-3) + 2] = [-5, -1].
The second street lamp lights up the area from [1 - 2, 1 + 2] = [-1, 3].
The third street lamp lights up the area from [3 - 3, 3 + 3] = [0, 6].
Position -1 has a brightness of 2, illuminated by the first and second street light.
Positions 0, 1, 2, and 3 have a brightness of 2, illuminated by the second and third street light.
Out of all these positions, -1 is the smallest, so return it.
Example 2:
Input: lights = [[1,0],[0,1]]
Output: 1
Explanation:
The first street lamp lights up the area from [1 - 0, 1 + 0] = [1, 1].
The second street lamp lights up the area from [0 - 1, 0 + 1] = [-1, 1].
Position 1 has a brightness of 2, illuminated by the first and second street light.
Return 1 because it is the brightest position on the street.
Example 3:
Input: lights = [[1,2]]
Output: -1
Explanation:
The first street lamp lights up the area from [1 - 2, 1 + 2] = [-1, 3].
Positions -1, 0, 1, 2, and 3 have a brightness of 1, illuminated by the first street light.
Out of all these positions, -1 is the smallest, so return it.
Constraints:
1 <= lights.length <= 10^5lights[i].length == 2-10^8 <= position_i <= 10^80 <= range_i <= 10^8
Solution
Approach: Difference Array + Sorting
A lamp at position with range lights the interval [position - range, position + range]. Record it as a difference: add 1 at the left end and subtract 1 at right + 1, using a hash map from position to change.
Then visit the positions that appear in the map in increasing order, keeping a running sum s, the number of lamps lighting the current position. Whenever s is strictly greater than the best brightness so far, remember it and the position. Using a strict comparison and increasing order means the smallest position wins a tie.
Complexity: O(n log n) time for the sort and O(n) space, where n is the number of lights.
from collections import defaultdict
class Solution:
def brightestPosition(self, lights: List[List[int]]) -> int:
d = defaultdict(int)
for i, j in lights:
l, r = i - j, i + j
d[l] += 1
d[r + 1] -= 1
ans = s = mx = 0
for k in sorted(d):
s += d[k]
if mx < s:
mx = s
ans = k
return ans