All problems
1185HardHash TableStringSorting

The Longest Sealed Stretch of the Ribbon

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3104Find Longest Self-Contained Substring

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 ribbon ribbon holds lowercase letters. A stretch of neighbouring letters is sealed when it is not the whole ribbon and no letter appearing inside it appears anywhere outside it.

Return the length of the longest sealed stretch, or -1 when the ribbon has none.

Examples

Example 1

Input
ribbon = "baab"
Output
2

The two middle letters are the only a on the ribbon, so that stretch is sealed. Reaching any further pulls in a b that also stands outside.

Example 2

Input
ribbon = "abbcca"
Output
4

The four middle letters hold only b and c, and neither appears outside them, so a stretch of four is sealed.

Example 3

Input
ribbon = "aa"
Output
-1

The only stretch holding every a is the whole ribbon, which does not count.

Constraints

  • 2 <= ribbon.length <= 5 * 10^4
  • ribbon holds only lowercase English letters

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 max_substring_length(ribbon: str) -> int:
Java
public int maxSubstringLength(String ribbon)
September 7
Apply