codejump
EasyPro challengePythonJavaScriptTypeScript

Strings — Repeated Substring Pattern

AlgorithmsStringsKMP

solve(s) — return true if s can be built by repeating a shorter substring two or
more times ("abab" is "ab" twice).

Trying every divisor of the length is fine, but the failure table of KMP answers it in one
pass: let n = s.length and b = lps[n - 1] (the longest border of the whole string). The
string is periodic exactly when b > 0 and n is divisible by n - b (the length of the
smallest period).

Examples

solve("abab")           → true
solve("aba")            → false
solve("abcabcabcabc")   → true
solve("a")              → false

Sample tests

Test #1ab twice
Input: ["abab"]
Output: true
Test #2Border but not periodic
Input: ["aba"]
Output: false
Test #3Repeated four times
Input: ["abcabcabcabc"]
Output: true