Lv.3kmpstringz-algorithm
All Periods of a String
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
For a string s of length , an integer with is a period of s if s[i] = s[i + p] for every
— shifting s by positions, the overlapping parts agree. is always a period.
Return all periods of s in ascending order.
Examples
| s | result |
|---|---|
"abaababa" | [5, 7, 8] |
"aaaa" | [1, 2, 3, 4] |
"abcabcab" | [3, 6, 8] |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(s: string) → int[]
Constraints
-
s.length sconsists of lowercase English letters only.
Expected complexity
- Time
- O(N)
- Space
- O(N)
Examples
| s | Expected |
|---|---|
"abaababa" | [5,7,8] |
"aaaa" | [1,2,3,4] |
"abcabcab" | [3,6,8] |
Hint
Hint
is a period exactly when the suffix starting at equals a prefix of s, i.e. z[p] = N - p where z[i] is the
longest common prefix of s and s[i..]. The Z-algorithm computes all z values in (equivalently, follow KMP
failure links: each border of length gives the period ). Comparing every shift directly is on strings
like "aaaa…" and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1192 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 12 | verdict only |
| performance | 60 | 4 | verdict only |