0
0
KotlinProgramBeginner · 2 min read

Kotlin Program to Remove Duplicates from String

You can remove duplicates from a string in Kotlin by using toSet() to get unique characters and then joinToString("") to combine them back into a string, like val result = input.toSet().joinToString("").
📋

Examples

Inputhello
Outputhelo
Inputkotlin
Outputkotlin
Inputaaaaa
Outputa
🧠

How to Think About It

To remove duplicates from a string, think about keeping only the first occurrence of each character and ignoring the rest. You can collect characters as you see them and skip any that you already added. This way, you preserve the order and remove repeats.
📐

Algorithm

1
Get the input string.
2
Create an empty set to track characters seen.
3
Create an empty result string builder.
4
For each character in the input string:
5
Check if the character is not in the set.
6
If not, add it to the set and append it to the result.
7
Return the result string.
💻

Code

kotlin
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))
}
Output
helo
🔍

Dry Run

Let's trace the input "hello" through the code to see how duplicates are removed.

1

Initialize

seen = {}, result = ""

2

Process 'h'

'h' not in seen, add 'h' to seen and result seen = {'h'}, result = "h"

3

Process 'e'

'e' not in seen, add 'e' to seen and result seen = {'h', 'e'}, result = "he"

4

Process 'l'

'l' not in seen, add 'l' to seen and result seen = {'h', 'e', 'l'}, result = "hel"

5

Process second 'l'

'l' already in seen, skip seen = {'h', 'e', 'l'}, result = "hel"

6

Process 'o'

'o' not in seen, add 'o' to seen and result seen = {'h', 'e', 'l', 'o'}, result = "helo"

7

Return result

Return "helo"

CharacterSeen SetResult 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

Using toSet and joinToString
kotlin
fun removeDuplicates(input: String): String = input.toSet().joinToString("")

fun main() {
    println(removeDuplicates("hello"))
}
This is shorter but does not preserve the original order of characters.
Using filterIndexed and indexOf
kotlin
fun removeDuplicates(input: String): String = input.filterIndexed { index, c -> input.indexOf(c) == index }

fun main() {
    println(removeDuplicates("hello"))
}
This preserves order but is less efficient because it searches the string repeatedly.

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.

ApproachTimeSpaceBest For
Set with loopO(n)O(n)Preserving order, efficient
toSet() + joinToStringO(n)O(n)Short code, order not preserved
filterIndexed + indexOfO(n²)O(n)Preserving order, simple code but slower
💡
Use a set to track seen characters and a StringBuilder to build the result efficiently.
⚠️
Trying to remove duplicates by replacing characters without preserving order or using inefficient repeated searches.