Longest string with two distinct characters in JavaScript

We need to write a JavaScript function that finds the longest substring containing at most two distinct characters. The function takes a string as input and returns the length of the longest valid substring.

For example, if the input string is 'kjeljsdl', the longest substring with at most 2 distinct characters is 'jljl' with length 4.

Understanding the Problem

A substring with at most two distinct characters means we can have:

  • Only one character repeated: "aaa"
  • Two different characters in any combination: "abab", "aabb"

Sliding Window Approach

The most efficient solution uses a sliding window technique with a character frequency map:

const str = 'kjeljsdl';

const longestSubstring = (str = '') => {
    if (str.length <= 2) {
        return str.length;
    }
    
    let left = 0;
    let maxLength = 0;
    const charCount = new Map();
    
    for (let right = 0; right < str.length; right++) {
        const rightChar = str[right];
        charCount.set(rightChar, (charCount.get(rightChar) || 0) + 1);
        
        // Shrink window if more than 2 distinct characters
        while (charCount.size > 2) {
            const leftChar = str[left];
            charCount.set(leftChar, charCount.get(leftChar) - 1);
            
            if (charCount.get(leftChar) === 0) {
                charCount.delete(leftChar);
            }
            left++;
        }
        
        maxLength = Math.max(maxLength, right - left + 1);
    }
    
    return maxLength;
};

console.log(longestSubstring(str));
console.log(longestSubstring('aabbcc'));
console.log(longestSubstring('abcdef'));
4
4
2

How It Works

The sliding window algorithm maintains:

  • Two pointers: left and right defining the current window
  • Character map: Tracks frequency of characters in current window
  • Expansion: Move right pointer to include new characters
  • Contraction: Move left pointer when window has more than 2 distinct characters

Step-by-Step Example

For string "kjeljsdl":

const str = 'kjeljsdl';
const longestSubstring = (str = '') => {
    let left = 0, maxLength = 0;
    const charCount = new Map();
    
    for (let right = 0; right < str.length; right++) {
        const char = str[right];
        charCount.set(char, (charCount.get(char) || 0) + 1);
        
        console.log(`Right: ${right}, Char: '${char}', Window: '${str.substring(left, right + 1)}'`);
        
        while (charCount.size > 2) {
            const leftChar = str[left];
            charCount.set(leftChar, charCount.get(leftChar) - 1);
            if (charCount.get(leftChar) === 0) {
                charCount.delete(leftChar);
            }
            left++;
            console.log(`  Shrunk window to: '${str.substring(left, right + 1)}'`);
        }
        
        maxLength = Math.max(maxLength, right - left + 1);
        console.log(`  Current max length: ${maxLength}`);
    }
    
    return maxLength;
};

console.log('Final result:', longestSubstring(str));
Right: 0, Char: 'k', Window: 'k'
  Current max length: 1
Right: 1, Char: 'j', Window: 'kj'
  Current max length: 2
Right: 2, Char: 'e', Window: 'kje'
  Shrunk window to: 'je'
  Current max length: 2
Right: 3, Char: 'l', Window: 'jel'
  Shrunk window to: 'el'
  Current max length: 2
Right: 4, Char: 'j', Window: 'elj'
  Shrunk window to: 'lj'
  Current max length: 2
Right: 5, Char: 's', Window: 'ljs'
  Shrunk window to: 'js'
  Current max length: 2
Right: 6, Char: 'd', Window: 'jsd'
  Shrunk window to: 'sd'
  Current max length: 2
Right: 7, Char: 'l', Window: 'sdl'
  Shrunk window to: 'dl'
  Current max length: 2
Final result: 2

Time Complexity

Time: O(n) where n is the string length. Each character is visited at most twice.

Space: O(1) since the map stores at most 3 characters at any time.

Conclusion

The sliding window approach efficiently finds the longest substring with at most two distinct characters in linear time. This technique is optimal for substring problems with constraints.

Updated on: 2026-03-15T23:19:00+05:30

439 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements