First Non Repeating Character Coding Challenge
For this semester I will be solving different coding problems that are commonly asked in developer interviews. I have applied for several developer internships this last month and need to get prepared on solving these problems along with being able to explain my solutions. The first problem I did this week is called first non repeating character.
The goal of this problem is to be able to write a function that takes in a string. You want to be able to return the index of the first non repeating character in the string. For example if you are give the string "aabbcddee" the first non repeating character would be the letter c. In this case you would return the index number 4. If you were given the string "aabbccddee" you would return -1. This is because part of the problem is if there is not a non repeating character is a string then we just return -1.
The way I go about these problems is I try to break it down into smaller problems. Lets just say we have the string "aabbcddee". The first thing you want to do is go through every single character one at a time in your string to check if it is repeating. You also want to keep track of the index since it is what we will be returning if it is non repeating. To do this we will use a for loop using enumerate through the string that way we have access to both the index and the character. Once we have access to every character in the string we will call the count method. When using the count method on the string you pass a character as an argument and it returns how many times that character appears in the string. Since we only care about the first non repeating character we will create a condition. If the string.count(character) == 1 then we will just simply return the index of that location and the function will be finishing. If it is not then we will run through the entire string until we exit. If we exit the string without returning any value then we know that there was not a non repeating character in the string. In this case we would just return -1 which is outside of our for loop and will only be executed if there was no non repeating character in the string.
Sergio,
ReplyDeleteNice work this week. It does seem like a bit light on the workload for a 9 hour week, but I'll let it go this time as we get back into the swing of things. I'm excited to watch your progress this semester! Best of luck on your internships, too!