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 −

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
Updated on: 2020-10-07T13:28:37+05:30

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements