/**
* 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 input The input string.
* @returns The last repeated character, or null if none exists.
*/
function findLastRepeatedCharacter(input: string): string | null {
// Map character -> frequency
const frequencies: Map<string, number> = new Map<string, number>();
// Count character occurrences.
for (const ch of input) {
const count: number = frequencies.get(ch) ?? 0;
frequencies.set(ch, count + 1);
}
// Traverse from right to left.
for (let i: number = input.length - 1; i >= 0; i--) {
const ch: string = input[i];
if ((frequencies.get(ch) ?? 0) > 1) {
return ch;
}
}
// No repeated character found.
return null;
}
// Test cases
console.log(findLastRepeatedCharacter("abca"));
console.log(findLastRepeatedCharacter("abcbd"));
const result: string | null = findLastRepeatedCharacter("abcde");
console.log(result ?? " ");
console.log(findLastRepeatedCharacter("abcdxypcbop"));
console.log(findLastRepeatedCharacter("abcdxypcbadom"));
/*
run:
a
b
p
d
*/