Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Python - Least Frequent Character in String
Next article icon

Python - Least Frequent Character in String

Last Updated : 16 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task is to find the least frequent character in a string, we count how many times each character appears and pick the one with the lowest count.

Using collections.Counter

The most efficient way to do this is by using collections.Counter which counts character frequencies in one go and makes it easy to find the least frequent character.

Python
from collections import Counter s = "GeeksforGeeks" freq = Counter(s) res = min(freq, key=freq.get) print(str(res)) 

Output
f 

Explanation:

  • Counter(s): This creates a dictionary where each character in the string is a key, and the value is its frequency.
  • min(freq, key=freq.get): This finds the character with the lowest frequency.

Table of Content

  • Using dict
  • Using Sorting
  • Using str.count()

Using dict

Using a dictionary, we count the frequency of each character in a single pass and directly find the least frequent character. This approach avoids re-scanning the string making it more efficient than naive methods.

Python
s = "GeeksforGeeks" d = {}  # Initialize an empty dictionary  for char in s:  # Loop through each character in `s`     d[char] = d.get(char, 0) + 1  res = min(d, key=d.get) print(str(res))  

Output
f 

Explanation:

  • d.get(char, 0): This retrieves the current frequency of char, defaulting to 0 if the character is not found.
  • min(d, key=d.get): This finds the character with the lowest frequency in the dictionary d.

Using Sorting

Using sorting, we first count the frequency of each character in the string and then sort the characters by their frequency in ascending order. The least frequent character is extracted from the first element of the sorted list.

Python
s = "GeeksforGeeks" # Creating an empty dictionary d = {}  # Counting the frequency of each character in the string for char in s:     d[char] = d.get(char, 0) + 1   # Sorting `d` items by frequency sorted_freq = sorted(d.items(), key=lambda item: item[1])  # Extracting the least frequent character res = sorted_freq[0][0] print(res) 

Output
f 

Explanation:

  • d[char] = d.get(char, 0) + 1: This checks if the character already exists in the dictionary d . If it does it increments its count, otherwise it initializes the count to 1.
  • sorted(d.items(), key=lambda item: item[1]): This sorts the items in the dictionary by the frequency in ascending order.
  • sorted_freq[0][0]: After sorting, the least frequent character is the first element in the sorted listsorted_freqand its character is extracted using [0][0].

Using str.count()

count()function counts the occurrences of each character and min() is used to identify the character with the lowest frequency. This approach is straightforward but becomes inefficient for larger strings due to its quadratic time complexity.

Python
s = "GeeksforGeeks" res = min(s, key=lambda char:            s.count(char)) print(str(res)) 

Output
f 

Explanation:

  • min(s, key=...): This finds the character with the minimum frequency in the string s .
  • lambda char: s.count(char): For each character this lambda function calculates the frequency of that character in the string using s.count(char).

Next Article
Python - Least Frequent Character in String

M

manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

    Maximum Frequency Character in String - Python
    The task of finding the maximum frequency character in a string involves identifying the character that appears the most number of times. For example, in the string "hello world", the character 'l' appears the most frequently (3 times).Using collection.CounterCounter class from the collections modul
    3 min read
    Specific Characters Frequency in String List-Python
    The task of counting the frequency of specific characters in a string list in Python involves determining how often certain characters appear across all strings in a given list.For example, given a string list ["geeksforgeeks"] and a target list ['e', 'g'], the output would count how many times 'e'
    4 min read
    Python - Expand Character Frequency String
    Given a string, which characters followed by its frequency, create the appropriate string. Examples: Input : test_str = 'g7f2g3i2s2b3e4' Output : gggggggffgggiissbbbeeee Explanation : g is succeeded by 7 and repeated 7 times. Input : test_str = 'g1f1g1' Output : gfg Explanation : f is succeeded by 1
    4 min read
    Python | Longest Run of given Character in String
    Sometimes, while working with Strings, we can have a problem in which we need to perform the extraction of length of longest consecution of certain letter. This can have application in web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method
    6 min read
    Python | Lowercase first character of String
    The problem of capitalizing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the first character of the string to lowercase. Let us discuss certain ways in which this can be performed. Method #1: Using string sli
    4 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