Chat app~25 min2s · 256 MBtarget O(26 n) time, O(26) counts and O(26) stack spaceclassic twin: lc-395divide-and-conquer
A chat app tags every message with one lowercase letter, such as a for a photo and b for a link. The tags of a conversation make a string.
A steady stretch is a run of neighbouring messages in which every tag that appears, appears at least k times. You need the length of the longest steady stretch.
Your team lead says: A tag that is too rare in a range can never be part of an answer inside it. Split the range at that tag.
Write longest_stretch(tags, k).
tags.k times.Input: tags = "aabbbcdd", k = 2
Output: 5Each call counts the letters of its range. It splits at every letter that appears fewer than 2 times, or returns the length of the range when none does.
| Call on | Tags that appear fewer than 2 times | Action |
|---|---|---|
aabbbcdd |
c | split at c |
aabbb |
none | the whole range works: length 5 |
dd |
none | the whole range works: length 2 |
The longest steady stretch is aabbb, of length 5.
Input: tags = "abcd", k = 2
Output: 0Every letter appears once, so every call splits at every letter, and no piece remains.
Input: tags = "aaabb", k = 3
Output: 3The letter b appears twice, which is below 3, so the string splits at both. The piece aaa is steady.
1 ≤ tags.length ≤ 100,000tags has only lowercase letters a to z1 ≤ k ≤ 100,000A string of 100,000 characters has 5,000,050,000 stretches. Checking each one with its counts is far too slow. A split at the rare letters removes at least one of the 26 letters at each level, so the recursion is at most 26 levels deep.