Find Duplicate Characters in a Python String (2 ways)
A common interview question. Learn to find duplicate characters in a string (2 ways).

If you prefer videos over text, check out the video below.
Problem
Given a string with a length greater than 0, write a function find_duplicates()
to find all the duplicate characters in a string.
Example -
find_duplicates('Hello') - ['l']
find_duplicates('Hippopotamus') - ['p', 'o']
find_duplicates('Python') - [] (An empty list)
We are going to discuss 2 ways of solving this question.
Method 1
The first way is a very generic python code that loops over all the elements in the string and stores the number of times each element occurs. It’s simple but effective.
# Method 1
def find_duplicates(s):
elements = {}
for char in s:
if elements.get(char,None) != None:
elements[char]+=1
else:
elements[char] = 1
return [k for k,v in elements.items() if v>1]
print(find_duplicates("Hello"))
>>> ['l']
print(find_duplicates("Hippopotamus"))
>>> ['p', 'o']
print(find_duplicates("Python"))
>>> []
Method 2
The second way is by using the collections
library. Specifically, the Counter
method. This method reduces the above code to merely a few lines.
Watch how !!
# Method 2
from collections import Counter
def find_duplicates(s):
elements = Counter(s)
return [k for k,v in elements.items() if v>1]
print(find_duplicates("Hello"))
>>> ['l']
print(find_duplicates("Hippopotamus"))
>>> ['p', 'o']
print(find_duplicates("Python"))
>>> []
With just 2 lines of code, we were easily able to achieve our objective.
Let me know if you have a better way of doing this, through Twitter.