
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Index of First Recurring Character in a 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
Advertisements