Maximum Length Substring With Two Occurrences (LeetCode 3090): Solution and Explanation
Slide a window across the string and keep a count for each letter inside it. When a letter shows up a third time, move the left edge forward until it is back to two, then record the window length.
Intuition
If a substring is valid, every shorter substring inside it is valid too. That is the property that lets a sliding window work: the best window ending at right starts at the smallest valid left, and that left never moves backwards.
Adding one character can only break the rule for that one letter. So after adding s[right], the only thing to check is whether its count went above 2.
To fix it, drop characters from the left until one copy of that letter has left the window. Other letters' counts only go down while doing this, so they stay valid.
Approach: Sliding window with letter counts
- Create
countof size 26, and setleft = 0,best = 0. - For each
right, incrementcount[s[right]]. - While that count is greater than 2, decrement
count[s[left]]and incrementleft. - Set
best = max(best, right - left + 1). - Return
best.
Step-by-step example
s = "bcbbbcba"
- right = 0..2: "bcb" is fine (b twice, c once), best = 3.
- right = 3: a third b. Drop s[0] = b, left = 1. Window "cbb", length 3.
- right = 4: a third b again. Drop c and b, left = 3. Window "bb", length 2.
- right = 5: "bbc", length 3. right = 6: third b, drop s[3], left = 4, window "bcb".
- right = 7: "bcba" has length 4, new best. Answer: 4.
Code: Python, Java, C++
1class Solution:
2 def maximumLengthSubstring(self, s: str) -> int:
3 count = [0] * 26
4 left = 0
5 best = 0
6 for right, ch in enumerate(s):
7 c = ord(ch) - ord('a')
8 count[c] += 1
9 while count[c] > 2:
10 count[ord(s[left]) - ord('a')] -= 1
11 left += 1
12 best = max(best, right - left + 1)
13 return best1class Solution {
2 public int maximumLengthSubstring(String s) {
3 int[] count = new int[26];
4 int left = 0;
5 int best = 0;
6 for (int right = 0; right < s.length(); right++) {
7 int c = s.charAt(right) - 'a';
8 count[c]++;
9 while (count[c] > 2) {
10 count[s.charAt(left) - 'a']--;
11 left++;
12 }
13 best = Math.max(best, right - left + 1);
14 }
15 return best;
16 }
17}1class Solution {
2public:
3 int maximumLengthSubstring(string s) {
4 int count[26] = {0};
5 int left = 0;
6 int best = 0;
7 for (int right = 0; right < (int)s.size(); right++) {
8 int c = s[right] - 'a';
9 count[c]++;
10 while (count[c] > 2) {
11 count[s[left] - 'a']--;
12 left++;
13 }
14 best = max(best, right - left + 1);
15 }
16 return best;
17 }
18};Time and space complexity
O(n)
Each index enters the window once and leaves it at most once.
O(1)
A fixed array of 26 counters.
Other approaches
Brute force over all substrings (time O(n^2), space O(1))
For each start, extend the end while counting letters and stop at the first third copy. With n at most 100 this is fast enough, but it does not scale.
Common mistakes
- Checking every letter's count after each step. Only the letter that just entered can exceed 2.
- Using
ifinstead ofwhilewhen shrinking. The first character removed may be a different letter, so several steps can be needed. - Updating
bestbefore the window is fixed, which counts an invalid window.
Frequently asked questions
Why does only the new letter need checking?
Before adding s[right], the window was valid. Adding one character raises only that letter's count, so it is the only one that can reach 3.
How does this generalise?
Replace 2 with any limit k and the same code solves the longest subarray with at most k copies of each value, as in Length of Longest Subarray With at Most K Frequency.
What is the time and space complexity?
O(n) time, since both pointers only move forward, and O(1) space for 26 counters.