Find Longest Self-Contained Substring - Problem
Given a string s, your task is to find the length of the longest self-contained substring of s.
A substring t of a string s is called self-contained if:
t != s(the substring is not the entire string)- For every character in
t, it doesn't exist in the rest ofs(outside oft)
Return the length of the longest self-contained substring of s if it exists, otherwise return -1.
Input & Output
Example 1 — Basic Self-Contained
$
Input:
s = "abcdef"
›
Output:
5
💡 Note:
The substring "abcde" (length 5) is self-contained because none of its characters (a,b,c,d,e) appear in the remaining part "f"
Example 2 — No Self-Contained
$
Input:
s = "aaa"
›
Output:
-1
💡 Note:
No substring can be self-contained because character 'a' appears throughout the entire string
Example 3 — Multiple Options
$
Input:
s = "abcabc"
›
Output:
3
💡 Note:
Multiple substrings like "abc" (first occurrence) are self-contained, but none longer than 3 characters can avoid character overlap
Constraints
- 1 ≤ s.length ≤ 103
- s consists of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input String
Given string with various characters
2
Check Substrings
Find substrings where characters are isolated
3
Return Length
Length of longest valid substring or -1
Key Takeaway
🎯 Key Insight: A substring is self-contained when its characters don't appear anywhere else in the original string
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code