Frequency counting
Beginner · 7 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Frequency counting means going through your data once and keeping a tally per distinct value, usually in a hash map. Once the tally is done, any question like "how many times did this appear?" is answered instantly.
Practical use cases
- Web app: Live poll results. A poll page shows how many people picked each option. Rather than recounting all votes on every refresh, the server keeps a counter per option and adds one on each vote. The result bars update immediately even with 1 lakh votes.
- Web app: Top search terms on an admin dashboard. A shop owner wants to see the most searched words this week. The code reads the search log once, adding one to a counter for each word, and then shows the highest few. The owner sees the answer immediately instead of waiting for a slow query.
- Web app: Anagram check in a word game. A word game asks whether two words use exactly the same letters. The code counts letters in the first word, subtracts for the second, and checks that all counts reach zero. This is much faster than trying every rearrangement, so the game can check hundreds of guesses per second without lag.
- System: Log analysis for errors. Operations teams count how often each error code appears in server logs. A sudden jump in one code, for example 500 errors, flags an outage right away. The tally on the dashboard makes the spike stand out without anyone reading thousands of lines.
The story: Raju's Tally Wall
At the end of every day Raju wanted to know which snack had sold the most. He had a long slip of paper listing every order: chai, samosa, chai, vada, chai... hundreds of lines. Counting them by hand, he would circle every chai, then every samosa, going over the whole list again for each snack. By the time he finished, the tea had gone cold.
Mira stopped by with a better idea. "Raju bhaiya, read the slips only once. Keep a wall with a chalk tally for each snack. When you read 'chai', go to the chai tally and add one. If it is a snack you have never seen, start a new tally at one."
Raju read the whole list in a single pass, and the wall showed: chai 3, samosa 2, vada 1. The wall was a hash map from item to count, and the trick is called frequency counting. Finding the winner was easy afterwards: just look at which tally is the biggest.
How to spot this problem, and where you need it
You need to know how many times each thing appears, or whether two collections contain the same things, and counting by rescanning is too slow.
Signs you need it
- The task says "most frequent", "count of each", "how many times", "same characters" or "majority element".
- You catch yourself counting the same value again and again with nested loops or repeated COUNT queries.
- A report loops through all rows for each category to total it up and the page becomes slower with more data.
Where to use it in a project
- Dashboards showing top products, top pages, popular tags, or most common errors.
- Validation features such as anagram checks, duplicate-word detection and checking if two lists have the same members.
The solution
Create an empty map from value to count. Walk through your data once. For each item, add one to its count, creating the entry at 1 if it is new. When finished, the map holds every tally. To answer a question, look up the key; to find the most frequent, scan the map once. For letters only, a plain array of 26 counters works even faster.
Payoff: Before: counting each value separately, up to 1 million checks per question. After: one pass, then each answer is a single lookup.
Explain it like I am 8
Imagine sorting a bag of coloured beads. Instead of picking colours again and again, you put out one cup for each colour and drop every bead in its cup as you go. When you are done, count what is in each cup.
How it works, step by step
- Start with an empty map (the tally).
- Go through the items once.
- For each item: if it is in the map, add one to its count; if not, set it to 1. (In code:
count[x] = (count[x] ?? 0) + 1.) - After the pass, the map holds how often every item appeared.
- To find the most frequent item, scan the map (or keep a "best so far" while counting).
The code in four languages
PHP
<?php
// Count how often each word appears, in one pass.
function countFrequency(array $items): array {
$counts = [];
foreach ($items as $x) {
$counts[$x] = ($counts[$x] ?? 0) + 1; // start at 0 if unseen, then add one
}
return $counts;
}
$orders = ['chai', 'samosa', 'chai', 'vada', 'chai', 'samosa'];
$counts = countFrequency($orders);
foreach ($counts as $item => $n) echo "$item: $n\n";
// Most popular item
arsort($counts); // biggest count first
echo 'Most popular: ' . array_key_first($counts) . "\n"; // chai
JavaScript
// Count how often each word appears, in one pass.
function countFrequency(items) {
const counts = new Map();
for (const x of items) {
counts.set(x, (counts.get(x) ?? 0) + 1); // start at 0 if unseen, then add one
}
return counts;
}
const orders = ['chai', 'samosa', 'chai', 'vada', 'chai', 'samosa'];
const counts = countFrequency(orders);
for (const [item, n] of counts) console.log(item + ': ' + n);
// Most popular item
let best = null;
for (const [item, n] of counts) if (best === null || n > counts.get(best)) best = item;
console.log('Most popular: ' + best); // chaiJava
import java.util.*;
public class Main {
// Count how often each word appears, in one pass.
static Map<String, Integer> countFrequency(String[] items) {
Map<String, Integer> counts = new LinkedHashMap<>(); // keeps first-seen order for printing
for (String x : items) {
counts.put(x, counts.getOrDefault(x, 0) + 1); // start at 0 if unseen, then add one
}
return counts;
}
public static void main(String[] args) {
String[] orders = {"chai", "samosa", "chai", "vada", "chai", "samosa"};
Map<String, Integer> counts = countFrequency(orders);
for (Map.Entry<String, Integer> e : counts.entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
// Most popular item
String best = null;
for (String item : counts.keySet()) {
if (best == null || counts.get(item) > counts.get(best)) best = item;
}
System.out.println("Most popular: " + best); // chai
}
}Go
package main
import "fmt"
// countFrequency counts how often each word appears, in one pass.
// It also returns the words in first-seen order so printing is predictable.
func countFrequency(items []string) (map[string]int, []string) {
counts := map[string]int{}
var order []string
for _, x := range items {
if _, seen := counts[x]; !seen {
order = append(order, x)
}
counts[x]++ // a missing key counts as 0, then add one
}
return counts, order
}
func main() {
orders := []string{"chai", "samosa", "chai", "vada", "chai", "samosa"}
counts, order := countFrequency(orders)
for _, item := range order {
fmt.Printf("%s: %d\n", item, counts[item])
}
// Most popular item
best := ""
for _, item := range order {
if best == "" || counts[item] > counts[best] {
best = item
}
}
fmt.Println("Most popular:", best) // chai
}Time: O(n) · Extra space: O(k). One pass over n items with a quick map update each, and the map holds only the k different items.
Watch out for
- Forgetting to initialise a new key to 0 (or 1), leading to a warning or a broken total.
- Counting with nested loops (for each item, scan everything) which costs O(n²).
- Using an object as a map with keys like
"constructor"in JavaScript; preferMapfor arbitrary keys.
Quick check
- How many passes over the data does frequency counting need?
- One
- One per distinct item
- Two per item
- What do you do when you meet an item you have not seen before?
- Ignore it
- Add it to the map with count 1
- Sort the map
- What are the keys and values in the map?
- Count as key, item as value
- Item as key, count as value
- Position as key, item as value