Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Concatenated string with uncommon characters in Python
Next article icon

Find all duplicate characters in string in Python

Last Updated : 20 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • 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()
  • Using collections.Counter

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:

  • 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.

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:

  • 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)).



Next Article
Concatenated string with uncommon characters in Python

A

AFZAL ANSARI
Improve
Article Tags :
  • Python
  • Python string-programs
  • python-string
Practice Tags :
  • python

Similar Reads

  • Count occurrences of a character in string in Python
    We are given a string, and our task is to count how many times a specific character appears in it using Python. This can be done using methods like .count(), loops, or collections.Counter. For example, in the string "banana", using "banana".count('a') will return 3 since the letter 'a' appears three
    2 min read
  • Remove All Duplicates from a Given String in Python
    The task of removing all duplicates from a given string in Python involves retaining only the first occurrence of each character while preserving the original order. Given an input string, the goal is to eliminate repeated characters and return a new string with unique characters. For example, with
    2 min read
  • Count the number of Unique Characters in a String in Python
    We are given a string, and our task is to find the number of unique characters in it. For example, if the string is "hello world", the unique characters are {h, e, l, o, w, r, d}, so the output should be 8. Using setSet in Python is an unordered collection of unique elements automatically removing d
    2 min read
  • How to Find Chinese And Japanese Character in a String in Python
    Detecting Chinese or Japanese characters in a string can be useful for a variety of applications, such as text preprocessing, language detection, and character classification. In this article, we’ll explore simple yet effective ways to identify Chinese or Japanese characters in a string using Python
    5 min read
  • Concatenated string with uncommon characters in Python
    The goal is to combine two strings and identify the characters that appear in one string but not the other. These uncommon characters are then joined together in a specific order. In this article, we'll explore various methods to solve this problem using Python. Using set symmetric difference We can
    3 min read
  • Check if a string exists in a PDF file in Python
    In this article, we'll learn how to use Python to determine whether a string is present in a PDF file. In Python, strings are essential for Projects, applications software, etc. Most of the time, we have to determine whether a string is present in a PDF file or not. Here, we'll discuss how to check
    2 min read
  • Possible Words using given characters in Python
    Given a dictionary and a character array, print all valid words that are possible using characters from the array. Note: Repetitions of characters is not allowed. Examples: Input : Dict = ["go","bat","me","eat","goal","boy", "run"] arr = ['e','o','b', 'a','m','g', 'l'] Output : go, me, goal. This pr
    5 min read
  • Python | Count the Number of matching characters in a pair of string
    The problem is about finding how many characters are the same in two strings. We compare the strings and count the common characters between them. In this article, we'll look at different ways to solve this problem. Using Set Sets are collections of unique items, so by converting both strings into s
    2 min read
  • Python - Check if String Contain Only Defined Characters using Regex
    In this article, we are going to see how to check whether the given string contains only a certain set of characters in Python. These defined characters will be represented using sets. Examples: Input: ‘657’ let us say regular expression contains the following characters- (‘78653’) Output: Valid Exp
    2 min read
  • Python code to print common characters of two Strings in alphabetical order
    Given two strings, print all the common characters in lexicographical order. If there are no common letters, print -1. All letters are lower case. Examples: Input : string1 : geeks string2 : forgeeks Output : eegks Explanation: The letters that are common between the two strings are e(2 times), g(1
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences