Lv.3dphashstring
Word Break
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given a string s without spaces and a dictionary words, return whether s can be split into pieces that are all
dictionary words (words may be reused).
Examples
| s | words | result |
|---|---|---|
"applepenapple" | ["apple", "pen"] | true |
"catsandog" | ["cats", "dog", "sand", "and", "cat"] | false |
"aaaaaaa" | ["aaa", "aaaa"] | true |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(s: string, words: string[]) → bool
Constraints
-
s.length,words.length,words[i].length - Lowercase English letters only; the dictionary may contain duplicates.
Expected complexity
- Time
- O(N * L)
- Space
- O(N + total word length)
Examples
| s | words | Expected |
|---|---|---|
"applepenapple" | ["apple","pen"] | true |
"catsandog" | ["cats","dog","sand","and","cat"] | false |
"aaaaaaa" | ["aaa","aaaa"] | true |
Hint
Hint
DP over prefixes: ok[0] = true, and ok[i] holds if some word w ends at i with ok[i - |w|]. Because words are at most
20 letters, only check pieces of length 1..20 (hash set) or walk a trie forward from each true position. Checking every
earlier split point creates substrings 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 | 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 | 4 | verdict only |