The Indian Engineer

Problem 796 Rotate String

Posted on 5 mins

String String Matching

Problem Statement

Link - Problem 796

Question

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 1:

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

Example 2:

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

Constraints:

Solution

class Solution {
public:
    bool rotateString(string s, string goal) {
        if(s.size()!=goal.size())
            return false;

        string test = s+s;
        int t = test.size(), g = goal.size();
        int j;
        for(int i=0; i<t-g; i++){
            j = 0;
            while(j<g && test[i+j] == goal[j]){
                j++;
            }
            if(j==g)
                return true;
        }

        return false;
    }
};

Complexity Analysis

| Algorithm                             | Time Complexity | Space Complexity |
| ------------------------------------- | --------------- | ---------------- |
| KMP variant with string concatenation | O(nm)           | O(n)             |

Explanation

Intial Thoughts

To solve this problem, consider the concept of a circular buffer where the string s is treated as a ring. The goal is to find if the string goal can be obtained by rotating this ring. Initially, think about the conditions under which s can become goal after some shifts. Consider the lengths of the strings and how shifts affect the position of characters. Think about how to efficiently compare all possible rotations of s with goal.

Intuitive Analysis

Intuitively, solving this problem involves understanding that a shift operation is essentially a circular rotation of the string s. The key insight is that if s can become goal after some shifts, then goal must be a substring of s repeated twice (s+s), because no matter how many times you shift s, you’re essentially looking at different parts of this doubled string. Thus, the solution involves checking if goal is a substring of s+s, which covers all possible rotations of s. This approach allows for an efficient solution by avoiding the need to actually perform the rotations and compare each time.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Easy difficulty.