Explorer
Data Structures & Algorithms

Check if string s can become goal after any number of rotations.

Problem Statement

Given two strings `s` and `goal`, return `true` if and only if `s` can become `goal` after some number of shifts on `s`. A shift on `s` consists of moving the leftmost character of `s` to the rightmost position.

Examples

Input: s = "abcde", goal = "cdeab"

Output: true

Explanation: Goal string can be obtained by shifting characters of s.

Input: s = "abcde", goal = "abced"

Output: false

Explanation: Goal string cannot be formed by shifting characters of s.

Complexity

Time Complexity: O(N)

Space Complexity: O(N)

Hints

šŸ’” Hint 1: Any rotation of s will always appear as a substring of s + s. šŸ’” Hint 2: First check if s and goal have identical length. šŸ’” Hint 3: Return s.length === goal.length && (s + s).includes(goal).

Editorial & Approach

Problem Overview & Intuition

Concatenating s with itself (s + s) contains every cyclic shift of s of length N. Therefore, goal is a valid rotation of s if and only if lengths match and (s + s).includes(goal).

Step-by-Step Approach

  1. Check if s.length !== goal.length; if so, return false.
  2. Return (s + s).includes(goal).

Optimal Implementation (JavaScript)

function rotateString(s, goal) {
  if (s.length !== goal.length) return false;
  return (s + s).includes(goal);
}

Complexity Analysis

Time Complexity O(N) — string search in 2N length string.
Space Complexity O(N) — memory for concatenated string.

Edge Cases & Corner Traps Handled

  • Different length strings: returns false.
  • Identical strings: returns true.
  • Single character match/mismatch.

Rotate String

Easy
Given two strings `s` and `goal`, return `true` if and only if `s` can become `goal` after some number of shifts on `s`. A shift on `s` consists of moving the leftmost character of `s` to the rightmost position.
Example Scenarios
1Example 1
Input: s = "abcde", goal = "cdeab"
Output: true
Explanation:

Goal string can be obtained by shifting characters of s.

2Example 2
Input: s = "abcde", goal = "abced"
Output: false
Explanation:

Goal string cannot be formed by shifting characters of s.

Editor
Loading Editor...
s =
"abcde"
goal =
"cdeab"
Output:Click "Run" above to execute and verify your code here.
true