Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find all duplicate characters in a string
This article teaches you how to write a Python program to find all duplicate characters in a string using different approaches.
Characters that repeat themselves within a string are referred to as duplicate characters. When we refer to finding duplicate characters in a string, we mean identifying every character that appears more than once in the string.
Input-Output Scenario
Following is the input-output scenario to find all the duplicate characters in a string ?
Input: TutorialsPoint Output: t, o, i
As we can see, the duplicate characters in the given string "TutorialsPoint" are "t" with 3 repetitions, "o" with 2 repetitions and "i" with 2 repetitions.
Algorithm
The following algorithm will search a string for duplicate characters ?
- Create a string and store it in a variable
- Use nested loops to check each character against all other characters
- Count occurrences of each character
- If a character's count is more than 1, it's a duplicate
- Print the duplicate characters
Using Nested Loops
The basic approach uses nested loops to compare each character with all subsequent characters in the string ?
text = "tutorialspoint"
duplicates = []
print("Duplicate characters:")
for i in range(len(text)):
count = 1
# Skip if character already processed
if text[i] in duplicates:
continue
for j in range(i + 1, len(text)):
if text[i] == text[j]:
count += 1
if count > 1:
duplicates.append(text[i])
print(f"{text[i]} appears {count} times")
Duplicate characters: t appears 3 times o appears 2 times i appears 2 times
Using count() Method
The count() method returns the frequency of a character in the string. This approach is more concise ?
text = "tutorialspoint"
duplicate_chars = []
for character in text:
# Check if character appears more than once
if text.count(character) > 1:
# Add to list if not already present
if character not in duplicate_chars:
duplicate_chars.append(character)
print("Duplicate characters:", *duplicate_chars)
Duplicate characters: t o i
Using Counter() Method
The Counter class from the collections module creates a dictionary with characters as keys and their frequencies as values ?
from collections import Counter
def find_duplicates(text):
# Create dictionary with character frequencies
char_count = Counter(text)
duplicates = []
# Find characters with count > 1
for char, count in char_count.items():
if count > 1:
duplicates.append(char)
return duplicates
# Test the function
text = 'TutorialsPoint'
result = find_duplicates(text)
print("Duplicate characters:", result)
Duplicate characters: ['t', 'o', 'i']
Using Dictionary Approach
Manually creating a dictionary to track character frequencies provides more control over the counting process ?
def find_duplicates_dict(text):
char_freq = {}
duplicates = []
# Count frequency of each character
for char in text:
char_freq[char] = char_freq.get(char, 0) + 1
# Find duplicates
for char, freq in char_freq.items():
if freq > 1:
duplicates.append(char)
return duplicates
text = "tutorialspoint"
result = find_duplicates_dict(text)
print("Duplicate characters:", result)
print("Character frequencies:")
for char in result:
print(f"'{char}': {text.count(char)} times")
Duplicate characters: ['t', 'o', 'i'] Character frequencies: 't': 3 times 'o': 2 times 'i': 2 times
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Nested Loops | O(n²) | O(1) | Learning purposes |
| count() Method | O(n²) | O(n) | Simple implementation |
| Counter() | O(n) | O(n) | Built-in efficiency |
| Dictionary | O(n) | O(n) | Custom logic needed |
Conclusion
Use Counter() from collections for the most efficient solution. For simple cases, the count() method provides readable code. The dictionary approach offers flexibility for custom requirements.
