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.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice