Funcia
Lv.3kmpstringz-algorithm

All Periods of a String

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

For a string s of length NN, an integer pp with 1≤p≤N1 \le p \le N is a period of s if s[i] = s[i + p] for every 0≤i<N−p0 \le i < N - p — shifting s by pp positions, the overlapping parts agree. p=Np = N is always a period.

Return all periods of s in ascending order.

Examples

sresult
"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

  • 1≤N=1 \le N = s.length ≤500,000\le 500{,}000
  • s consists of lowercase English letters only.

Expected complexity

Time
O(N)
Space
O(N)

Examples

sExpected
"abaababa"[5,7,8]
"aaaa"[1,2,3,4]
"abcabcab"[3,6,8]

Hint

Hint

pp is a period exactly when the suffix starting at pp 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 O(N)O(N) (equivalently, follow KMP failure links: each border of length bb gives the period N−bN - b). Comparing every shift directly is O(N2)O(N^2) on strings like "aaaa…" and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251192 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4012verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.