Tutorialspoint
Problem
Solution
Submissions

Check if Two Strings are Rotations of Each Other

Certification: Intermediate Level Accuracy: 83.33% Submissions: 6 Points: 5

Write a Python function to check if two strings are rotations of each other.

Example 1
  • Input: string1 = "abcd", string2 = "cdab"
  • Output: True
  • Explanation:
    • Step 1: Check if both strings have the same length. "abcd" and "cdab" both have length 4.
    • Step 2: Concatenate string1 with itself: "abcd" + "abcd" = "abcdabcd".
    • Step 3: Check if string2 is a substring of the concatenated string: "cdab" is a substring of "abcdabcd".
    • Step 4: Since "cdab" is a substring of "abcdabcd", return True.
    • Step 5: This confirms that "cdab" is a rotation of "abcd".
Example 2
  • Input: string1 = "hello", string2 = "world"
  • Output: False
  • Explanation:
    • Step 1: Check if both strings have the same length. "hello" and "world" both have length 5.
    • Step 2: Concatenate string1 with itself: "hello" + "hello" = "hellohello".
    • Step 3: Check if string2 is a substring of the concatenated string: "world" is not a substring of "hellohello".
    • Step 4: Since "world" is not a substring of "hellohello", return False.
    • Step 5: This confirms that "world" is not a rotation of "hello".
Constraints
  • 1 <= len(string1), len(string2) <= 1000
  • Time Complexity: O(n) where n is the length of the strings
  • Space Complexity: O(n)
StringsKPMGSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Concatenate the first string with itself and check if the second string is a substring of the concatenated string.
  • Handle edge cases where the lengths of the two strings are different.

Steps to solve by this approach:

 Step 1: Check if both strings have equal length (requirement for rotation)
 
 Step 2: Concatenate str1 with itself to create a temporary string (str1+str1)  
 Step 3: Check if str2 is a substring of the concatenated string  
 Step 4: If str2 exists within the concatenated string, strings are rotations  
 Step 5: Return True if they are rotations, False otherwise  
 Step 6: This works because concatenation contains all possible rotations  
 Step 7: Example: "abcd" and "cdab" are rotations since "cdab" is in "abcdabcd"

Submitted Code :