Python3 Program to Check if a string can be formed from another string by at most X circular clockwise shifts
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:
Python3
# Python3 implementation to check # that the given string can be # converted to another string # by circular clockwise shift # Function to check that the # string s1 can be converted # to s2 by clockwise circular # shift of all characters of # str1 atmost X times def isConversionPossible(s1, s2, x): n = len (s1) s1 = list (s1) s2 = list (s2) for i in range (n): # Difference between the # ASCII numbers of characters diff = ord (s2[i]) - ord (s1[i]) # If both characters # are the same if diff = = 0 : continue # Condition to check if the # difference less than 0 then # find the circular shift by # adding 26 to it if diff < 0 : diff = diff + 26 # If difference between # their ASCII values # exceeds X if diff > x: return False return True # Driver Code if __name__ = = "__main__" : s1 = "you" s2 = "ara" x = 6 # Function Call result = isConversionPossible(s1, s2, x) if result: print ( "YES" ) else : print ( "NO" ) |
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!
Contact Us