Library Ribbon Canonical Code
Smallest circular ordering under rotation and reversal
A library attaches a circular identification ribbon to each archival reel. The ribbon contains lowercase English letters, represented by the string ribbon in clockwise order from an arbitrary position.
A scanner may choose any position as its starting point and read either clockwise or counterclockwise. It reads exactly one full circuit, including every position once.
Return the lexicographically smallest string the scanner can produce.
For strings of equal length, lexicographic order is determined by the first position where they differ, using a < b < ... < z. Different scanning choices may produce the same string; only the resulting string is returned.
Examples
Example 1
Input: ribbon = "adcb" Output: "abcd"
Starting at the only occurrence of `a` is best. From that position, counterclockwise reading encounters `b` next, while clockwise reading encounters `d` next.
Example 2
Input: ribbon = "baca" Output: "abac"
There are two occurrences of `a` to consider as starting positions. Compare their subsequent letters, in both directions, to determine the smallest complete reading.
Example 3
Input: ribbon = "baba" Output: "abab"
The repeated two-letter pattern lets multiple starting positions produce the same smallest reading. These choices do not need to be distinguished.
Constraints
- 1 <= ribbon.length <= 100000
- ribbon contains only lowercase English letters
An intended solution takes O(n) time and O(n) auxiliary space, where n is the ribbon length. Reversing the stored string and considering all of its rotations covers every counterclockwise reading of the original ribbon.
Hints
Show hint 1Hint 1
First solve the problem for one fixed direction. Compare two candidate starting positions without constructing every rotation.
Show hint 2Hint 2
If two candidates match for k letters and then one loses, the losing candidate and its next k starting positions can all be discarded. Apply this elimination in both orientations.
Follow-up questions
What an interviewer might ask once you have a working solution.
- How would you also return a starting index and direction, breaking ties by the smallest original index and then preferring clockwise?
- How would the solution change if the ribbon contained arbitrary integer labels instead of letters?
Practice this with an AI interviewer
Explain your approach out loud, write Python or JavaScript, run it against hidden tests (including large inputs), and get a scored debrief.
Start this problem