For a given string, what's the best way to figure out first unique character in a string
- Create a object or map that holds the count of characters in a string
- Loop through the string and update the charObj
- Loop through the string again and check charObj and return the index when a character count is 1
- 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 😍
Top comments (0)