Problem Description
Given an array of length n where every position is 0 except one position p which is 1, you are allowed to perform a reversal operation on any contiguous subarray of fixed length k as long as the subarray does not contain any banned indices. When you reverse the subarray, the lone 1 will move to a new position determined by the reversal. The goal is to determine, for every index in the array, the minimum number of operations needed to get the 1 there (or –1 if it is impossible).
Key Insights
- The reversal operation with fixed size k implies that if the current index is i and you reverse a subarray covering i, then the new index j of the 1 is computed by the formula: j = 2*s + k - 1 - i, where s is the starting position of the subarray.
- For a valid reversal, the starting index s must satisfy: max(0, i - k + 1) ≤ s ≤ min(i, n - k).
- Thus, from index i, the 1 can move to any index j in the range: [2 * max(0, i - k + 1) + k - 1 - i, 2 * min(i, n - k) + k - 1 - i].
- An important observation is that the parity (odd or even) of the new position j is fixed given i and k (j = k - 1 - i (mod 2)). This helps group indices and efficiently query candidates.
- We can use a Breadth First Search (BFS) starting at position p, and maintain two ordered sets (or sorted lists) for unvisited indices (grouped by parity) so that we can quickly remove and iterate over all indices within a queried interval.
Space and Time Complexity
Time Complexity: O(n log n)
Space Complexity: O(n)
Solution
We solve the problem using a BFS traversal where each state is the current position of the 1. For each state (or index) i, we compute the valid range of destination indices j that can be reached by any reversal operation. The transformation is based on choosing a valid subarray starting index s and the formula: j = 2*s + k - 1 - i. Because s moves within a continuous range, the set of reachable j's forms a continuous interval. Moreover, since j is computed as (k - 1 - i) plus an even number, only one parity (even or odd) is possible.
To efficiently find all reachable positions in an interval with the fixed parity, we keep two ordered sets (or sorted collections) for even and odd indices that are allowed (i.e. not banned and not already visited). We then perform BFS from the starting index p, removing and marking the reachable nodes as visited, and updating their distance (number of operations). This yields the minimum number of operations needed for each index.