3090. Maximum Length Substring With Two Occurrences LeetCode Solution
In this guide, you will get 3090. Maximum Length Substring With Two Occurrences LeetCode Solution with the best time and space complexity. The solution to Maximum Length Substring With Two Occurrences problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Maximum Length Substring With Two Occurrences solution in C++
- Maximum Length Substring With Two Occurrences solution in Java
- Maximum Length Substring With Two Occurrences solution in Python
- Additional Resources
Problem Statement of Maximum Length Substring With Two Occurrences
Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character.
Example 1:
Input: s = “bcbbbcba”
Output: 4
Explanation:
The following substring has a length of 4 and contains at most two occurrences of each character: “bcbbbcba”.
Example 2:
Input: s = “aaaa”
Output: 2
Explanation:
The following substring has a length of 2 and contains at most two occurrences of each character: “aaaa”.
Constraints:
2 <= s.length <= 100
s consists only of lowercase English letters.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(26) = O(1)
3090. Maximum Length Substring With Two Occurrences LeetCode Solution in C++
class Solution {
public:
int maximumLengthSubstring(string s) {
int ans = 0;
vector<int> count(26);
for (int l = 0, r = 0; r < s.length(); ++r) {
++count[s[r] - 'a'];
while (count[s[r] - 'a'] > 2)
--count[s[l++] - 'a'];
ans = max(ans, r - l + 1);
}
return ans;
}
};
/* code provided by PROGIEZ */
3090. Maximum Length Substring With Two Occurrences LeetCode Solution in Java
class Solution {
public int maximumLengthSubstring(String s) {
int ans = 0;
int[] count = new int[26];
for (int l = 0, r = 0; r < s.length(); ++r) {
++count[s.charAt(r) - 'a'];
while (count[s.charAt(r) - 'a'] > 2)
--count[s.charAt(l++) - 'a'];
ans = Math.max(ans, r - l + 1);
}
return ans;
}
}
// code provided by PROGIEZ
3090. Maximum Length Substring With Two Occurrences LeetCode Solution in Python
class Solution:
def maximumLengthSubstring(self, s: str) -> int:
ans = 0
count = collections.Counter()
l = 0
for r, c in enumerate(s):
count[c] += 1
while count[c] > 2:
count[s[l]] -= 1
l += 1
ans = max(ans, r - l + 1)
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.