A RetroSearch Logo

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

Search Query:

Showing content from https://www.geeksforgeeks.org/python-least-frequent-character-in-string/ below:

Python - Least Frequent Character in String

Python - Least Frequent Character in String

Last Updated : 12 Jul, 2025

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

Explanation:

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

Explanation:

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)

Explanation:

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

Explanation:



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