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 of s (outside of t)

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
Find Longest Self-Contained SubstringInput: "abcdef"abcdefgSelf-contained substring "bcdef" (length 5)Characters b,c,d,e,f only appear within this substring✗ Cannot include entire string✓ Characters isolated within boundsOutput: 5Length of longest self-contained substring
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
Asked in
Google 25 Microsoft 18
24.5K Views
Medium Frequency
~25 min Avg. Time
680 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen