First Unique Character in a String

Most problems like this one can be solved by using the character count map. This approach is very effective as it can give you O(n) time complexity.

class Solution {
    fun firstUniqChar(s: String): Int {
        if(s.length == 1) return 0
        
        var array = IntArray(26)
        
        for(x in 0 until s.length){
            array[s[x] - 'a'] = array[s[x] - 'a'] + 1
        }
        
        for(x in 0 until s.length){
            if(array[s[x] - 'a'] == 1) return x
        }
        
        return -1
    }
}
Runtime: 216 ms, faster than 89.52% of Kotlin online submissions for First Unique Character in a String.
Memory Usage: 35.9 MB, less than 100.00% of Kotlin online submissions for First Unique Character in a String.

The idea is to store a character count map and then go through the characters again and if you find a single-occuring letter, then return it’s index.