Repeated Substring Pattern Problem
Description
LeetCode Problem 459.
Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
Example 1:
Input: s = "abab"
Output: true
Explanation: It is the substring "ab" twice.
Example 2:
Input: s = "aba"
Output: false
Example 3:
Input: s = "abcabcabcabc"
Output: true
Explanation: It is the substring "abc" four times or the substring "abcabc" twice.
Constraints:
- 1 <= s.length <= 10^4
- s consists of lowercase English letters.
Solution
Approach: Try Every Block Length That Divides n
If s is made of copies of a block, the block is a prefix of s, and its length length must divide n = len(s) evenly. It must also repeat at least twice, so length <= n / 2. That leaves few candidates: a number up to 104 has at most 64 divisors.
For each candidate length, checking the copies one by one is the same as checking that every character equals the one length positions before it:
s[i] == s[i - length] for every i from length to n - 1
If that holds, s has period length, and since length divides n, s is exactly n / length copies of s[0 : length]. Return true at the first length that passes; if none does, return false.
For "abcabcabcabc" the lengths 1 and 2 fail at the first comparison, and length 3 passes, so the answer is true.
Two details: skip lengths that do not divide n. "abcabcab" has period 3, but 8 is not a multiple of 3, so it is not made of whole copies. And a single character (n = 1) has no candidate length, so it is false: one copy is not "multiple copies".
Complexity: O(n · d(n)) time, where n is the length of s and d(n) is its number of divisors, and O(1) extra space.
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
n = len(s)
for length in range(1, n // 2 + 1): # the block must repeat at least twice
if n % length != 0:
continue
if self.is_repeat_of(s, length):
return True
return False
def is_repeat_of(self, s: str, length: int) -> bool:
"""s is copies of s[:length] exactly when every character equals the one `length` before it."""
for i in range(length, len(s)):
if s[i] != s[i - length]:
return False
return True