Skip to content
BytePatterns

Smallest Repeating Unit

MediumStrings#kmp#string-period~25m

Problem

Given a non-empty string s, return the shortest string u such that s is u written a whole number of times in a row. If no shorter unit works, the answer is s itself. The answer should take O(n) time.

Examples

Input:  s = "xyzxyzxyz"
Output: "xyz"
Why:    three copies of "xyz"
Input:  s = "abaab"
Output: "abaab"
Why:    a shift of 3 lines "ab" up with itself, but 3 does not divide 5
Input:  s = "q"
Output: "q"
Why:    edge case, a single letter is its own unit

Hints

0 / 3

Stuck on the idea rather than the code? String Matching Intuition covers it.