Show problems as
Classic problem #3104HardHash TableStringSorting

Find Longest Self-Contained Substring

Real-world version: The Longest Sealed Stretch of the Ribbon
Tracked in this browser only
Read Find Longest Self-Contained Substring on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

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

Python
def max_substring_length(ribbon: str) -> int:
Java
public int maxSubstringLength(String ribbon)