Given two strings, the task is to find if a string can be obtained by rotating another string two places.
Examples:
Input : string1 = “amazon”, string2 = “azonam” Output: Yes // rotated anti-clockwiseInput : string1 = “amazon”, string2 = “onamaz” Output : Yes // rotated clockwise
Asked in : Amazon Interview
1- There can be only two cases:
a) Clockwise rotated
b) Anti-clockwise rotated
2- If clockwise rotated that means elements
are shifted in right.
So, check if a substring[2.... len-1] of
string2 when concatenated with substring[0,1]
of string2 is equal to string1. Then, return true.
3- Else, check if it is rotated anti-clockwise
that means elements are shifted to left.
So, check if concatenation of substring[len-2, len-1]
with substring[0....len-3] makes it equals to
string1. Then return true.
4- Else, return false.
Below is the implementation of the above approach.
Javascript
<script>
function isRotated(str1, str2)
{
if (str1.length != str2.length)
return false;
if (str1.length < 2)
{
return str1.localeCompare(str2);
}
let clock_rot = "";
let anticlock_rot = "";
let len = str2.length;
anticlock_rot = anticlock_rot +
str2.substring(len - 2,
len + 1) +
str2.substring(0, len - 1) ;
clock_rot = clock_rot +
str2.substring(2, str2.length -
2 + 1) +
str2.substring(0, 2 + 1);
return (str1.localeCompare(clock_rot) ||
str1.localeCompare(anticlock_rot));
}
let str1 = "geeks";
let str2 = "eksge";
document.write(isRotated(str1, str2) ?
"Yes" : "No");
</script>
Output:
Yes
Time Complexity : O(n), where n is the size of the given string.
Please refer complete article on Check if a string can be obtained by rotating another string 2 places for more details!
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
23 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...