How to find the first repeated character in a string with TypeScript

2 Answers

0 votes
/**
 * Finds the first repeated character in a string.
 *
 * Examples:
 *   "abca"         -> "a"
 *   "abcbd"        -> "b"
 *   "abcde"        -> null
 *   "abcdxypcbop"  -> "c"
 *
 * Time Complexity: O(n)
 * Space Complexity: O(n)
 *
 * @param input The input string.
 * @returns The first repeated character, or null if none exists.
 */
function findFirstRepeatedCharacter(input: string): string | null {
    const seen: Set<string> = new Set<string>();

    for (const ch of input) {
        // If the character has already been seen,
        // it is the first repeated character.
        if (seen.has(ch)) {
            return ch;
        }

        seen.add(ch);
    }

    // No repeated character found.
    return null;
}

// Test cases
console.log(findFirstRepeatedCharacter("abca"));       
console.log(findFirstRepeatedCharacter("abcbd"));       
console.log(findFirstRepeatedCharacter("abcde"));       
console.log(findFirstRepeatedCharacter("abcdxypcbop"));  


/*
run:

a
b
null
c

*/

 



answered Sep 5, 2022 by avibootz
edited 6 days ago by avibootz
0 votes
function findFirstRepeatedCharacter(input: string): string | null {
    const seen: Set<string> = new Set<string>();

    for (const ch of input) {
        const character: string = ch;

        if (seen.has(character)) {
            return character;
        }

        seen.add(character);
    }

    return null;
}

// Test cases
console.log(findFirstRepeatedCharacter("abca"));       
console.log(findFirstRepeatedCharacter("abcbd"));       
console.log(findFirstRepeatedCharacter("abcde"));       
console.log(findFirstRepeatedCharacter("abcdxypcbop"));  


/*
run:

a
b
null
c

*/

 



answered 6 days ago by avibootz
...