Problem 796 Rotate String
Table of Contents
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.
- 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 <= 100sandgoalconsist of lowercase English letters.
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
- The problem can be approached by considering all possible shifts of the string
sand checking if any of them match thegoalstring - A key insight is that if
scan becomegoalafter some shifts, thengoalmust be a substring ofsconcatenated with itself - This is because a shift operation is equivalent to moving the leftmost character to the rightmost position, which can be simulated by concatenating
swith itself - The solution works by checking all substrings of
s+sthat have the same length asgoalto see if any of them matchgoal - This approach ensures that all possible shifts of
sare considered, and it does so in a way that is efficient and easy to implement - The time complexity of this approach is O(n), where n is the length of
s, because we are iterating over all substrings ofs+sthat have the same length asgoal - The space complexity is also O(n) because we need to store the concatenated string
s+s
2. Implementation
- The solution starts by checking if the lengths of
sandgoalare equal, and if not, it immediately returnsfalsebecausescannot becomegoalafter any number of shifts - It then creates a new string
testby concatenatingswith itself, which allows us to simulate all possible shifts ofs - The solution then iterates over all substrings of
testthat have the same length asgoal, and for each one, it checks if it matchesgoalby comparing characters one by one using a while loop - If a match is found, the solution immediately returns
true, indicating thatscan becomegoalafter some shifts - If no match is found after checking all substrings, the solution returns
false, indicating thatscannot becomegoalafter any number of shifts - The use of
t = test.size()andg = goal.size()simplifies the code and makes it more readable by avoiding repeated calculations of the lengths oftestandgoal - The variable
jis used to keep track of the current position in the substring being compared togoal, and it is incremented as long as the characters match
Complexity Analysis
Time Complexity:
- The algorithm iterates over the concatenated string
testwith two nested loops, where the outer loop runst-gtimes and the inner loop runsgtimes in the worst case, resulting in a time complexity of O((t-g)g). Sincet = 2nandg = n, this simplifies to O(nn) = O(n^2) but is often reported as O(nm) where n and m are the lengths ofsandgoalrespectively. - The dominant operation is the while loop comparison
test[i+j] == goal[j], which occurs for each character in the strings up togtimes for each of thet-gstarting positions. - Justification of Big O classification lies in the fact that the number of operations grows quadratically with the size of the input strings, hence the O(n^2) or O(nm) classification.
Space Complexity:
- The algorithm creates a new string
testwhich is the concatenation ofswith itself, resulting in a space complexity that is directly proportional to the size ofs. - The impact of the data structure (in this case, the string
test) is that it requires additional memory that scales linearly with the size of the input strings. - Justification of the space complexity as O(n) arises from the fact that the memory usage is directly proportional to the size of the input string
s, where n is the length ofs.
Footnote
This question is rated as Easy difficulty.