#include <stdio.h>
/*
* Finds the last repeated character in a string.
*
* Examples:
* "abca" -> 'a'
* "abcbd" -> 'b'
* "abcde" -> '\0' (no repeated character)
* "abcdxypcbop" -> 'p'
*
* Time Complexity: O(n)
* Space Complexity: O(1)
*
* Returns:
* The last repeated character, or '\0' if no character repeats.
*/
char findLastRepeatedCharacter(const char *str)
{
if (str == NULL) {
return '\0';
}
int frequency[256] = {0};
/* First pass: count occurrences of each character. */
const char *p = str;
while (*p) {
frequency[(unsigned char)*p]++;
p++;
}
/* Second pass: scan from right to left. */
p--; /* Move back from '\0' to the last character. */
while (p >= str) {
if (frequency[(unsigned char)*p] > 1) {
return *p;
}
p--;
}
return '\0';
}
int main(void)
{
printf("%c\n", findLastRepeatedCharacter("abca"));
printf("%c\n", findLastRepeatedCharacter("abcbd"));
char result = findLastRepeatedCharacter("abcde");
printf("%c\n", result ? result : ' ');
printf("%c\n", findLastRepeatedCharacter("abcdxypcbop"));
printf("%c\n", findLastRepeatedCharacter("abcdxypcbadom"));
return 0;
}
/*
run:
a
b
p
d
*/