![]() |
VOOZH | about |
There are 2n boxes in a line. Two adjacent boxes are empty, and all other boxes have a letter "A" or "B". Both letters appear in exactly n-1 boxes.
Your task is to move the letters so that all letters "A" appear before any letter "B". On each turn you can choose any two adjacent boxes that have a letter and move the letters to the two adjacent empty boxes, preserving their order.
It can be proven that either there is a solution that consists of at most 10n turns or there are no solutions.
Examples:
Input: N = 3, string = AB..BA
Output:
2
ABBA..
A..ABB
Explanation:
- The first transformation swaps the two characters at indices 2 and 3 to create "ABBA..".
- The second transformation swaps the characters at indices 1 and 2, and at indices 4 and 5, resulting in "A..ABB".
Input: N = 3, tstring = ABAB..
Output: -1
Explanation: It is not possible to transform the string to the desired form. This is because no sequence of swaps can produce a string with alternating 'A' and 'B' characters.
Approach: To solve the problem, follow the below idea:
To solve the problem efficiently, we first define a function solve(n) to create all possible string configurations for a given length n. Using a queue-based breadth-first search (BFS) approach, we start from the initial string configuration and iteratively explore all possible swaps. During the search, we store the predecessor of each string configuration to reconstruct the transformation path later. If the input length is less than 4, we extend the search by considering configurations of length n*2. For lengths of 4 or more, we check if the first two characters need swapping and perform the swap if necessary. Then, we conduct BFS for configurations of length 8. Subsequently, we iterate through the string, applying transformations for each segment of length 8. Finally, we output the number of transformations performed along with the transformed strings, providing a concise and effective solution strategy.
Step-by-step algorithm:
Below is the implementation of the algorithm:
2 ABBA.. A..ABB
Time complexity : O(448 + E) where E is the number of edges and depends on the length of the string.
Auxiliary Space: O(448)