A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-counter-find-duplicate-characters-string/ below:

Find all duplicate characters in string in Python

Find all duplicate characters in string in Python

Last Updated : 20 Nov, 2024

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.

Python
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:

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:

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.

Python
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:

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.

Python
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:

Note: This method is more concise and efficient (O(n)).


Find duplicates in a string using Counter method - Python Programming


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4