Kotlin Program to Remove Duplicates from String
toSet() to get unique characters and then joinToString("") to combine them back into a string, like val result = input.toSet().joinToString("").Examples
How to Think About It
Algorithm
Code
fun removeDuplicates(input: String): String {
val seen = mutableSetOf<Char>()
val result = StringBuilder()
for (char in input) {
if (char !in seen) {
seen.add(char)
result.append(char)
}
}
return result.toString()
}
fun main() {
val input = "hello"
println(removeDuplicates(input))
}Dry Run
Let's trace the input "hello" through the code to see how duplicates are removed.
Initialize
seen = {}, result = ""
Process 'h'
'h' not in seen, add 'h' to seen and result seen = {'h'}, result = "h"
Process 'e'
'e' not in seen, add 'e' to seen and result seen = {'h', 'e'}, result = "he"
Process 'l'
'l' not in seen, add 'l' to seen and result seen = {'h', 'e', 'l'}, result = "hel"
Process second 'l'
'l' already in seen, skip seen = {'h', 'e', 'l'}, result = "hel"
Process 'o'
'o' not in seen, add 'o' to seen and result seen = {'h', 'e', 'l', 'o'}, result = "helo"
Return result
Return "helo"
| Character | Seen Set | Result String |
|---|---|---|
| h | {h} | h |
| e | {h, e} | he |
| l | {h, e, l} | hel |
| l | {h, e, l} | hel |
| o | {h, e, l, o} | helo |
Why This Works
Step 1: Track seen characters
We use a mutableSetOf to remember which characters we already added, so we don't add duplicates.
Step 2: Build result string
We append characters to a StringBuilder only if they are not in the set, preserving order.
Step 3: Return final string
After processing all characters, we convert the StringBuilder to a string and return it.
Alternative Approaches
fun removeDuplicates(input: String): String = input.toSet().joinToString("") fun main() { println(removeDuplicates("hello")) }
fun removeDuplicates(input: String): String = input.filterIndexed { index, c -> input.indexOf(c) == index }
fun main() {
println(removeDuplicates("hello"))
}Complexity: O(n) time, O(n) space
Time Complexity
The code loops through each character once, so it runs in linear time relative to the string length.
Space Complexity
It uses extra space for the set and the result string, both proportional to the number of unique characters.
Which Approach is Fastest?
Using a set with a loop is fastest and preserves order; using toSet() alone is faster but loses order.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Set with loop | O(n) | O(n) | Preserving order, efficient |
| toSet() + joinToString | O(n) | O(n) | Short code, order not preserved |
| filterIndexed + indexOf | O(n²) | O(n) | Preserving order, simple code but slower |