796. Rotate String

EasyStringString Matching
Leetcode Link

Problem Description

The problem presents a scenario where we have two strings, s and goal, and we are tasked with determining whether s can be transformed into goal through a series of shifts. A shift operation is defined as taking the first character from s and moving it to the end of the string. The task is to perform as many shifts as needed to check if s can match goal. We need to return true if it's possible and false otherwise.


The intuition behind the solution is founded on the idea of concatenation and sub-string checking. By appending string s to itself, we create a new string that contains all possible shifts of s. This is because any shift of a string of length n is a sub-string starting from some index i to index i + n in the double-length string. If goal is a sub-string of this doubled string, then it must be possible to shift the original s to match goal. It is essential, however, to ensure that s and goal are of the same length before checking for a sub-string match, as having different lengths automatically implies that no amount of shifting will make the two strings equal.

Not Sure What to Study? Take the 2-min Quiz to Find Your Missing Piece:

What are the most two important steps in writing a depth first search function? (Select 2)

Solution Approach

The implementation of the solution is quite straightforward and elegant due to the simplicity of the logic involved. It leverages both the Python string methods and the concept of string concatenation and sub-string search. Here's how it's done using the given solution code:

  1. First, the solution checks if s and goal have the same length, as different lengths would make it impossible for s to be shifted into goal. This is done with the expression len(s) == len(goal). If they are not of equal length, the function will return False.

  2. Next, if the lengths are equal, the solution concatenates string s with itself using s + s. This double-length string contains all the possible shifts of string s. For example, for s = "abcde", s + s = "abcdeabcde" would include "eabcd", "deabc", "cdeab", and so on, as its substrings.

  3. The final check is to see if goal is a sub-string within this concatenated version of s. This is achieved with the expression goal in s + s. In Python, the in operator checks if one string is contained within another, returning True if it is found and False if not.

By combining these steps, the function rotateString assesses whether there exists a sequence of shifts that transform s into goal. If goal exists as a sub-string in s + s, that means goal could be reached by shifting s a certain number of times.

In terms of algorithms and data structures, this approach uses a linear search underneath the in operation, and the extra space used is directly proportional to the size of string s due to the concatenation. However, since string concatenation and searching are highly optimized in Python, this solution is both space and time-efficient for the problem at hand.

Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:

What is the space complexity of the following code?

1int sum(int n) {
2  if (n <= 0) {
3    return 0;
4  }
5  return n + sum(n - 1);

Example Walkthrough

Let's walk through an example to illustrate the solution approach for the problem of determining if one string can be transformed into another through cyclic shifts.

Imagine we have s = "abc" and goal = "cab". We want to find out if by cyclically shifting s, we can obtain goal.

  1. First of all, we check if both s and goal have the same length. Here, both s and goal have a length of 3, so we pass this check.

  2. We then concatenate s with itself. So, s + s = "abcabc". Notice that this new string, "abcabc", contains all possible shifts of s:

    • The original string "abc" (starting at index 0)
    • The first shift "bca" (starting at index 1)
    • The second shift "cab" (starting at index 2)
  3. Finally, we look for goal in this new doubled string. goal = "cab" is a substring of s + s = "abcabc", starting from index 2 to index 4.

Because we found goal within s + s, we can confidently return True, which signifies that it is possible to get goal by shifting s two places to the right.

Had goal not been found within the double string s + s, we would have returned False, meaning no amount of shifting would have matched s to goal.

By following these steps with Python's concise string operations, we have a solution that is both elegant and efficient.

Not Sure What to Study? Take the 2-min Quiz:

What is the best way of checking if an element exists in a sorted array once in terms of time complexity? Select the best that applies.

Python Solution

1class Solution:
2    def rotateString(self, s: str, goal: str) -> bool:
3        # Compare the lengths of the strings to ensure they are the same, 
4        # which is a prerequisite for one to be a rotation of the other.
5        if len(s) != len(goal):
6            return False
8        # Concatenate the string 's' with itself, which covers all possible rotations.
9        # If 'goal' is a rotated version of 's', it will be a substring of 's+s'.
10        # Check if 'goal' is present within this concatenated string.
11        return goal in (s + s)
13# Example usage:
14# solution = Solution()
15# result = solution.rotateString("abcde", "cdeab")
16# print(result)  # Output would be True since "cdeab" is a rotation of "abcde"

Java Solution

1class Solution {
2    // Method to check if the string 'goal' can be obtained by rotating 's'.
3    public boolean rotateString(String s, String goal) {
4        // Check if the two strings are of the same length.
5        // If they aren't, they cannot be rotations of each other.
6        if (s.length() != goal.length()) {
7            return false;
8        }
10        // Concatenate 's' with itself. In such a string, any rotation of 's'
11        // would appear as a substring.
12        String doubledS = s + s;
14        // Check if the concatenated string contains 'goal' as a substring.
15        // If it does, 'goal' is a rotation of 's'.
16        return doubledS.contains(goal);
17    }

C++ Solution

1#include <string> // Include necessary library for using strings
2#include <cstring> // Include C-string library for strstr function
4class Solution {
6    // Function to check if string 's' after rotation can become string 'goal'
7    bool rotateString(std::string s, std::string goal) {
8        // First check if the sizes of both strings are equal, an essential condition for rotation
9        if (s.size() != goal.size()) {
10            return false; // If sizes differ, one cannot be a rotation of the other
11        }
13        // Double the string 's' so that it contains all possible rotations
14        std::string doubled_s = s + s;
16        // Use the C library function 'strstr' to check if 'goal' is a substring of 'doubled_s'
17        // 'strstr' returns a pointer to the first occurrence of 'goal' in 'doubled_s', or a null pointer if 'goal' is not present
18        // 'data()' method provides a pointer to the start of the string data
19        return strstr(doubled_s.data(), goal.data()) != nullptr;
20    }

Typescript Solution

1// Checks whether the string 's' can be rotated to match the string 'goal'
2function rotateString(s: string, goal: string): boolean {
3    // Check if the lengths of both strings are equal, as a necessary condition for rotation
4    if (s.length !== goal.length) {
5        return false;
6    }
8    // Concatenate the goal string with itself
9    const doubledGoal = goal + goal;
11    // Check if the original string 's' is a substring of the concatenated string 'doubledGoal'
12    // This would imply that 's' can be rotated to form 'goal'
13    return doubledGoal.includes(s);
Fast Track Your Learning with Our Quick Skills Quiz:

What's the output of running the following function using input 56?

2    '2': 'abc',
3    '3': 'def',
4    '4': 'ghi',
5    '5': 'jkl',
6    '6': 'mno',
7    '7': 'pqrs',
8    '8': 'tuv',
9    '9': 'wxyz',
12def letter_combinations_of_phone_number(digits):
13    def dfs(path, res):
14        if len(path) == len(digits):
15            res.append(''.join(path))
16            return
18        next_number = digits[len(path)]
19        for letter in KEYBOARD[next_number]:
20            path.append(letter)
21            dfs(path, res)
22            path.pop()
24    res = []
25    dfs([], res)
26    return res
1private static final Map<Character, char[]> KEYBOARD = Map.of(
2    '2', "abc".toCharArray(),
3    '3', "def".toCharArray(),
4    '4', "ghi".toCharArray(),
5    '5', "jkl".toCharArray(),
6    '6', "mno".toCharArray(),
7    '7', "pqrs".toCharArray(),
8    '8', "tuv".toCharArray(),
9    '9', "wxyz".toCharArray()
12public static List<String> letterCombinationsOfPhoneNumber(String digits) {
13    List<String> res = new ArrayList<>();
14    dfs(new StringBuilder(), res, digits.toCharArray());
15    return res;
18private static void dfs(StringBuilder path, List<String> res, char[] digits) {
19    if (path.length() == digits.length) {
20        res.add(path.toString());
21        return;
22    }
23    char next_digit = digits[path.length()];
24    for (char letter : KEYBOARD.get(next_digit)) {
25        path.append(letter);
26        dfs(path, res, digits);
27        path.deleteCharAt(path.length() - 1);
28    }
1const KEYBOARD = {
2    '2': 'abc',
3    '3': 'def',
4    '4': 'ghi',
5    '5': 'jkl',
6    '6': 'mno',
7    '7': 'pqrs',
8    '8': 'tuv',
9    '9': 'wxyz',
12function letter_combinations_of_phone_number(digits) {
13    let res = [];
14    dfs(digits, [], res);
15    return res;
18function dfs(digits, path, res) {
19    if (path.length === digits.length) {
20        res.push(path.join(''));
21        return;
22    }
23    let next_number = digits.charAt(path.length);
24    for (let letter of KEYBOARD[next_number]) {
25        path.push(letter);
26        dfs(digits, path, res);
27        path.pop();
28    }

Time and Space Complexity

The given Python function rotateString checks if s rotated can be equal to goal by appending s to itself and checking if goal is a substring of the result.

Time Complexity

The time complexity of the function is determined primarily by the in operation where goal is checked to be a substring of s + s. In the worst-case scenario, the in statement takes O(n*m) time, where n is the length of the string s and m is the length of the string goal. In this code, since we ensure that len(s) == len(goal), we can simplify this to O(n^2).

However, most modern Python implementations use optimized substring search algorithms like the Boyer-Moore or the Knuth-Morris-Pratt algorithm, which on average can provide sub-linear performance in practice, but for the worst-case analysis, we can consider O(n^2).

Space Complexity

Space complexity is determined by the additional space used by the program beyond the input and output. For this code, creating s + s generates a temporary string that requires O(n) space, where n is the length of s (since s and goal are the same length).

Thus, the space complexity of the function is O(n).

Learn more about how to find time and space complexity quickly.

Recommended Readings

Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.

TA 👨‍🏫