Problem
Given two string s1 and s2 how will you check if s1 is a rotated version of s2 ?
OR
Assume you have a method isSubstring() which checks if one word is a substring of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring.
OR
Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.
A shift on s consists of moving the leftmost character of s to the rightmost position.
- For example, if
s = "kodeknight", then it will be"odeknightk"after one shift.
Examples
Example 1:
| |
Example 2:
| |
Solutions
Method 1 - Club One of the String and Rely Upon Substring Method
To determine if string s can become string goal after some number of shifts, the key observation is:
- A shift operation can be visualised as a rotation of the string.
- If we concatenate
swith itself (s + s), all possible rotations ofsare contained within this concatenated string.
Thus, if goal is a rotation of s, it will be a substring of s + s.
Steps to solve:
- Check if
sandgoalhave the same length. If not, returnfalse. - Check if
goalis a substring ofs + s.
Here is the solution :
- First make sure s1 and s2 are of the same length.
- Check to see if s2 is a substring of s1 concatenated with s1.
| |
Code
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(n^2), wherenis the length of strings. - 🧺 Space complexity:
O(n)
Method 2 - Rolling Hash
We can use Rabin Karp algorithm using rolling hash to implement substring method.
Complexity
- ⏰ Time complexity:
O(n), wherenis the length of strings. - 🧺 Space complexity:
O(n)
Method 3 - Knuth Morris Pratt
We can use KMP algorithm to implement substring method.
Complexity
- ⏰ Time complexity:
O(n), wherenis the length of strings. - 🧺 Space complexity:
O(n)