Word frequency counter
Count how often each word appears in a sentence, ignoring punctuation and letter case.
Course progress
Problem 30 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
text = "Code, test, code, learn."
Expected output
code: 2 test: 1 learn: 1
What is happening?
Normalize words to lowercase and ignore punctuation. Code appears twice, while test and learn each appear once.
Solution strategy
Build the right mental model
Extract word-like sequences with a regular expression, normalize them to lowercase, and increment their dictionary counts.
Core concepts
dictionary · text processing
Complexity
Time O(n), space O(k), where k is the number of distinct words.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for word-frequency
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
static Dictionary<string, int> CountWords(string text)
{
var counts = new Dictionary<string, int>();
foreach (Match match in Regex.Matches(text.ToLowerInvariant(), @"[a-z0-9']+"))
{
int count;
counts.TryGetValue(match.Value, out count);
counts[match.Value] = count + 1;
}
return counts;
}
static void Main()
{
foreach (var pair in CountWords("Code, test, code, learn."))
Console.WriteLine(pair.Key + ": " + pair.Value);
}
}Knowledge check
Questions students often ask
What is the main idea behind word frequency counter?
Extract word-like sequences with a regular expression, normalize them to lowercase, and increment their dictionary counts.
What is the time and space complexity of this solution?
Time O(n), space O(k), where k is the number of distinct words.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.