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.
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 firstname.lastname@example.org. 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.
- Find repeated character present first in a string
- Efficiently find first repeated character in a string without using any additional data structure in one traversal
- Count occurrences of a character in a repeated string
- Find a string such that every character is lexicographically greater than its immediate next character
- Find the first repeated word in a string
- Find the character in first string that is present at minimum index in second string
- Queries to find the first non-repeating character in the sub-string of a string
- Queries to find the last non-repeating character in the sub-string of a given string
- Repeated Character Whose First Appearance is Leftmost
- Find last index of a character in a string
- Find k-th character of decrypted string | Set - 2
- Find one extra character in a string
- Find k'th character of decrypted string | Set 1
- Given a string, find its first non-repeating character
- Find the last non repeating character in string