Sunday, November 17, 2024
Google search engine
HomeLanguagesPython – Least Frequent Character in String

Python – Least Frequent Character in String

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 = "Lazyroar"
 
# 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 Lazyroar is : " + str(res))


Output : 

The original string is : Lazyroar
The minimum of all characters in Lazyroar 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 = "Lazyroar"
 
# 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 Lazyroar is : " + str(res))


Output : 

The original string is : Lazyroar
The minimum of all characters in Lazyroar 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 = "Lazyroar"
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: Lazyroar
The minimum of all characters in Lazyroar 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 = "neveropen"
 
print(least_frequent_char(input_str))


Output

f

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

RELATED ARTICLES

Most Popular

Recent Comments