loading...

First Unique Character in a String

chakrihacker profile image Subramanya Chakravarthy ・1 min read

For a given string, what's the best way to figure out first unique character in a string

  1. Create a object or map that holds the count of characters in a string
  2. Loop through the string and update the charObj
  3. Loop through the string again and check charObj and return the index when a character count is 1
  4. If there is no unique character at the end return -1

here's the code

let charMap = new Map()

for(let i = 0; i < s.length; i++) {
    if(charMap.has(s[i])) {
        charMap.set(s[i], charMap.get(s[i]) + 1)
    } else {
        charMap.set(s[i], 1)
    }
}

for(let i = 0; i < s.length; i++) {
    if(charMap.get(s[i]) == 1) {
        return i
    }
}

return -1

Thanks for reading 😍

Discussion

markdown guide