#796

Rotate String

Easy
StringString MatchingString MatchingSubstring Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of generating all rotations, we can concatenate the string `s` with itself. If `goal` is a substring of this new string, then `s` can be rotated to form `goal`. This is efficient and avoids unnecessary computations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the lengths of `s` and `goal` are equal. If not, return false.
  2. 2Step 2: Concatenate `s` with itself to form `s + s`.
  3. 3Step 3: Check if `goal` is a substring of `s + s`. If it is, return true; otherwise, return false.
solution.py4 lines
1def rotateString(s, goal):
2    if len(s) != len(goal):
3        return False
4    return goal in (s + s)

Complexity note: The time complexity is O(n) due to the substring search, and the space complexity is O(n) for the concatenated string.

  • 1Concatenating the string allows us to check for rotations efficiently.
  • 2The problem can be reduced to a substring search rather than generating all rotations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.