Description
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 <= 100sconsists only of lowercase English letters.
Solutions
This is a sliding window solution that finds the longest substring where each letter appears at most twice, but instead of counting occurrences it remembers where they happened: arr holds, for each of the 26 lowercase letters, the last two indices at which that letter was seen (initialized to [-1, -1]). As right scans the string, the current letter's older stored index arr[pos][0] is the position of its second-to-last occurrence — if the window still included it, adding the current character would make a third copy, so left = Math.max(left, arr[pos][0] + 1) jumps the window start just past it in a single step (no inner loop needed). Then arr[pos] = [arr[pos][1], right] shifts the record so it keeps only the two most recent positions, and res = Math.max(res, right - left + 1) tracks the biggest valid window, which is returned at the end. This runs in O(n) time with constant extra space.
/**
* @param {string} s
* @return {number}
*/
var maximumLengthSubstring = function(s) {
const arr = Array.from({ length: 26 }, () => Array(2).fill(-1));
let left = 0;
let res = 0;
for (let right = 0; right < s.length; right++) {
const pos = s.charCodeAt(right) - 97;
left = Math.max(left, arr[pos][0] + 1);
arr[pos] = [arr[pos][1], right];
res = Math.max(res, right - left + 1);
}
return res;
};