Ruby Program to Find Most Frequent Character
string.chars.group_by(&:itself).transform_values(&:count).max_by(&:last).first in Ruby to find the most frequent character in a string.Examples
How to Think About It
Algorithm
Code
def most_frequent_char(str) str.chars.group_by(&:itself).transform_values(&:count).max_by(&:last).first end puts most_frequent_char("hello")
Dry Run
Let's trace the string "hello" through the code
Split string into characters
["h", "e", "l", "l", "o"]
Group characters by themselves
{"h"=>["h"], "e"=>["e"], "l"=>["l", "l"], "o"=>["o"]}
Count occurrences of each character
{"h"=>1, "e"=>1, "l"=>2, "o"=>1}
Find character with max count
["l", 2]
Return the character
"l"
| Character | Count |
|---|---|
| h | 1 |
| e | 1 |
| l | 2 |
| o | 1 |
Why This Works
Step 1: Split string into characters
Using chars breaks the string into an array of single characters to work with each one.
Step 2: Group characters
Using group_by(&:itself) groups identical characters together in a hash.
Step 3: Count each group
Using transform_values(&:count) counts how many times each character appears.
Step 4: Find max count
Using max_by(&:last) finds the character with the highest count.
Alternative Approaches
def most_frequent_char(str) freq = Hash.new(0) str.each_char { |c| freq[c] += 1 } freq.max_by { |_, count| count }[0] end puts most_frequent_char("hello")
def most_frequent_char(str) str.chars.tally.max_by { |_, count| count }[0] end puts most_frequent_char("hello")
Complexity: O(n) time, O(k) space
Time Complexity
The program loops through each character once to count frequencies, so it runs in O(n) time where n is the string length.
Space Complexity
It uses extra space to store counts for each unique character, which is O(k) where k is the number of unique characters.
Which Approach is Fastest?
Using tally is fastest and most readable, while manual hash counting is more verbose but clear.
| Approach | Time | Space | Best For |
|---|---|---|---|
| group_by + transform_values | O(n) | O(k) | Readable grouping and counting |
| manual hash counting | O(n) | O(k) | Explicit counting, beginner-friendly |
| Enumerable#tally | O(n) | O(k) | Shortest and most efficient for Ruby 2.7+ |
tally method for a clean and efficient way to count characters.