Design and Analysis of AlgorithmsUnit 910 min read
Advanced Topics: Huffman Coding & Matrix Chain Multiplication
Unit 9 of Design and Analysis of Algorithms covers two key advanced algorithmic techniques: Huffman Coding (optimal prefix-free compression) and Matrix Chain Multiplication (dynamic programming for minimizing scalar multiplications), with real-world applications in data compression and computational efficiency.
Key Concepts & Definitions
1. Huffman Coding: Optimal Prefix-Free Compression
Core Idea
Huffman coding is a greedy algorithm that assigns variable-length codes to input characters based on their frequency, ensuring the most frequent characters get the shortest codes. It guarantees the minimum expected code length for a given set of frequencies.
How It Works
- Build a Binary Tree:
- Start with a leaf node for each character, labeled with its frequency.
- Repeatedly combine the two least frequent nodes into a new internal node (sum of their frequencies) until only one tree remains.
- Assign Codes:
- Traverse the tree from root to leaf: left edge =
0, right edge =1. - The path from root to leaf gives the binary code for the character.
- Traverse the tree from root to leaf: left edge =
Why Prefix-Free?
Prefix-free codes ensure no code is a prefix of another, eliminating ambiguity during decoding. Huffman codes are optimal (no other prefix-free code can give a shorter expected length).
Visual: Huffman Tree Construction
graph TD
A["Root"] --> B["a(30)"]
A --> C["b(20)"]
A --> D["c(25)"]
A --> E["d(15)"]
A --> F["e(35)"]
C --> G["b(20)"]
C --> H["d(15)"]
G --> I["b(20)"]
H --> J["d(15)"]
D --> K["c(25)"]
K --> L["c(25)"]
F --> M["e(35)"]
M --> N["e(35)"]State After Step 3 (Combining d and b):
graph TD
A["Root"] --> B["a(30)"]
A --> C["b+d(35)"]
A --> D["c(25)"]
A --> E["e(35)"]
C --> F["b(20)"]
C --> G["d(15)"]In the Real World
WhatsApp Messages:
- Uses Huffman-like compression (or similar variable-length encoding) to reduce the size of text messages before transmission, saving bandwidth and reducing data costs for users.
eSewa & Khalti Transactions:
- When you send money via eSewa, the app compresses the transaction data (including recipient details, amount, and metadata) using Huffman coding (or related techniques) to minimize the data sent over the network, speeding up processing.
YouTube Video Compression:
- YouTube’s video encoding pipeline uses Huffman coding (alongside other entropy coding methods like arithmetic coding) to compress video frames. For example, frequent pixel patterns (like skies or walls) get shorter codes, while rare patterns (like fast-moving objects) get longer ones.
Nepal Stock Exchange (NEPSE) Data:
- NEPSE’s trading platform processes thousands of stock transactions per second. Matrix chain multiplication optimizes how the system groups and processes matrix-like data (e.g., order books or portfolio matrices) to minimize computational overhead.
Worked Example: Huffman Coding for "SUPER DUPER CSIT"
Step 1: Calculate Frequencies
Assume the string is: S U P E R D U P E R C S I T
(Spaces are treated as a character too. Frequencies after counting:)
| Character | Frequency |
|---|---|
| S | 2 |
| U | 2 |
| P | 2 |
| E | 3 |
| R | 2 |
| (space) | 2 |
| D | 1 |
| C | 1 |
| I | 1 |
| T | 1 |
Step 2: Build the Huffman Tree
- Combine
D,C,I,T(all frequency 1) pairwise:D(1) + C(1) = DC(2)I(1) + T(1) = IT(2)
- Now combine
DC(2)andIT(2)→DCIT(4) - Combine
DCIT(4)with the next smallest (S,U,P,R,(space)all 2):DCIT(4) + S(2) = DCITS(6)
- Repeat until one tree remains.
Final Huffman Tree (Partial):
graph TD
A["Root(20)"] --> B["E(3)"]
A --> C["DCITS(14)"]
C --> D["DCIT(4)"]
C --> E["SUR(6)"]
D --> F["D(1)"]
D --> G["C(1)"]
D --> H["I(1)"]
D --> I["T(1)"]
E --> J["S(2)"]
E --> K["U(2)"]
E --> L["R(2)"]Step 3: Assign Codes
| Character | Huffman Code |
|---|---|
| E | 0 |
| D | 1000 |
| C | 1001 |
| I | 1010 |
| T | 1011 |
| S | 110 |
| U | 1110 |
| R | 1111 |
| (space) | 11110 |
Total Bits for "SUPER DUPER CSIT":
Original (ASCII, 8 bits/char): 16 chars × 8 = 128 bits
Huffman-encoded: S(110) + U(1110) + P(1111) + E(0) + R(1111) + ... = 72 bits
Compression Ratio: ~44% savings!
Matrix Chain Multiplication (MCM): Dynamic Programming Approach
Core Idea
Given a sequence of matrices , where has dimensions , the goal is to parenthesize the product to minimize the number of scalar multiplications.
Key Insight: The cost of multiplying two matrices and is . Parenthesization changes the order of multiplications, affecting the total cost.
Visual: Matrix Multiplication Cost
For matrices , , :
- : Cost =
- : Cost = Optimal: (cheaper by 1750 multiplications!)
Dynamic Programming Solution
Algorithm Steps
Define Subproblems: Let = minimum cost to multiply matrices to . Let = optimal split point between and .
Base Case: (no cost to multiply a single matrix).
Recurrence: For : that minimizes the above.
Fill Tables: Compute for all in a bottom-up manner.
Example: , , ,
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 0 | 750 | 2250 | 15000 |
| 2 | - | 0 | 3000 | 12000 |
| 3 | - | - | 0 | 6000 |
| 4 | - | - | - | 0 |
Optimal Parenthesization:
- (split at : )
- (split at : )
- (split at : )
Final Parenthesization:
Code Implementation (Python)
def matrix_chain_order(p):
n = len(p) - 1
m = [[0 for _ in range(n+1)] for _ in range(n+1)]
s = [[0 for _ in range(n+1)] for _ in range(n+1)]
for length in range(2, n+1): # length of chain
for i in range(1, n-length+2):
j = i + length - 1
m[i][j] = float('inf')
for k in range(i, j):
cost = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
if cost < m[i][j]:
m[i][j] = cost
s[i][j] = k
return m, s
# Example usage:
p = [5, 10, 15, 20, 30] # Dimensions: A(5×10), B(10×15), C(15×20), D(20×30)
m, s = matrix_chain_order(p)
print("Minimum cost:", m[1][4]) # Output: 15000
Trace of the Algorithm
| Step | Cost Calculation | |||||||
|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 2 | 1 | 0 | 0 | 750 | 1 | |
| 2 | 2 | 3 | 2 | 0 | 0 | 3000 | 2 | |
| 3 | 1 | 3 | 1 | 750 | 3000 | 2250 | 1 | |
| 4 | 3 | 4 | 3 | 0 | 0 | 9000 | 3 | |
| 5 | 1 | 4 | 1 | 2250 | 9000 | 15000 | 1 | |
| 6 | 1 | 4 | 2 | 750 | 6000 | 15000 | 1 | |
| 7 | 1 | 4 | 3 | 2250 | 0 | 15000 | 1 |
Comparison: Huffman Coding vs. Other Compression Methods
| Method | Prefix-Free? | Optimality | Complexity | Use Case |
|---|---|---|---|---|
| Huffman Coding | Yes | Optimal | Text, small alphabets | |
| Arithmetic Coding | Yes | Optimal | High-precision compression | |
| LZW (Lempel-Ziv) | No | Suboptimal | GIF, TIFF, Unix compression | |
| Run-Length Encoding | No | Suboptimal | Simple patterns (e.g., fax) |
Exam Tip
Huffman Coding:
- Always sort frequencies before building the tree.
- For equal frequencies, combine any two (order doesn’t matter).
- Prefix-free is critical—never assign codes that are prefixes of others.
- Exam Pitfall: Forgetting to include all characters (even rare ones) in the tree.
Matrix Chain Multiplication:
- Memoization vs. DP: The DP table (
m[i][j]) is filled bottom-up; never top-down like recursion. - Parenthesization: The
s[i][j]table tracks splits. Always reconstruct the solution froms[i][j]. - Example Trick: For , , , the optimal is always (since ).
- Memoization vs. DP: The DP table (
Common Questions:
- "Distinguish DP and Memoization": DP is bottom-up (table-driven), memoization is top-down (recursive with caching).
- "Optimal Solution": In MCM, it’s the minimum scalar multiplications; in Huffman, it’s the shortest expected code length.
- "Greedy vs. DP": Huffman is greedy (locally optimal at each step), but DP (like MCM) requires global optimization.
Practice Problems
Huffman Coding: Given frequencies:
a:5, b:9, c:12, d:13, e:16, f:45.- Build the Huffman tree.
- Assign codes to
a,b,c. - Calculate the total bits for the string
"abacabadababa".
Matrix Chain Multiplication: For matrices , , , :
- Compute the minimum cost.
- Find the optimal parenthesization.
- Verify by calculating costs for all possible parenthesizations.
Theoretical:
- Why is Huffman coding not used for compressing images with many colors?
- Can MCM be solved with a greedy approach? Justify.
Based on the TU BSc CSIT syllabus for Design and Analysis of Algorithms (CSC314), unit 9.
Discussion
Loading…