Number of Distinct Substrings
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given a string s of lowercase English letters, return the number of distinct non-empty substrings of s (contiguous;
a substring that occurs in several places is counted once).
Examples
| s | result |
|---|---|
"abab" | 7 |
"aaa" | 3 |
"banana" | 15 |
Example 1 — a, b, ab, ba, aba, bab, abab.
Example 2 — a, aa, aaa.
Example 3 — 21 substring positions, 15 distinct contents.
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(s: string) → long
Constraints
-
s.length sconsists of lowercase English letters only.- The answer may not fit in 32 bits.
Expected complexity
- Time
- O(N log^2 N)
- Space
- O(N)
Examples
| s | Expected |
|---|---|
"abab" | 7 |
"aaa" | 3 |
"banana" | 15 |
Hint
Hint
Every substring is a prefix of some suffix, so the answer is minus the overlaps between lexicographically adjacent
suffixes: build the suffix array (prefix doubling, or with radix sort), compute the LCP
array with Kasai's algorithm in , and subtract . A suffix automaton also works. Comparing suffixes as
strings, or putting substrings in a set, is quadratic on repetitive strings like aaaa… and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 204 ms | estimated |
| C++ (GCC, gnu++23) | 204 ms | derived |
| Python 3.13 | 1832 ms | derived |
| Java 25 | 1388 ms | derived |
| Kotlin 2.4 (JVM) | 1408 ms | estimated |
| C# 14 (.NET 10) | 1408 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 12 | verdict only |
| performance | 60 | 5 | verdict only |