Monitoring~18 min2s · 256 MBtarget O(n) time, O(n) spacestrings
You work on a monitoring system. Devices send ring codes: a string of letters whose end connects back to its start. The same ring can be written starting at any letter, so two devices can report different strings for one ring.
Your team lead asks: "Give every ring one standard form, so equal rings look equal." The standard form is the smallest rotation in dictionary order. A code can have up to 100,000 letters.
Write smallest_rotation(code).
code is a string of lowercase letters.code takes some letters from the front and moves them to the end, in the same order. Moving none is allowed.Input: code = "cabca"
Output: "abcac"A string of 5 letters has 5 rotations, one for each starting place.
| Start | Rotation |
|---|---|
| 0 | cabca |
| 1 | abcac |
| 2 | bcaca |
| 3 | cacab |
| 4 | acabc |
The smallest in dictionary order is "abcac".
Input: code = "aaaa"
Output: "aaaa"All rotations are equal.
Input: code = "ba"
Output: "ab"The rotations are "ba" and "ab", and "ab" is smaller.
1 ≤ len(code) ≤ 100,000code holds only the letters a to zA string of n letters has n rotations, and each has n letters. Comparing all of them letter by letter can touch about 100,000 × 100,000 = 10,000,000,000 letters. You need to find the best starting place by comparing pairs of places, not by building every rotation.