arcbjorn

thoughtbook

Friday, December 23, 2022

First unique character in a string

Leetcode 387 problem.

A function to find the first non-repeating character in it and return its index. If it does not exist, it returns -1.

Go

  • Time complexity: O(n2)O(n^{2}) - n is a length of a string
  • Auxiliary space: O(1)O(1) - constant amount of space
func firstUniqChar(s string) int {
    for index, rune := range s {
        frequency := strings.Count(s, string(rune))

        if (frequency == 1) {
            return index
        }
    }

    return -1
}
Creative Commons Licence