AlgoTales · Roadmap

Character frequency

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Character frequency means counting how many times each letter appears in a text, using one counter per letter. A single pass gives you a tally sheet that answers many questions: which letter is most common, whether two words match, or what language a message is in.

Practical use cases

  • Web app: Guessing the language of a short message. A chat app wants to guess whether a message is English or Spanish to suggest a translation. It counts how often each letter appears and compares the pattern with typical English and Spanish letter counts. One pass over a short message is enough to make a decent guess.
  • Web app: First non-repeating letter in a coupon code. A promotions page generates codes and rejects any with too many repeated characters. A tally of each character in the code shows repeats at once and also gives the first unique letter, without comparing every pair of letters. Bad codes are rejected before they reach customers.
  • System: Compression and codebreaking. Compression tools give short codes to the most frequent letters, so common letters take little space. Codebreakers famously spot a simple cipher because the most frequent letter in the coded text is probably E. The same tally sheet drives both jobs.

The story: The Tally Sheet of Tiles

Raju's nephew had a bag of wooden letter tiles that spelled BANANA when laid out. Raju asked, "How many A tiles are there?" The boy counted A's by eye. Then Raju asked, "And N?" and the boy counted the whole row again. Then "And B?" and he counted again. By the third round he was cross-eyed.

Mira had a cleverer idea. "Draw a tally sheet: one small box for each letter, all starting at zero. Now walk through the tiles just once. Whenever you see an A, tick the A box. When you see an N, tick the N box."

After a single walk the sheet said A: 3, N: 2, B: 1. Any question about any letter could now be answered by glancing at the sheet, with no re-counting. A sheet that stores "letter → how many" is exactly what programmers call a frequency count, and it is the seed of anagram checks, word puzzles, and finding the most popular letter.

How to spot this problem, and where you need it

You need to know how often each character appears, or whether two texts have the same letters, and comparing every pair of characters is slow and complicated.

Signs you need it

  • The problem asks for the most frequent character, first non-repeating character, or whether a letter repeats.
  • You have a nested loop comparing each character with every other character in the string.
  • You need a quick fingerprint of a text to compare, group or classify it.

Where to use it in a project

  • Text analytics: word clouds, language detection, keyword and spam scoring in chat or comment systems.
  • Validation and games: checking repeated characters in codes, scoring a word-guessing game, anagram helpers.

The solution

Create a counter for every possible character, either an array of 26 numbers for lowercase English letters or a keyed array for anything else. Walk through the text once, and for each character add one to its counter. Afterwards, read the counters to answer your question: find the biggest, find the first with count one, or compare two sheets.

Payoff: Before: comparing each character with all others, 1,000,000 checks for a 1,000-letter text. After: one pass of 1,000 steps.

Explain it like I am 8

Put out one empty cup for every letter. Pick up the tiles one by one and drop each tile into its own cup. At the end, look at which cup is fullest. You only had to pick up each tile once.

How it works, step by step

  1. Make an empty tally: a map (or an array of 26 slots for a to z) where every count is 0.
  2. Walk the string from left to right, exactly like a normal traversal.
  3. For each letter, add 1 to its own box on the tally.
  4. Read the answer from the tally: the biggest count is the most common letter.

The code in four languages

PHP

<?php
// Count how many times each character appears.
function charFrequency(string $s): array {
    $freq = [];                                   // letter => how many
    for ($i = 0; $i < strlen($s); $i++) {
        $ch = $s[$i];
        $freq[$ch] = ($freq[$ch] ?? 0) + 1;       // start at 0 if unseen, then add one
    }
    return $freq;
}

$freq = charFrequency("BANANA");
print_r($freq);                                   // B=>1, A=>3, N=>2

// Which letter is most common?
$bestLetter = '';
$bestCount = 0;
foreach ($freq as $letter => $count) {
    if ($count > $bestCount) {
        $bestCount = $count;
        $bestLetter = $letter;
    }
}
echo "Most common: $bestLetter ($bestCount)\n";   // A (3)

JavaScript

// Count how many times each character appears.
function charFrequency(s) {
  const freq = {};                       // letter -> how many
  for (const ch of s) {
    freq[ch] = (freq[ch] || 0) + 1;      // start at 0 if unseen, then add one
  }
  return freq;
}

const freq = charFrequency('BANANA');
console.log(freq);                       // { B: 1, A: 3, N: 2 }

// Which letter is most common?
let bestLetter = '';
let bestCount = 0;
for (const letter in freq) {
  if (freq[letter] > bestCount) {
    bestCount = freq[letter];
    bestLetter = letter;
  }
}
console.log('Most common: ' + bestLetter + ' (' + bestCount + ')');   // A (3)

Java

import java.util.*;

public class Main {
    // Count how many times each character appears.
    static Map<Character, Integer> charFrequency(String s) {
        Map<Character, Integer> freq = new LinkedHashMap<>();   // letter -> how many
        for (char ch : s.toCharArray()) {
            freq.put(ch, freq.getOrDefault(ch, 0) + 1);         // start at 0 if unseen, then add one
        }
        return freq;
    }

    public static void main(String[] args) {
        Map<Character, Integer> freq = charFrequency("BANANA");
        System.out.println(freq);                               // {B=1, A=3, N=2}

        // Which letter is most common?
        char bestLetter = ' ';
        int bestCount = 0;
        for (Map.Entry<Character, Integer> e : freq.entrySet()) {
            if (e.getValue() > bestCount) {
                bestCount = e.getValue();
                bestLetter = e.getKey();
            }
        }
        System.out.println("Most common: " + bestLetter + " (" + bestCount + ")");   // A (3)
    }
}

Go

package main

import "fmt"

// charFrequency counts how many times each character appears.
func charFrequency(s string) map[string]int {
	freq := map[string]int{} // letter -> how many
	for _, ch := range s {
		freq[string(ch)]++ // a missing key counts as 0, so this just adds one
	}
	return freq
}

func main() {
	freq := charFrequency("BANANA")
	fmt.Println(freq) // map[A:3 B:1 N:2]  (Go prints maps sorted by key)

	// Which letter is most common?
	bestLetter := ""
	bestCount := 0
	for letter, count := range freq {
		if count > bestCount {
			bestCount = count
			bestLetter = letter
		}
	}
	fmt.Printf("Most common: %s (%d)\n", bestLetter, bestCount) // A (3)
}

Time: O(n) · Extra space: O(k). One pass over n letters; the tally only needs one box per different letter (k), at most 26 for plain English.

Watch out for

  • Reading $freq[$ch] before it exists. In PHP use ?? 0 so an unseen letter starts at zero instead of raising a notice.
  • Forgetting that "A" and "a" are different characters. Lower-case the text first if you want them to count together.

Quick check

  1. After counting "BANANA", what is the tally for N?
    • 3
    • 2
    • 1
  2. How many times do we walk over the string?
    • Once per different letter
    • Twice
    • Once
  3. Why is a tally (map) better than counting each letter separately?
    • It avoids re-scanning the string for every letter
    • It uses no memory
    • It sorts the letters