Go Program to Find Most Frequent Character
freq := make(map[rune]int); for _, ch := range input { freq[ch]++ } followed by finding the max count.Examples
How to Think About It
Algorithm
Code
package main import ( "fmt" ) func main() { input := "hello" freq := make(map[rune]int) for _, ch := range input { freq[ch]++ } maxChar := rune(0) maxCount := 0 for ch, count := range freq { if count > maxCount { maxCount = count maxChar = ch } } fmt.Printf("Most frequent character: %c\n", maxChar) }
Dry Run
Let's trace the input "hello" through the code
Initialize frequency map
freq = {}
Count characters
After 'h': freq = {'h':1} After 'e': freq = {'h':1, 'e':1} After 'l': freq = {'h':1, 'e':1, 'l':1} After second 'l': freq = {'h':1, 'e':1, 'l':2} After 'o': freq = {'h':1, 'e':1, 'l':2, 'o':1}
Find max frequency
maxChar = 'l', maxCount = 2
Print result
Output: Most frequent character: l
| Character | Count |
|---|---|
| h | 1 |
| e | 1 |
| l | 2 |
| o | 1 |
Why This Works
Step 1: Counting characters
We use a map with characters as keys and counts as values to keep track of how many times each character appears.
Step 2: Finding the maximum
We check each character's count and update the maximum count and character when we find a higher count.
Step 3: Output the result
The character with the highest count is printed as the most frequent character.
Alternative Approaches
package main import ( "fmt" ) func main() { input := "hello" var freq [256]int for i := 0; i < len(input); i++ { freq[input[i]]++ } maxChar := byte(0) maxCount := 0 for i := 0; i < 256; i++ { if freq[i] > maxCount { maxCount = freq[i] maxChar = byte(i) } } fmt.Printf("Most frequent character: %c\n", maxChar) }
package main import ( "fmt" "sort" ) func main() { input := "hello" freq := make(map[rune]int) for _, ch := range input { freq[ch]++ } type pair struct { char rune count int } pairs := make([]pair, 0, len(freq)) for ch, count := range freq { pairs = append(pairs, pair{ch, count}) } sort.Slice(pairs, func(i, j int) bool { return pairs[i].count > pairs[j].count }) fmt.Printf("Most frequent character: %c\n", pairs[0].char) }
Complexity: O(n) time, O(k) space
Time Complexity
The program loops through the string once to count characters, which is O(n), and then loops through the map keys, which is O(k), where k is the number of unique characters. Overall, O(n).
Space Complexity
The map stores counts for each unique character, so space is O(k). This is efficient for typical strings.
Which Approach is Fastest?
Using a map with runes is flexible and fast for Unicode. Using an array is faster but only for ASCII. Sorting is slower but useful for frequency order.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Map with rune keys | O(n) | O(k) | Unicode strings, general use |
| Array for ASCII | O(n) | O(1) | ASCII strings, performance critical |
| Sorting frequency pairs | O(n + k log k) | O(k) | When sorted frequency list is needed |