• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

Formal Definition

An unordered map (hash map) for frequency counting uses std::unordered_map<Key, int> where each key is an element from the input and the mapped value is its occurrence count. Unlike a frequency array, the map only stores entries for elements that actually appear, and keys can be of any hashable type.

Explanation

When the character range is unknown, large, or non-contiguous (e.g., mixed case, digits, Unicode), a frequency array becomes impractical. An unordered_map<char, int> stores only the characters that actually appear, with no ASCII math needed — freq[ch] works directly. The tradeoff is hashing overhead, potential collisions, and non-deterministic iteration order.

How It Works

  1. Declare unordered_map<char, int> freq
  2. Iterate through the string: for(char ch : s) { freq[ch]++; }
  3. The map automatically creates new key-value pairs for new characters
  4. To query: iterate key-value pairs or check specific keys
  5. No conversion needed — character is used as the key directly

Visual Explanation

unordered_map_freq INPUT Input: 'banana' MAP unordered_map<char,int> {} (empty) INPUT->MAP B freq['b']++ {b:1} MAP->B A freq['a']++ {a:1, b:1} B->A N freq['n']++ {a:1, b:1, n:1} A->N FINAL Final: {a:3, b:1, n:2} N->FINAL

Semantic Network

semantic_unordered_map THIS Unordered Map Frequency PRE1 Hash Map Flexibility THIS--PRE1 built from PRE2 Hash Collision Overhead THIS--PRE2 built from OUT1 Two-Phase Hashing THIS--OUT1 builds into OUT2 Anagram Detection THIS--OUT2 builds into CON1 Frequency Array THIS--CON1 contrasts with REL1 ASCII Math Elimination THIS--REL1 related REL2 Map Traversal Method THIS--REL2 related

Key Properties

  • Average O(1) insertion and lookup (amortized, may degrade to O(n) with collisions)
  • Only stores distinct elements — memory proportional to unique characters, not domain size
  • Keys can be any hashable type: char, string, int, long long
  • No ch - 'a' conversion needed — eliminates ASCII math entirely
  • Iteration order is unspecified and non-deterministic

Connections

Edge Cases & Gotchas

  • freq[ch]++ creates an entry with value 0 if the key does not exist, then increments — no manual insertion needed
  • Repeated insertions may trigger rehashing, which is O(n) amortized but can be a latency spike
  • unordered_map is not ordered — if you need sorted output, use map (O(log n) per operation) or sort the result
  • For small datasets (like lowercase-only strings), a map is slower than a frequency array despite both being O(1) — the constant factors matter
  • Memory per entry is higher than an array slot due to key storage, hash table overhead, and pointer chains