Open In App

Python – Least Frequent Character in String

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article gives us the methods to find the frequency of minimum occurring character in a python string. This is quite important utility nowadays and knowledge of it is always useful. Let’s discuss certain ways in which this task can be performed. 

Method 1 : Naive method + min() 

In this method, we simply iterate through the string and form a key in a dictionary of newly occurred element or if element is already occurred, we increase its value by 1. We find minimum occurring character by using min() on values. 

Python3




# Python 3 code to demonstrate
# Least Frequent Character in String
# naive method
 
# initializing string
test_str = "GeeksforGeeks"
 
# printing original string
print ("The original string is : " + test_str)
 
# using naive method to get
# Least Frequent Character in String
all_freq = {}
for i in test_str:
 if i in all_freq:
  all_freq[i] += 1
 else:
  all_freq[i] = 1
res = min(all_freq, key = all_freq.get)
 
# printing result
print ("The minimum of all characters in GeeksforGeeks is : " + str(res))


Output : 

The original string is : GeeksforGeeks
The minimum of all characters in GeeksforGeeks is : f

Time Complexity: O(n)
Auxiliary Space: O(n), where n is number of characters in string.

 Method 2 : Using collections.Counter() + min() 

The most suggested method that could be used to find all occurrences is this method, this actually gets all element frequency and could also be used to print single element frequency if required. We find minimum occurring character by using min() on values. 

Python3




# Python 3 code to demonstrate
# Least Frequent Character in String
# collections.Counter() + min()
from collections import Counter
 
# initializing string
test_str = "GeeksforGeeks"
 
# printing original string
print ("The original string is : " + test_str)
 
# using collections.Counter() + min() to get
# Least Frequent Character in String
res = Counter(test_str)
res = min(res, key = res.get)
 
# printing result
print ("The minimum of all characters in GeeksforGeeks is : " + str(res))


Output : 

The original string is : GeeksforGeeks
The minimum of all characters in GeeksforGeeks is : f

The time complexity of this code is O(nlogn) due to the sorting operation done by the min() function.

The auxiliary space used by this code is O(n) because the Counter() function creates a dictionary that stores the count of each character in the string, which can have a maximum of n distinct characters in it.

Method 3: Using defaultdict and list comprehension

In this Method, it finds the least frequent character in a given string by counting the frequency of each character using a defaultdict. It then finds the minimum frequency count and returns the least frequent character(s) by filtering the dictionary keys with the minimum frequency count. The resulting characters are then sorted and the first character is returned.

Python3




from collections import defaultdict
 
def least_frequent_char(string):
    freq = defaultdict(int)
    for char in string:
        freq[char] += 1
    min_freq = min(freq.values())
    least_frequent_chars = [char for char in freq if freq[char] == min_freq]
    return ''.join(sorted(least_frequent_chars))[0]
 
# Example usage
test_str = "GeeksorfGeeks"
least_frequent = least_frequent_char(test_str)
print(f"The least frequent character in '{test_str}' is: {least_frequent}")


Output

The least frequent character in 'GeeksorfGeeks' is: f

Time complexity: O(n)
Auxiliary space: O(n)

Method 4: Using numpy:

Algorithm :

  1. Create an empty dictionary freq.
  2. For each unique character in the input string string, count the number of times it appears in the string and add it to the dictionary freq with the character as the key and the count as the value.
  3. Find the minimum value in the dictionary freq using np.argmin.
  4. Return the corresponding key (character) with the minimum value.

Python3




import numpy as np
def least_frequent_char(string):
    freq = {char: string.count(char) for char in set(string)}
    return list(freq.keys())[np.argmin(list(freq.values()))]
# Example usage
input_string = "GeeksforGeeks"
min_char = least_frequent_char(input_string)
print("The original string is:", input_string)
print("The minimum of all characters in", input_string, "is:", min_char)
#This code is contributed by Jyothi Pinjala.


Output:

The original string is: GeeksforGeeks
The minimum of all characters in GeeksforGeeks is: f

The time complexity :O(n), where n is the length of the input string. This is because we need to loop through the string once to count the frequency of each character.
The space complexity: O(n), since we create a dictionary freq with at most n key-value pairs.has context menu

Approach: Using Dictionary

Steps:

  1. Create an empty dictionary to store the frequency of each character in the string.
  2. Traverse through the given string and update the count of each character in the dictionary.
  3. Find the minimum value in the dictionary.
  4. Traverse the dictionary and return the key whose value matches the minimum value.

Python3




# Python program for the above approach
 
# Function to find the least frequent characters
def least_frequent_char(input_str):
    freq_dict = {}
     
    for char in input_str:
        freq_dict[char] = freq_dict.get(char, 0) + 1
     
    min_value = min(freq_dict.values())
    least_frequent_char = ''
     
    # Traversing the dictionary
    for key, value in freq_dict.items():
        if value == min_value:
            least_frequent_char = key
            break
    return least_frequent_char
 
 
# Driver Code
input_str = "geeksforgeeks"
 
print(least_frequent_char(input_str))


Output

f

The time complexity: O(nlogn).
Auxiliary Space: O(n).



Similar Reads

Replace missing white spaces in a string with the least frequent character using Pandas
Let's create a program in python which will replace the white spaces in a string with the character that occurs in the string very least using the Pandas library. Example 1: String S = "akash loves gfg" here: 'g' comes: 2 times 's' comes: 2 times 'a' comes: 2 times 'h' comes: 1 time 'o' comes: 1 time 'k' comes: 1 time 'v' comes: 1 time 'e' comes: 1
2 min read
Python Program for Least frequent element in an array
Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them.Examples : Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1} Output : 3 3 appears minimum number of times in given array. Input : arr[] = {10, 20, 30} Output : 10 or 20 or 30 Method 1:A simple solution is to run two
3 min read
Kth most frequent Character in a given String
Given a string str and an integer K, the task is to find the K-th most frequent character in the string. If there are multiple characters that can account as K-th most frequent character then, print any one of them.Examples: Input: str = "GeeksforGeeks", K = 3 Output: f Explanation: K = 3, here 'e' appears 4 times & 'g', 'k', 's' appears 2 time
6 min read
Find the k most frequent words from data set in Python
Given the data set, we can find k number of most frequent words. The solution of this problem already present as Find the k most frequent words from a file. But we can solve this problem very efficiently in Python with the help of some high performance modules. In order to do this, we'll use a high performance data type module, which is collections
2 min read
Python | Find most frequent element in a list
Given a list, find the most frequent element in it. If there are multiple elements that appear maximum number of times, print any one of them. Examples: Input : [2, 1, 2, 2, 1, 3] Output : 2 Input : ['Dog', 'Cat', 'Dog'] Output : Dog Approach #1 : Naive ApproachThis is a brute force approach in which we make use of for loop to count the frequency o
4 min read
Python | Find top K frequent elements from a list of tuples
Given a list of tuples with word as first element and its frequency as second element, the task is to find top k frequent element. Below are some ways to above achieve the above task. Method #1: Using defaultdict C/C++ Code # Python code to find top 'k' frequent element # Importing import collections from operator import itemgetter from itertools i
5 min read
Python program for most frequent word in Strings List
Given Strings List, write a Python program to get word with most number of occurrences. Example: Input : test_list = ["gfg is best for geeks", "geeks love gfg", "gfg is best"] Output : gfg Explanation : gfg occurs 3 times, most in strings in total. Input : test_list = ["geeks love gfg", "geeks are best"] Output : geeks Explanation : geeks occurs 2
6 min read
Python program to read character by character from a file
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it. Example Input: GeeksOutput: G e e k sExplanation: Iterated through character by character from the input as shown in the output.Read a fi
2 min read
Python - Create a Dictionary with Key as First Character and Value as Words Starting with that Character
In this article, we will code a python program to create a dictionary with the key as the first character and value as words starting with that character. Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds t
6 min read
Python | Insert character after every character pair
Sometimes, we can have a problem in which we need to insert a specific character after a pair(second) characters using Python. This kind of problem can occur while working with data, that require insertion of commas or any other special character mainly in the Machine Learning domain. Let's discuss certain ways in which this problem can be solved.
6 min read
Practice Tags :
three90RightbarBannerImg