Find the first repeated character in a string
Given a string, find the first repeated character in it. We need to find the character that occurs more than once and whose index of second occurrence is smallest. A variation of this question is discussed here.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: ch = “geeksforgeeks”
e is the first element that repeats
Input: str = “hello geeks”
l is the first element that repeats
Simple Solution: The solution is to run two nested loops. Start traversing from left side. For every character, check if it repeats or not. If the character repeats, increment count of repeating characters. When the count becomes K, return the character.
Time Complexity of this solution is O(n2)
We can Use Sorting to solve the problem in O(n Log n) time. Following are detailed steps.
- Copy the given array to an auxiliary array temp.
- Sort the temp array using a O(N log N) time sorting algorithm.
- Scan the input array from left to right. For every element, count its occurrences in temp using binary search. As soon as we find a character that occurs more than once, we return the character.
This step can be done in O(N Log N) time.
An efficient solution is to use Hashing to solve this in O(N) time on average.
- Create an empty hash.
- Scan each character of input string and insert values to each keys in the hash.
- When any character appears more than once, hash key value is increment by 1, and return the character.
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
Similar Problem: finding first non-repeated character in a string.
This article is contributed by Afzal Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.