Explanation
We'll maintain the smallest lexicographically rotation after it's starting index, let it be . Then, the comparison between this one and another rotation, starting at index , is done by finding the first different character. This can be quickly done by binary searching the value such that . Furthermore, hashing can be used to compare the prefixes of the rotations.
The algorithm is also known as Booth's Algorithm.
Implementation
Time Complexity:
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!