/**
* Finds the last repeated character in a string.
*
* Examples:
* "abca" -> "a"
* "abcbd" -> "b"
* "abcde" -> null
* "abcdxypcbop" -> "p"
* "abcdxypcbadom" -> "d"
*
* Time Complexity: O(n)
* Space Complexity: O(k)
*
* @param string $input Input string.
* @return ?string The last repeated character, or null if none exists.
*/
function findLastRepeatedCharacter(string $input): ?string
{
// Count occurrences of each character.
$frequency = [];
$length = strlen($input);
for ($i = 0; $i < $length; $i++) {
$ch = $input[$i];
$frequency[$ch] = ($frequency[$ch] ?? 0) + 1;
}
// Traverse from right to left.
for ($i = $length - 1; $i >= 0; $i--) {
$ch = $input[$i];
if ($frequency[$ch] > 1) {
return $ch;
}
}
// No repeated character found.
return null;
}
// Test cases
echo findLastRepeatedCharacter("abca"), PHP_EOL;
echo findLastRepeatedCharacter("abcbd"), PHP_EOL;
$result = findLastRepeatedCharacter("abcde");
echo ($result ?? ' '), PHP_EOL;
echo findLastRepeatedCharacter("abcdxypcbop"), PHP_EOL;
echo findLastRepeatedCharacter("abcdxypcbadom"), PHP_EOL;
/*
run:
a
b
p
d
*/