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:
- Find the minimum number of preprocess moves required to make two strings equal
- 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 to make frequency of all characters equal K
- Number of character corrections in the given strings to make them equal
- Operations required to make the string empty
- Minimum number of given operations required to convert a string to another string
- Minimum swaps required to make a binary string alternating
- Minimum cost to make two strings same
- Minimum cost to sort strings using reversal operations of different costs
- Minimum Cost To Make Two Strings Identical
- Count the number of carry operations required to add two numbers
- Minimum Cost to make two Numeric Strings Identical
- Minimum cells required to reach destination with jumps equal to cell values
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.