Sitemap

First Unique Character in a String, JavaScript, LeetCode

2 min readOct 20, 2021

--

This article will go over the First Unique Character in a String question in LeetCode’s Top Interview Questions (Easy Collection).

Press enter or click to view image in full size

Here is the problem as on LeetCode:

Press enter or click to view image in full size

As the problem title clearly describes, the output of the function should be the index of the first character in the string that does not repeat anywhere else in the string, and if there are no characters that are unique, return -1.

Get K. Johnson’s stories in your inbox

Join Medium for free to get updates from this writer.

I decided to use a counter object that used the character as the key and the amount of times it is seen in the string as the value. This way, if a character is repeated anywhere in the string, the object will be updated as we loop through. I then returned the index of the first value to have 1 occurrence and -1 if there were no characters that had 1 occurrence.

Another way I wanted to try out was to turn the string into an array with .split() then use .splice() to take out the character temporarily and check if there was another one in the array. If not, then it was a unique character and returned its index. If no unique characters were found, returned -1. The runtime on this solution was much longer than the previous but used slightly less code.

--

--