I recently went through this problem on Codewars. The problem asks you to write a function that takes in a string and returns the first character that is not repeated anywhere in the string. The first example given is the string ‘stress’, the expected output is “t” as it only occurs once in the string, and it also occurs before “r” and “e”; as they are also unique in the string. The problem also tests strings that have varying letter cases. The computer sees “s” and “S” as not equal, but the problem asks that you treat them as the same character. The last piece to this problem is that if the string does not contain any non-repeating characters; you are to return an empty string “” or none.
I will show my first attempt at this while using a frequency hash. My thought was to count the number of times each character appeared by creating a hash map. Once I have the hash map set I would go through it and find the first character that had a value of 1; if nothing met this condition, I would return an empty string “” at the end of my function. See below for the original attempt, followed by an explanation of the code.
Looking at this shows how much work is being done to search for this one character if it exists. A loop to create the hash map, and a loop to find the first key in the hash that has a value of 1. I revisited this question with Johnny Noriega; a friend I made in a coding boot camp. He is a very talented individual who has taught me a lot during our pair coding sessions. Together, we were able to craft a cleaner solution than my loop soup from above.
In our solution, we found that an array of the string needs to be created and all characters set to lowercase in order to pass the case constraint in the problem. According to the problem “s” and “S” are the same, but to a computer, they are not. We then ran a find function on the array in search of the first character that did not repeat. We did this by checking to see if the index of our current character was equal to the last index of the character. keep in mind all of these characters had been converted to lowercase. What we got back from our find function running on the array was set to a result variable. Our last line was a ternary that checked if our result variable contained anything; if it did, we brought back the character based on the index. If our result was empty, we returned an empty string. The biggest takeaway I learned was that I still had access to the array we were running the find function on within the find iteration. In the end, we were able to solve this with three lines of code shown below.