Find all duplicate characters in string in Python
In this article, we will explore various methods to find all duplicate characters in string. The simplest approach is by using a loop with dictionary.
Using Loop with Dictionary
We can use a for loop to find duplicate characters efficiently. First we count the occurrences of each character by iterating through the string and updating a dictionary. Then we loop through the dictionary to identify characters with a frequency greater than 1 and append them to the result list.
s = "GeeksforGeeks"
d = {}
res = []
# Count characters
for c in s:
d[c] = d.get(c, 0) + 1
# Find duplicate
for c, cnt in d.items():
if cnt > 1:
res.append(c)
print(res)
Output
['G', 'e', 'k', 's']
Explanation:
- Use a dictionary (d) to store the frequency of each character.
- Check if the count of any character is greater than 1 (duplicates) then add into res list
Note: This method is better for most cases due to its efficiency (O(n)) and simplicity.
Let’s explore other different methods to find all duplicate characters in string:
Table of Content
Using count()
The count() method can be used to determine the frequency of each character in the string directly. While this approach is simple but it is less efficient for larger strings due to repeated traversals.
s = "GeeksforGeeks"
res = []
# Iterate over the unique elements in 's'
for c in set(s): # Use set to avoid repeated checks
if s.count(c) > 1:
res.append(c)
print(res)
Output
['G', 'k', 'e', 's']
Explanation:
- We use a set() to loop through unique characters only. This will avoiding redundant checks.
- For each unique character s.count(c) counts how many times it appears in the string.
- If count is greater than 1 then character is added to the res list.
Note: This method is easy to use but inefficient for large strings (O(n2)). Use only for small inputs.
Using collections.Counter
The collections.Counter module provides a simple way to count occurrences of elements in a string.
from collections import Counter
s = "GeeksforGeeks"
# Create a Counter object to count occurrences
# of each character in string
d = Counter(s)
# Create a list of characters that occur more than once
res = [c for c, cnt in d.items() if cnt > 1]
print(res)
Output
['G', 'e', 'k', 's']
Explanation:
- The Counter() function counts each character in the string.
- Use a list comprehension to extract characters with a count greater than 1.
Note: This method is more concise and efficient (O(n)).