Bank app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-187string-algorithms
A banking app lets people see their spending as a pattern. Each purchase in a statement is one letter: a for food, b for transport, c for bills and d for leisure.
The app looks for habits, which are stretches of k purchases in a row that show up many times. Your team lead asks: "List every stretch that appears at least m times, in the order each one first appears."
Write frequent_stretches(history, k, m).
history is the statement, one letter for each purchase, oldest first.k consecutive letters. Two occurrences of a stretch may overlap.m times, once each, in the order of the position where it first starts.k is longer than history.Input: history = "abbaabbabba", k = 3, m = 2
Output: ["abb", "bba"]The history has 9 stretches of 3 letters. Count each stretch, remember where it first starts, and keep those with at least 2 occurrences.
| Stretch | First start | Occurrences | At least 2? |
|---|---|---|---|
| abb | 0 | 3 | yes |
| bba | 1 | 3 | yes |
| baa | 2 | 1 | no |
| aab | 3 | 1 | no |
| bab | 6 | 1 | no |
Input: history = "abcd", k = 6, m = 1
Output: []The history has 4 letters, so the only stretch of 6 does not fit, and the answer is empty.
Input: history = "aaaa", k = 2, m = 3
Output: ["aa"]Overlaps count: in aaaa the stretch aa starts at 0, 1 and 2, which is 3 occurrences.
1 ≤ len(history) ≤ 200,0001 ≤ k ≤ 121 ≤ m ≤ 100,000history uses only the letters a, b, c and d.Counting each stretch by comparing it with every start position costs about n × n × k steps, which is 4e+11 for 200,000 letters. Four letters need 2 bits each, so a stretch of at most 12 letters fits in 24 bits. A code updated in one step per letter lets one pass count all stretches, in about 400,000 steps.