1148. Light Strip Toggles
A long corridor has a lamp at every integer position from 0 upward, and all lamps start switched off. Each entry [a, b] of toggles is a switch-panel press that flips every lamp from position a to position b inclusive; the two ends may be given in either order. After all presses, return how many lamps are lit. The count can reach about 10^9, so return a long.
1 <= toggles.length <= 10^5 and 0 <= a, b <= 10^9, so touching every lamp is too slow. Collect the boundaries a and b + 1 of all presses, sort them and sweep, adding the length of every stretch covered an odd number of times. The intended complexity is O(q log q) time and O(q) space for q presses.
Example 1
- Input:
- toggles = [[1,3]]
- Output:
- 3
- Explanation:
Lamps 1, 2 and 3 are flipped on, so 3 lamps are lit.
Example 2
- Input:
- toggles = [[1,5],[3,8]]
- Output:
- 5
- Explanation:
Lamps 1-2 are flipped once, 3-5 twice (back off), and 6-8 once, so 2 + 3 = 5 lamps are lit.
Example 3
- Input:
- toggles = [[5,2]]
- Output:
- 4
- Explanation:
The ends are reversed, so lamps 2 to 5 are flipped and 4 lamps are lit.
Constraints
1 ≤ toggles.length ≤ 105
0 ≤ a, b ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(q log q)
- Space
- O(q)