How to find the first repeated character in a string with Node.js

1 Answer

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 {string} input - The input string.
 * @returns {string|null} The first repeated character, or null if none exists.
 */
function findFirstRepeatedCharacter(input) {
    if (typeof input !== 'string' || input.length === 0) {
        return null;
    }

    const seen = new Set();

    for (const ch of input) {
        // Set.has() checks whether we've already seen this 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
...