Skip to main content

Rotate String

LeetCode 812 | Difficulty: Easy​

Easy

Problem Description​

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.

- For example, if `s = "abcde"`, then it will be `"bcdea"` after one shift.

Example 1:

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

Example 2:

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

Constraints:

- `1 <= s.length, goal.length <= 100`

- `s` and `goal` consist of lowercase English letters.

Topics: String, String Matching


Approach​

String Processing​

Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 115 ms)​

MetricValue
Runtime115 ms
Memory35.7 MB
Date2022-01-21
Solution
public class Solution {
public bool RotateString(string s, string goal) {
return s.Length == goal.Length && (s+s).IndexOf(goal)>=0;
}
}
πŸ“œ 1 more C# submission(s)

Submission (2022-01-21) β€” 141 ms, 35.9 MB​

public class Solution {
public bool RotateString(string s, string goal) {
return s.Length == goal.Length && (s+s).Contains(goal);
}
}

Complexity Analysis​

ApproachTimeSpace
Solution$O(n)$$O(1) to O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.