Python Program to Find Most Frequent Character in String
max(string, key=string.count) which returns the character that appears the most times.Examples
How to Think About It
Algorithm
Code
def most_frequent_char(s): return max(s, key=s.count) input_str = "mississippi" print(most_frequent_char(input_str))
Dry Run
Let's trace the string 'mississippi' through the code.
Input string
s = 'mississippi'
Count characters
Counts: m=1, i=4, s=4, p=2
Find max count character
Characters with max count 4 are 'i' and 's', max returns first found 'i'
Return result
Return 'i'
| Character | Count |
|---|---|
| m | 1 |
| i | 4 |
| s | 4 |
| p | 2 |
Why This Works
Step 1: Counting characters
The count method counts how many times each character appears in the string.
Step 2: Finding maximum
The max function with key=s.count finds the character with the highest count.
Step 3: Returning result
The character with the highest frequency is returned as the most frequent character.
Alternative Approaches
from collections import Counter def most_frequent_char(s): counts = Counter(s) return counts.most_common(1)[0][0] input_str = "mississippi" print(most_frequent_char(input_str))
def most_frequent_char(s): counts = {} for char in s: counts[char] = counts.get(char, 0) + 1 max_char = max(counts, key=counts.get) return max_char input_str = "mississippi" print(most_frequent_char(input_str))
Complexity: O(n^2) time, O(n) space
Time Complexity
Using max(s, key=s.count) calls count for each character, which scans the string each time, leading to O(n^2) time for string length n.
Space Complexity
The method uses O(1) extra space if counting on the fly, but storing counts in a dictionary or Counter uses O(n) space.
Which Approach is Fastest?
Using collections.Counter is faster with O(n) time because it counts all characters in one pass.
| Approach | Time | Space | Best For |
|---|---|---|---|
| max with s.count | O(n^2) | O(1) | Short strings, simple code |
| collections.Counter | O(n) | O(n) | Long strings, efficient counting |
| Manual dictionary count | O(n) | O(n) | Learning counting logic, no imports |
collections.Counter for an easy and efficient way to count characters.max with key=s.count can be slow for long strings because it counts each character multiple times.