Open In App

Find all Duplicate Characters in String in Python

Last Updated : 31 Oct, 2025
Comments
Improve
Suggest changes
35 Likes
Like
Report

Given a string, the task is to find all characters that appear more than once in it. For example:

Input: "GeeksforGeeks"
Output: ['G', 'e', 'k', 's']

Below are multiple methods to find all duplicate characters in a string efficiently.

Using collections.Counter

Counter() function automatically counts how many times each character appears. Then, we can easily extract characters that occur more than once.

Python
from collections import Counter

s = "GeeksforGeeks"
d = Counter(s) 

res = [c for c, cnt in d.items() if cnt > 1]
print(res) 

Output
['G', 'e', 'k', 's']

Explanation:

  • Counter(s) counts each character and stores as {char: count}.
  • d.items() returns key-value pairs of character and frequency.
  • [c for c, cnt in d.items() if cnt > 1] filters only duplicate characters.

Using Loop with Dictionary

Here, for loop is used 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.

Python
s = "GeeksforGeeks"
d = {}
res = []

for c in s:
    d[c] = d.get(c, 0) + 1

for c, cnt in d.items():
    if cnt > 1:
        res.append(c)

print(res)

Output
['G', 'e', 'k', 's']

Explanation:

  • d.get(c, 0) returns current count (default 0) if key doesn’t exist.
  • The first loop counts how many times each character appears.
  • The second loop adds characters with count > 1 into res.

Using defaultdict from collections

This method is similar to the dictionary approach but uses defaultdict to automatically handle missing keys. It counts character occurrences efficiently without needing manual initialization.

Python
from collections import defaultdict

s = "GeeksforGeeks"
d = defaultdict(int)

for c in s:
    d[c] += 1

res = [c for c in d if d[c] > 1]
print(res)

Output
['G', 'e', 'k', 's']

Explanation:

  • defaultdict(int) automatically initializes missing keys with 0.
  • Loop increments count for each character.
  • A list comprehension collects duplicates.

Using set() and 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.

Python
s = "GeeksforGeeks"
res = []

for c in set(s): 
    if s.count(c) > 1:
        res.append(c)

print(res)

Output
['k', 's', 'G', 'e']

Explanation:

  • set(s) removes duplicate characters for iteration efficiency.
  • s.count(c) counts how many times c appears in s.
  • If frequency > 1, character is added to res.

Find duplicates in a string using Counter method - Python Programming

Explore