All problems
0170EasyHash TableStringSliding Window

Longest Twice-Only Stretch

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3090Maximum Length Substring With Two Occurrences

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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