Given a string str containing only characters x and y, the task is to perform the following operations while possible:
Find an index such that s[i] = ‘x’ and s[i+1] = ‘y’ and delete both the characters s[i] and s[i+1], if no such index is found then find an index such that s[i] = ‘y’ and s[i+1] = ‘x’ and swap(s[i], s[i+1]).
Print the final string after performing the given operation.
Input: str = “xyyxx”
Step 1: yxx (xy got deleted)
Step 2: xyx (yx got swapped)
Step 3: x (xy got deleted)
Input: str = “xxyyxyy”
Approach: In the final string there will be either only x or only y because if we have both x and y in the string then there would be a point where we have either xy or yx as sub-string.
- If it’s xy, we delete it straight away.
- If it is yx, we reverse it to get xy and then delete it.
Since in each deletion step, one x and one y gets deleted, the final string would have min(x, y) number of x and y characters deleted.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count of distinct possible strings after performing given operations
- Find the maximum occurring character after performing the given operations
- Final state of the string after modification
- Sub-string that contains all lowercase alphabets after performing the given operation
- Find value after N operations to remove N characters of string S with given constraints
- Print the final string when minimum value strings get concatenated in every operation
- Restore original String from given Encrypted String by the given operations
- Lexicographically smallest string after M operations
- Minimum number of given operations required to convert a string to another string
- Count number of ways to convert string S to T by performing K cyclic shifts
- Find the final co-ordinates reached by following a sequence of directions
- Minimum given operations required to convert a given binary string to all 1's
- Check whether given string can be generated after concatenating given strings
- Binary array after M range toggle operations
- Print string after removing all (“10” or “01”) from the binary string
- Minimum reduce operations to convert a given string into a palindrome
- Encrypt the given string with the following operations
- Maximum number of given operations to remove the entire string
- Minimum operations required to make the string satisfy the given condition
- Minimum number of operations required to obtain a given Binary String
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.