
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- if s[i] in chars, then
- return -1
Let us see the following implementation to get better understanding −
Example
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
- Related Articles
- Find the index of the first unique character in a given string using C++
- Python program to change character of a string using given index
- Find the character in first string that is present at minimum index in second string in Python
- Python program to find occurrence to each character in given string
- Finding the index of the first repeating character in a string in JavaScript
- Java program to find the Frequency of a character in a given String
- Return index of first repeating character in a string - JavaScript
- How to find the first character of a string in C#?
- Return the index of first character that appears twice in a string in JavaScript
- Python Program to Remove the nth Index Character from a Non-Empty String
- C# program to replace n-th character from a given index in a string
- Java Program to Capitalize the first character of each word in a String
- How to find its first non-repeating character in a given string in android?
- Python Program to Form a New String where the First Character and the Last Character have been Exchanged
- Find the first repeated character in a string using C++.

Advertisements