Check whether one string is a rotation of another
Problem
Return true if s2 can be obtained by rotating s1, that is, by moving some prefix of s1 to its end.
Example 1
Input: s1 = "ABCD", s2 = "CDAB" Output: true
Example 2
Input: s1 = "ABCD", s2 = "ACBD" Output: false
Also asked as: Write a Code to check whether one string is a rotation of another
Test cases
Case 1
Input: "ABCD", "CDAB" Expected: true
Case 2
Input: "ABCD", "ACBD" Expected: false
Case 3
Input: "abc", "abcd" Expected: false
Case 4
Input: "aa", "aa" Expected: true
View solutionHide solution1 approach
1. Double-and-search
Time O(n) with a linear substring searchSpace O(n)
b is a rotation of a iff b is a substring of a + a (and lengths match).
function isRotation(a, b) { return a.length === b.length && (a + a).includes(b);}