Hash Tables
Frequency Count
Walk a sequence and count occurrences of each value in a map. Classic "get current count, add one, write back" loop.
Algorithm
Canonical input
["fig", "apple", "fig", "pear", "apple", "fig"] produces the final map
{fig: 3, apple: 2, pear: 1}.
Basic Implementation
basic.cs
using System;
using System.Collections.Generic;
class Program {
static void Main() {
string[] words = new string[] { "fig", "apple", "fig", "pear", "apple", "fig" };
Dictionary<string, int> counts = new Dictionary<string, int>();
List<string> order = new List<string>();
for (int i = 0; i < words.Length; i++) {
string word = words[i];
if (!counts.ContainsKey(word)) {
order.Add(word);
counts[word] = 1;
} else {
int prev = counts[word];
counts[word] = prev + 1;
}
}
Console.Write("{");
for (int i = 0; i < order.Count; i++) {
if (i > 0) {
Console.Write(", ");
}
string key = order[i];
Console.Write(key + ": " + counts[key]);
}
Console.WriteLine("}");
}
}
Complexity
- Time: O(n) average with
Dictionary<string, int>. - Space: O(k) where k is the number of distinct keys.
Implementation notes
- C#:
Dictionary<string, int> counts = new Dictionary<string, int>();is the idiomatic map; thecounts.ContainsKey(word)predicate plus an explicit assignment keeps the lesson on the read-or-default path without hiding it behindTryGetValueor LINQ groupings. - The auxiliary
orderlist preserves first-seen order so the final printout is deterministic —Dictionary<,>iteration order is not a contract you can rely on. - The replay renders the map as a list of key/value rows in first-seen order and animates the count increment on each frame.
get-or-default
A first-time `word` triggers the "default" branch: append to `order` and set `counts[word] = 1`. A repeat read-modify-writes `counts[word] = prev + 1`.
first-seen order
Keys are tracked in `order` (a `List<string>`) to keep the printout deterministic; C#'s `Dictionary<TKey, TValue>` iteration order is implementation-defined.