Implement the checkStringRotation method that checks whether one string is a rotation of another string.

The input contains two strings, first and second. Your task is to check whether second can be created by rotating first.

A rotation moves characters from the beginning of a string to the end without changing their order. For example, waterbottle rotated by five characters becomes erbottlewat.

Example 1

Input
first (string) = waterbottle
second (string) = erbottlewat
Returns (boolean) true

Example 2

Input
first (string) = abcde
second (string) = cdeab
Returns (boolean) true

Example 3

Input
first (string) = abcde
second (string) = abced
Returns (boolean) false

Two strings can be rotations only if they have the same length.

If second is a rotation of first, it must appear inside first + first. Doubling the first string contains every possible rotation as a substring.

So, first compare lengths, then check whether the second string exists in the doubled string.

Pseudocode:

function checkStringRotation(first, second):
    if length(first) != length(second):
        return false
    doubled = first + first
    if doubled contains second:
        return true
    return false
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.