First Unique Character in a String
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Approach1: HashMap
Tjis approach is very intuitive, we do a first pass of the characters of the string at hand and store their frequency in a map. We then do a second iteration over the string with the first character that we encounter with a frequency that is equal to 1 (unique), we return it's index.
Time: O(n) Space: O(k) k = distinct characters
Approach1: HashMap2
This approach is the same as the one implemented above with the exception that we're using the list as HashMap to map the characters to their frequency.
Approach1: HashMap (Java )
Approach2: Ordered Dictionary
The above approaches are good soulution however they can be improved since we're scanning the array twice. To prevent a second pass, we use a Set to validate whether or not a character has been seen before. If the Character is not in the Set, we add it to the Set as well as the Map otherwise we remove it from the map. Since our Items were being entered in order, the first item would be the first unque one.
Why the improvement ?
ex1: Take an example of DNA sequence: there could be millions of letters long with just 4 alphabet letter. What happened if the non-repeated letter is at the end of DNA sequence? We could dramatically increase our running time by scanning gthe array just once.
ex2: Let's say we have a trading platform, and we want the first non repeating orders. This due to some Buy Side Traders having made the efforts to render our algorithm less efficient by splitting large market orders into smaller sub-orders that arrive at the same time to all the exchanges. With a simple pass, we can improve the runtime of our algorithm as we would be analyzing that data stream as it comes in.
Time: O(n) Space: O(k) k = distinct characters
Approach2: Ordered Dictionary (Java Version)
Last updated
Was this helpful?