Minimum string such that every adjacent character of given string is still adjacent
Given a string S, the task is to find the minimum length string such that every adjacent character of the string remains adjacent in the minimum length string.
Input: S = “acabpba”
The given string can be converted to “pbac” in which,
every adjacent character remains adjacent.
Input: S = “abcdea”
It is impossible to find such string.
Approach: The idea is to prepare a graph like structure in which every adjacent nodes of the graph denotes the adjacent character of the string. There can be two cases in which such type of string is not possible –
- If a character contains three or more adjacent characters.
- If two characters do not have only one adjacent character, except in the case of string of length 1.
If the above conditions for a string are true, then simply traverse the graph with Depth First Search Traversal and the path of this traversal will be the minimum length string. Source vertex for the DFS will be any one of the characters with only one adjacent character.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.