Hidden Password

Time limit2sMemory limit128 MB

Summary
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 SS of lowercase Latin letters with length LL. He then forms all L−1L-1 one-letter left cyclic shifts of the string and, among all of these strings (including SS 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 66 in the original string (positions are counted from 00).

Given a string SS, 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 TT of test cases. Each of the next TT lines describes one test case: first the length LL of the string (5≤L≤1000005 \le L \le 100000), then, separated by one space, the string SS itself.

Output

Output exactly TT lines, each containing a single number: the start position found for the corresponding test case.

Examples1

  1. Example 1

    Input
    2
    6 baabaa
    7 alabala
    
    Expected output
    1
    6