Find Longest Self-Contained Substring - Problem
Imagine you have a string and need to find the longest self-contained substring within it. A substring is considered self-contained if:
- It's not the entire original string
- Every character in this substring exists only within this substring and nowhere else in the original string
For example, in the string "abcdefabc", the substring "def" is self-contained because 'd', 'e', and 'f' don't appear anywhere else in the string.
Goal: Find the length of the longest such self-contained substring. If no self-contained substring exists, return -1.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "abcdefabc"
โบ
Output:
3
๐ก Note:
The substring "def" (positions 3-5) is self-contained because characters 'd', 'e', and 'f' appear only in this substring and nowhere else in the string. Length = 3.
example_2.py โ No Self-Contained Substring
$
Input:
s = "aabbcc"
โบ
Output:
-1
๐ก Note:
No self-contained substring exists. Every possible substring contains characters that also appear elsewhere in the string.
example_3.py โ Multiple Valid Substrings
$
Input:
s = "abcxyzabc"
โบ
Output:
3
๐ก Note:
The substring "xyz" (positions 3-5) is self-contained with length 3. Characters 'x', 'y', 'z' don't appear anywhere else in the string.
Constraints
- 1 โค s.length โค 104
- s consists of lowercase English letters only
- A self-contained substring cannot be the entire original string
- Return -1 if no valid self-contained substring exists
Visualization
Tap to expand
Understanding the Visualization
1
City Census
Count where each 'resident' (character) lives in the entire 'city' (string)
2
Neighborhood Check
For each potential 'neighborhood' (substring), verify if it's truly exclusive
3
Find Largest
Identify the biggest exclusive neighborhood that meets our criteria
Key Takeaway
๐ฏ Key Insight: A substring is self-contained when its character frequencies exactly match the global frequencies for those characters - like finding a neighborhood where all residents are exclusive to that area!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code