Given an input string, find the first repeated character in the String. Basically, we need to find a character that occurs more than once and whose index of second occurrence is the smallest.
Input: ch = "atechdaily"
a is the first element that repeats
Input: str = "hello world"
l is the first element that repeats
There is one simple solution to find first repeating character in String where we use 2 nested loops. Algorithm starts by traversing characters from left to right, for each character, check if it repeats or not, if the character repeats, just print the repeated character. Although this algorithm looks simpler, its time Complexity is O(n2)
So, we are going to use "Hashing" to find first Repeating Character in String.
In above algorithm, we have first created an empty HashSet. Then we are traversing the String from 0 to length of string. Then for each character in string, we check if the character is present in HashSet or not. If its not present, we simply add the character as an element in HashSet. But if the character is present, then we simply print the character as it's a repeated character.
Time Complexity for Above Algorithm is O(N).