0
0
GoProgramBeginner · 2 min read

Go Program to Find Most Frequent Character

In Go, you can find the most frequent character by counting each character's occurrences using a map and then selecting the character with the highest count, for example: freq := make(map[rune]int); for _, ch := range input { freq[ch]++ } followed by finding the max count.
📋

Examples

Inputhello
Outputl
Inputaabbccddeeff
Outputa
Inputzzzyyyxxx
Outputz
🧠

How to Think About It

To find the most frequent character, first count how many times each character appears by going through the string one by one. Then, look at all counts and pick the character with the biggest number. This way, you know which character shows up the most.
📐

Algorithm

1
Get the input string.
2
Create a map to store character counts.
3
Loop through each character in the string and increase its count in the map.
4
Find the character with the highest count in the map.
5
Return or print that character.
💻

Code

go
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

1

Initialize frequency map

freq = {}

2

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}

3

Find max frequency

maxChar = 'l', maxCount = 2

4

Print result

Output: Most frequent character: l

CharacterCount
h1
e1
l2
o1
💡

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

Using an array for ASCII characters
go
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)
}
This method is faster for ASCII strings but only works for single-byte characters.
Using sorting
go
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)
}
Sorting is less efficient but useful if you want a list of characters by frequency.

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.

ApproachTimeSpaceBest For
Map with rune keysO(n)O(k)Unicode strings, general use
Array for ASCIIO(n)O(1)ASCII strings, performance critical
Sorting frequency pairsO(n + k log k)O(k)When sorted frequency list is needed
💡
Use a map[rune]int to count characters easily in Go strings with Unicode support.
⚠️
Beginners often forget to handle Unicode characters properly and use byte instead of rune, which can cause errors with multi-byte characters.