Sub topic 11
Finding Periods and Repetitions
This chapter assumes you know the prefix function from earlier chapters: pi[i] is the length of the longest proper border of s[0..i]. It also assumes you can read Python and Big-O notation. The prefix function does more than drive KMP search. With one subtraction, it also tells you how a string repeats.
What a Period Is
A positive integer p is a period of a string s of length n if s[i] == s[i + p] for every i with 0 <= i < n - p. In other words, if you shift the string right by p, the overlapping parts agree. Every string has period n, because nothing overlaps.
"abcabcabc"has periods 3, 6, and 9."abcab"has periods 3 and 5. The last block"ab"is a partial copy of"abc"."abacaba"has periods 4, 6, and 7.
Periods Are Borders in Disguise
Saying p is a period means the prefix of length n - p equals the suffix of length n - p. That is exactly the definition of a border. So:
pis a period ofsif and only ifshas a border of lengthn - p.- The longest border gives the smallest period:
p = n - pi[n - 1].
For "abcabcabc", the prefix function is [0, 0, 0, 1, 2, 3, 4, 5, 6]. The longest border is 6, so the smallest period is 9 - 6 = 3.
Detecting Full Repetitions
A string is a repetition (a power) if it equals some shorter block written k ≥ 2 times. Having a short period is not enough, because "abcab" has period 3 but is not a whole number of copies of "abc". The test is whether the smallest period divides n.
def prefix_function(p):
pi = [0] * len(p)
k = 0
for i in range(1, len(p)):
while k > 0 and p[i] != p[k]:
k = pi[k - 1]
if p[i] == p[k]:
k += 1
pi[i] = k
return pi
def smallest_period(s):
if not s:
return 0
n = len(s)
p = n - prefix_function(s)[-1]
return p if n % p == 0 else n
print(smallest_period("abcabcabc")) # 3
print(smallest_period("abcab")) # 5Note what this function returns. For "abcab" it returns 5, meaning "no shorter repeating unit", even though 3 is the smallest period. The name follows the topic spine's convention, which is the smallest period that divides n.
Repetitions in Every Prefix
The array covers every prefix at no extra cost. Prefix s[0..i] has length L = i + 1 and smallest period L - pi[i]. In O(n) total time, this finds every prefix that is a power:
def prefix_powers(s):
pi = prefix_function(s)
result = []
for i in range(len(s)):
L = i + 1
p = L - pi[i]
if pi[i] > 0 and L % p == 0:
result.append((L, p, L // p))
return result
print(prefix_powers("abababab")) # [(4, 2, 2), (6, 2, 3), (8, 2, 4)]The pi[i] > 0 check filters out the trivial case p = L, where the block appears only once.
All Periods, Not Just the Smallest
Following the border chain pi[n-1], pi[b-1], ... lists every border, and each border b gives a period n - b.
def all_periods(s):
n = len(s)
if n == 0:
return []
pi = prefix_function(s)
periods = []
b = pi[n - 1]
while b > 0:
periods.append(n - b)
b = pi[b - 1]
periods.append(n)
return periods
print(all_periods("abacaba")) # [4, 6, 7]Common Mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Treating `n - pi[n-1]` as the repeating unit without checking divisibility | Reports `"abcab"` as made of `"abc"` | Check `n % p == 0` |
| Forgetting the empty string | `prefix_function("")[-1]` raises `IndexError` | Handle `n == 0` first |
| Counting `p = n` as a repetition | Every string looks like a power | Require `pi[n-1] > 0` or k ≥ 2 |
Exercise
Compute the prefix function of "aabaaba". What is its smallest period, and what does smallest_period return?
Show answer
The prefix function is [0, 1, 0, 1, 2, 3, 4]. The longest border is 4, so the smallest period is 7 - 4 = 3 ("aab" repeated, then "a"). Since 7 % 3 != 0, smallest_period returns 7: the string is not a whole repetition.
Exercise
Using the border chain, list all periods of "aaaa".
Show answer
The prefix function is [0, 1, 2, 3]. The borders are 3, 2, 1, so the periods are 1, 2, 3, and also 4 (the length itself). all_periods("aaaa") returns [1, 2, 3, 4].