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

Framing

When solving character frequency problems, the first implementation decision is: frequency array (int freq[26]) or hash map (unordered_map<char,int>)? Both are O(1) for access, both solve the same Phase 1 problem, but they differ significantly in performance, memory, flexibility, and determinism. This synthesis compares them across the dimensions that matter in coding interviews and competitive programming.

Comparison

DimensionFrequency ArrayHash Map
Access timeTrue O(1) — single CPU instructionAverage O(1) — hash + possible chain walk
Worst-caseO(1) alwaysO(n) with hash collisions
MemoryFixed O(|Σ|) — e.g., 104 bytes for 26 intsO(m) where m = distinct keys, but higher per-entry overhead
Character rangeMust be known and small (e.g., a–z)Any hashable type — char, string, int, custom
ASCII mathRequires ch - 'a' and i + 'a'None — direct key usage
Iteration orderDeterministic (0–25 index order)Non-deterministic (bucket layout)
Sparse dataWastes iteration over empty slotsOnly visits present entries
Stack vs heapStack allocation (fast, no fragmentation)Heap allocation (slower, may fragment)
Implementation complexityTrivial — 1 line declarationSlightly more — need #include <unordered_map>
RehashingNeverAmortized O(n) when load factor exceeded

When to Choose Each

Choose frequency array when:

  • The problem guarantees a limited character set (e.g., “string of lowercase letters”)
  • Maximum performance is required (time-critical section, embedded systems)
  • Deterministic output order is needed (alphabetical by default)
  • Memory is constrained and the domain is small

Choose hash map when:

  • The character set is unknown or mixed (uppercase, digits, symbols)
  • Keys are not characters (word frequencies, integer frequencies)
  • The input is sparse over a large domain (better memory for few distinct keys)
  • The problem involves Unicode or extended character sets

Insights Beyond Individual Concepts

The array-vs-map choice reveals a deeper principle in software engineering: the best data structure depends on the constraints of the problem, not on abstract asymptotic analysis. Both are “O(1)” but the constants differ by orders of magnitude. A naive preference for maps (because they are more flexible) misses the performance advantage of arrays, and a naive preference for arrays (because they are faster) misses the flexibility advantage of maps.

The interview answer that demonstrates mastery is the conditional one: “It depends on the character range.” This shows the candidate understands the tradeoffs rather than having memorized a rule.

Connections