Leetcode•Nov 25, 2026

Swap For Longest Repeated Character Substring

Hazrat Ali

Leetcode

You are given a string text. You can swap two of the characters in the text.

Return the length of the longest substring with repeated characters.

 

Example 1:

Input: text = "ababa"
Output: 3
Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3.

Example 2:

Input: text = "aaabaaa"
Output: 6
Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6.

Example 3:

Input: text = "aaaaa"
Output: 5
Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.
Solution
var maxRepOpt1 = function(text) {
    let freq = {};


    for (let ch of text) {
        freq[ch] = (freq[ch] || 0) + 1;
    }

    let n = text.length;
    let result = 0;

    let i = 0;

    while (i < n) {
        let j = i;


        while (j < n && text[j] === text[i]) {
            j++;
        }

        let left = j - i;
        result = Math.max(result, Math.min(left + 1, freq[text[i]]));

        let k = j + 1;

        if (k < n && text[k] === text[i]) {
            while (k < n && text[k] === text[i]) {
                k++;
            }

            let right = k - j - 1;

            result = Math.max(
                result,
                Math.min(left + right + 1, freq[text[i]])
            );
        }

        i = j;
    }

    return result;
};
 

Comments