DSAVisualiseData Structures & Algorithms Studio
Chapter 06 · trie, string-hashing, substring-search, compression

Strings & Compression

String algorithms exploit prefix overlap, rolling polynomial arithmetic, and frequency-based prefix codes to search, index, and compress textual data efficiently. Tries store shared prefixes across dictionaries; Rabin-Karp searches patterns via rolling hashes; Huffman coding constructs optimal prefix-free variable-length codes.

Key Invariants & Rules

  • In a Trie, all descendants of a node share the common string prefix associated with that node.
  • Terminal trie flags indicate valid dictionary words independent of tree depth.
  • Rabin-Karp updates its rolling window hash in O(1) arithmetic: hash = (hash - leading·B^(M-1))·B + trailing.
  • Huffman trees are prefix-free: no character code is a prefix of any other character code.
  • Huffman PriorityQueue merges the two least-frequent subtrees at each step until a single root remains.

Must-Know Algorithms

Trie AutocompleteO(L) insert/search where L is word length

Tree of character transitions finding prefix completions in time independent of dictionary size.

Rabin-Karp SearchO(N+M) avg time, O(1) rolling step

Rolling hash algorithm comparing text windows in constant time.

Huffman CompressionO(N log K) build time for alphabet size K

Greedy optimal prefix code minimizing expected bit length based on character frequency.

Learning Path (4 Lessons)

Self-Check & Concept Review

1. Why does Rabin-Karp check full string equality when a hash match occurs?

Different substrings can yield the exact same hash modulo Q; checking characters confirms a true match.

2. What ensures that Huffman codes can be uniquely decoded without delimiter characters between symbols?

Because every symbol is a leaf in the Huffman tree, reading bits from root to leaf uniquely identifies each character without ambiguity.

3. In an R-way Trie with alphabet size R, what is the search time for a key of length L?

Search follows one child pointer per character in the key, examining at most L transitions regardless of total words in the trie.

4. How does rolling hash subtraction maintain positive modulo values in Java integer arithmetic?

In Java % is remainder; adding Q ensures the operand is positive before wrapping.

5. In Huffman coding, which symbols receive the shortest bit sequences?

Huffman assigns shorter bit codes to higher-frequency symbols to minimize expected weighted bit length.