Find Longest Self-Contained Substring Problem
#3104
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3104.
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 and for every character in t, it doesn't exist in the rest of s.
Return the length of the longest self-contained substring of s if it exists, otherwise, return -1.
Example 1:
Input: s = "abba"
Output: 2
Explanation:
Let's check the substring "bb". You can see that no other "b" is outside of this substring. Hence the answer is 2.
Example 2:
Input: s = "abab"
Output: -1
Explanation:
Every substring we choose does not satisfy the described property (there is some character which is inside and outside of that substring). So the answer would be -1.
Example 3:
Input: s = "abacd"
Output: 4
Explanation:
Let's check the substring "abac". There is only one character outside of this substring and that is "d". There is no "d" inside the chosen substring, so it satisfies the condition and the answer is 4.
Constraints:
2 <= s.length <= 5 * 10^4sconsists only of lowercase English letters.
Solution
Approach: Enumerate the Start Character
Record the first and last position of each letter. A self-contained substring must start at the first occurrence of some letter c, so try each letter as the start i. Walk j to the right while keeping mx, the furthest last-occurrence of any letter seen so far:
- If a letter at
jfirst appears beforei, the substring cannot start ati: stop. - Otherwise update
mx. Whenmx == j, the window[i, j]contains every occurrence of its letters; if it is not the whole string, it is a candidate for the answer.
Return the best length, or -1.
Complexity: O(26 n) time and O(26) space.
class Solution:
def maxSubstringLength(self, s: str) -> int:
first, last = {}, {}
for i, c in enumerate(s):
if c not in first:
first[c] = i
last[c] = i
ans, n = -1, len(s)
for c, i in first.items():
mx = last[c]
for j in range(i, n):
a, b = first[s[j]], last[s[j]]
if a < i:
break
mx = max(mx, b)
if mx == j and j - i + 1 < n:
ans = max(ans, j - i + 1)
return ans