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