[Solved] Charlie has a magic mirror that shows the right-rotated versions of a given word

Charlie has a magic mirror that shows the right-rotated versions of a given word. To generate different right rotations of a word, the word is written in a circle in a clockwise order and read it starting from any given character in a clockwise order until all the characters are covered. For example, in the word “sample”, if we start with ‘p’, we get the right rotated word as “plesam.

Write an algorithm to output 1 if the word1 is a right rotation of word2 otherwise output-1.

Input

The first line of the input consists of a string word1, representing the first word.

The second line consists of a string word2, representing the second word.

Output

Print 1 if the word1 is a right rotation of word2 otherwise print -1.

Note: Both word? and word2 contain only lowercase letters between az
Example

plesam

Output:

1

Explanation:

For the word “sample”, if we start with “p”, we get the right-rotated word as “plesam”. There are six such right rotations of “sample”, including the original word. So, the output is 1.

Solution

if len(word1) != len(word2):
        return -1
    if word1 == word2:
        return 1
    for i in range(len(word1)):
        if word1[i:] + word1[:i] == word2:
            return 1
    return -1

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

πŸ“Œ Nodejs and Android 😎
πŸ“Œ Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *