First Unique Character
1 min read

First Unique Character

Given a string, return the index of its first unique character. If a unique character does not exist, return -1.

Ex: Given the following strings...

"abcabd", return 2
"thedailybyte", return 1
"developer", return 0
    fun firstUniqChar(s: String): Int {
        val countMap = hashMapOf<Char,Int>()
        
        for(i in s.indices) {
            countMap[s[i]] = countMap.getOrDefault(s[i],0) + 1
        }
        for(i in s.indices) {
            if(countMap[s[i]] == 1){
                return i
            }
        }
        
        return -1
    }

The idea here is to iterate through the string and add the character count to hashmap based on the number of times a character appears in the string.

Enjoying these posts? Subscribe for more