/**
* 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 input The input string.
* @return The first repeated character, or null if none exists.
*/
fun findFirstRepeatedCharacter(input: String): Char? {
val seen: MutableSet<Char> = mutableSetOf()
for (ch in input) {
// add() returns false if the character
// is already present in the set.
if (!seen.add(ch)) {
return ch
}
}
// No repeated character found.
return null
}
fun main() {
val testCases = listOf(
"abca",
"abcbd",
"abcde",
"abcdxypcbop"
)
for (input in testCases) {
val result = findFirstRepeatedCharacter(input)
println(result ?: "No repeated character")
}
}
/*
run:
a
b
No repeated character
c
*/