Table of Contents

ExplanationImplementation

Explanation

We'll maintain the smallest lexicographically rotation after it's starting index, let it be ii. Then, the comparison between this one and another rotation, starting at index jj, is done by finding the first different character. This can be quickly done by binary searching the value dd such that Si+dSj+dS_{i+d} \neq S_{j+d}. Furthermore, hashing can be used to compare the prefixes of the rotations.

The algorithm is also known as Booth's Algorithm.

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N \cdot \log{N})

C++

#include <bits/stdc++.h>
using namespace std;
Code Snippet: Hashing Template (from the module) (Click to expand)
int main() {
string s;
cin >> s;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!