Given two strings A and B, both strings contain characters a and b and are of equal lengths. There is one _ (empty space) in both the strings. The task is to convert first string into second string by doing the minimum number of the following operations:
- If _ is at position i then _ can be swapped with a character at position i+1 or i-1.
- If characters at positions i+1 and i+2 are different then _ can be swapped with a character at position i+1 or i+2.
- Similarly, if characters at positions i-1 and i-2 are different then _ can be swapped with a character at position i-1 or i-2.
Input: A = “aba_a”, B = “_baaa”
Move 1 : A = “ab_aa” (Swapped A with A)
Move 2 : A = “_baaa” (Swapped A with A)
Input: A = “a_b”, B = “ab_”
Source: Directi Interview Set 7
- Apply a simple Breadth First Search over the string and an element of the queue used for BFS will contain the pair str, pos where pos is the position of _ in the string str.
- Also maintain a map vis which will store the string as key and the minimum moves to get to the string as value.
- For every string str from the queue, generate a new string tmp based on the four conditions given and update the vis map as vis[tmp] = vis[str] + 1.
- Repeat the above steps until the queue is empty or the required string is generated i.e. tmp == B
- If the required string is generated then return vis[str] + 1 which is the minimum number of operations required to change A to B.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Minimum number of operations required to make two strings equal
- Find the minimum number of preprocess moves required to make two strings equal
- Minimum operations required to make every element greater than or equal to K
- Minimum move to end operations to make all strings equal
- Minimum number of pairs required to make two strings same
- Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character
- Minimum operations required to make the string satisfy the given condition
- Minimum operations to make frequency of all characters equal K
- Minimum swaps to make two strings equal by swapping only with third string
- Minimum number of operations required to set all elements of a binary matrix
- Minimum number of swaps required to make the string K periodic
- Number of character corrections in the given strings to make them equal
- Operations required to make the string empty
- Minimum number of swaps to make two binary string equal
- Minimum number of given operations required to convert a string to another string
Improved By : sanjeev2552