1233. Switchboard Toggles

A control room has a row of switches, each either off (0) or on (1), written as the string bits. Operators then send a list of toggle commands ops. Each command [l, r] flips every switch at positions l through r (0-based, both ends included): an on switch becomes off and an off switch becomes on. Commands are applied in any order with the same final effect, because flips commute.

Return the final state of the row as a string of 0 and 1 characters. Record each command in an XOR difference array, take its running XOR across the positions, and combine it with the original bits instead of flipping range by range.

The intended solution runs in O(n + m) time and O(n) space, where m is the number of commands.

Example 1

Input:
bits = "0101", ops = [[0,1],[1,3]]
Output:
"1110"
Explanation:

The first command turns 0101 into 1001; the second flips positions 1 to 3 and gives 1110.

Example 2

Input:
bits = "111", ops = []
Output:
"111"
Explanation:

With no commands every switch keeps its starting state.

Constraints

1 ≤ bits.length ≤ 1000

bits contains only the characters 0 and 1

0 ≤ ops.length ≤ 1000

0 ≤ l ≤ r < bits.length for every [l, r] in ops

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)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…