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.

Examples:

Input: S = “acabpba”
Output: pbac
Explanation:
The given string can be converted to “pbac” in which,
every adjacent character remains adjacent.

Input: S = “abcdea”
Output: Impossible
Explanation:
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:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the
// minimum length string such that
// adjacent characters of the string
// remains adjacent in the string
  
#include <bits/stdc++.h>
using namespace std;
  
class graph {
    int arr[26][2];
    vector<int> alpha;
    vector<int> answer;
  
public:
    // Constructor for the graph
    graph()
    {
        // Initialize the matrix by -1
        for (int i = 0; i < 26; i++) {
            for (int j = 0; j < 2; j++)
                arr[i][j] = -1;
        }
  
        // Initialize the alphabet array
        alpha = vector<int>(26);
    }
  
    // Function to do Depth first
    // search Traversal
    void dfs(int v)
    {
        // Pushing current character
        answer.push_back(v);
  
        alpha[v] = 1;
  
        for (int i = 0; i < 2; i++) {
            if (alpha[arr[v][i]] == 1
                || arr[v][i] == -1)
                continue;
  
            dfs(arr[v][i]);
        }
    }
  
    // Function to find the minimum
    // length string
    void minString(string str)
    {
        // Condition if given string
        // length is 1
        if (str.length() == 1) {
            cout << str << "\n";
            return;
        }
  
        bool flag = true;
  
        // Loop to find the adjacency
        // list of the given string
        for (int i = 0; i < str.length() - 1;
             i++) {
            int j = str[i] - 'a';
            int k = str[i + 1] - 'a';
  
            // Condition if character
            // already present
            if (arr[j][0] == k
                || arr[j][1] == k) {
            }
            else if (arr[j][0] == -1)
                arr[j][0] = k;
            else if (arr[j][1] == -1)
                arr[j][1] = k;
  
            // Condition if a character
            // have more than two different
            // adjacent characters
            else {
                flag = false;
                break;
            }
  
            if (arr[k][0] == j
                || arr[k][1] == j) {
            }
            else if (arr[k][0] == -1)
                arr[k][0] = j;
            else if (arr[k][1] == -1)
                arr[k][1] = j;
  
            // Condition if a character
            // have more than two different
            // adjacent characters
            else {
                flag = false;
                break;
            }
        }
  
        // Variable to check string contain
        // two end characters or not
        bool contain_ends = false;
  
        int count = 0;
        int index;
  
        for (int i = 0; i < 26; i++) {
  
            // Condition if a character has
            // only one type of adjacent
            // character
            if ((arr[i][0] == -1
                 && arr[i][1] != -1)
                || (arr[i][1] == -1
                    && arr[i][0] != -1)) {
                count++;
                index = i;
            }
  
            // Condition if the given string
            // has exactly two characters
            // having only one type of adjacent
            // character
            if (count == 2)
                contain_ends = true;
  
            if (count == 3)
                contain_ends = false;
        }
  
        if (contain_ends == false
            || flag == false) {
            cout << "Impossible"
                 << "\n";
            return;
        }
  
        // Depth first Search Traversal
        // on one of the possible end
        // character of the string
        dfs(index);
  
        // Loop to print the answer
        for (int i = 0; i < answer.size();
             i++) {
            char ch = answer[i] + 'a';
            cout << ch;
        }
    }
};
  
// Driver Code
int main()
{
    string s = "abcdea";
  
    graph g;
    g.minString(s);
  
    return 0;
}

chevron_right


Output:

pbac

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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.