Given two strings, the task is to find if a string can be obtained by rotating another string two places.
Input: string1 = “amazon”, string2 = “azonam”
// rotated anti-clockwise
Input: string1 = “amazon”, string2 = “onamaz”
// rotated clockwise
Asked in: Amazon Interview
1- There can be only two cases: a) Clockwise rotated b) Anti-clockwise rotated 2- If clockwise rotated that means elements are shifted in right. So, check if a substring[2.... len-1] of string2 when concatenated with substring[0,1] of string2 is equal to string1. Then, return true. 3- Else, check if it is rotated anti-clockwise that means elements are shifted to left. So, check if concatenation of substring[len-2, len-1] with substring[0....len-3] makes it equals to string1. Then return true. 4- Else, return false.
Below is the implementation of above approach.
Exercise : Check if string2 is obtained by rotating string1 by k places.
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Check if a string can be obtained by rotating another string d places
- Lexicographically smallest string obtained after concatenating array
- Find i’th index character in a binary string obtained after n iterations | Set 2
- Find i'th Index character in a binary string obtained after n iterations
- String slicing in Python to check if a string can become empty by recursive deletion
- Check if a string can be converted to another string by replacing vowels and consonants
- Queries to check if string B exists as substring in string A
- Check if a string can become empty by recursively deleting a given sub-string
- Check if a string can be repeated to make another string
- Check whether second string can be formed from characters of first string
- Check if a string contains a palindromic sub-string of even length
- Check if it is possible to sort the array after rotating it
- Check if a given string is sum-string
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
- Check if it is possible to transform one string to another