← Home

796. Rotate String

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
796

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 796. Rotate String, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are rotateString.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N^2)O(N
  • Space: O(1)O(1). We only use pointers to elements of A and B.

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02We are given two strings, A and B.
03
04A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A.
05
06Example 1:
07Input: A = 'abcde', B = 'cdeab'
08Output: true
09
10Example 2:
11Input: A = 'abcde', B = 'abced'
12Output: false
13Note:
14
15A and B will have length at most 100.
16**/
17
18//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Rotate String.
19//Memory Usage: 8.1 MB, less than 100.00% of C++ online submissions for Rotate String.
20
21class Solution {
22public:
23    bool rotateString(string A, string B) {
24        if(A.size() != B.size()) return false;
25        if(A.size() == 0) return true;
26        
27        vector<int> candidateA;
28        
29        for(int i = 0; i < A.size(); i++){
30            if(A[i] == B[0]){
31                candidateA.push_back(i);
32            }
33        }
34        
35        for(int start : candidateA){
36            bool isRotate = true;
37            for(int i = 0; i < A.size(); i++){
38                if(A[(start+i)%A.size()] != B[i]){
39                    isRotate = false;
40                    break;
41                }
42            }
43            if(isRotate){
44                return true;
45            }
46        }
47        
48        return false;
49    }
50};
51
52/**
53Approach #1: Brute Force [Accepted]
54Complexity Analysis
55
56Time Complexity: O(N^2)O(N 
572
58 ), where NN is the length of A. For each rotation s, we check up to NN elements in A and B.
59
60Space Complexity: O(1)O(1). We only use pointers to elements of A and B.
61**/
62
63/**
64Approach #2: Simple Check [Accepted]
65Intuition and Algorithm
66
67All rotations of A are contained in A+A. Thus, we can simply check whether B is a substring of A+A. We also need to check A.length == B.length, otherwise we will fail cases like A = "a", B = "aa".
68**/
69/**
70Complexity Analysis
71
72Time Complexity: O(N^2)O(N 
732
74 ), where NN is the length of A.
75
76Space Complexity: O(N)O(N), the space used building A+A.
77**/
78/**
79class Solution {
80public:
81    bool rotateString(string A, string B) {
82        return A.size() == B.size() && (A+A).find(B)!=string::npos;
83    }
84};
85**/
86
87/**
88Approach #3: Rolling Hash [Accepted]
89**/
90
91/**
92Approach #4: KMP (Knuth-Morris-Pratt) [Accepted]
93**/

Cost

Complexity

Time
O(N^2)O(N
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(1)O(1). We only use pointers to elements of A and B.
Auxiliary state plus the answer structure where the problem requires one.