Maximum Length Substring With Two Occurrences
Real-world version: Longest Twice-Only StretchThe statement here is our own: the same inputs, outputs and technique.
A vibration monitor writes one lowercase symbol per tick, and the whole shift arrives as the string log. Analysts study the shift by framing a stretch of consecutive ticks: a frame is picked by choosing a first tick and a last tick, and it keeps every tick between them with nothing skipped.
A frame is readable when no symbol inside it is written more than twice. A symbol that never appears in the frame is fine, one that appears once is fine, one that appears twice is fine, and a third appearance of the same symbol spoils the frame no matter how the ticks are spaced.
Work out the largest number of ticks a readable frame can span. A frame holding a single tick is always readable, so at least one frame always qualifies.
Examples
Example 1
- Input
- log = "mnmmnq"
- Output
- 5
The whole shift writes `m` three times, so it is not readable. Dropping the opening tick leaves `nmmnq`, where `n` appears twice, `m` twice and `q` once, spanning five ticks.
Example 2
- Input
- log = "zzz"
- Output
- 2
Any frame reaching all three ticks writes `z` a third time, so the best readable frame keeps two neighbouring ticks.
Example 3
- Input
- log = "cluster"
- Output
- 7
No symbol repeats anywhere in the shift, so the frame covering every tick is already readable.
Constraints
- 2 <= log.length <= 100
- `log` consists of lowercase English letters only.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def longest_twice_only_stretch(log: str) -> int:public int longestTwiceOnlyStretch(String log)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 17 test cases: 17 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Substrings of Size Three with Distinct CharactersReal-world version: Three Clean Pigment WindowsEasy
- Longest Nice SubstringReal-world version: Longest Matched-Case RunEasy
- Longest Substring Without Repeating CharactersReal-world version: Largest Clean Tap BlockMedium
- Longest Repeating Character ReplacementReal-world version: Longest Repainted StretchMedium