DevPath

← All problems

First Unique Character

Easy strings · hashing

Description

Return the index of the first character that does not repeat, or -1 if every character repeats.

Constraints

0 <= length <= 100000

Examples

Input: s = "loveleetcode"

Output: 2

Hints (1)
  • Count each character, then scan for the first count of one.

Solutions

Count then scan. · Time O(n) · Space O(1)

func firstUniqChar(s string) int {
    count := map[byte]int{}
    for i := 0; i < len(s); i++ {
        count[s[i]]++
    }
    for i := 0; i < len(s); i++ {
        if count[s[i]] == 1 {
            return i
        }
    }
    return -1
}

Create a free account to submit solutions, track progress and save problems.

Create account