Sort a string lexicographically using triple cyclic shifts

Given a string consisting of the first N distinct alphabets, the task is to sort the string by using at most N/2 moves. Each move involves the following:

  • Select any 3 distinct indices.
  • Perform a cyclic shift on the alphabets at these indices.

If it is possible to sort the strings, print the count of required moves. Otherwise, print “Not Possible”.

Examples:

Input: str = “cbda”
Output:
possible
1
Explanation:
Selecting the indices 0, 2 and 3 and performing a single circular shift among them, the given string “cbda” is converted to “abcd”.

Input: str = “cba”
Output: Not Possible



Approach:
In order to solve the problem, follow the steps below:

  • Store the integers denoting correct of characters of the string in a vector .
  • Place those elements correctly which can all occupy correct indices in a single cycle.
  • Traverse an element of the vector
  • If the element is not at its sorted index position, check if two or more numbers can be placed at correct indices in one cycle. If the condition is satisfied, perform the cycle otherwise check if there is a distinct index that does not hold the correct element available. If the condition is satisfied, select this index as the third index of the cycle and perform the cycle. If neither of the above conditions are satisfied, sorting would be impossible. Hence, break out of the loop and print “Not Possible”.
  • Once a cyclic shift is performed, store the indices involved in the shift.
  • If the element is at its sorted position, move to the next index.
  • Repeat the above two steps for all vector elements.
  • After the traversal is completed, if the entire array is in sorted order, print the shifts required. Else print “Not Possible”.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program for sorting a
// string using cyclic shift
// of three indices
#include <bits/stdc++.h>
using namespace std;
  
void sortString(vector<int>& arr, int n,
                int moves)
{
  
    // Store the indices
    // which haven't attained
    // its correct position
    vector<int> pos;
    // Store the indices
    // undergoing cyclic shifts
    vector<vector<int> > indices;
  
    bool flag = false;
  
    for (int i = 0; i < n; i++) {
  
        // If the element is not at
        // it's correct position
        if (arr[i] != i) {
  
            // Check if all 3 indices can be
            // placed to respective correct
            // indices in a single move
            if (arr[arr[arr[i]]] == i
                && arr[arr[i]] != i) {
  
                int temp = arr[arr[i]];
                indices.push_back({ i, arr[i],
                                    arr[arr[i]] });
                swap(arr[i], arr[arr[i]]);
                swap(arr[i], arr[temp]);
            }
        }
  
        // If the i-th index is still
        // not present in its correct
        // position, store the index
        if (arr[i] != i) {
            pos.push_back(i);
        }
    }
  
    for (int i = 0; i < n; i++) {
  
        if (arr[i] != i) {
  
            int pos1 = i, pos2 = arr[i];
            int pos3 = arr[arr[i]];
  
            // To check if swapping two indices
            // places them in their correct
            // position
            if (pos3 != pos1) {
  
                indices.push_back({ pos1,
                                    pos2,
                                    pos3 });
                swap(arr[pos1], arr[pos2]);
                swap(arr[pos1], arr[pos3]);
                pos.erase(find(
                    pos.begin(),
                    pos.end(), pos2));
                pos.erase(find(
                    pos.begin(),
                    pos.end(), pos3));
  
                if (arr[pos1] == pos1) {
                    pos.erase(find(
                        pos.begin(),
                        pos.end(),
                        pos1));
                }
            }
            else {
  
                if (pos3
                    == *pos.begin()) {
  
                    if (*pos.begin()
                        != pos.back()) {
                        auto it
                            = ++pos.begin();
                        pos3 = *(it);
  
                        if (*it != pos.back()
                            && pos3 == pos2) {
                            pos3 = *(++it);
                        }
                        else if (*it == pos.back()
                                 && pos3 == pos2) {
  
                            flag = true;
                            break;
                        }
                    }
                    else {
                        flag = true;
                        break;
                    }
                }
  
                indices.push_back({ pos1, pos2,
                                    pos3 });
                swap(arr[pos1], arr[pos2]);
                swap(arr[pos1], arr[pos3]);
                pos.erase(find(
                    pos.begin(),
                    pos.end(),
                    pos2));
            }
        }
  
        if (arr[i] != i) {
            i--;
        }
    }
  
    if (flag == true
        || indices.size() > moves) {
  
        cout << "Not Possible" << endl;
    }
    else {
        cout << indices.size() << endl;
  
        // Inorder to see the indices that
        // were swapped in rotations,
        // uncomment the below code
  
        /*
        for (int i = 0; i < indices.size();
             i++) {
  
            cout << indices[i][0] << " "
                 << indices[i][1] << " "
                 << indices[i][2] << endl;
        }
       */
    }
}
  
// Driver Code
int main()
{
  
    string s = "adceb";
    vector<int> arr;
  
    for (int i = 0; i < s.size(); i++) {
        arr.push_back(s[i] - 'a');
    }
  
    sortString(arr, s.size(),
               floor(s.size() / 2));
}

chevron_right


Output:

1

competitive-programming-img




My Personal Notes arrow_drop_up

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.