LeetCode 3104: Find Longest Self-Contained Substring Solution
Master LeetCode problem 3104 (Find Longest Self-Contained Substring), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3104. Find Longest Self-Contained Substring
Problem Explanation
Explanation
To solve this problem, we can use a binary search approach. The idea is to get the minimum length of the substring required to contain all unique characters in the given string. We can start with a minimum length of 1 and a maximum length of the total number of unique characters in the string. Then we perform a binary search within this range to find the longest self-contained substring.
Here are the steps:
- Count the frequency of each character in the string.
- Perform a binary search between 1 and the number of unique characters in the string.
- For each mid value in the binary search, check if there exists a substring of that length containing all unique characters. If such a substring exists, update the result and continue the binary search in the upper half. Otherwise, search in the lower half.
- Continue until the lower bound is less than or equal to the upper bound.
Time complexity: O(n log n), where n is the length of the input string. Space complexity: O(n) for storing the frequency of characters.
Solution Code
class Solution {
public String findLongestSubString(String s) {
int[] count = new int[128];
int uniqueChars = 0;
for (char c : s.toCharArray()) {
if (count[c] == 0) {
uniqueChars++;
}
count[c]++;
}
int start = 0, end = 0;
int minLen = Integer.MAX_VALUE;
int minStart = 0;
while (end < s.length()) {
if (--count[s.charAt(end)] == 0) {
uniqueChars--;
}
end++;
while (uniqueChars == 0) {
if (end - start < minLen) {
minLen = end - start;
minStart = start;
}
if (++count[s.charAt(start)] > 0) {
uniqueChars++;
}
start++;
}
}
return s.substring(minStart, minStart + minLen);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3104 (Find Longest Self-Contained Substring)?
This page provides optimized solutions for LeetCode problem 3104 (Find Longest Self-Contained Substring) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3104 (Find Longest Self-Contained Substring)?
The time complexity for LeetCode 3104 (Find Longest Self-Contained Substring) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3104 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3104 in Java, C++, or Python.