Sub topic 11
Finding Periods and Repetitions
This chapter assumes you have read the earlier chapters on borders and the prefix function. You should be able to compute pi by hand and know that pi[i] is the length of the longest proper border of p[0..i]. It also assumes you are comfortable with Python and zero-based indexing.
So far the prefix function has served KMP search. The same array also answers questions about the internal structure of a single string. Does it repeat? What is its shortest repeating unit? Which of its prefixes are made of whole copies of a smaller block? Each answer comes from one linear pass and some arithmetic.
What a Period Is
A positive integer p is a period of a string s of length n if every character equals the character p positions later:
s[i] == s[i + p]for everyiwith0 <= i < n - p.
Put another way, if you shift s right by p positions, the overlapping parts agree. The length n is always a period, because then there is nothing to compare. The minimal period is the smallest such p.
A period does not have to divide the length. The string abcab has period 3: s[0] = s[3] = 'a' and s[1] = s[4] = 'b'. Its length 5 is not a multiple of 3, so abcab is "abc" repeated and then cut short.
When the period does divide the length, the string is an exact repetition. abcabcabc has period 3, and 9 / 3 = 3, so it equals "abc" * 3. Strings of this form, u * k with k >= 2, are called powers. A string that is not a power is called primitive.
The Border–Period Duality
Periods and borders describe the same thing from two angles:
shas a border of lengthbif and only ifn - bis a period ofs.
The proof is a direct reading of the definitions. A border of length b means s[0..b-1] == s[n-b..n-1]. Character by character, that says s[i] == s[i + (n - b)] for 0 <= i < b, which is exactly the period condition for p = n - b, because n - p = b.
The table shows this for s = "abcabcab", with n = 8. Its longest proper border is abcab, of length 5, so the period is 3.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| `s` | a | b | c | a | b | c | a | b |
| `s` shifted by 3 | a | b | c | a | b | |||
| Agrees? | yes | yes | yes | yes | yes |
The overlap is the border. A longer border means a smaller shift that still lines up, so:
- minimal period =
n - pi[n - 1]
The longest proper border gives the smallest period, and the prefix function hands you that border for free.
Code: Periods from the Prefix Function
The block below defines the prefix function again so it runs on its own. It then defines three functions:
minimal_periodreturns the true minimal period.smallest_periodreturns the length of the shortest unit whose whole copies make ups.all_periodslists every period.
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 minimal_period(s):
if not s:
return 0
return len(s) - prefix_function(s)[-1]
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
def all_periods(s):
n = len(s)
if n == 0:
return []
pi = prefix_function(s)
periods = []
b = pi[-1]
while b > 0:
periods.append(n - b)
b = pi[b - 1]
periods.append(n)
return periods
print(minimal_period("abcab")) # 3
print(smallest_period("abcabcabc")) # 3
print(smallest_period("abcab")) # 5
print(all_periods("abacaba")) # [4, 6, 7]Watch the difference between the first two functions. For abcab, minimal_period returns 3, which is a true period. smallest_period returns 5, because no unit shorter than the whole string tiles abcab exactly. The right one depends on the question. If you are asked "what is the period?", use minimal_period. If you are asked "what is the repeating block?", use smallest_period.
all_periods walks the border chain, the same chain KMP follows on a mismatch. Every border of s is found by repeatedly applying b = pi[b - 1], starting from pi[n - 1]. By the duality, each border gives a period. For abacaba the borders are aba (length 3) and a (length 1), so the periods are 7 − 3 = 4, 7 − 1 = 6, and 7. The periods come out in increasing order because the borders shrink.
Why "p Divides n" Is the Right Test
One claim needs justification. Suppose the minimal period p does not divide n. Could s still be a power of some longer unit q?
It cannot, and the reason is the Fine–Wilf theorem. One form of it says: if p and q are both periods of s and p + q <= n, then gcd(p, q) is also a period.
Assume s = u * k with |u| = q and k >= 2. Then:
qis a period ofs, andq <= n / 2.p <= q, becausepis the minimal period. Sop + q <= 2q <= n.- By Fine–Wilf,
gcd(p, q)is a period. It cannot be smaller thanp, sogcd(p, q) = p, which meanspdividesq. qdividesn, sopdividesn.
Therefore, if s is a power at all, p divides n. The test n % p == 0 with p < n is both necessary and sufficient. It also shows that the unit s[0..p-1] is the shortest possible: every other repeating unit is made of copies of it.
Repetitions in Every Prefix
The prefix function stores a border for every prefix, not just the whole string. So you get the minimal period of every prefix s[0..i] in one pass: it is (i + 1) - pi[i].
A classic exercise asks: for every prefix that is a power, report its length and the largest exponent k. Apply the same divisibility test to each prefix.
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 prefix_powers(s):
pi = prefix_function(s)
result = []
for i in range(1, len(s)):
length = i + 1
p = length - pi[i]
if pi[i] > 0 and length % p == 0:
result.append((length, length // p))
return result
def is_power(s):
if not s:
return False
b = prefix_function(s)[-1]
return b > 0 and len(s) % (len(s) - b) == 0
print(prefix_powers("aabaabaabaab"))
# [(2, 2), (6, 2), (9, 3), (12, 4)]
print(is_power("abab"), is_power("aba")) # True FalseFor aabaabaabaab, the prefix of length 2 is "a" * 2. The prefixes of length 6, 9, and 12 are "aab" repeated 2, 3, and 4 times. Prefixes such as length 7 (aabaaba) have period 3, but 3 does not divide 7, so they are skipped.
The whole computation is O(n) time and O(n) space, the cost of one prefix-function pass.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Reporting `n - pi[n-1]` as "the repeating unit" for every string | Says `abcab` is built from `abc` | Check `n % p == 0` before treating `p` as a unit |
| Forgetting the `pi[n-1] > 0` guard | Every string counts as a power of itself | Require `p < n`, which is the same as `pi[n-1] > 0` |
| Using `pi[n]` instead of `pi[n-1]` | `IndexError`, or the wrong prefix | The whole string's border is at the last index, `n - 1` |
| Listing periods by testing every `p` from 1 to `n` | O(n²) time | Walk the border chain with `b = pi[b - 1]` |
| Calling `prefix_function("")[-1]` | `IndexError` on empty input | Handle the empty string first |
A Related Trick: Search in the Doubled String
Another well-known test says s is a power if and only if s occurs in (s + s)[1:-1], the doubled string with its first and last characters removed. Running kmp_search from the earlier chapter on that string gives the same answer in O(n). The first match position plus 1 is the length of the shortest repeating unit. The prefix-function test does the same job without building a 2n-character string, so prefer it when you already have pi.
Exercises
Exercise
Compute the prefix function of s = "abaababaab" and use it to find the minimal period of s. Is s a power of a shorter string?
Show answer
pi = [0, 0, 1, 1, 2, 3, 2, 3, 4, 5]. The minimal period is 10 - 5 = 5. Since 10 % 5 == 0 and 5 < 10, s is a power: s = "abaab" * 2.
Exercise
List all periods of s = "aabaaba" by walking the border chain, and check one of them against the definition.
Show answer
pi = [0, 1, 0, 1, 2, 3, 4], so the chain of borders is 4 ("aaba"), then pi[3] = 1 ("a"), then pi[0] = 0. The periods are 7 - 4 = 3, 7 - 1 = 6, and 7. Check period 3: s[0..3] = "aaba" must equal s[3..6] = "aaba", and it does.
Exercise
A string has length 12 and pi[11] = 8. What is its minimal period, and is it a power? Answer the same question for length 12 and pi[11] = 7.
Show answer
With pi[11] = 8, the period is 4 and 12 % 4 == 0, so the string is its first 4 characters repeated 3 times. With pi[11] = 7, the period is 5 and 12 % 5 != 0, so the string is primitive even though 5 is a valid period.
Exercise
Why can prefixpowers report all power prefixes in O(n) total time, when checking each prefix separately with smallestperiod would take O(n^2)?
Show answer
One prefix-function pass computes pi[i] for every i in O(n) amortized time. The minimal period of each prefix is (i + 1) - pi[i], so each prefix then costs O(1). Calling smallest_period on each prefix would recompute the prefix function from scratch every time, at O(i) per prefix.