• + 0 comments

    Here is an approch for typescript using regex. A bit longer due to comments and variable names.

    function alternate(s: string): number {
        // Write your code here
        // get unique chars in input string
        const availableChars = Array.from(new Set<string>(s.split('')));
        
        // build available pair options
        const availablePairs: [string, string][] = [];
        availableChars.forEach((firstChar) => {
            availableChars.forEach((secondChar) => {
                if (firstChar === secondChar) {
                    // same, not an option
                    return;
                }
                // add pair combonation to list of available pairs
                availablePairs.push([firstChar, secondChar]);
            });
        });
        
        // build array of lenths for each available pair
        const pairsStrLenValues: number[] = availablePairs.map(([a, b]): number => {
            // regex to find char that are not the current pair
            const findUnavailableCharsRegex = new RegExp(`[^${a}${b}]`, 'gi');
            // regex to find duplicates of char a in string
            const findDuplicateACharRegex = new RegExp(`[${a}]{2}`);
            // regex to find duplicates of char b in string
            const findDuplicateBCharRegex = new RegExp(`[${b}]{2}`);
            
            // remove all char that are not in the current pair
            // @ts-ignore (due to lib version)
            const cleanedString = s.replaceAll(findUnavailableCharsRegex, ``);
            
            // check for duplicates of char a and char b to check if cleaned string is valid
            const doesCleanStringHaveDuplicateAChar = !!findDuplicateACharRegex.exec(cleanedString);
            const doesCleanStringHaveDuplicateBChar = !!findDuplicateBCharRegex.exec(cleanedString);
            
            const isCleanedStringValid: boolean = (
                !doesCleanStringHaveDuplicateAChar
                && !doesCleanStringHaveDuplicateBChar
            );
            if (!isCleanedStringValid) {
                // cleaned string not valid so return length of zero
                return 0;
            }
            // return length of valid string
            return cleanedString.length;
            
        });
        
        return Math.max(0, ...pairsStrLenValues);
    
    }