Number of Counterclockwise shifts to make a string palindrome

Given a string of lowercase English alphabets, find the number of counterclockwise shifts of characters required to make the string palindrome. It is given that shifting the string will always result in the palindrome.

Examples:

Input: str = “baabbccb”
Output: 2
Shifting the string counter clockwise 2 times,
will make the string palindrome.
1st shift : aabbccbb
2nd shift :abbccbba



Input: bbaabbcc
Output: 3
Shifting the string counter clockwise
3 times will make the string palindrome.
1st shift : baabbccb
2nd shift : aabbccbb
3rd shift : abbccbba

Naive Approach: A naive approach is to one by one shift character of the given string counter-clockwise cyclically and check if the string is palindrome or not.

Better Approach: A better approach is to append the string with itself and iterate from the first character to the last character of the given string. The substring from i to i+n (where i is in range [0,n-1]) in the appended string will be the string obtained after every counterclockwise shift. Check for the substring if it is palindrome or not. The number of shift operations will be i.

Below is the implementation of above approach:



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find counter clockwise
// shifts to make string palindrome.
#include <bits/stdc++.h>
using namespace std;
  
// Function to check if given string is
// palindrome or not.
bool isPalindrome(string str, int l, int r)
{
    while (l < r) {
        if (str[l] != str[r])
            return false;
  
        l++;
        r--;
    }
  
    return true;
}
  
// Function to find counter clockwise shifts
// to make string palindrome.
int CyclicShifts(string str)
{
  
    int n = str.length();
  
    // Pointer to starting of current
    // shifted string.
    int left = 0;
  
    // Pointer to ending of current
    // shifted string.
    int right = n - 1;
  
    // Concatenate string with itself
    str = str + str;
  
    // To store counterclockwise shifts
    int cnt = 0;
  
    // Move left and right pointers one
    // step at a time.
    while (right < 2 * n - 1) {
  
        // Check if current shifted string
        // is palindrome or not
        if (isPalindrome(str, left, right))
            break;
  
        // If string is not palindrome
        // then increase count of number
        // of shifts by 1.
        cnt++;
  
        left++;
        right++;
    }
  
    return cnt;
}
  
// Driver code.
int main()
{
    string str = "bccbbaab";
  
    cout << CyclicShifts(str);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find counter clockwise
// shifts to make string palindrome.
class GFG 
{
  
// Function to check if given string is
// palindrome or not.
static boolean isPalindrome(String str, int l, int r)
{
    while (l < r) 
    {
        if (str.charAt(l) != str.charAt(r))
            return false;
  
        l++;
        r--;
    }
    return true;
}
  
// Function to find counter clockwise shifts
// to make string palindrome.
static int CyclicShifts(String str)
{
  
    int n = str.length();
  
    // Pointer to starting of current
    // shifted string.
    int left = 0;
  
    // Pointer to ending of current
    // shifted string.
    int right = n - 1;
  
    // Concatenate string with itself
    str = str + str;
  
    // To store counterclockwise shifts
    int cnt = 0;
  
    // Move left and right pointers one
    // step at a time.
    while (right < 2 * n - 1
    {
  
        // Check if current shifted string
        // is palindrome or not
        if (isPalindrome(str, left, right))
            break;
  
        // If string is not palindrome
        // then increase count of number
        // of shifts by 1.
        cnt++;
  
        left++;
        right++;
    }
    return cnt;
}
  
// Driver code.
public static void main(String[] args) 
{
    String str = "bccbbaab";
  
    System.out.println(CyclicShifts(str));
}
  
// This code is contributed by Rajput-Ji

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to find counter clockwise
# shifts to make string palindrome.
  
# Function to check if given string 
# is palindrome or not.
def isPalindrome(str, l, r):
  
    while (l < r) :
        if (str[l] != str[r]):
            return False
  
        l += 1
        r -= 1
  
    return True
  
# Function to find counter clockwise 
# shifts to make string palindrome.
def CyclicShifts(str):
  
    n = len(str)
  
    # Pointer to starting of current
    # shifted string.
    left = 0
  
    # Pointer to ending of current
    # shifted string.
    right = n - 1
  
    # Concatenate string with itself
    str = str + str
  
    # To store counterclockwise shifts
    cnt = 0
  
    # Move left and right pointers 
    # one step at a time.
    while (right < 2 * n - 1) :
  
        # Check if current shifted string
        # is palindrome or not
        if (isPalindrome(str, left, right)):
            break
  
        # If string is not palindrome
        # then increase count of number
        # of shifts by 1.
        cnt += 1
  
        left += 1
        right += 1
  
    return cnt
  
# Driver code.
if __name__ == "__main__":
      
    str = "bccbbaab";
  
    print(CyclicShifts(str))
  
# This code is contributed by ita_c

chevron_right


Output:

2

Time Complexity: O(N2)
Auxiliary Space: O(N)

Efficient Approach: An efficient approach is to use Cumulative Hash. The string is shifted cyclically according to the method explained above and the hash value of this string is compared to the hash value of the reversed string. If both values are same then current shifted string is palindrome otherwise string is again shifted. The count of shifts will be i at any step. To calculate value of both strings below hash function is used:

H(s) = ∑ (31i * (Si – ‘a’)) % mod, 0 ≤ i ≤ (length of string – 1)
where, H(x) = Hash function
s = given string
mod = 109 + 7

Iterate for all the substrings and check for if it is a palindrome or not using the hash function stated above and the cumulative hash technique.

Below is the implementation of above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find counter clockwise
// shifts to make string palindrome.
#include <bits/stdc++.h>
  
#define mod 1000000007
using namespace std;
  
// Function to find counter clockwise shifts
// to make string palindrome.
int CyclicShifts(string str)
{
  
    int n = str.length(), i;
  
    // To store power of 31.
    // po[i] = 31^i;
    long long int po[2 * n + 2];
  
    // To store hash value of string.
    long long int preval[2 * n + 2];
  
    // To store hash value of reversed
    // string.
    long long int suffval[2 * n + 2];
  
    // To find hash value of string str[i..j]
    long long int val1;
  
    // To store hash value of reversed string
    // str[j..i]
    long long int val2;
  
    // To store number of counter clockwise
    // shifts.
    int cnt = 0;
  
    // Concatenate string with itself to shift
    // it cyclically.
    str = str + str;
  
    // Calculate powers of 31 upto 2*n which
    // will be used in hash function.
    po[0] = 1;
    for (i = 1; i <= 2 * n; i++) {
        po[i] = (po[i - 1] * 31) % mod;
    }
  
    // Hash value of string str[0..i] is stored in
    // preval[i].
    for (i = 1; i <= 2 * n; i++) {
        preval[i] = ((preval[i - 1] * 31) % mod +
                    (str[i - 1] - 'a')) % mod;
    }
  
    // Hash value of string str[i..n-1] is stored
    // in suffval[i].
    for (i = 2 * n; i > 0; i--) {
        suffval[i] = ((suffval[i + 1] * 31) % mod +
                      (str[i - 1] - 'a')) % mod;
    }
  
    // Characters in string str[0..i] is present
    // at position [(n-1-i)..(n-1)] in reversed
    // string. If hash value of both are same
    // then string is palindrome else not.
    for (i = 1; i <= n; i++) {
  
        // Hash value of shifted string starting at
        // index i and ending at index i+n-1.
        val1 = (preval[i + n - 1] - 
               ((po[n] * preval[i - 1]) % mod)) % mod;
        if (val1 < 0)
            val1 += mod;
  
        // Hash value of corresponding string when
        // reversed starting at index i+n-1 and
        // ending at index i.
        val2 = (suffval[i] - ((po[n] * suffval[i + n])
                                        % mod)) % mod;
        if (val2 < 0)
            val2 += mod;
  
        // If both hash value are same then current
        // string str[i..(i+n-1)] is palindrome.
        // Else increase the shift count.
        if (val1 != val2)
            cnt++;
        else
            break;
    }
  
    return cnt;
}
  
// Driver code.
int main()
{
    string str = "bccbbaab";
  
    cout << CyclicShifts(str);
    return 0;
}

chevron_right


Output:

2

Time Complexity: O(N)
Auxiliary Space: O(N)



My Personal Notes arrow_drop_up

A Programmer and A Machine learning Enthusiast

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.



Improved By : Ita_c, Rajput-Ji