LeetCode 3090: Maximum Length Substring With Two Occurrences Solution
Master LeetCode problem 3090 (Maximum Length Substring With Two Occurrences), a easy 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.
3090. Maximum Length Substring With Two Occurrences
Problem Explanation
Explanation
To solve this problem, we can use a sliding window approach. We will maintain a hashmap to keep track of the frequency of characters in the current window. We will also keep track of the start and end indices of the window. As we iterate through the string, we will expand the window until we have at most two occurrences of each character. If we encounter a character that violates this condition, we will shrink the window from the left side until the condition is satisfied again. At each step, we will update the maximum length of the valid substring.
Time complexity: O(n) where n is the length of the input string s. Space complexity: O(1) since the hashmap will have at most 26 entries for lowercase English letters.
Solution Code
class Solution {
public int maxLengthTwoOccurrences(String s) {
int[] freq = new int[26];
int start = 0, end = 0;
int maxLen = 0;
while (end < s.length()) {
freq[s.charAt(end) - 'a']++;
while (countOccurences(freq) > 2) {
freq[s.charAt(start) - 'a']--;
start++;
}
maxLen = Math.max(maxLen, end - start + 1);
end++;
}
return maxLen;
}
private int countOccurences(int[] freq) {
int count = 0;
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
count++;
}
}
return count;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3090 (Maximum Length Substring With Two Occurrences)?
This page provides optimized solutions for LeetCode problem 3090 (Maximum Length Substring With Two Occurrences) 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 3090 (Maximum Length Substring With Two Occurrences)?
The time complexity for LeetCode 3090 (Maximum Length Substring With Two Occurrences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3090 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3090 in Java, C++, or Python.