1168. XOR Neighbour Ring
A ring of lamps is described by cells, where each entry is 0 (off) or 1 (on) and the last lamp is adjacent to the first. In one step every lamp is replaced, all at once, by the XOR of its left and right neighbours (indices wrap around, so with one lamp both neighbours are the lamp itself).
Return the ring after exactly k steps. The result is fully determined, with no tie to break. Here 1 <= n <= 10^5, each cell is 0 or 1, and 0 <= k <= 10^15, so the steps cannot be simulated one by one.
Because 2^j steps equal XOR-ing the cells at distance 2^j, apply one jump per set bit of k, in O(n log k) time and O(n) space.
Example 1
- Input:
- cells = [1,0,0,0], k = 1
- Output:
- [0,1,0,1]
- Explanation:
Each cell becomes the XOR of its two neighbours around the ring, which gives 0, 1, 0, 1.
Example 2
- Input:
- cells = [1,1,0], k = 0
- Output:
- [1,1,0]
- Explanation:
With k = 0 no step is applied, so the ring is returned unchanged.
Example 3
- Input:
- cells = [1,0,1,1,0], k = 2
- Output:
- [0,1,1,1,1]
- Explanation:
One step turns 1,0,1,1,0 into 0,0,1,1,0 and a second step turns that into 0,1,1,1,1.
Constraints
1 ≤ n ≤ 105
cells[i] is 0 or 1
0 ≤ k ≤ 1015
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(n log k)
- Space
- O(n)