Python - Count all prefixes in given string with greatest frequency
Last Updated :
11 Jul, 2025
Counting all prefixes in a given string with the greatest frequency involves identifying substrings that start from the beginning of the string and determining which appears most frequently.
Using a Dictionary (DefaultDict)
This approach uses defaultdict
from the collections
module to store prefix counts, as seen earlier:
Python
from collections import defaultdict
s = "geeks"
prefix_count = defaultdict(int)
# Generate all prefixes and count them
for i in range(1, len(s) + 1):
prefix = s[:i]
prefix_count[prefix] += 1
# Find the greatest frequency
max_f = max(prefix_count.values())
# Collect prefixes with the greatest frequency
frequent_prefixes = [prefix for prefix, count in prefix_count.items() if count == max_f]
print(f"{frequent_prefixes}")
print(f"{max_f}")
Output['g', 'ge', 'gee', 'geek', 'geeks']
1
Explanation
- The code iterates through the string, creating prefixes of increasing length and counts their occurrences using a
defaultdict(int)
. - It finds the highest frequency of any prefix by calling
max()
on the values of the prefix_count
dictionary. - The code collects all prefixes with the greatest frequency and prints them along with the frequency value.
Let's explore various other methods to Count all prefixes in given string with greatest frequency.
Using a Regular Dictionary
One of the most efficient ways to count the frequency of prefixes is by using a regular dictionary, a data structure that maps keys (in this case, prefixes) to their corresponding counts.
Python
s = "Geeks"
count = {}
# Generate all prefixes and count them
for i in range(1, len(s) + 1):
count[s[:i]] = count.get(s[:i], 0) + 1
# Find the greatest frequency
max_freq = max(count.values())
# Collect prefixes with the greatest frequency
freq_prefixes = [p for p, c in count.items() if c == max_freq]
print(f"{freq_prefixes}")
print(f"{max_freq}")
Output['G', 'Ge', 'Gee', 'Geek', 'Geeks']
1
Explanation
- The code loops through the string
s
, creating prefixes of increasing lengths and counts their occurrences using the count.get(s[:i], 0) + 1
method to update the dictionary count
. - It finds the highest frequency of any prefix by using
max(count.values())
. - It gathers all prefixes with the greatest frequency into
freq_prefixes
and prints both the prefixes and the frequency value.
Using set
and list
By iterating through the string and generating all possible prefixes, we can update the
list
to record the frequency of each prefix while leveraging the set to ensure that we don't count duplicates.
Python
s = "geeks"
prefix_count = []
# Generate all prefixes and count them
for i in range(1, len(s) + 1):
prefix = s[:i]
prefix_count.append(prefix)
# Track the greatest frequency
unique_prefixes = set(prefix_count)
max_freq = 0
freq_prefixes = []
for prefix in unique_prefixes:
count = prefix_count.count(prefix)
if count > max_freq:
max_freq = count
freq_prefixes = [prefix]
elif count == max_freq:
freq_prefixes.append(prefix)
print(f"Prefixes with the greatest frequency: {freq_prefixes}")
print(f"Greatest frequency: {max_freq}")
OutputPrefixes with the greatest frequency: ['gee', 'ge', 'geek', 'g', 'geeks']
Greatest frequency: 1
Explanation
- The code creates all possible prefixes of the string
s
and stores them in the list prefix_count
. - It converts
prefix_count
to a set to get unique prefixes and counts the occurrences of each prefix. The prefix with the highest count is tracked by comparing counts and updating max_freq
. - All prefixes with the greatest frequency are collected in
freq_prefixes
, which are then printed along with the frequency value.
Similar Reads
Find frequency of each word in a string in Python Write a python code to find the frequency of each word in a given string. Examples: Input : str[] = "Apple Mango Orange Mango Guava Guava Mango" Output : frequency of Apple is : 1 frequency of Mango is : 3 frequency of Orange is : 1 frequency of Guava is : 2 Input : str = "Train Bus Bus Train Taxi A
7 min read
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
Python - Find all elements count in list In Python, counting the occurrences of all elements in a list is to determine how many times each unique element appears in the list. In this article, we will explore different methods to achieve this. The collections.Counter class is specifically designed for counting hashable objects. It provides
3 min read
Find all duplicate characters in string in Python 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 DictionaryWe can use a for loop to find duplicate characters efficiently. First we count the occurrences of each character by iteratin
2 min read
Python | Check if frequencies of all characters of a string are different Given a string S consisting only of lowercase letters, the task is to check if the frequency of all characters of the string is unique. Examples: Input : abaccc Output : Yes âaâ occurs two times, âbâ occurs once and âcâ occurs three times. Input : aabbc Output : No Frequency of both 'a' and 'b' are
3 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 du
2 min read