This problem involves determining the number of positions on a street that meet a minimum brightness requirement, given the positions and ranges of streetlights. The optimal approach leverages the concept of a difference array for efficient calculation.
A difference array allows for efficient updates to ranges of values. Instead of directly updating each element within a range, we only modify the beginning and ending points of the range. This significantly reduces the time complexity compared to iterating through each element in the range.
1. Building the Difference Array:
d
of size n + 1
(where n
is the length of the street) with zeros. The extra element simplifies boundary handling.[position, range]
:
i = max(0, position - range)
and end index j = min(n - 1, position + range)
of the lit area.d[i]
by 1 (representing the start of the lit area).d[j + 1]
by 1 (representing the end of the lit area). This is crucial; the prefix sum will correctly account for the lighting.2. Prefix Sum Calculation:
d
. This prefix sum at index k
represents the brightness at position k
on the street. The decrement in d[j+1]
ensures that the brightness doesn't overcount beyond the lamp's range.3. Checking Requirements:
requirement
array simultaneously.i
, if the prefix sum d[i]
is greater than or equal to requirement[i]
, increment the count of positions meeting the requirement.4. Returning the Result:
d
which stores brightness information for each position.from itertools import accumulate
class Solution:
def meetRequirement(self, n: int, lights: List[List[int]], requirement: List[int]) -> int:
d = [0] * (n + 1)
for p, r in lights:
i, j = max(0, p - r), min(n - 1, p + r)
d[i] += 1
d[j + 1] -= 1
prefix_sum = list(accumulate(d)) #Efficient prefix sum calculation
count = 0
for i in range(n):
if prefix_sum[i] >= requirement[i]:
count += 1
return count
The code in other languages (Java, C++, Go, TypeScript) follows the same logic, only differing in syntax. The use of accumulate
(Python) or equivalent functions in other languages provides an efficient way to compute the prefix sum. The difference array approach avoids redundant calculations making it far more efficient than brute force methods.