Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Unique Characters in String

My function should return a boolean indicating whether the input String contains all unique characters.

e.g. "abc" returns true, "abca" returns false

fun uniqueCharacters(s: String): Boolean = s.groupBy { it }
    .values
    .stream()
    .allMatch { it.size == 1 }

Is there a more efficient way of solving this problem? If I was solving this in non-functional way I would store all the characters in a Map with the value being the count of that character so far, if it is greater than one then break and return false.

Not sure how best to translate this into a functional Kotlin piece of code.

like image 963
h1h1 Avatar asked Jan 26 '26 23:01

h1h1


1 Answers

You can use all function and Set::add as predicate for it

fun main() {
    println("abc".allUnique()) // true
    println("abca".allUnique()) // false
}

fun String.allUnique(): Boolean = all(hashSetOf<Char>()::add)

It's lazy, the function returns the result when it finds the first duplicate

like image 77
IR42 Avatar answered Jan 29 '26 01:01

IR42