Can One String Be Rotated Into Another?
Efficiently Check If One String Is a Shifted Version of Another
If you’re not a medium member, you can read the story through this link.
Problem
Given two strings A and B, return whether or not A can be shifted some number of times to get B.
For example, if A is abcde and B is cdeab, return true. If A is abc and B is acb, return false.
Problem Breakdown
We are given two strings A
and B
, and we need to check if A
can be shifted (rotated) a certain number of times to get B
.
Example
- A = “abcde” and B = “cdeab” → return
true
because "abcde" can be shifted to form "cdeab". - A = “abc” and B = “acb” → return
false
because no shift will make "abc" become "acb".
Approach
Length Check: First, if the lengths of A
and B
are different, it’s impossible for one string to be a shifted version of the other.
String Rotation Insight: If we concatenate A
with itself (i.e., A + A
), all possible rotations of A
will be present as a substring within this new string. For example:
- A = “abcde”
- A + A = “abcdeabcde” The string “cdeab” will be a substring of…