/**
* 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
*/