BITS Pilani
CS F364: Design and Analysis of Algorithms

Matrix Chain Multiplication

Lecture 11 |2026-06-04

Matrix Chain Multiplication

  • Matrix Chain Multiplication
  • RNA Secondary Structure Prediction

Recap: Dynamic Programming so far

Lecture 10 introduced DP — two key ideas:

Concept Fibonacci LCS
Subproblems F_1,\dots,F_n C[i,j] for prefixes
Recurrence F_n = F_{n-1}+F_{n-2} C[i,j] = \dots from substrings
Table 1D array 2D matrix
Time O(n) O(mn)

Both rely on optimal substructure and overlapping subproblems — we’ll see the same pattern in today’s new problems.

Where does the name come from?

  • In the 1950s, Richard Bellman was developing a theory for multistage decision processes at the RAND Corporation.

  • The Secretary of Defense, Charles Wilson, had “a pathological fear and hatred of the word, research” — he would turn red and get violent if anyone used it in his presence.

  • RAND was employed by the Air Force, which Wilson headed. Bellman needed a name that described time-varying, multistage optimization — but wouldn’t trigger Washington.

“Thus, I thought dynamic programming was a good name. It was something not even a Congressman could object to. So I used it as an umbrella for my activities.”Richard Bellman, Eye of the Hurricane (1984)

Matrix Multiplication Review

Matrix: An p\times q array of numbers with p rows and q columns.

Product: C = A_{p\times q} \times B_{q\times r} produces a p\times r matrix where: c[i,j] = \sum_{k=1}^{q} a[i,k]\cdot b[k,j]

Cost: Each of the pr entries needs \Theta(q) operations → \Theta(pqr) total.

Parenthesization Matters

Matrix multiplication is associative: (AB)C = A(BC) — the result is the same regardless of grouping.

However, the cost is not the same!

A(5\times4),\; B(4\times6),\; C(6\times2)

  • (AB)C: (5\cdot4\cdot6) + (5\cdot6\cdot2) = 120 + 60 = \mathbf{180}
  • A(BC): (4\cdot6\cdot2) + (5\cdot4\cdot2) = 48 + 40 = \mathbf{88}

The cheaper order is 2\times faster!

Key observation: Choosing the right parenthesization can drastically reduce computation cost.

Matrix Chain Multiplication — Problem

Given: n matrices A_1,\dots,A_n with dimensions p_{i-1}\times p_i.

Goal: Find the parenthesization of A_1A_2\cdots A_n that minimizes the number of scalar multiplications.

Example: A_1(5\times4), A_2(4\times6), A_3(6\times2)

  • (A_1A_2)A_3: 5\cdot4\cdot6 + 5\cdot6\cdot2 = 120+60 = 180
  • A_1(A_2A_3): 4\cdot6\cdot2 + 5\cdot4\cdot2 = 48+40 = 88

Key insight: Parenthesization matters — costs can differ by 2\times or more!

Why Exhaustive Search Fails

The number of distinct parenthesizations of n matrices is the Catalan number: C_{n-1} = \frac{1}{n}\binom{2n-2}{n-1} \;\sim\; \frac{4^{n-1}}{(n-1)^{3/2}\sqrt{\pi}}

  • n=10: 4,862 — slow but manageable
  • n=20: 1.8 \times 10^9 — brute-force infeasible
  • n=30: 3.8 \times 10^{15} — exceeds CPU speeds

Recurrence: P(1)=1, P(n)=\sum_{k=1}^{n-1} P(k)\,P(n-k)

DP approach: O(n^3) — polynomial instead of exponential!

DP: Optimal Substructure

Key idea: In the optimal parenthesization of A_i A_{i+1}\cdots A_j, the last multiplication splits at some k: A_{i\dots j} = A_{i\dots k}\; A_{k+1\dots j},\qquad \text{each optimally parenthesized}

  • The sub-chains A_{i\dots k} and A_{k+1\dots j} must themselves be optimally parenthesized (cut-and-paste argument).
  • Result A_{i\dots j} has dimension p_{i-1}\times p_j.

A_{3\dots6} = (A_3(A_4A_5))(A_6) → split at k=5

DP: The Recurrence

Let m[i,j] = minimum cost to compute A_{i\dots j}. We try all possible split points k:

m[i,j] = \begin{cases} 0 & i=j,\\[6pt] \min\limits_{i\le k<j}\big(m[i,k] + m[k+1,j] + p_{i-1}p_kp_j\big) & i<j \end{cases}

Cost breakdown:

  • Left subproblem: m[i,k]
  • Right subproblem: m[k+1,j]
  • Combine: p_{i-1} \times p_k \times p_j

Base case: m[i,i] = 0

— single matrix, no multiplication needed.

DP: Table Structure

We fill m[i,j] for increasing chain length l = 2, 3, \dots, n:

l=2:   m[1,2]  m[2,3]  m[3,4]  ...
l=3:   m[1,3]  m[2,4]  m[3,5]  ...
l=4:   m[1,4]  m[2,5]  m[3,6]  ...
...
l=n:   m[1,n]
  • For each m[i,j], evaluate all k in [i, j-1]
  • Store the optimal split s[i,j] = k for reconstruction
  • O(n^2) entries, each taking O(n) time → O(n^3) total

Complexity Analysis

DP vs. Exhaustive Search:

Approach Time Space
Brute-force (Catalan) \Omega(4^n / n^{3/2})
Dynamic Programming \Theta(n^3) \Theta(n^2)

Why O(n^3)?

  1. Outer loop: chain length l = 2 to nO(n)
  2. Middle loop: start index iO(n)
  3. Inner loop: split point kO(n)
  4. Constant work per (i,k) pair

Key takeaway: Exponential \to polynomial — DP turns an infeasible problem into a practical one.

DP Complexity Progression

MCM introduces a fundamentally more complex DP structure:

Problem Table Dims Time What’s new
Fibonacci 1D: F[n] O(n) memoization
LCS 2D: C[i,j] O(mn) 2D table
MCM 2D m[i,j] O(n^3) interval DP, \min over k

Interval DP problem: subproblems are contiguous intervals [i,j], and we try all split points k. The extra loop over k adds a third dimension to the computation — this is a powerful pattern for many problems (Optimal BST, polygon triangulation, etc.).

Reconstructing Parenthesization

We store s[i,j] = the optimal split k for A_{i\dots j}. Recurse to print:

Print-Parens(s, i, j):
    if i == j: print "A" + i
    else:
        print "("
        Print-Parens(s, i, s[i,j])
        Print-Parens(s, s[i,j]+1, j)
        print ")"

RNA Secondary Structure Prediction

  • Matrix Chain Multiplication
  • RNA Secondary Structure Prediction

Basic Biology

  • In 1953, James Watson and Francis Crick proposed that DNA is shaped like a double helix.

  • The two strands of the DNA double helix are held together by hydrogen bonds between nitrogenous bases on opposite strands.

  • Bases: \{A, C, T, G\}.

  • Pairing: A-T, G-C.

From DNA to RNA

image

Various types of RNA:

  • messenger RNA (mRNA)

  • transfer RNA (tRNA)

  • Ribosomal RNA (rRNA)

  • micro RNA (miRNA)

  • so on...

Basics of RNA

  • RNA is a basic biological molecule. It is single stranded (unlike the double helix of DNA).

  • DNA has a fixed, stable double-helix structure — its shape is always the same.

  • RNA folds back on itself, forming base pairs between complementary bases on the same strand. This folding produces a secondary structure — and this structure varies depending on the RNA sequence.

  • The secondary structure of an RNA molecule often governs its biological function (e.g., ribozymes, tRNA cloverleaf, regulatory elements).

  • Goal: Given an RNA sequence, predict its secondary structure — i.e., determine which bases pair up when it folds.

Rules for RNA secondary structure formation

  • Pairs of bases match up; each base matches with one other base.

  • Adenine always matches with Uracil.

  • Cytosine always matches with Guanine.

  • There are no kinks in the folded molecule.

  • Structures are knot-free.

image

Problem Formulation

Problem Given a single stranded RNA molecule, determine a secondary structure with the maximum possible number of base pairs.

Notation: A single stranded RNA molecule is a string B = b_1b_2...b_n where each b_i\in\{A, C, G, U\}.

A secondary structure on B is a set S of pairs (i, j) where 1\leq i, j\leq n, following the rules below.

Rules for a secondary structure formation

  • [No sharp turn] The ends of each pair are separated by at least 4 interleaving bases. i.e, if (i,j)\in S then i< j-4.

  • The elements of each base pair in S consist of either \{A, U\} or \{G, C\} (in either order).

  • S is a matching: no base appears in more than one pair.

  • [No knots] If (i, j) and (k, l) are two pairs in S, then we cannot have i<k<j<l.

A different view of secondary structure

The energy of a secondary structure is proportional to the number of base pairs in it.

image

Algorithm: Approach-1

  1. Let OPT(j) be the maximum number of base pairs in a secondary structure for b_1b_2...b_j. OPT(j) = 0, if j\leq 5.

  2. In the optimal secondary structure on b_1b_2...b_j:

    • If j is not a member of any pair, use OPT(j-1).

    • If j makes a pair with some t< j-4, knot condition yields two independent subproblems! One is OPT(t-1), Other ??

Visualization of the problem

image

Algorithm: Correct Approach

  • Let OPT(i,j) be the maximum number of base pairs in a secondary structure for b_ib_{i+1}...b_j. Clearly, OPT(i,j) = 0 if i\geq j-4.

  • In the optimal secondary structure on b_ib_{i+1}...b_j:

    • If j is not a member of any pair, use OPT(i, j-1).

    • If j pairs with some t< j-4, knot condition yields to independent subproblems! One is OPT(i, t-1), and the other is OPT(t+1, j-1).

  • Recurrence: OPT(i,j) = \max\begin{cases} OPT(i, j-1) & \text{$j$ is unpaired},\\[4pt] \max\limits_{\substack{t < j-4 \\ (b_t,b_j)\text{ pairs}}} \big(OPT(i, t-1) + 1 + OPT(t+1, j-1)\big) & \text{$j$ pairs with $t$} \end{cases}

Algorithm Complexity

  • Number of subproblems: O(n^2) — one for each pair (i,j).

  • Work per subproblem:

    • Either skip j (constant time), or try all possible t < j-4 where b_t pairs with b_j.
    • In the worst case, O(n) per subproblem.
  • Total time: O(n^3).

  • Space: O(n^2) for the DP table.