Lv.3kmpstring
Pattern Occurrences
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Return how many times pattern occurs in text as a contiguous substring, counting overlapping occurrences ("aa" occurs
three times in "aaaa").
Examples
| text | pattern | result |
|---|---|---|
"abababa" | "aba" | 3 |
"aaaa" | "aa" | 3 |
"abc" | "abcd" | 0 |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(text: string, pattern: string) → int
Constraints
-
text.length,pattern.length - Both strings consist of lowercase English letters.
Expected complexity
- Time
- O(N + M)
- Space
- O(M)
Examples
| text | pattern | Expected |
|---|---|---|
"abababa" | "aba" | 3 |
"aaaa" | "aa" | 3 |
"abc" | "abcd" | 0 |
Hint
Hint
Use KMP: build the failure function of pattern, scan text keeping the matched length j, and after a full match fall back
to fail[j - 1] so overlapping matches are found. . Comparing the pattern at every start is on inputs like
"aaa…a", and str.count-style helpers skip overlaps.
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 | 1000 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 | 10 | verdict only |
| performance | 60 | 5 | verdict only |