Show problems as
Classic problem #3090EasyHash TableStringSliding Window

Maximum Length Substring With Two Occurrences

Real-world version: Longest Twice-Only Stretch
Tracked in this browser only
Read Maximum Length Substring With Two Occurrences on LeetCode(opens in a new tab)

The 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.

Python
def longest_twice_only_stretch(log: str) -> int:
Java
public int longestTwiceOnlyStretch(String log)