Solution: Let’s say you want to check whether str1 and str2 is the rotation of one another or not.
- Create a new String with str3= str1 + str1
- Check if str3 contains str2 or not.
- if str3 contains str2 then str2 is the rotation of str1 else it is not
Let's say you need to check whether
str1andstr2is the rotation of one another or not.
- Create a new String with
str3=str1+str1 - Check if
str3containsstr2or not. - if
str3containsstr2thenstr2is rotation ofstr1else it is not
- Java Program to check if one String is the rotation of another.
package org.cloudTechtwitter; public class StringRotationMain { public static void main(String[] args) { System.out.println( "CloudTechtwitter and TechtwitterCloud are rotation of each other : " + isRotation("CloudTechtwitter", "TechtwitterCloud")); System.out.println( "CloudTechtwitter and TechCloudtwitter are rotation of each other : " + isRotation("CloudTechtwitter", "TechCloudtwitter")); } public static boolean isRotation(String str, String rotation) { String str2 = str + str; if (str2.contains(rotation)) { return true; } return false; } }
Python Code
def is_rotation(s1: str, s2: str) -> bool: if len(s1) != len(s2): return False return (s1 + s1).find(s2) != -1 print(is_rotation("CloudTechtwitter", "TechtwitterCloud")) # True print(is_rotation("CloudTechtwitter", "TechCloudtwitter")) # False
📌 Final Comparison
Approach Time Complexity Space Complexity Best Use Double the first string and check if second is a substring O(n) O(n) ⭐ Best and simple rotation check Naive nested loop substring search O(n²) O(1) Basic but slow approach Built-in substring functions (contains / find) O(n) O(1) ✔ Clean standard library method