1229. Lamps Lit Once
A street has n positions numbered 0 to n - 1. Each lamp is given as [p, r]: it stands at position p and lights every street position from max(0, p - r) to min(n - 1, p + r), both ends included.
Return how many positions are lit by exactly one lamp. A position lit by two or more lamps, or by none, does not count. The list lamps may be empty, in which case the answer is 0.
Do not loop over every lamp for every position. Add 1 at the start and subtract 1 just after the end of each lit range in a difference array, take running sums, and count the cells equal to 1. Time O(n + m), space O(n), where m is the number of lamps.
Example 1
- Input:
- n = 14, lamps = [[2,2],[6,1],[9,3],[12,0]]
- Output:
- 10
- Explanation:
Lamps cover 0-4, 5-7, 6-12 and 12; positions 0-5 and 8-11 are lit once (10 positions) while 6, 7 and 12 are lit twice and 13 is dark.
Example 2
- Input:
- n = 9, lamps = [[4,1],[7,0]]
- Output:
- 4
- Explanation:
Lamps cover 3-5 and 7 only, so positions 3, 4, 5 and 7 are each lit exactly once.
Example 3
- Input:
- n = 11, lamps = [[0,3],[5,2],[10,1],[8,0]]
- Output:
- 10
- Explanation:
Lamps cover 0-3, 3-7, 9-10 and 8; only position 3 is lit twice, so positions 0-2, 4-8, 9 and 10 are lit once, which is 10 positions.
Constraints
1 ≤ n ≤ 1000
0 ≤ lamps.length ≤ 1000
0 ≤ p < n
0 ≤ r ≤ n
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n + m)
- Space
- O(n)