Hidden Password
Time limit2sMemory limit128 MB
Find the starting index of the lexicographically smallest rotation of a string, choosing the smallest index in case of ties (Booth's algorithm).
- Level
Medium6 of 10
- Topics
- String, String matching, Greedy
- Solved
- No attempts yet
Problem
Programmers sometimes hide their passwords in strange ways. Here is how Billy "Hacker" Geits hides his. Billy picks a string of lowercase Latin letters with length . He then forms all one-letter left cyclic shifts of the string and, among all of these strings (including itself), takes a prefix of the lexicographically smallest one as his password.
For example, take the string alabala. Its one-letter left cyclic shifts (including the original string) are:
alabala
labalaa
abalaal
balaala
alaalab
laalaba
aalabal
The lexicographically smallest of them is aalabal. Its first letter is at position in the original string (positions are counted from ).
Given a string , write a program that finds the start position of its smallest lexicographic one-letter left cyclic shift. If the smallest shift occurs more than once, output the smallest start position.
Input
The first line of input contains the number of test cases. Each of the next lines describes one test case: first the length of the string (), then, separated by one space, the string itself.
Output
Output exactly lines, each containing a single number: the start position found for the corresponding test case.