# Program to find the index of first Recurring Character in the given string in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a string s, we have to find the index of the first recurring character in it. If we cannot find no recurring characters, then return -1.

So, if the input is like "abcade", then the output will be 3, as 'a' is again present at index 3.

To solve this, we will follow these steps −

• define a map chars
• for i in range 0 to size of s, do
• if s[i] in chars, then
• return i
• otherwise,
• chars[s[i]] := chars[s[i]] + 1
• return -1

Let us see the following implementation to get better understanding −

## Example

Live Demo

from collections import defaultdict
class Solution:
def solve(self, s):
chars = defaultdict(int)
for i in range(len(s)):
if s[i] in chars:
return i
else:
chars[s[i]] += 1
return -1
ob = Solution()
print(ob.solve("abcade"))

## Input

"abcade"

## Output

3