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: -1
💡 Note: No substring can be self-contained because characters 'a', 'b', 'c' each appear in both halves of the string, violating the self-contained requirement

Constraints

  • 1 ≤ s.length ≤ 103
  • s consists of lowercase English letters

Visualization

Tap to expand
Find Longest Self-Contained Substring INPUT String s = "abcdef" a 0 b 1 c 2 d 3 e 4 f 5 Self-contained means: Every char in substring must NOT appear outside it Valid Substrings: "abcde" (len=5) OK "bcdef" (len=5) OK Invalid: "abcdef" (t == s) ALGORITHM STEPS 1 Track First/Last Positions Record first and last index of each character in s 2 Sliding Window Start Expand window from left, track chars in window 3 Validate Self-Contained Check if all chars' first and last pos are in window 4 Update Max Length If valid and t != s, update longest found Window Example: a b c d e f "abcde" is self-contained (f outside) FINAL RESULT Longest Self-Contained: a b c d e "abcde" or "bcdef" Output: 5 Verification: "abcde" length = 5 'f' not in "abcde" - OK "abcde" != "abcdef" - OK Valid Self-Contained! Key Insight: The optimized sliding window approach tracks first and last occurrence of each character. A substring is self-contained if ALL characters within it have BOTH their first AND last occurrences inside the window. This enables O(n) time complexity with O(1) space for fixed alphabet. TutorialsPoint - Find Longest Self-Contained Substring | Optimized Sliding Window Approach
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