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

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 −


 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
            chars[s[i]] += 1
      return -1
ob = Solution()