LeetCode Challenge: First Unique Character in a String
This week’s coding challenge is the First Unique Character in a String challenge on LeetCode. This challenge’s instructions are relatively straightforward, you want tofind the first character in a given string and return the index of the character in the string that is completely unique, or doesn’t repeat later in the string. If none of the characters in the string are unique, then the function should return -1. For example, if you were given the string “leetcode”, the function should return 0, since the character with at the index of 0, “l”, doesn’t appear again in the string. Alternatively, for the string “adam”, the function should return 1. The letter at index 0 is “a”, which appears again at index 2, but the letter at index 1 is “d”, which is unique.
I know I’m going to likely need to have to create an object and populate it with key-value pairs from the characters in the given string. The value of each character key will be the number of times it appears in the string. After this object is populated, it’ll be pretty easy to find the solution. I just need to check if any value is 1, meaning that it’s a unique character in the string.
First, I want to create the empty object variable and the structure of the loop that I’ll use to populate that empty object variable.
Then, inside the loop at line 5 in the below screenshot, I want to check if the character in the string is a key that currently exists in the object. Using the same “leetcode” example from earlier, in the first iteration of the loop it’ll check if obj[“l”] exists. Since it doesn’t at this point, it’ll have a value of 1. If obj[“l”] already existed, it would instead add one to the current value of that key.
After that loop is completed, and the object is populated, I want to loop again to check the values of each key-value pair. As I said earlier, if the value of a key being checked is 1, then the character is unique, and the loop can break and return the current value of i, which will be the index of the character that the challenge is asking for.
This function has a great Big O time notation, since running a loop is O(n), running two loops that aren’t nested would be O(n * 2), which can be simplified to O(n) since in extreme cases, the doubling up won’t mean much in terms of runtime.