Skip to content
Related Articles

Related Articles

C++ Program to Check if a string can be formed from another string by at most X circular clockwise shifts

Improve Article
Save Article
Like Article
  • Last Updated : 25 Jan, 2022

Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times.

Input: S1 = “abcd”, S2 = “dddd”, X = 3 
Output: Yes 
Explanation: 
Given string S1 can be converted to string S2 as- 
Character “a” – Shift 3 times – “d” 
Character “b” – Shift 2 times – “d” 
Character “c” – Shift 1 times – “d” 
Character “d” – Shift 0 times – “d”

Input: S1 = “you”, S2 = “ara”, X = 6 
Output: Yes 
Explanation: 
Given string S1 can be converted to string S2 as – 
Character “y” – Circular Shift 2 times – “a” 
Character “o” – Shift 3 times – “r” 
Character “u” – Circular Shift 6 times – “a”  

Approach: The idea is to traverse the string and for each index and find the difference between the ASCII values of the character at the respective indices of the two strings. If the difference is less than 0, then for a circular shift, add 26 to get the actual difference. If for any index, the difference exceeds X, then S2 can’t be formed from S1, otherwise possible. 
Below is the implementation of the above approach: 

C++




// C++ implementation to check
// that a given string can be
// converted to another string
// by circular clockwise shift
// of each character by atmost
// X times
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to check that all
// characters of s1 can be
// converted to s2 by circular
// clockwise shift atmost X times
void isConversionPossible(string s1,
                          string s2, int x)
{
    int diff, n;
    n = s1.length();
  
    // Check for all characters of
    // the strings whether the
    // difference between their
    // ascii values is less than
    // X or not
    for (int i = 0; i < n; i++) {
  
        // If both the characters
        // are same
        if (s1[i] == s2[i])
            continue;
  
        // Calculate the difference
        // between the ASCII values
        // of the characters
        diff = (int(s2[i] - s1[i])
                + 26)
               % 26;
  
        // If difference exceeds X
        if (diff > x) {
            cout << "NO" << endl;
            return;
        }
    }
  
    cout << "YES" << endl;
}
  
// Driver Code
int main()
{
    string s1 = "you";
    string s2 = "ara";
  
    int x = 6;
  
    // Function call
    isConversionPossible(s1, s2, x);
  
    return 0;
}
Output: 
YES

 

Time Complexity:O(N),N=Length(S1)

Auxiliary Space:O(1)

Please refer complete article on Check if a string can be formed from another string by at most X circular clockwise shifts for more details!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!