/**
* 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.
* @return ?string The first repeated character, or null if none exists.
*/
function findFirstRepeatedCharacter(string $input): ?string
{
$seen = [];
$length = strlen($input);
for ($i = 0; $i < $length; $i++) {
$ch = $input[$i];
// If we've seen this character before,
// it is the first repeated character.
if (isset($seen[$ch])) {
return $ch;
}
$seen[$ch] = true;
}
// No repeated character found.
return null;
}
$testCases = [
"abca",
"abcbd",
"abcde",
"abcdxypcbop"
];
foreach ($testCases as $input) {
$result = findFirstRepeatedCharacter($input);
echo ($result ?? "No repeated character") . PHP_EOL;
}
/*
run:
a
b
No repeated character
c
*/