Given a string, find the repeated character present first in the string.
Examples:
Input : geeksforgeeks Output : g (mind that it will be g, not e.) Input : abcdabcd Output : a Input : abcd Output : -1 No character repeats
Asked in: Goldman Sachs internship
We have discussed different approaches in Find repeated character present first in a string.
How to solve this problem using one traversal of input string?
Method 1 (Traversing from Left to Right) We traverse the string from left to right. We keep track of the leftmost index of every character. If a character repeats, we compare its leftmsot index with current result and update the result if result is greater
|
|
First Repeating character is g
Time Complexity : O(n). It does only one traversal of input string.
Auxiliary Space : O(1)
Method 2 (Traversing Right to Left) We traverse the string from right to left. We keep track of the visited characters. If a character repeats, we update the result.
|
|
First Repeating character is g
Time Complexity : O(n). It does only one traversal of input string.
Auxiliary Space : O(1)
The method 2 is better than method 1 as it does fewer comparisons.
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 protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.
Leave a Reply