๐ Day 77/150 – Find Duplicate Characters in a String in Python
Strings are one of the most commonly used data types in Python, and a frequent interview or practice question is finding duplicate characters in a string. Duplicate characters are those that appear more than once in the given text.
In this blog, we'll explore multiple ways to identify duplicate characters in a string using Python.
Method 1 – Using a Dictionary
A dictionary can store the frequency of each character. Once the count is calculated, we can print characters whose frequency is greater than 1.
Output
rg
m
Why Use This Method?
- Efficient and easy to understand
- Works well for large strings
- Time Complexity: O(n)
Method 2 – Taking User Input
This method allows users to enter their own string and find duplicate characters dynamically.
Example Input
hello world
Output
l
o
Method 3 – Using Nested Loops
This approach compares each character with the remaining characters in the string.
Output
['r', 'g', 'm']
Pros
- No dictionary required
- Useful for understanding string comparisons
Cons
- Less efficient for larger strings
- Time Complexity: O(n²)
Method 4 – Using Set and count()
A concise approach is to use a set to get unique characters and count their occurrences.
Output
r
g
m
Pros
- Short and readable
- Easy to implement
Cons
- count() scans the string repeatedly
- Not ideal for very large strings
๐ฏ Real-World Applications
Finding duplicate characters is useful in:
- Data validation
- Text processing
- Password analysis
- Frequency analysis
- Coding interviews and programming challenges


0 Comments:
Post a Comment