Maps app~35 min2s · 256 MBtarget O(n × m) time, O(m) spaceclassic twin: lc-115dp
A maps app records every trip as a log of stop codes, one letter for each stop passed. A saved route is a short pattern of stop codes, in order, that a rider cares about. The rider may pass other stops in between.
The app wants to know how many different ways the saved route appears in the trip log. Two ways are different when they use at least one different position of the log.
Write count_occurrences(text, pattern).
text is the trip log, lowercase letters.pattern is the saved route, lowercase letters.text, in increasing order, whose letters spell pattern. Give the result modulo 1,000,000,007.Input: text = "banana", pattern = "ana"
Output: 4Let ways[j] be the number of ways to pick the first j letters of the pattern, in order, from the part of the text read so far. Picking no letters is one way. When a text letter equals pattern letter j, it can end a pick of the first j letters: add ways[j - 1] to ways[j]. Go through j downwards, so the letter is used for at most one pattern letter.
| after reading | 0 (none) | 1 (a) | 2 (an) | 3 (ana) |
|---|---|---|---|---|
| (none) | 1 | 0 | 0 | 0 |
| 1 (b) | 1 | 0 | 0 | 0 |
| 2 (a) | 1 | 1 | 0 | 0 |
| 3 (n) | 1 | 1 | 1 | 0 |
| 4 (a) | 1 | 2 | 1 | 1 |
| 5 (n) | 1 | 2 | 3 | 1 |
| 6 (a) | 1 | 3 | 3 | 4 |
The last cell holds 4. The picks use the positions (1, 2, 3), (1, 2, 5), (1, 4, 5) and (3, 4, 5), counting from 0.
Input: text = "abc", pattern = "d"
Output: 0The letter d never appears.
Input: text = "aaa", pattern = "aa"
Output: 3Any two of the three positions spell aa.
1 ≤ len(text) ≤ 1000 and 1 ≤ len(pattern) ≤ 1000The table has up to 1,000 × 1,000 = one million entries, and each takes one step. The number of ways can be a number with hundreds of digits, which is why the answer is reduced by a modulus. Counting the ways one at a time cannot finish.