Skip to main content

Master Solved Algorithms

TITLE

Step-by-Step Solved Algorithms Guide (Unit 1 to Unit 7)​

EXAM MASTER STRATEGY

This guide provides complete, step-by-step numerical solutions accompanied by visual graphs, state-space trees, and automata for every algorithm across all 7 units of Design and Analysis of Algorithms. Every step is broken down with one calculation per line to make revision easy and exam-ready.

Unit - 1

Basics of Algorithms and Mathematics​

1.1 Karatsuba Integer Multiplication​

1.1.1 Concept​

  • Standard grade-school multiplication takes 44 sub-multiplications for 22-digit halves.
  • Karatsuba's algorithm performs only 33 recursive multiplications.
  • The cross-term (ad+bc)(ad + bc) is obtained via the algebraic identity: Middle=(a+b)(c+d)−ac−bd\text{Middle} = (a + b)(c + d) - ac - bd

1.1.2 Problem Statement & Input​

  • Multiply two 44-digit integers:
    • X=1234X = 1234
    • Y=5678Y = 5678
  • Number of digits: n=4n = 4
  • Half-length: m=⌈n/2⌉=2m = \lceil n / 2 \rceil = 2

1.1.3 Step-by-Step Solved Walkthrough​

Step 1: Split the Numbers into Halves​
  • Number XX:
    • High half: a=⌊1234/102⌋=12a = \lfloor 1234 / 10^2 \rfloor = 12
    • Low half: b=1234(mod102)=34b = 1234 \pmod{10^2} = 34
  • Number YY:
    • High half: c=⌊5678/102⌋=56c = \lfloor 5678 / 10^2 \rfloor = 56
    • Low half: d=5678(mod102)=78d = 5678 \pmod{10^2} = 78
Step 2: Compute the Three Primary Products​
  • Product 1 (High halves product): p1=a×cp_1 = a \times c p1=12×56p_1 = 12 \times 56 p1=672p_1 = 672

  • Product 2 (Low halves product): p2=b×dp_2 = b \times d p2=34×78p_2 = 34 \times 78 p2=2652p_2 = 2652

  • Product 3 (Sum of halves product): p3=(a+b)×(c+d)p_3 = (a + b) \times (c + d) a+b=12+34=46a + b = 12 + 34 = 46 c+d=56+78=134c + d = 56 + 78 = 134 p3=46×134p_3 = 46 \times 134 p3=6164p_3 = 6164

Step 3: Compute the Middle Cross-Term​
  • Cross-term formula: Middle=p3−p1−p2\text{Middle} = p_3 - p_1 - p_2 Middle=6164−672−2652\text{Middle} = 6164 - 672 - 2652 Middle=6164−3324\text{Middle} = 6164 - 3324 Middle=2840\text{Middle} = 2840
Step 4: Assemble the Final Product​
  • Standard assembly formula: Result=p1⋅102m+Middle⋅10m+p2\text{Result} = p_1 \cdot 10^{2m} + \text{Middle} \cdot 10^m + p_2
  • Substituting values: Term1=672×104=6,720,000\text{Term}_1 = 672 \times 10^4 = 6,720,000 Term2=2840×102=284,000\text{Term}_2 = 2840 \times 10^2 = 284,000 Term3=2652\text{Term}_3 = 2652
  • Summation: Result=6,720,000+284,000+2,652\text{Result} = 6,720,000 + 284,000 + 2,652 Result=7,006,652\text{Result} = 7,006,652
Step 5: Verification​
  • Direct multiplication: 1234×5678=7,006,6521234 \times 5678 = 7,006,652
  • The result matches exactly.

1.1.4 Complexity Analysis​

  • Recurrence relation: T(n)=3T(n/2)+O(n)T(n) = 3T(n/2) + O(n)
  • By Master Theorem: a=3,b=2,log⁡23≈1.585a = 3, \quad b = 2, \quad \log_2 3 \approx 1.585
  • Time Complexity: Θ(nlog⁡23)≈O(n1.585)\Theta(n^{\log_2 3}) \approx \mathbf{O(n^{1.585})}
  • Space Complexity: O(n)\mathbf{O(n)} due to recursive call stack.

1.2 Master Theorem for Recurrence Relations​

1.2.1 Standard Form​

  • General recurrence: T(n)=aT(n/b)+f(n)T(n) = a T(n/b) + f(n)
  • Parameters:
    • a≥1a \ge 1: Number of subproblems.
    • b>1b > 1: Subproblem reduction factor.
    • f(n)f(n): Cost of dividing and combining.
  • Critical exponent: ccrit=log⁡bac_{\text{crit}} = \log_b a

1.2.2 Case 1 Example: T(n)=4T(n/2)+nT(n) = 4T(n/2) + n​

  • Parameter extraction:
    • a=4a = 4
    • b=2b = 2
    • f(n)=n=n1f(n) = n = n^1
  • Calculate critical exponent: log⁡ba=log⁡24=2\log_b a = \log_2 4 = 2
  • Compare powers:
    • Power in f(n)f(n) is c=1c = 1.
    • Critical power is 22.
    • Since 1<21 < 2, we have f(n)=O(n2−ϵ)f(n) = O(n^{2 - \epsilon}) for ϵ=1\epsilon = 1.
  • Conclusion: T(n)=Θ(nlog⁡ba)=Θ(n2)T(n) = \Theta(n^{\log_b a}) = \mathbf{\Theta(n^2)}

1.2.3 Case 2 Example: T(n)=2T(n/2)+nT(n) = 2T(n/2) + n (Merge Sort)​

  • Parameter extraction:
    • a=2a = 2
    • b=2b = 2
    • f(n)=n=n1f(n) = n = n^1
  • Calculate critical exponent: log⁡ba=log⁡22=1\log_b a = \log_2 2 = 1
  • Compare powers:
    • Power in f(n)f(n) is c=1c = 1.
    • Critical power is 11.
    • Since f(n)=Θ(nlog⁡ba)=Θ(n1)f(n) = \Theta(n^{\log_b a}) = \Theta(n^1).
  • Conclusion: T(n)=Θ(nlog⁡balog⁡n)=Θ(nlog⁡n)T(n) = \Theta(n^{\log_b a} \log n) = \mathbf{\Theta(n \log n)}

1.2.4 Case 3 Example: T(n)=2T(n/2)+n2T(n) = 2T(n/2) + n^2​

  • Parameter extraction:
    • a=2a = 2
    • b=2b = 2
    • f(n)=n2f(n) = n^2
  • Calculate critical exponent: log⁡ba=log⁡22=1\log_b a = \log_2 2 = 1
  • Compare powers:
    • Power in f(n)f(n) is c=2c = 2.
    • Critical power is 11.
    • Since 2>12 > 1, we have f(n)=Ω(n1+ϵ)f(n) = \Omega(n^{1 + \epsilon}) for ϵ=1\epsilon = 1.
  • Check Regularity Condition: af(n/b)≤kf(n)for k<1a f(n/b) \le k f(n) \quad \text{for } k < 1 2(n/2)2≤kn22 (n/2)^2 \le k n^2 2×n24≤kn22 \times \frac{n^2}{4} \le k n^2 n22≤kn2\frac{n^2}{2} \le k n^2 12≤k(Holds for k=1/2<1)\frac{1}{2} \le k \quad (\text{Holds for } k = 1/2 < 1)
  • Conclusion: T(n)=Θ(f(n))=Θ(n2)T(n) = \Theta(f(n)) = \mathbf{\Theta(n^2)}

1.3 Substitution Method (Mathematical Induction)​

1.3.1 Problem Definition​

  • Solve the recurrence: T(n)=2T(⌊n/2⌋)+nT(n) = 2T(\lfloor n/2 \rfloor) + n
  • Base case: T(1)=1T(1) = 1
  • Target:
    • Prove that T(n)=O(nlog⁡2n)T(n) = O(n \log_2 n).

1.3.2 Inductive Hypothesis​

  • Assume that for all integers k<nk < n: T(k)≤c⋅klog⁡2kT(k) \le c \cdot k \log_2 k
  • Constant c>0c > 0 will be determined.

1.3.3 Inductive Step Proof​

  • Start with the recurrence definition: T(n)=2T(n/2)+nT(n) = 2T(n/2) + n
  • Substitute the hypothesis for k=n/2k = n/2: T(n)≤2[c(n2)log⁡2(n2)]+nT(n) \le 2 \left[ c \left(\frac{n}{2}\right) \log_2\left(\frac{n}{2}\right) \right] + n
  • Simplify the constant factor: T(n)≤cnlog⁡2(n2)+nT(n) \le c n \log_2\left(\frac{n}{2}\right) + n
  • Apply logarithm quotient rule log⁡2(n/2)=log⁡2n−log⁡22\log_2(n/2) = \log_2 n - \log_2 2: T(n)≤cn(log⁡2n−1)+nT(n) \le c n (\log_2 n - 1) + n
  • Expand the bracket: T(n)≤cnlog⁡2n−cn+nT(n) \le c n \log_2 n - c n + n
  • Factor out nn: T(n)≤cnlog⁡2n−(c−1)nT(n) \le c n \log_2 n - (c - 1)n
  • For the bound T(n)≤cnlog⁡2nT(n) \le c n \log_2 n to hold, we need: −(c−1)n≤0-(c - 1)n \le 0 c−1≥0c - 1 \ge 0 c≥1c \ge 1

1.3.4 Base Case Verification​

  • Choose n=2n = 2: T(2)=2T(1)+2=2(1)+2=4T(2) = 2T(1) + 2 = 2(1) + 2 = 4
  • Check against bound: c⋅2log⁡22=2cc \cdot 2 \log_2 2 = 2c
  • Requirement: 4≤2c  ⟹  c≥24 \le 2c \implies c \ge 2
  • Choosing c=2c = 2 satisfies both the base case and the inductive step.
  • Conclusion: T(n)=O(nlog⁡n)T(n) = \mathbf{O(n \log n)}

1.4 Recursion Tree Method​

1.4.1 Recurrence Relation​

  • Recurrence: T(n)=2T(n/2)+cnT(n) = 2T(n/2) + cn

1.4.2 Tree Level Costs​

  • Level 0 (Root node):
    • Number of nodes: 20=12^0 = 1
    • Size of subproblem: nn
    • Cost per node: cncn
    • Total level cost: 1×cn=cn1 \times cn = cn
  • Level 1:
    • Number of nodes: 21=22^1 = 2
    • Size of subproblem: n/2n/2
    • Cost per node: c(n/2)c(n/2)
    • Total level cost: 2×c(n/2)=cn2 \times c(n/2) = cn
  • Level 2:
    • Number of nodes: 22=42^2 = 4
    • Size of subproblem: n/4n/4
    • Cost per node: c(n/4)c(n/4)
    • Total level cost: 4×c(n/4)=cn4 \times c(n/4) = cn
  • Level ii (General level):
    • Number of nodes: 2i2^i
    • Size of subproblem: n/2in / 2^i
    • Cost per node: c(n/2i)c(n / 2^i)
    • Total level cost: 2i×c(n/2i)=cn2^i \times c(n / 2^i) = cn

1.4.3 Visual Recursion Tree Diagram​

1.4.4 Tree Height & Total Work Sum​

  • Tree depth hh: n2h=1  ⟹  2h=n  ⟹  h=log⁡2n\frac{n}{2^h} = 1 \implies 2^h = n \implies h = \log_2 n
  • Total number of levels: Levels=h+1=log⁡2n+1\text{Levels} = h + 1 = \log_2 n + 1
  • Total cost across all levels: Total Cost=∑i=0log⁡2ncn\text{Total Cost} = \sum_{i=0}^{\log_2 n} cn Total Cost=cn×(log⁡2n+1)\text{Total Cost} = cn \times (\log_2 n + 1) Total Cost=cnlog⁡2n+cn\text{Total Cost} = cn \log_2 n + cn
  • Asymptotic behavior: T(n)=Θ(nlog⁡n)T(n) = \mathbf{\Theta(n \log n)}
Unit - 2

Divide & Conquer Algorithms​

2.1.1 Concept​

  • Works on sorted arrays by repeatedly comparing the target key with the middle element.
  • If key matches, index is returned.
  • If key is smaller, search space reduces to left half.
  • If key is greater, search space reduces to right half.

2.1.2 Numerical Problem​

  • Sorted array: A=[11,22,33,44,55,66,77,88,99]A = [11, 22, 33, 44, 55, 66, 77, 88, 99]
  • Indices: 00 to 88
  • Target key: Key=66\text{Key} = 66

2.1.3 Iteration-by-Iteration Trace​

Iteration 1​
  • Lower pointer: low=0\text{low} = 0
  • Upper pointer: high=8\text{high} = 8
  • Calculate mid: mid=⌊0+82⌋=4\text{mid} = \left\lfloor \frac{0 + 8}{2} \right\rfloor = 4
  • Inspect element: A[4]=55A[4] = 55
  • Compare: 66>5566 > 55
  • Action:
    • Target lies in the right half.
    • Update: low=mid+1=4+1=5\text{low} = \text{mid} + 1 = 4 + 1 = 5
Iteration 2​
  • Lower pointer: low=5\text{low} = 5
  • Upper pointer: high=8\text{high} = 8
  • Calculate mid: mid=⌊5+82⌋=⌊6.5⌋=6\text{mid} = \left\lfloor \frac{5 + 8}{2} \right\rfloor = \lfloor 6.5 \rfloor = 6
  • Inspect element: A[6]=66A[6] = 66
  • Compare: 66==6666 == 66
  • Action:
    • Match found at index 66.
    • Search terminates.

2.1.4 Complexity​

  • Comparisons made: 22
  • Time Complexity:
    • Best Case: O(1)O(1)
    • Average Case: O(log⁡n)O(\log n)
    • Worst Case: O(log⁡n)\mathbf{O(\log n)}
  • Space Complexity: O(1)\mathbf{O(1)} (Iterative).

2.2 Merge Sort​

2.2.1 Concept​

  • Follows the Divide, Conquer, and Combine paradigm:
    • Divide: Split array into two halves at midpoint.
    • Conquer: Recursively sort both subarrays.
    • Combine: Merge the two sorted subarrays using two pointers.

2.2.2 Numerical Problem​

  • Input array: A=[38,27,43,3,9,82,10]A = [38, 27, 43, 3, 9, 82, 10]
  • Size: n=7n = 7

2.2.3 Divide Step Tree​

  • Level 0: [38,27,43,3,9,82,10][38, 27, 43, 3, 9, 82, 10]
  • Level 1:
    • Left: [38,27,43,3][38, 27, 43, 3]
    • Right: [9,82,10][9, 82, 10]
  • Level 2:
    • From Left: [38,27][38, 27] and [43,3][43, 3]
    • From Right: [9][9] and [82,10][82, 10]
  • Level 3 (Base Cases):
    • [38],[27],[43],[3],[9],[82],[10][38], [27], [43], [3], [9], [82], [10]

2.2.4 Conquer & Merge Step​

Sub-Merge 1​
  • Merge [38][38] and [27][27]:
    • Compare 3838 and 27  ⟹  27<3827 \implies 27 < 38
    • Result: [27,38][27, 38]
Sub-Merge 2​
  • Merge [43][43] and [3][3]:
    • Compare 4343 and 3  ⟹  3<433 \implies 3 < 43
    • Result: [3,43][3, 43]
Sub-Merge 3​
  • Merge [27,38][27, 38] and [3,43][3, 43]:
    • Compare 2727 and 3  ⟹  3 \implies Take 33
    • Compare 2727 and 43  ⟹  43 \implies Take 2727
    • Compare 3838 and 43  ⟹  43 \implies Take 3838
    • Remaining: Take 4343
    • Result: [3,27,38,43][3, 27, 38, 43]
Sub-Merge 4​
  • Merge [82][82] and [10][10]:
    • Compare 8282 and 10  ⟹  10 \implies Take 1010
    • Result: [10,82][10, 82]
Sub-Merge 5​
  • Merge [9][9] and [10,82][10, 82]:
    • Compare 99 and 10  ⟹  10 \implies Take 99
    • Remaining: Take [10,82][10, 82]
    • Result: [9,10,82][9, 10, 82]
Final Merge Step​
  • Left subarray: [3,27,38,43][3, 27, 38, 43]
  • Right subarray: [9,10,82][9, 10, 82]
  • Pointer comparison trace:
    • Compare 33 and 9  ⟹  9 \implies Output 33
    • Compare 2727 and 9  ⟹  9 \implies Output 99
    • Compare 2727 and 10  ⟹  10 \implies Output 1010
    • Compare 2727 and 82  ⟹  82 \implies Output 2727
    • Compare 3838 and 82  ⟹  82 \implies Output 3838
    • Compare 4343 and 82  ⟹  82 \implies Output 4343
    • Exhausted left subarray   ⟹  \implies Append remaining 8282

2.2.5 Visual Merge Sort Tree Diagram​

2.2.6 Final Sorted Output & Complexity​

  • Sorted array: [3,9,10,27,38,43,82]\mathbf{[3, 9, 10, 27, 38, 43, 82]}
  • Time Complexity:
    • Best Case: Θ(nlog⁡n)\Theta(n \log n)
    • Average Case: Θ(nlog⁡n)\Theta(n \log n)
    • Worst Case: Θ(nlog⁡n)\mathbf{\Theta(n \log n)}
  • Auxiliary Space: O(n)\mathbf{O(n)}.

2.3 Quick Sort (Lomuto Partitioning)​

2.3.1 Concept & Partition Logic​

  • Chooses the last element as the pivot: P=A[high]P = A[\text{high}].
  • Maintains index ii tracking elements smaller than or equal to PP.
  • Traverses with index jj: whenever A[j]≤PA[j] \le P, increment ii and swap A[i]A[i] with A[j]A[j].
  • Finally places pivot at i+1i + 1.

2.3.2 Numerical Problem​

  • Input array: A=[28,12,45,19,53,37]A = [28, 12, 45, 19, 53, 37]
  • Indices: 00 to 55
  • Pivot: P=A[5]=37P = A[5] = 37

2.3.3 Step-by-Step Index Swap Trace​

  • Initialize:
    • i=low−1=−1i = \text{low} - 1 = -1
Step j=0j = 0​
  • Value: A[0]=28A[0] = 28
  • Test: 28≤3728 \le 37 (True)
  • Increment ii: i=0i = 0
  • Swap A[0]A[0] with A[0]A[0] (no movement):
    • State: [28,12,45,19,53,37][28, 12, 45, 19, 53, 37]
Step j=1j = 1​
  • Value: A[1]=12A[1] = 12
  • Test: 12≤3712 \le 37 (True)
  • Increment ii: i=1i = 1
  • Swap A[1]A[1] with A[1]A[1]:
    • State: [28,12,45,19,53,37][28, 12, 45, 19, 53, 37]
Step j=2j = 2​
  • Value: A[2]=45A[2] = 45
  • Test: 45≤3745 \le 37 (False)
  • No swap, ii remains 11.
    • State: [28,12,45,19,53,37][28, 12, 45, 19, 53, 37]
Step j=3j = 3​
  • Value: A[3]=19A[3] = 19
  • Test: 19≤3719 \le 37 (True)
  • Increment ii: i=2i = 2
  • Swap A[i]A[i] with A[j]  ⟹  A[j] \implies Swap A[2](45)A[2](45) with A[3](19)A[3](19):
    • State: [28,12,19,45,53,37][28, 12, 19, 45, 53, 37]
Step j=4j = 4​
  • Value: A[4]=53A[4] = 53
  • Test: 53≤3753 \le 37 (False)
  • No swap, ii remains 22.
    • State: [28,12,19,45,53,37][28, 12, 19, 45, 53, 37]
Pivot Placement Step​
  • End of loop reached.
  • Swap pivot A[high](37)A[\text{high}](37) with A[i+1](A[3]=45)A[i + 1](A[3] = 45):
    • Swap A[5]A[5] with A[3]A[3]
  • Final partitioned array: [28,12,19,37‾,53,45][\mathbf{28, 12, 19}, \underline{\mathbf{37}}, \mathbf{53, 45}]
  • Pivot index: 33
  • Subarrays formed:
    • Left: [28,12,19][28, 12, 19]
    • Right: [53,45][53, 45]

2.3.4 Complexity​

  • Time Complexity:
    • Best Case: O(nlog⁡n)O(n \log n)
    • Average Case: O(nlog⁡n)O(n \log n)
    • Worst Case: O(n2)\mathbf{O(n^2)} (when array is already sorted or reverse sorted)
  • Space Complexity: O(log⁡n)\mathbf{O(\log n)} recursion stack.

2.4 Strassen's Matrix Multiplication (2×22 \times 2)​

2.4.1 Concept & Matrix Blocks​

  • Standard multiplication uses 88 scalar multiplications.
  • Strassen uses 77 products, saving computational overhead on large matrices.

2.4.2 Numerical Input Matrices​

  • Matrix AA: A=[1375]A = \begin{bmatrix} 1 & 3 \\ 7 & 5 \end{bmatrix}

    • a11=1a_{11} = 1
    • a12=3a_{12} = 3
    • a21=7a_{21} = 7
    • a22=5a_{22} = 5
  • Matrix BB: B=[6842]B = \begin{bmatrix} 6 & 8 \\ 4 & 2 \end{bmatrix}

    • b11=6b_{11} = 6
    • b12=8b_{12} = 8
    • b21=4b_{21} = 4
    • b22=2b_{22} = 2

2.4.3 The 7 Auxiliary Products (P1P_1 to P7P_7)​

  • Product P1P_1: P1=(a11+a22)(b11+b22)P_1 = (a_{11} + a_{22})(b_{11} + b_{22}) P1=(1+5)(6+2)P_1 = (1 + 5)(6 + 2) P1=6×8P_1 = 6 \times 8 P1=48P_1 = 48

  • Product P2P_2: P2=(a21+a22)b11P_2 = (a_{21} + a_{22}) b_{11} P2=(7+5)×6P_2 = (7 + 5) \times 6 P2=12×6P_2 = 12 \times 6 P2=72P_2 = 72

  • Product P3P_3: P3=a11(b12−b22)P_3 = a_{11} (b_{12} - b_{22}) P3=1×(8−2)P_3 = 1 \times (8 - 2) P3=1×6P_3 = 1 \times 6 P3=6P_3 = 6

  • Product P4P_4: P4=a22(b21−b11)P_4 = a_{22} (b_{21} - b_{11}) P4=5×(4−6)P_4 = 5 \times (4 - 6) P4=5×(−2)P_4 = 5 \times (-2) P4=−10P_4 = -10

  • Product P5P_5: P5=(a11+a12)b22P_5 = (a_{11} + a_{12}) b_{22} P5=(1+3)×2P_5 = (1 + 3) \times 2 P5=4×2P_5 = 4 \times 2 P5=8P_5 = 8

  • Product P6P_6: P6=(a21−a11)(b11+b12)P_6 = (a_{21} - a_{11})(b_{11} + b_{12}) P6=(7−1)(6+8)P_6 = (7 - 1)(6 + 8) P6=6×14P_6 = 6 \times 14 P6=84P_6 = 84

  • Product P7P_7: P7=(a12−a22)(b21+b22)P_7 = (a_{12} - a_{22})(b_{21} + b_{22}) P7=(3−5)(4+2)P_7 = (3 - 5)(4 + 2) P7=(−2)×6P_7 = (-2) \times 6 P7=−12P_7 = -12

2.4.4 Result Matrix Assembly (C11,C12,C21,C22C_{11}, C_{12}, C_{21}, C_{22})​

  • Entry C11C_{11}: C11=P1+P4−P5+P7C_{11} = P_1 + P_4 - P_5 + P_7 C11=48+(−10)−8+(−12)C_{11} = 48 + (-10) - 8 + (-12) C11=48−10−8−12C_{11} = 48 - 10 - 8 - 12 C11=18C_{11} = 18

  • Entry C12C_{12}: C12=P3+P5C_{12} = P_3 + P_5 C12=6+8C_{12} = 6 + 8 C12=14C_{12} = 14

  • Entry C21C_{21}: C21=P2+P4C_{21} = P_2 + P_4 C21=72+(−10)C_{21} = 72 + (-10) C21=62C_{21} = 62

  • Entry C22C_{22}: C22=P1−P2+P3+P6C_{22} = P_1 - P_2 + P_3 + P_6 C22=48−72+6+84C_{22} = 48 - 72 + 6 + 84 C22=−24+6+84C_{22} = -24 + 6 + 84 C22=66C_{22} = 66

  • Resultant Matrix CC: C=[18146266]C = \begin{bmatrix} 18 & 14 \\ 62 & 66 \end{bmatrix}

2.4.5 Verification & Complexity​

  • Standard multiplication check:
    • C11=1(6)+3(4)=6+12=18C_{11} = 1(6) + 3(4) = 6 + 12 = 18
    • C12=1(8)+3(2)=8+6=14C_{12} = 1(8) + 3(2) = 8 + 6 = 14
    • C21=7(6)+5(4)=42+20=62C_{21} = 7(6) + 5(4) = 42 + 20 = 62
    • C22=7(8)+5(2)=56+10=66C_{22} = 7(8) + 5(2) = 56 + 10 = 66
  • Time Complexity: T(n)=7T(n/2)+O(n2)T(n) = 7T(n/2) + O(n^2) T(n)=Θ(nlog⁡27)≈O(n2.807)T(n) = \Theta(n^{\log_2 7}) \approx \mathbf{O(n^{2.807})} (Standard multiplication is O(n3)O(n^3)).

2.5 Divide and Conquer Modular Exponentiation​

2.5.1 Recursive Exponentiation Rule​

  • For base aa and exponent nn:
    • If n==0n == 0: a0=1a^0 = 1
    • If nn is even: an=(an/2)2a^n = (a^{n/2})^2
    • If nn is odd: an=a×(a(n−1)/2)2a^n = a \times (a^{(n-1)/2})^2

2.5.2 Numerical Problem​

  • Compute: 310(mod1000)3^{10} \pmod{1000}

2.5.3 Step-by-Step Computation​

  • Step 1: Break down 3103^{10} (even power): 310=(35)23^{10} = (3^5)^2
  • Step 2: Break down 353^5 (odd power): 35=3×(32)23^5 = 3 \times (3^2)^2
  • Step 3: Compute 323^2: 32=93^2 = 9
  • Step 4: Compute (32)2(3^2)^2: 92=819^2 = 81
  • Step 5: Compute 353^5: 35=3×81=2433^5 = 3 \times 81 = 243
  • Step 6: Compute 3103^{10}: 310=2432=59,0493^{10} = 243^2 = 59,049
  • Step 7: Apply modulo 10001000: 59,049(mod1000)=4959,049 \pmod{1000} = \mathbf{49}

2.5.4 Complexity Comparison​

  • Sequential multiplication multiplications: 99 multiplications
  • Divide and conquer multiplications: 44 multiplications
  • Time Complexity: O(log⁡n)\mathbf{O(\log n)}
Unit - 3

Greedy Algorithms​

3.1 Kruskal's Algorithm (Minimum Spanning Tree)​

3.1.1 Graph Problem Input​

  • Vertices: V={A,B,C,D,E}V = \{A, B, C, D, E\}
  • Total Vertices: ∣V∣=5|V| = 5
  • Target MST Edges: ∣V∣−1=4|V| - 1 = 4
  • Edges with weights:
    • (A,B):1(A, B): 1
    • (B,C):2(B, C): 2
    • (B,D):3(B, D): 3
    • (A,C):4(A, C): 4
    • (C,D):5(C, D): 5
    • (D,E):6(D, E): 6
    • (C,E):7(C, E): 7

3.1.2 Visual Graph Representation​

3.1.3 Edge Sorting Step​

  • Sorted list of edges in non-decreasing order:
    1. (A,B)(A, B) with weight 11
    2. (B,C)(B, C) with weight 22
    3. (B,D)(B, D) with weight 33
    4. (A,C)(A, C) with weight 44
    5. (C,D)(C, D) with weight 55
    6. (D,E)(D, E) with weight 66
    7. (C,E)(C, E) with weight 77

3.1.4 Edge-by-Edge Disjoint Set (DSU) Trace​

  • Initialize disjoint sets: {A},{B},{C},{D},{E}\{A\}, \{B\}, \{C\}, \{D\}, \{E\}
Consideration 1: Edge (A,B)(A, B) with weight 11​
  • Set of AA: {A}\{A\}
  • Set of BB: {B}\{B\}
  • Check: Find(A)≠Find(B)\text{Find}(A) \ne \text{Find}(B)
  • Decision: Accept edge
  • Union: {A,B}\{A, B\}
  • MST Edges: {(A,B)}\{(A, B)\}
Consideration 2: Edge (B,C)(B, C) with weight 22​
  • Set of BB: {A,B}\{A, B\}
  • Set of CC: {C}\{C\}
  • Check: Find(B)≠Find(C)\text{Find}(B) \ne \text{Find}(C)
  • Decision: Accept edge
  • Union: {A,B,C}\{A, B, C\}
  • MST Edges: {(A,B),(B,C)}\{(A, B), (B, C)\}
Consideration 3: Edge (B,D)(B, D) with weight 33​
  • Set of BB: {A,B,C}\{A, B, C\}
  • Set of DD: {D}\{D\}
  • Check: Find(B)≠Find(D)\text{Find}(B) \ne \text{Find}(D)
  • Decision: Accept edge
  • Union: {A,B,C,D}\{A, B, C, D\}
  • MST Edges: {(A,B),(B,C),(B,D)}\{(A, B), (B, C), (B, D)\}
Consideration 4: Edge (A,C)(A, C) with weight 44​
  • Set of AA: {A,B,C,D}\{A, B, C, D\}
  • Set of CC: {A,B,C,D}\{A, B, C, D\}
  • Check: Find(A)==Find(C)\text{Find}(A) == \text{Find}(C) (Both in same set)
  • Decision: Reject edge (Creates cycle A−B−C−AA-B-C-A)
Consideration 5: Edge (C,D)(C, D) with weight 55​
  • Set of CC: {A,B,C,D}\{A, B, C, D\}
  • Set of DD: {A,B,C,D}\{A, B, C, D\}
  • Check: Find(C)==Find(D)\text{Find}(C) == \text{Find}(D)
  • Decision: Reject edge (Creates cycle B−C−D−BB-C-D-B)
Consideration 6: Edge (D,E)(D, E) with weight 66​
  • Set of DD: {A,B,C,D}\{A, B, C, D\}
  • Set of EE: {E}\{E\}
  • Check: Find(D)≠Find(E)\text{Find}(D) \ne \text{Find}(E)
  • Decision: Accept edge
  • Union: {A,B,C,D,E}\{A, B, C, D, E\}
  • MST Edges: {(A,B),(B,C),(B,D),(D,E)}\{(A, B), (B, C), (B, D), (D, E)\}

3.1.5 Final MST Visual Graph & Weight​

  • Total edges chosen: 44 (=∣V∣−1=|V| - 1)
  • Final MST Tree Graph:
  • Total weight calculation: Total Cost=1+2+3+6=12\text{Total Cost} = 1 + 2 + 3 + 6 = \mathbf{12}
  • Time Complexity: O(Elog⁡E)\mathbf{O(E \log E)} or O(Elog⁡V)\mathbf{O(E \log V)}

3.2 Prim's Algorithm (Minimum Spanning Tree)​

3.2.1 Graph Problem Input & Starting Vertex​

  • Same graph: V={A,B,C,D,E}V = \{A, B, C, D, E\}
  • Starting root vertex: AA
  • Target MST vertices: all 55 vertices

3.2.2 Step-by-Step Cut Set Growth​

Iteration 0 (Initialization)​
  • Spanning tree set: S={A}S = \{A\}
  • Unvisited set: V∖S={B,C,D,E}V \setminus S = \{B, C, D, E\}
  • Initial cost: 00
Iteration 1​
  • Crossing edges from S={A}S = \{A\}:
    • (A,B)(A, B): weight 11
    • (A,C)(A, C): weight 44
  • Minimum cut edge: (A,B)(A, B) with weight 11
  • Add BB to SS:
    • S={A,B}S = \{A, B\}
    • Current cost: 11
Iteration 2​
  • Crossing edges from S={A,B}S = \{A, B\}:
    • (A,C)(A, C): weight 44
    • (B,C)(B, C): weight 22
    • (B,D)(B, D): weight 33
  • Minimum cut edge: (B,C)(B, C) with weight 22
  • Add CC to SS:
    • S={A,B,C}S = \{A, B, C\}
    • Current cost: 1+2=31 + 2 = 3
Iteration 3​
  • Crossing edges from S={A,B,C}S = \{A, B, C\}:
    • (B,D)(B, D): weight 33
    • (C,D)(C, D): weight 55
    • (C,E)(C, E): weight 77
  • Minimum cut edge: (B,D)(B, D) with weight 33
  • Add DD to SS:
    • S={A,B,C,D}S = \{A, B, C, D\}
    • Current cost: 3+3=63 + 3 = 6
Iteration 4​
  • Crossing edges from S={A,B,C,D}S = \{A, B, C, D\}:
    • (D,E)(D, E): weight 66
    • (C,E)(C, E): weight 77
  • Minimum cut edge: (D,E)(D, E) with weight 66
  • Add EE to SS:
    • S={A,B,C,D,E}S = \{A, B, C, D, E\}
    • Current cost: 6+6=126 + 6 = 12

3.2.3 Final MST & Complexity​

  • Selected tree edges: {(A,B),(B,C),(B,D),(D,E)}\{(A, B), (B, C), (B, D), (D, E)\}
  • Total weight: 12\mathbf{12}
  • Time Complexity:
    • With Adjacency Matrix: O(V2)O(V^2)
    • With Min-Heap & Adjacency List: O(Elog⁡V)\mathbf{O(E \log V)}

3.3 Dijkstra's Single-Source Shortest Path​

3.3.1 Directed Graph & Edge Weights​

  • Vertices: {S,A,B,C,D}\{S, A, B, C, D\}
  • Source: SS
  • Edges:
    • (S,A)=10(S, A) = 10
    • (S,C)=5(S, C) = 5
    • (C,A)=3(C, A) = 3
    • (C,B)=9(C, B) = 9
    • (C,D)=2(C, D) = 2
    • (A,B)=1(A, B) = 1
    • (D,B)=4(D, B) = 4

3.3.2 Visual Input Graph​

3.3.3 Initialization​

  • Distance array:
    • d[S]=0d[S] = 0
    • d[A]=∞d[A] = \infty
    • d[B]=∞d[B] = \infty
    • d[C]=∞d[C] = \infty
    • d[D]=∞d[D] = \infty
  • Visited set: U=∅U = \emptyset

3.3.4 Step-by-Step Node Selection & Relaxation​

Step 1: Process Node SS​
  • Select minimum unvisited: SS with d[S]=0d[S] = 0
  • Mark SS as visited: U={S}U = \{S\}
  • Relax edge (S,A)(S, A): d[A]=min⁡(∞,0+10)=10d[A] = \min(\infty, 0 + 10) = 10
  • Relax edge (S,C)(S, C): d[C]=min⁡(∞,0+5)=5d[C] = \min(\infty, 0 + 5) = 5
  • Current distances: d[S]=0,d[A]=10,d[B]=∞,d[C]=5,d[D]=∞d[S]=0, \quad d[A]=10, \quad d[B]=\infty, \quad d[C]=5, \quad d[D]=\infty
Step 2: Process Node CC​
  • Select minimum unvisited: CC with d[C]=5d[C] = 5
  • Mark CC as visited: U={S,C}U = \{S, C\}
  • Relax edge (C,A)(C, A): d[A]=min⁡(10,5+3)=8d[A] = \min(10, 5 + 3) = 8
  • Relax edge (C,B)(C, B): d[B]=min⁡(∞,5+9)=14d[B] = \min(\infty, 5 + 9) = 14
  • Relax edge (C,D)(C, D): d[D]=min⁡(∞,5+2)=7d[D] = \min(\infty, 5 + 2) = 7
  • Current distances: d[S]=0,d[A]=8,d[B]=14,d[C]=5,d[D]=7d[S]=0, \quad d[A]=8, \quad d[B]=14, \quad d[C]=5, \quad d[D]=7
Step 3: Process Node DD​
  • Select minimum unvisited: DD with d[D]=7d[D] = 7
  • Mark DD as visited: U={S,C,D}U = \{S, C, D\}
  • Relax edge (D,B)(D, B): d[B]=min⁡(14,7+4)=11d[B] = \min(14, 7 + 4) = 11
  • Current distances: d[S]=0,d[A]=8,d[B]=11,d[C]=5,d[D]=7d[S]=0, \quad d[A]=8, \quad d[B]=11, \quad d[C]=5, \quad d[D]=7
Step 4: Process Node AA​
  • Select minimum unvisited: AA with d[A]=8d[A] = 8
  • Mark AA as visited: U={S,C,D,A}U = \{S, C, D, A\}
  • Relax edge (A,B)(A, B): d[B]=min⁡(11,8+1)=9d[B] = \min(11, 8 + 1) = 9
  • Current distances: d[S]=0,d[A]=8,d[B]=9,d[C]=5,d[D]=7d[S]=0, \quad d[A]=8, \quad d[B]=9, \quad d[C]=5, \quad d[D]=7
Step 5: Process Node BB​
  • Select minimum unvisited: BB with d[B]=9d[B] = 9
  • Mark BB as visited: U={S,C,D,A,B}U = \{S, C, D, A, B\}
  • No outgoing edges from BB.

3.3.5 Shortest Path Tree Visual Diagram​

  • Shortest paths from SS:
    • To SS: Cost =0= 0
    • To CC: Cost =5= 5, Path: S→CS \to C
    • To DD: Cost =7= 7, Path: S→C→DS \to C \to D
    • To AA: Cost =8= 8, Path: S→C→AS \to C \to A
    • To BB: Cost =9= 9, Path: S→C→A→BS \to C \to A \to B
  • Time Complexity: O((V+E)log⁡V)\mathbf{O((V + E) \log V)}

3.4 Fractional Knapsack Problem​

3.4.1 Problem Definition & Capacity​

  • Knapsack capacity: W=50W = 50
  • Item list:
    • Item 1: Profit P1=60P_1 = 60, Weight W1=10W_1 = 10
    • Item 2: Profit P2=100P_2 = 100, Weight W2=20W_2 = 20
    • Item 3: Profit P3=120P_3 = 120, Weight W3=30W_3 = 30

3.4.2 Ratio Calculation (Pi/WiP_i / W_i)​

  • Ratio for Item 1: r1=6010=6.0r_1 = \frac{60}{10} = 6.0
  • Ratio for Item 2: r2=10020=5.0r_2 = \frac{100}{20} = 5.0
  • Ratio for Item 3: r3=12030=4.0r_3 = \frac{120}{30} = 4.0

3.4.3 Sorted Ratio Order​

  • Descending order:
    • Item 1 (r1=6.0r_1 = 6.0)
    • Item 2 (r2=5.0r_2 = 5.0)
    • Item 3 (r3=4.0r_3 = 4.0)

3.4.4 Greedy Item Selection Walkthrough​

Take Item 1​
  • Current capacity: 5050
  • Item 1 weight: 10≤5010 \le 50
  • Action: Take full item (x1=1.0x_1 = 1.0)
  • Profit added: 6060
  • Remaining capacity: 50−10=4050 - 10 = 40
  • Current total profit: 6060
Take Item 2​
  • Current capacity: 4040
  • Item 2 weight: 20≤4020 \le 40
  • Action: Take full item (x2=1.0x_2 = 1.0)
  • Profit added: 100100
  • Remaining capacity: 40−20=2040 - 20 = 20
  • Current total profit: 60+100=16060 + 100 = 160
Take Fraction of Item 3​
  • Current capacity: 2020
  • Item 3 weight: 30>2030 > 20 (Cannot take completely)
  • Action: Take fractional part: x3=Remaining CapacityItem Weight=2030=23x_3 = \frac{\text{Remaining Capacity}}{\text{Item Weight}} = \frac{20}{30} = \frac{2}{3}
  • Profit added: 120×(23)=80120 \times \left(\frac{2}{3}\right) = 80
  • Remaining capacity: 20−20=020 - 20 = 0

3.4.5 Final Solution Vector & Max Profit​

  • Selection fractions: x=(1,1,23)x = \left(1, 1, \frac{2}{3}\right)
  • Total optimal profit: 60+100+80=24060 + 100 + 80 = \mathbf{240}
  • Time Complexity: O(nlog⁡n)\mathbf{O(n \log n)} (sorting dominant).

3.5 Activity Selection Problem​

3.5.1 Problem Data (Start & Finish Times)​

  • Activities with (si,fi)(s_i, f_i):
    • A1A_1: Start =1= 1, Finish =3= 3
    • A2A_2: Start =2= 2, Finish =5= 5
    • A3A_3: Start =4= 4, Finish =7= 7
    • A4A_4: Start =1= 1, Finish =8= 8
    • A5A_5: Start =5= 5, Finish =9= 9
    • A6A_6: Start =8= 8, Finish =10= 10

3.5.2 Sorting by Finish Time​

  • Finish times are already sorted:
    • A1(1,3)A_1(1, 3)
    • A2(2,5)A_2(2, 5)
    • A3(4,7)A_3(4, 7)
    • A4(1,8)A_4(1, 8)
    • A5(5,9)A_5(5, 9)
    • A6(8,10)A_6(8, 10)

3.5.3 Compatibility Check Trace​

Consider Activity A1(1,3)A_1(1, 3)​
  • First activity is always selected.
  • Action: Select A1A_1
  • Selected set: {A1}\{A_1\}
  • Last finish time: flast=3f_{\text{last}} = 3
Consider Activity A2(2,5)A_2(2, 5)​
  • Start time: s2=2s_2 = 2
  • Test: s2<flast  ⟹  2<3s_2 < f_{\text{last}} \implies 2 < 3 (Overlap)
  • Action: Reject A2A_2
Consider Activity A3(4,7)A_3(4, 7)​
  • Start time: s3=4s_3 = 4
  • Test: s3≥flast  ⟹  4≥3s_3 \ge f_{\text{last}} \implies 4 \ge 3 (Compatible)
  • Action: Select A3A_3
  • Selected set: {A1,A3}\{A_1, A_3\}
  • Last finish time: flast=7f_{\text{last}} = 7
Consider Activity A4(1,8)A_4(1, 8)​
  • Start time: s4=1s_4 = 1
  • Test: s4<flast  ⟹  1<7s_4 < f_{\text{last}} \implies 1 < 7
  • Action: Reject A4A_4
Consider Activity A5(5,9)A_5(5, 9)​
  • Start time: s5=5s_5 = 5
  • Test: s5<flast  ⟹  5<7s_5 < f_{\text{last}} \implies 5 < 7
  • Action: Reject A5A_5
Consider Activity A6(8,10)A_6(8, 10)​
  • Start time: s6=8s_6 = 8
  • Test: s6≥flast  ⟹  8≥7s_6 \ge f_{\text{last}} \implies 8 \ge 7 (Compatible)
  • Action: Select A6A_6
  • Selected set: {A1,A3,A6}\{A_1, A_3, A_6\}
  • Last finish time: flast=10f_{\text{last}} = 10

3.5.4 Selected Activities & Complexity​

  • Maximum set of mutually compatible activities: {A1,A3,A6}\mathbf{\{A_1, A_3, A_6\}}
  • Total count: 33
  • Time Complexity: O(nlog⁡n)\mathbf{O(n \log n)} if unsorted; O(n)\mathbf{O(n)} if sorted.

3.6 Huffman Coding​

3.6.1 Character Frequencies Input​

  • Character set with frequencies:
    • f:5f: 5
    • e:9e: 9
    • c:12c: 12
    • b:13b: 13
    • d:16d: 16
    • a:45a: 45

3.6.2 Step-by-Step Min-Heap Tree Merge​

Merge 1​
  • Two smallest frequencies: f(5)f(5) and e(9)e(9)
  • Create parent node N1N_1: weight(N1)=5+9=14\text{weight}(N_1) = 5 + 9 = 14
  • Remaining nodes: c(12),b(13),N1(14),d(16),a(45)c(12), b(13), N_1(14), d(16), a(45)
Merge 2​
  • Two smallest frequencies: c(12)c(12) and b(13)b(13)
  • Create parent node N2N_2: weight(N2)=12+13=25\text{weight}(N_2) = 12 + 13 = 25
  • Remaining nodes: N1(14),d(16),N2(25),a(45)N_1(14), d(16), N_2(25), a(45)
Merge 3​
  • Two smallest frequencies: N1(14)N_1(14) and d(16)d(16)
  • Create parent node N3N_3: weight(N3)=14+16=30\text{weight}(N_3) = 14 + 16 = 30
  • Remaining nodes: N2(25),N3(30),a(45)N_2(25), N_3(30), a(45)
Merge 4​
  • Two smallest frequencies: N2(25)N_2(25) and N3(30)N_3(30)
  • Create parent node N4N_4: weight(N4)=25+30=55\text{weight}(N_4) = 25 + 30 = 55
  • Remaining nodes: a(45),N4(55)a(45), N_4(55)
Merge 5​
  • Two remaining nodes: a(45)a(45) and N4(55)N_4(55)
  • Create root node: weight(Root)=45+55=100\text{weight}(\text{Root}) = 45 + 55 = 100

3.6.3 Visual Huffman Tree Diagram​

3.6.4 Prefix Code Generation Table​

  • Traverse left as 00, right as 11:
    • Character aa: Code =0= \mathbf{0} (Length 11)
    • Character cc: Path Root→1→0→0  ⟹  100\text{Root} \to 1 \to 0 \to 0 \implies \mathbf{100} (Length 33)
    • Character bb: Path Root→1→0→1  ⟹  101\text{Root} \to 1 \to 0 \to 1 \implies \mathbf{101} (Length 33)
    • Character dd: Path Root→1→1→1  ⟹  111\text{Root} \to 1 \to 1 \to 1 \implies \mathbf{111} (Length 33)
    • Character ff: Path Root→1→1→0→0  ⟹  1100\text{Root} \to 1 \to 1 \to 0 \to 0 \implies \mathbf{1100} (Length 44)
    • Character ee: Path Root→1→1→0→1  ⟹  1101\text{Root} \to 1 \to 1 \to 0 \to 1 \implies \mathbf{1101} (Length 44)

3.6.5 Total Bit Length Calculation & Ratio​

  • Bits required per character:
    • a:45×1=45a: 45 \times 1 = 45
    • c:12×3=36c: 12 \times 3 = 36
    • b:13×3=39b: 13 \times 3 = 39
    • d:16×3=48d: 16 \times 3 = 48
    • f:5×4=20f: 5 \times 4 = 20
    • e:9×4=36e: 9 \times 4 = 36
  • Total encoded message size: Total Bits=45+36+39+48+20+36=224 bits\text{Total Bits} = 45 + 36 + 39 + 48 + 20 + 36 = \mathbf{224\text{ bits}}
  • Fixed-length comparison (33 bits per char for 66 chars): 100×3=300 bits100 \times 3 = 300\text{ bits}
  • Space saved: 300−224300×100%=25.33%\frac{300 - 224}{300} \times 100\% = 25.33\%
  • Time Complexity: O(nlog⁡n)\mathbf{O(n \log n)}
Unit - 4

Dynamic Programming​

4.1 0/1 Knapsack Problem (Tabulation)​

4.1.1 Problem Parameters & Recurrence​

  • Knapsack capacity: W=5W = 5
  • Number of items: n=4n = 4
  • Items:
    • Item 1: w1=2,v1=3w_1 = 2, v_1 = 3
    • Item 2: w2=3,v2=4w_2 = 3, v_2 = 4
    • Item 3: w3=4,v3=5w_3 = 4, v_3 = 5
    • Item 4: w4=5,v4=6w_4 = 5, v_4 = 6
  • Recurrence relation: V[i][w]={V[i−1][w]if wi>wmax⁡(V[i−1][w],vi+V[i−1][w−wi])if wi≤wV[i][w] = \begin{cases} V[i-1][w] & \text{if } w_i > w \\ \max(V[i-1][w], v_i + V[i-1][w - w_i]) & \text{if } w_i \le w \end{cases}

4.1.2 DP Table Construction Walkthrough​

Row i=0i = 0 (No Items)​
  • For all capacities w=0w = 0 to 55: V[0][w]=0V[0][w] = 0
Row i=1i = 1 (Item 1: w1=2,v1=3w_1 = 2, v_1 = 3)​
  • w=0w = 0: V[1][0]=0V[1][0] = 0
  • w=1w = 1: w1>1  ⟹  V[1][1]=V[0][1]=0w_1 > 1 \implies V[1][1] = V[0][1] = 0
  • w=2w = 2: max⁡(V[0][2],3+V[0][0])=max⁡(0,3)=3\max(V[0][2], 3 + V[0][0]) = \max(0, 3) = 3
  • w=3w = 3: max⁡(V[0][3],3+V[0][1])=max⁡(0,3)=3\max(V[0][3], 3 + V[0][1]) = \max(0, 3) = 3
  • w=4w = 4: max⁡(V[0][4],3+V[0][2])=max⁡(0,3)=3\max(V[0][4], 3 + V[0][2]) = \max(0, 3) = 3
  • w=5w = 5: max⁡(V[0][5],3+V[0][3])=max⁡(0,3)=3\max(V[0][5], 3 + V[0][3]) = \max(0, 3) = 3
Row i=2i = 2 (Item 2: w2=3,v2=4w_2 = 3, v_2 = 4)​
  • w=0w = 0: V[2][0]=0V[2][0] = 0
  • w=1w = 1: w2>1  ⟹  V[2][1]=V[1][1]=0w_2 > 1 \implies V[2][1] = V[1][1] = 0
  • w=2w = 2: w2>2  ⟹  V[2][2]=V[1][2]=3w_2 > 2 \implies V[2][2] = V[1][2] = 3
  • w=3w = 3: max⁡(V[1][3],4+V[1][0])=max⁡(3,4)=4\max(V[1][3], 4 + V[1][0]) = \max(3, 4) = 4
  • w=4w = 4: max⁡(V[1][4],4+V[1][1])=max⁡(3,4+0)=4\max(V[1][4], 4 + V[1][1]) = \max(3, 4 + 0) = 4
  • w=5w = 5: max⁡(V[1][5],4+V[1][2])=max⁡(3,4+3)=7\max(V[1][5], 4 + V[1][2]) = \max(3, 4 + 3) = \mathbf{7}
Row i=3i = 3 (Item 3: w3=4,v3=5w_3 = 4, v_3 = 5)​
  • w=0w = 0: V[3][0]=0V[3][0] = 0
  • w=1w = 1: V[3][1]=0V[3][1] = 0
  • w=2w = 2: V[3][2]=3V[3][2] = 3
  • w=3w = 3: V[3][3]=4V[3][3] = 4
  • w=4w = 4: max⁡(V[2][4],5+V[2][0])=max⁡(4,5)=5\max(V[2][4], 5 + V[2][0]) = \max(4, 5) = 5
  • w=5w = 5: max⁡(V[2][5],5+V[2][1])=max⁡(7,5+0)=7\max(V[2][5], 5 + V[2][1]) = \max(7, 5 + 0) = \mathbf{7}
Row i=4i = 4 (Item 4: w4=5,v4=6w_4 = 5, v_4 = 6)​
  • w=0w = 0: V[4][0]=0V[4][0] = 0
  • w=1w = 1: V[4][1]=0V[4][1] = 0
  • w=2w = 2: V[4][2]=3V[4][2] = 3
  • w=3w = 3: V[4][3]=4V[4][3] = 4
  • w=4w = 4: V[4][4]=5V[4][4] = 5
  • w=5w = 5: max⁡(V[3][5],6+V[3][0])=max⁡(7,6+0)=7\max(V[3][5], 6 + V[3][0]) = \max(7, 6 + 0) = \mathbf{7}

4.1.3 Complete DP Matrix Table​

i↓∖w→i \downarrow \setminus w \tow=0w = 0w=1w = 1w=2w = 2w=3w = 3w=4w = 4w=5w = 5
i=0i = 0000000
i=1(2,3)i = 1 (2, 3)003333
i=2(3,4)i = 2 (3, 4)003447
i=3(4,5)i = 3 (4, 5)003457
i=4(5,6)i = 4 (5, 6)003457

4.1.4 Item Backtracking Trace​

  • Check Item 4 at (4,5)(4, 5):
    • V[4][5]==V[3][5]  ⟹  7==7V[4][5] == V[3][5] \implies 7 == 7
    • Item 4 is NOT selected.
  • Check Item 3 at (3,5)(3, 5):
    • V[3][5]==V[2][5]  ⟹  7==7V[3][5] == V[2][5] \implies 7 == 7
    • Item 3 is NOT selected.
  • Check Item 2 at (2,5)(2, 5):
    • V[2][5]≠V[1][5]  ⟹  7≠3V[2][5] \ne V[1][5] \implies 7 \ne 3
    • Item 2 is SELECTED (w2=3,v2=4w_2 = 3, v_2 = 4).
    • Remaining capacity: 5−3=25 - 3 = 2.
  • Check Item 1 at (1,2)(1, 2):
    • V[1][2]≠V[0][2]  ⟹  3≠0V[1][2] \ne V[0][2] \implies 3 \ne 0
    • Item 1 is SELECTED (w1=2,v1=3w_1 = 2, v_1 = 3).
    • Remaining capacity: 2−2=02 - 2 = 0.

4.1.5 Optimal Subset & Complexity​

  • Selected items: {Item 1,Item 2}\{\text{Item 1}, \text{Item 2}\}
  • Total weight: 2+3=52 + 3 = 5
  • Total max profit: 3+4=73 + 4 = \mathbf{7}
  • Time Complexity: O(nW)\mathbf{O(n W)}
  • Space Complexity: O(nW)\mathbf{O(n W)} (reducible to O(W)O(W)).

4.2 Binomial Coefficient (C(n,k)C(n, k))​

4.2.1 Recurrence & Base Cases​

  • Pascal's identity: C(n,k)=C(n−1,k−1)+C(n−1,k)C(n, k) = C(n-1, k-1) + C(n-1, k)
  • Base cases: C(n,0)=1,C(n,n)=1C(n, 0) = 1, \quad C(n, n) = 1

4.2.2 Line-by-Line DP Table Calculation for (53)\binom{5}{3}​

  • Row 00: C(0,0)=1C(0, 0) = 1
  • Row 11: C(1,0)=1,C(1,1)=1C(1, 0) = 1, \quad C(1, 1) = 1
  • Row 22: C(2,0)=1C(2, 0) = 1 C(2,1)=C(1,0)+C(1,1)=1+1=2C(2, 1) = C(1, 0) + C(1, 1) = 1 + 1 = 2 C(2,2)=1C(2, 2) = 1
  • Row 33: C(3,0)=1C(3, 0) = 1 C(3,1)=C(2,0)+C(2,1)=1+2=3C(3, 1) = C(2, 0) + C(2, 1) = 1 + 2 = 3 C(3,2)=C(2,1)+C(2,2)=2+1=3C(3, 2) = C(2, 1) + C(2, 2) = 2 + 1 = 3 C(3,3)=1C(3, 3) = 1
  • Row 44: C(4,0)=1C(4, 0) = 1 C(4,1)=C(3,0)+C(3,1)=1+3=4C(4, 1) = C(3, 0) + C(3, 1) = 1 + 3 = 4 C(4,2)=C(3,1)+C(3,2)=3+3=6C(4, 2) = C(3, 1) + C(3, 2) = 3 + 3 = 6 C(4,3)=C(3,2)+C(3,3)=3+1=4C(4, 3) = C(3, 2) + C(3, 3) = 3 + 1 = 4 C(4,4)=1C(4, 4) = 1
  • Row 55: C(5,0)=1C(5, 0) = 1 C(5,1)=C(4,0)+C(4,1)=1+4=5C(5, 1) = C(4, 0) + C(4, 1) = 1 + 4 = 5 C(5,2)=C(4,1)+C(4,2)=4+6=10C(5, 2) = C(4, 1) + C(4, 2) = 4 + 6 = 10 C(5,3)=C(4,2)+C(4,3)=6+4=10C(5, 3) = C(4, 2) + C(4, 3) = 6 + 4 = \mathbf{10}

4.2.3 Final Value & Space Optimization​

  • Result: (53)=10\binom{5}{3} = \mathbf{10}
  • Time Complexity: O(nk)\mathbf{O(n k)}
  • Space Complexity: O(k)\mathbf{O(k)} using 1D array.

4.3 Floyd-Warshall All-Pairs Shortest Path​

4.3.1 Problem Graph & Initial Matrix D(0)D^{(0)}​

  • Directed graph with 44 vertices: D(0)=[03∞7802∞5∞012∞∞0]D^{(0)} = \begin{bmatrix} 0 & 3 & \infty & 7 \\ 8 & 0 & 2 & \infty \\ 5 & \infty & 0 & 1 \\ 2 & \infty & \infty & 0 \end{bmatrix}

4.3.2 Visual Directed Graph​

4.3.3 Recurrence Formula​

D(k)[i][j]=min⁡(D(k−1)[i][j],D(k−1)[i][k]+D(k−1)[k][j])D^{(k)}[i][j] = \min\left(D^{(k-1)}[i][j], D^{(k-1)}[i][k] + D^{(k-1)}[k][j]\right)

4.3.4 Intermediate Matrices D(1),D(2),D(3),D(4)D^{(1)}, D^{(2)}, D^{(3)}, D^{(4)}​

Pass k=1k = 1 (Intermediate Node 11)​
  • Column 11 and Row 11 remain unchanged.
  • D(1)[2][4]=min⁡(∞,D(0)[2][1]+D(0)[1][4])=min⁡(∞,8+7)=15D^{(1)}[2][4] = \min(\infty, D^{(0)}[2][1] + D^{(0)}[1][4]) = \min(\infty, 8 + 7) = 15
  • D(1)[3][2]=min⁡(∞,D(0)[3][1]+D(0)[1][2])=min⁡(∞,5+3)=8D^{(1)}[3][2] = \min(\infty, D^{(0)}[3][1] + D^{(0)}[1][2]) = \min(\infty, 5 + 3) = 8
  • D(1)[4][2]=min⁡(∞,D(0)[4][1]+D(0)[1][2])=min⁡(∞,2+3)=5D^{(1)}[4][2] = \min(\infty, D^{(0)}[4][1] + D^{(0)}[1][2]) = \min(\infty, 2 + 3) = 5
  • D(1)[4][4]=min⁡(0,2+7)=0D^{(1)}[4][4] = \min(0, 2 + 7) = 0
  • Matrix D(1)D^{(1)}: D(1)=[03∞780215580125∞0]D^{(1)} = \begin{bmatrix} 0 & 3 & \infty & 7 \\ 8 & 0 & 2 & 15 \\ 5 & 8 & 0 & 1 \\ 2 & 5 & \infty & 0 \end{bmatrix}
Pass k=2k = 2 (Intermediate Node 22)​
  • D(2)[1][3]=min⁡(∞,D(1)[1][2]+D(1)[2][3])=min⁡(∞,3+2)=5D^{(2)}[1][3] = \min(\infty, D^{(1)}[1][2] + D^{(1)}[2][3]) = \min(\infty, 3 + 2) = 5
  • D(2)[3][3]=min⁡(0,8+2)=0D^{(2)}[3][3] = \min(0, 8 + 2) = 0
  • D(2)[4][3]=min⁡(∞,D(1)[4][2]+D(1)[2][3])=min⁡(∞,5+2)=7D^{(2)}[4][3] = \min(\infty, D^{(1)}[4][2] + D^{(1)}[2][3]) = \min(\infty, 5 + 2) = 7
  • Matrix D(2)D^{(2)}: D(2)=[03578021558012570]D^{(2)} = \begin{bmatrix} 0 & 3 & 5 & 7 \\ 8 & 0 & 2 & 15 \\ 5 & 8 & 0 & 1 \\ 2 & 5 & 7 & 0 \end{bmatrix}
Pass k=3k = 3 (Intermediate Node 33)​
  • D(3)[1][4]=min⁡(7,D(2)[1][3]+D(2)[3][4])=min⁡(7,5+1)=6D^{(3)}[1][4] = \min(7, D^{(2)}[1][3] + D^{(2)}[3][4]) = \min(7, 5 + 1) = 6
  • D(3)[2][4]=min⁡(15,D(2)[2][3]+D(2)[3][4])=min⁡(15,2+1)=3D^{(3)}[2][4] = \min(15, D^{(2)}[2][3] + D^{(2)}[3][4]) = \min(15, 2 + 1) = 3
  • D(3)[2][1]=min⁡(8,2+5)=7D^{(3)}[2][1] = \min(8, 2 + 5) = 7
  • Matrix D(3)D^{(3)}: D(3)=[0356702358012570]D^{(3)} = \begin{bmatrix} 0 & 3 & 5 & 6 \\ 7 & 0 & 2 & 3 \\ 5 & 8 & 0 & 1 \\ 2 & 5 & 7 & 0 \end{bmatrix}
Pass k=4k = 4 (Intermediate Node 44)​
  • D(4)[2][1]=min⁡(7,D(3)[2][4]+D(3)[4][1])=min⁡(7,3+2)=5D^{(4)}[2][1] = \min(7, D^{(3)}[2][4] + D^{(3)}[4][1]) = \min(7, 3 + 2) = 5
  • D(4)[3][1]=min⁡(5,D(3)[3][4]+D(3)[4][1])=min⁡(5,1+2)=3D^{(4)}[3][1] = \min(5, D^{(3)}[3][4] + D^{(3)}[4][1]) = \min(5, 1 + 2) = 3
  • D(4)[3][2]=min⁡(8,D(3)[3][4]+D(3)[4][2])=min⁡(8,1+5)=6D^{(4)}[3][2] = \min(8, D^{(3)}[3][4] + D^{(3)}[4][2]) = \min(8, 1 + 5) = 6

4.3.5 Final All-Pairs Distance Matrix & Complexity​

  • Final matrix D(4)D^{(4)}: D(4)=[0356502336012570]D^{(4)} = \begin{bmatrix} 0 & 3 & 5 & 6 \\ 5 & 0 & 2 & 3 \\ 3 & 6 & 0 & 1 \\ 2 & 5 & 7 & 0 \end{bmatrix}
  • Time Complexity: Θ(V3)\mathbf{\Theta(V^3)}
  • Space Complexity: Θ(V2)\mathbf{\Theta(V^2)}

4.4 Matrix Chain Multiplication (MCM)​

4.4.1 Matrix Chain Dimensions​

  • Three matrices:
    • A1A_1: dimension 10×3010 \times 30
    • A2A_2: dimension 30×530 \times 5
    • A3A_3: dimension 5×605 \times 60
  • Dimension array: p=[10,30,5,60],n=3p = [10, 30, 5, 60], \quad n = 3

4.4.2 MCM Recurrence Formula​

m[i,j]=min⁡i≤k<j{m[i,k]+m[k+1,j]+pi−1pkpj}m[i, j] = \min_{i \le k < j} \{m[i, k] + m[k+1, j] + p_{i-1} p_k p_j\}

4.4.3 Chain Length l=1l = 1 (Base Cases)​

  • Cost to multiply a single matrix: m[1,1]=0m[1, 1] = 0 m[2,2]=0m[2, 2] = 0 m[3,3]=0m[3, 3] = 0

4.4.4 Chain Length l=2l = 2 (Individual Calculations)​

  • Multiplying A1A2A_1 A_2 (i=1,j=2,k=1i = 1, j = 2, k = 1): m[1,2]=m[1,1]+m[2,2]+p0p1p2m[1, 2] = m[1, 1] + m[2, 2] + p_0 p_1 p_2 m[1,2]=0+0+(10×30×5)m[1, 2] = 0 + 0 + (10 \times 30 \times 5) m[1,2]=1500m[1, 2] = 1500 s[1,2]=1s[1, 2] = 1

  • Multiplying A2A3A_2 A_3 (i=2,j=3,k=2i = 2, j = 3, k = 2): m[2,3]=m[2,2]+m[3,3]+p1p2p3m[2, 3] = m[2, 2] + m[3, 3] + p_1 p_2 p_3 m[2,3]=0+0+(30×5×60)m[2, 3] = 0 + 0 + (30 \times 5 \times 60) m[2,3]=9000m[2, 3] = 9000 s[2,3]=2s[2, 3] = 2

4.4.5 Chain Length l=3l = 3 (Split Minimization Trace)​

  • Multiply entire chain: m[1,3]m[1, 3] (i=1,j=3i = 1, j = 3)

  • Option k=1k = 1: Split as (A1)(A2A3)(A_1)(A_2 A_3) Cost1=m[1,1]+m[2,3]+p0p1p3\text{Cost}_1 = m[1, 1] + m[2, 3] + p_0 p_1 p_3 Cost1=0+9000+(10×30×60)\text{Cost}_1 = 0 + 9000 + (10 \times 30 \times 60) Cost1=9000+18000\text{Cost}_1 = 9000 + 18000 Cost1=27,000\text{Cost}_1 = 27,000

  • Option k=2k = 2: Split as (A1A2)(A3)(A_1 A_2)(A_3) Cost2=m[1,2]+m[3,3]+p0p2p3\text{Cost}_2 = m[1, 2] + m[3, 3] + p_0 p_2 p_3 Cost2=1500+0+(10×5×60)\text{Cost}_2 = 1500 + 0 + (10 \times 5 \times 60) Cost2=1500+3000\text{Cost}_2 = 1500 + 3000 Cost2=4500\text{Cost}_2 = 4500

  • Minimum cost choice: m[1,3]=min⁡(27000,4500)=4500m[1, 3] = \min(27000, 4500) = \mathbf{4500} s[1,3]=2s[1, 3] = 2

4.4.6 Optimal Parenthesization & Multiplications Count​

  • Optimal parenthesization from split table: ((A1A2)A3)\mathbf{((A_1 A_2) A_3)}
  • Minimum scalar multiplications required: 4500\mathbf{4500}
  • Time Complexity: Θ(n3)\mathbf{\Theta(n^3)}
  • Space Complexity: Θ(n2)\mathbf{\Theta(n^2)}

4.5 Longest Common Subsequence (LCS)​

4.5.1 Input Sequences & Recurrence​

  • Sequences:
    • X="ABCBDAB"X = \text{"ABCBDAB"} (m=7m = 7)
    • Y="BDCABA"Y = \text{"BDCABA"} (n=6n = 6)
  • Recurrence: c[i,j]={0if i=0 or j=0c[i−1,j−1]+1if X[i]==Y[j]max⁡(c[i−1,j],c[i,j−1])if X[i]≠Y[j]c[i, j] = \begin{cases} 0 & \text{if } i=0 \text{ or } j=0 \\ c[i-1, j-1] + 1 & \text{if } X[i] == Y[j] \\ \max(c[i-1, j], c[i, j-1]) & \text{if } X[i] \ne Y[j] \end{cases}

4.5.2 DP Table Construction​

  • Step-by-step matching logic:
    • If X[i]==Y[j]X[i] == Y[j]: take diagonal value plus 11.
    • If X[i]≠Y[j]X[i] \ne Y[j]: take maximum of top cell c[i−1,j]c[i-1, j] and left cell c[i,j−1]c[i, j-1].

4.5.3 Complete Cell Matrix​

X↓∖Y→X \downarrow \setminus Y \to∅\emptysetBBDDCCAABBAA
∅\emptyset0000000
AA0000111
BB0111122
CC0112222
BB0112233
DD0122233
AA0122334
BB0122344

4.5.4 Backtracking the Common Subsequence​

  • Start at c[7,6]=4c[7, 6] = 4:
    • X[7]=′B′,Y[6]=′A′  ⟹  X[7] = 'B', Y[6] = 'A' \implies Mismatch. Take max(top, left)   ⟹  \implies move up to (6,6)(6, 6) with value 44.
    • X[6]=′A′,Y[6]=′A′  ⟹  X[6] = 'A', Y[6] = 'A' \implies Match! Add ′A′'A' to LCS. Move diagonal to (5,5)(5, 5) with value 33.
    • X[5]=′D′,Y[5]=′B′  ⟹  X[5] = 'D', Y[5] = 'B' \implies Mismatch. Move up to (4,5)(4, 5) with value 33.
    • Follow up to (4,5)(4, 5): X[4]=′B′,Y[5]=′B′  ⟹  X[4] = 'B', Y[5] = 'B' \implies Match! Add ′B′'B' to LCS. Move diagonal to (3,4)(3, 4) with value 22.
    • Follow up to (3,3)(3, 3): X[3]=′C′,Y[3]=′C′  ⟹  X[3] = 'C', Y[3] = 'C' \implies Match! Add ′C′'C' to LCS. Move diagonal to (2,2)(2, 2) with value 11.
    • Follow to (2,1)(2, 1): X[2]=′B′,Y[1]=′B′  ⟹  X[2] = 'B', Y[1] = 'B' \implies Match! Add ′B′'B' to LCS. Move diagonal to (1,0)(1, 0) with value 00.

4.5.5 Final LCS String & Length​

  • Reverse the matched characters:
    • Sequence: ′B′→′C′→′B′→′A′'B' \to 'C' \to 'B' \to 'A'
    • LCS String: "BCBA"\mathbf{\text{"BCBA"}} (or "BDAB"\text{"BDAB"})
  • LCS Length: 4\mathbf{4}
  • Time Complexity: Θ(m⋅n)\mathbf{\Theta(m \cdot n)}
  • Space Complexity: Θ(m⋅n)\mathbf{\Theta(m \cdot n)}
Unit - 5

Exploring Graphs​

5.1 Breadth-First Search (BFS)​

5.1.1 Graph Structure & Starting Vertex​

  • Vertices: V={1,2,3,4,5,6}V = \{1, 2, 3, 4, 5, 6\}
  • Undirected edges: (1,2),(1,3),(2,4),(2,5),(3,5),(4,6),(5,6)(1, 2), (1, 3), (2, 4), (2, 5), (3, 5), (4, 6), (5, 6)
  • Starting source vertex: 11

5.1.2 Visual Graph & Level Frontiers​

5.1.3 Step-by-Step Queue & Distance Updates​

Initialization​
  • Visited: {1}\{1\}
  • Queue: [1]
  • Distance array: d[1]=0,d[2…6]=∞d[1] = 0, \quad d[2 \dots 6] = \infty
Step 1: Dequeue 11​
  • Dequeued vertex: 11
  • Unvisited neighbors: 2,32, 3
  • Updates:
    • d[2]=d[1]+1=1d[2] = d[1] + 1 = 1
    • d[3]=d[1]+1=1d[3] = d[1] + 1 = 1
  • Enqueue: 2,32, 3
  • Queue: [2, 3]
  • Visited: {1,2,3}\{1, 2, 3\}
Step 2: Dequeue 22​
  • Dequeued vertex: 22
  • Unvisited neighbors: 4,54, 5
  • Updates:
    • d[4]=d[2]+1=2d[4] = d[2] + 1 = 2
    • d[5]=d[2]+1=2d[5] = d[2] + 1 = 2
  • Enqueue: 4,54, 5
  • Queue: [3, 4, 5]
  • Visited: {1,2,3,4,5}\{1, 2, 3, 4, 5\}
Step 3: Dequeue 33​
  • Dequeued vertex: 33
  • Neighbors: 11 (already visited), 55 (already visited)
  • No new vertices enqueued.
  • Queue: [4, 5]
Step 4: Dequeue 44​
  • Dequeued vertex: 44
  • Unvisited neighbors: 66
  • Updates:
    • d[6]=d[4]+1=3d[6] = d[4] + 1 = 3
  • Enqueue: 66
  • Queue: [5, 6]
  • Visited: {1,2,3,4,5,6}\{1, 2, 3, 4, 5, 6\}
Step 5: Dequeue 55​
  • Dequeued vertex: 55
  • Neighbors: 2,3,62, 3, 6 (all visited)
  • Queue: [6]
Step 6: Dequeue 66​
  • Dequeued vertex: 66
  • Queue: [] (Empty)
  • Traversal complete.

5.1.4 Final BFS Traversal Sequence & Tree Edges​

  • BFS Node Visitation Order: 1→2→3→4→5→6\mathbf{1 \to 2 \to 3 \to 4 \to 5 \to 6}
  • BFS Tree Edges: (1,2),(1,3),(2,4),(2,5),(4,6)(1, 2), \quad (1, 3), \quad (2, 4), \quad (2, 5), \quad (4, 6)
  • Time Complexity: O(V+E)\mathbf{O(V + E)}
  • Space Complexity: O(V)\mathbf{O(V)} (Queue).

5.2 Depth-First Search (DFS) & Edge Classification​

5.2.1 Graph Structure & Initialization​

  • Directed graph with vertices {1,2,3,4}\{1, 2, 3, 4\}:
    • 1→21 \to 2
    • 1→31 \to 3
    • 2→42 \to 4
    • 3→43 \to 4
    • 4→14 \to 1
  • Global timer: time=0\text{time} = 0

5.2.2 Visual DFS Edge Classification Graph​

5.2.3 Step-by-Step Recursion Stack & Timestamp Trace (d[u],f[u]d[u], f[u])​

  • Step 1: Visit node 11:
    • time=1\text{time} = 1
    • Discovery time: d[1]=1d[1] = 1
  • Step 2: Traverse tree edge 1→21 \to 2, visit node 22:
    • time=2\text{time} = 2
    • Discovery time: d[2]=2d[2] = 2
  • Step 3: Traverse tree edge 2→42 \to 4, visit node 44:
    • time=3\text{time} = 3
    • Discovery time: d[4]=3d[4] = 3
  • Step 4: Explore edge 4→14 \to 1:
    • Node 11 is currently in the active recursion stack (GRAY).
    • This indicates an ancestor relationship.
    • Classification: Back Edge (Cycle detected!)
  • Step 5: Finish node 44:
    • time=4\text{time} = 4
    • Finishing time: f[4]=4f[4] = 4
  • Step 6: Backtrack to node 22 and finish:
    • time=5\text{time} = 5
    • Finishing time: f[2]=5f[2] = 5
  • Step 7: Backtrack to node 11, explore tree edge 1→31 \to 3, visit node 33:
    • time=6\text{time} = 6
    • Discovery time: d[3]=6d[3] = 6
  • Step 8: Explore edge 3→43 \to 4:
    • Node 44 is already completely processed (BLACK) and is not an ancestor.
    • Classification: Cross Edge
  • Step 9: Finish node 33:
    • time=7\text{time} = 7
    • Finishing time: f[3]=7f[3] = 7
  • Step 10: Finish node 11:
    • time=8\text{time} = 8
    • Finishing time: f[1]=8f[1] = 8

5.2.4 Edge Classification Summary​

  • Tree Edges: (1→2),(2→4),(1→3)(1 \to 2), (2 \to 4), (1 \to 3)
  • Back Edge: (4→1)(4 \to 1)
  • Cross Edge: (3→4)(3 \to 4)
  • Time Complexity: O(V+E)\mathbf{O(V + E)}

5.3 Topological Sorting​

5.3.1 DAG Definition & Visual Graph​

  • Directed Acyclic Graph (DAG) with vertices {A,B,C,D,E}\{A, B, C, D, E\}:

5.3.2 Kahn's Algorithm Trace (In-Degree Elimination)​

Step 1: In-Degree Calculation​
  • Node AA: in(A)=0\text{in}(A) = 0
  • Node BB: in(B)=1\text{in}(B) = 1
  • Node CC: in(C)=1\text{in}(C) = 1
  • Node DD: in(D)=2\text{in}(D) = 2
  • Node EE: in(E)=1\text{in}(E) = 1
Step 2: Initialize Queue​
  • Enqueue nodes with in-degree 00: Queue=[A]\text{Queue} = [A]
Step 3: Dequeue AA​
  • Output: AA
  • Decrement neighbor in-degrees:
    • in(B)=1−1=0  ⟹  \text{in}(B) = 1 - 1 = 0 \implies Enqueue BB
    • in(C)=1−1=0  ⟹  \text{in}(C) = 1 - 1 = 0 \implies Enqueue CC
  • Queue=[B,C]\text{Queue} = [B, C]
Step 4: Dequeue BB​
  • Output: BB
  • Decrement neighbor in-degrees:
    • in(D)=2−1=1\text{in}(D) = 2 - 1 = 1
  • Queue=[C]\text{Queue} = [C]
Step 5: Dequeue CC​
  • Output: CC
  • Decrement neighbor in-degrees:
    • in(D)=1−1=0  ⟹  \text{in}(D) = 1 - 1 = 0 \implies Enqueue DD
  • Queue=[D]\text{Queue} = [D]
Step 6: Dequeue DD​
  • Output: DD
  • Decrement neighbor in-degrees:
    • in(E)=1−1=0  ⟹  \text{in}(E) = 1 - 1 = 0 \implies Enqueue EE
  • Queue=[E]\text{Queue} = [E]
Step 7: Dequeue EE​
  • Output: EE
  • Decrement neighbors: None
  • Queue=[]\text{Queue} = []

5.3.3 Linear Topological Order Flow​

  • Topological ordering: A→B→C→D→E\mathbf{A \to B \to C \to D \to E}
  • Time Complexity: O(V+E)\mathbf{O(V + E)}

5.4 Strongly Connected Components (Kosaraju's Algorithm)​

5.4.1 Directed Graph Input & Component Subgraphs​

5.4.2 Pass 1: Forward DFS & Finish-Time Stack​

  • Run DFS on original graph GG:
    • Start at 1→2→3→4→51 \to 2 \to 3 \to 4 \to 5
    • Finish 5  ⟹  5 \implies Push 55
    • Finish 4  ⟹  4 \implies Push 44
    • Finish 3  ⟹  3 \implies Push 33
    • Finish 2  ⟹  2 \implies Push 22
    • Finish 1  ⟹  1 \implies Push 11
  • Resulting Stack (top to bottom): Stack=[1,2,3,4,5]\text{Stack} = [1, 2, 3, 4, 5]

5.4.3 Pass 2: Transpose Graph GTG^T Construction​

  • Reverse the direction of all edges: 2→1,3→2,1→3,4→3,5→4,4→52 \to 1, \quad 3 \to 2, \quad 1 \to 3, \quad 4 \to 3, \quad 5 \to 4, \quad 4 \to 5

5.4.4 Pass 3: Reverse DFS & SCC Extraction​

  • Pop 11 from Stack:
    • DFS on GTG^T from 11 visits: {1,3,2}\{1, 3, 2\}
    • Component 1: {1,2,3}\{1, 2, 3\}
  • Next unvisited on Stack is 44:
    • Pop 44 from Stack
    • DFS on GTG^T from 44 visits: {4,5}\{4, 5\}
    • Component 2: {4,5}\{4, 5\}
  • Strongly Connected Components: {1,2,3}and{4,5}\mathbf{\{1, 2, 3\}} \quad \text{and} \quad \mathbf{\{4, 5\}}
  • Time Complexity: O(V+E)\mathbf{O(V + E)}

5.5 Articulation Points & Bridges​

5.5.1 Graph Problem Input & Visual Diagram​

  • Undirected graph with 55 vertices:

5.5.2 Discovery Times and Low Values (disc[u],low[u]disc[u], low[u])​

  • DFS traversal starting at node 11:
    • Visit 11: disc[1]=1,low[1]=1disc[1] = 1, low[1] = 1
    • Visit 22: disc[2]=2,low[2]=2disc[2] = 2, low[2] = 2
    • Visit 33: disc[3]=3,low[3]=3disc[3] = 3, low[3] = 3
    • Back edge (3−1)(3-1): low[3]=min⁡(3,disc[1])=1low[3] = \min(3, disc[1]) = 1
    • Propagate back to 22: low[2]=min⁡(2,low[3])=1low[2] = \min(2, low[3]) = 1
    • Propagate back to 11: low[1]=1low[1] = 1
    • From 33, explore tree edge 3−43-4:
      • Visit 44: disc[4]=4,low[4]=4disc[4] = 4, low[4] = 4
      • Explore tree edge 4−54-5:
        • Visit 55: disc[5]=5,low[5]=5disc[5] = 5, low[5] = 5

5.5.3 Cut Vertex Condition Testing​

  • Non-root condition: Vertex uu is an articulation point if it has a child vv such that: low[v]≥disc[u]low[v] \ge disc[u]
  • Test Node 33 with child 44: low[4]=4,disc[3]=3low[4] = 4, \quad disc[3] = 3 4≥3  ⟹  Node 3 is an Articulation Point!4 \ge 3 \implies \mathbf{\text{Node 3 is an Articulation Point!}}
  • Test Node 44 with child 55: low[5]=5,disc[4]=4low[5] = 5, \quad disc[4] = 4 5≥4  ⟹  Node 4 is an Articulation Point!5 \ge 4 \implies \mathbf{\text{Node 4 is an Articulation Point!}}

5.5.4 Bridge Condition Testing & Output​

  • Bridge condition: Edge (u,v)(u, v) is a bridge if: low[v]>disc[u]low[v] > disc[u]
  • Test edge (3,4)(3, 4): low[4]=4>disc[3]=3  ⟹  Edge (3,4) is a Bridge!low[4] = 4 > disc[3] = 3 \implies \mathbf{\text{Edge }(3, 4)\text{ is a Bridge!}}
  • Test edge (4,5)(4, 5): low[5]=5>disc[4]=4  ⟹  Edge (4,5) is a Bridge!low[5] = 5 > disc[4] = 4 \implies \mathbf{\text{Edge }(4, 5)\text{ is a Bridge!}}
  • Articulation Points: {3,4}\{3, 4\}
  • Bridges: {(3,4),(4,5)}\{(3, 4), (4, 5)\}
  • Time Complexity: O(V+E)\mathbf{O(V + E)}
Unit - 6

Backtracking & Branch and Bound​

6.1 4-Queens Problem (Backtracking)​

6.1.1 Problem Statement & Board Model​

  • Place 44 queens on a 4×44 \times 4 chessboard such that no two queens attack each other.
  • Representation: array col[1..4] where col[i] is the column of the queen in row ii.

6.1.2 Non-Attacking Constraints​

  • Two queens in rows ii and jj conflict if:
    • Same column: col[i]==col[j]col[i] == col[j]
    • Same diagonal: ∣col[i]−col[j]∣==∣i−j∣|col[i] - col[j]| == |i - j|

6.1.3 Visual State-Space Search Tree​

6.1.4 Step-by-Step Exploration & Pruning​

Row 1: Place Queen 1​
  • Try Column 1:
    • col[1]=1\text{col}[1] = 1
    • State: [1, _, _, _]
Row 2: Place Queen 2​
  • Try Column 1: Conflict with Q1Q_1 (same column).
  • Try Column 2: Conflict with Q1Q_1 (∣2−1∣==∣2−1∣|2 - 1| == |2 - 1| diagonal).
  • Try Column 3: Safe!
    • col[2]=3\text{col}[2] = 3
    • State: [1, 3, _, _]
Row 3: Place Queen 3​
  • Try Column 1: Conflict with Q1Q_1 (same column).
  • Try Column 2: Conflict with Q2Q_2 (∣2−3∣==∣3−2∣|2 - 3| == |3 - 2| diagonal).
  • Try Column 3: Conflict with Q2Q_2 (same column).
  • Try Column 4: Conflict with Q2Q_2 (∣4−3∣==∣3−2∣|4 - 3| == |3 - 2| diagonal).
  • Dead end! No safe column in Row 3.
  • Action: Backtrack to Row 2.
Row 2 (Re-try):​
  • Try Column 4: Safe!
    • col[2]=4\text{col}[2] = 4
    • State: [1, 4, _, _]
Row 3:​
  • Try Column 1: Conflict with Q1Q_1.
  • Try Column 2: Safe!
    • col[3]=2\text{col}[3] = 2
    • State: [1, 4, 2, _]
Row 4:​
  • Try Column 1: Conflict with Q3Q_3 (∣1−2∣==∣4−3∣|1 - 2| == |4 - 3|).
  • Try Column 2: Conflict with Q3Q_3 (same column).
  • Try Column 3: Conflict with Q3Q_3 (∣3−2∣==∣4−3∣|3 - 2| == |4 - 3|).
  • Try Column 4: Conflict with Q2Q_2 (same column).
  • Dead end!
  • Action: Backtrack all the way to Row 1.
Row 1 (Re-try): Place Queen 1 at Column 2​
  • Try Column 2:
    • col[1]=2\text{col}[1] = 2
    • State: [2, _, _, _]
Row 2:​
  • Try Column 1: Conflict with Q1Q_1 diagonal.
  • Try Column 2: Conflict with Q1Q_1 column.
  • Try Column 3: Conflict with Q1Q_1 diagonal.
  • Try Column 4: Safe!
    • col[2]=4\text{col}[2] = 4
    • State: [2, 4, _, _]
Row 3:​
  • Try Column 1: Safe!
    • col[3]=1\text{col}[3] = 1
    • State: [2, 4, 1, _]
Row 4:​
  • Try Column 1: Conflict with Q3Q_3 column.
  • Try Column 2: Conflict with Q1Q_1 column.
  • Try Column 3: Safe!
    • col[4]=3\text{col}[4] = 3
    • State: [2, 4, 1, 3]

6.1.5 Final Solution Placement & Vector​

  • Solution Vector: [2,4,1,3]\mathbf{[2, 4, 1, 3]}
  • Visual Chessboard:
. Q . . (Row 1: Queen at Col 2)
. . . Q (Row 2: Queen at Col 4)
Q . . . (Row 3: Queen at Col 1)
. . Q . (Row 4: Queen at Col 3)
  • Time Complexity: O(N!)\mathbf{O(N!)}

6.2 0/1 Knapsack using Backtracking​

6.2.1 Problem Parameters & Items​

  • Capacity: W=7W = 7
  • Items sorted by Pi/WiP_i / W_i:
    • I1I_1: w1=3,p1=12w_1 = 3, p_1 = 12 (Ratio =4.0= 4.0)
    • I2I_2: w2=4,p2=16w_2 = 4, p_2 = 16 (Ratio =4.0= 4.0)
    • I3I_3: w3=5,p3=15w_3 = 5, p_3 = 15 (Ratio =3.0= 3.0)

6.2.2 State-Space Tree Exploration​

  • Root: weight =0= 0, profit =0= 0, best profit =0= 0.
Branch Left (Include I1I_1):​
  • Weight: 0+3=3≤70 + 3 = 3 \le 7
  • Profit: 0+12=120 + 12 = 12
    • Branch Left (Include I2I_2):
      • Weight: 3+4=7≤73 + 4 = 7 \le 7
      • Profit: 12+16=2812 + 16 = 28
      • Update best profit: best=28\text{best} = 28
        • Branch Left (Include I3I_3):
          • Weight: 7+5=12>77 + 5 = 12 > 7 (Over capacity!)
          • Prune: Infeasible branch.
        • Branch Right (Exclude I3I_3):
          • Leaf reached with profit 2828.
    • Branch Right (Exclude I2I_2):
      • Weight: 33
      • Profit: 1212
      • Maximum possible profit with remaining I3I_3: Bound=12+15=27\text{Bound} = 12 + 15 = 27
      • Since 27<best(28)27 < \text{best}(28):
        • Prune: Promising check fails.
Branch Right (Exclude I1I_1):​
  • Weight: 00
  • Profit: 00
  • Maximum possible profit with I2,I3I_2, I_3: Bound=16+15=31>28\text{Bound} = 16 + 15 = 31 > 28
    • Branch Left (Include I2I_2):
      • Weight: 44, Profit: 1616
      • Try include I3I_3: Weight 4+5=9>7  ⟹  4 + 5 = 9 > 7 \implies Infeasible.
      • Exclude I3I_3: Profit is 16<2816 < 28.
    • Branch Right (Exclude I2I_2):
      • Only I3I_3 left   ⟹  \implies Max profit 15<28  ⟹  15 < 28 \implies Prune.

6.2.3 Pruning Checks & Best Profit Updates​

  • Optimal solution: {I1,I2}\{I_1, I_2\}
  • Max profit: 28\mathbf{28}
  • Weight used: 3+4=73 + 4 = 7

6.3 0/1 Knapsack using Branch & Bound (LC-BB)​

6.3.1 Problem Instance & Relaxation Model​

  • Capacity: W=15W = 15
  • Sorted items:
    • I1I_1: w=2,p=10w = 2, p = 10 (p/w=5.0p/w = 5.0)
    • I2I_2: w=4,p=10w = 4, p = 10 (p/w=2.5p/w = 2.5)
    • I3I_3: w=6,p=12w = 6, p = 12 (p/w=2.0p/w = 2.0)
    • I4I_4: w=9,p=18w = 9, p = 18 (p/w=2.0p/w = 2.0)

6.3.2 Upper Bound (UBUB) Formula via Fractional Knapsack​

  • Upper bound formula at any node: UB=Current Profit+Fractional Knapsack on Remaining CapacityUB = \text{Current Profit} + \text{Fractional Knapsack on Remaining Capacity}

6.3.3 State-Space Tree Expansion & Priority Queue State​

  • Root Node (Node 1):
    • Current weight: 00
    • Current profit: 00
    • Take I1I_1 (w=2,p=10w=2, p=10), I2I_2 (w=4,p=10w=4, p=10), I3I_3 (w=6,p=12w=6, p=12)
    • Total weight: 1212, Total profit: 3232
    • Remaining capacity: 15−12=315 - 12 = 3
    • Fractional part of I4I_4: 39×18=6\frac{3}{9} \times 18 = 6
    • Upper Bound: UB=32+6=38UB = 32 + 6 = \mathbf{38}

6.3.4 Node Pruning & Optimal Leaf Finding​

  • Branch Left (Include I1I_1):
    • Current weight: 22, Profit: 1010
    • Upper Bound remains 3838.
  • Branch Right (Exclude I1I_1):
    • Upper bound drops below 3232.
  • Expanding promising nodes:
    • Take {I1,I2,I4}\{I_1, I_2, I_4\}:
      • Weight: 2+4+9=15≤152 + 4 + 9 = 15 \le 15
      • Profit: 10+10+18=3810 + 10 + 18 = \mathbf{38}
  • Any node with UB≤38UB \le 38 is pruned.
  • Final optimal profit: 38\mathbf{38}

6.4 Minimax Principle & Alpha-Beta Pruning​

6.4.1 Game Tree Layout & Visual Cutoff Diagram​

6.4.2 Alpha (α\alpha) and Beta (β\beta) Boundary Definitions​

  • α\alpha: Best score that Maximizer can guarantee so far (−∞-\infty initially).
  • β\beta: Best score that Minimizer can guarantee so far (+∞+\infty initially).
  • Prune condition: α≥β\alpha \ge \beta

6.4.3 Step-by-Step Node Evaluations & Cutoffs​

Subtree Under BB​
  • Leaf 1 under DD: value 33
  • Leaf 2 under DD: value 55
  • Node DD (MIN) selects: min⁡(3,5)=3\min(3, 5) = 3
  • Node BB (MIN) updates beta: βB=min⁡(+∞,3)=3\beta_B = \min(+\infty, 3) = 3
  • Subtree EE:
    • Leaf 1 under EE: value 66
    • Since 6>βB(3)6 > \beta_B(3), MIN at node BB will never select a value from EE.
  • Node BB returns value 33.
Root Node AA​
  • Node AA (MAX) receives 33 from child BB.
  • Update alpha: αA=max⁡(−∞,3)=3\alpha_A = \max(-\infty, 3) = \mathbf{3}
Subtree Under CC​
  • Node CC inherits α=3,β=+∞\alpha = 3, \beta = +\infty.
  • Subtree FF:
    • Leaf 1 under FF: value 11
    • Leaf 2 under FF: value 22
    • Node FF evaluates to: min⁡(1,2)=1\min(1, 2) = 1
  • Node CC (MIN) updates beta: βC=min⁡(+∞,1)=1\beta_C = \min(+\infty, 1) = \mathbf{1}
  • Pruning Check at Node CC: α=3,β=1\alpha = 3, \quad \beta = 1 α≥β(3≥1)\alpha \ge \beta \quad (3 \ge 1)
  • Condition Met: Cutoff / Prune Subtree GG entirely!
  • Leaves under GG (00 and 77) are never evaluated.

6.4.4 Final Root Optimal Decision​

  • Optimal minimax value at root: 3\mathbf{3}

6.5 Travelling Salesperson Problem (TSP) using Branch & Bound​

6.5.1 Cost Matrix Definition​

  • Initial 4×44 \times 4 cost matrix: M=[∞1015205∞910613∞12889∞]M = \begin{bmatrix} \infty & 10 & 15 & 20 \\ 5 & \infty & 9 & 10 \\ 6 & 13 & \infty & 12 \\ 8 & 8 & 9 & \infty \end{bmatrix}

6.5.2 Visual City Graph​

6.5.3 Row Reductions Step-by-Step​

  • Row 1: minimum is 1010
    • Subtract 1010: [∞,0,5,10][\infty, 0, 5, 10]
    • Reduction r1=10r_1 = 10
  • Row 2: minimum is 55
    • Subtract 55: [0,∞,4,5][0, \infty, 4, 5]
    • Reduction r2=5r_2 = 5
  • Row 3: minimum is 66
    • Subtract 66: [0,7,∞,6][0, 7, \infty, 6]
    • Reduction r3=6r_3 = 6
  • Row 4: minimum is 88
    • Subtract 88: [0,0,1,∞][0, 0, 1, \infty]
    • Reduction r4=8r_4 = 8
  • Sum of row reductions: ∑ri=10+5+6+8=29\sum r_i = 10 + 5 + 6 + 8 = 29

6.5.4 Column Reductions Step-by-Step​

  • Reduced matrix after row reduction: [∞05100∞4507∞6001∞]\begin{bmatrix} \infty & 0 & 5 & 10 \\ 0 & \infty & 4 & 5 \\ 0 & 7 & \infty & 6 \\ 0 & 0 & 1 & \infty \end{bmatrix}
  • Column 1: has 0  ⟹  c1=00 \implies c_1 = 0
  • Column 2: has 0  ⟹  c2=00 \implies c_2 = 0
  • Column 3: minimum is 11
    • Subtract 11: [4,3,∞,0]T[4, 3, \infty, 0]^T
    • Reduction c3=1c_3 = 1
  • Column 4: minimum is 55
    • Subtract 55: [5,0,1,∞]T[5, 0, 1, \infty]^T
    • Reduction c4=5c_4 = 5
  • Sum of column reductions: ∑cj=0+0+1+5=6\sum c_j = 0 + 0 + 1 + 5 = 6

6.5.5 Initial Lower Bound Calculation​

  • Root Lower Bound: Bound(Root)=∑ri+∑cj=29+6=35\text{Bound}(\text{Root}) = \sum r_i + \sum c_j = 29 + 6 = \mathbf{35}

6.5.6 Branching & Child Bound Computations​

  • Child bound formula for moving from city ii to city jj: Bound(child)=Bound(parent)+A[i,j]+r\text{Bound}(child) = \text{Bound}(parent) + A[i, j] + r
  • Set row ii to ∞\infty
  • Set column jj to ∞\infty
  • Set cell (j,1)(j, 1) to ∞\infty
  • The branch with the minimum lower bound is explored until the full tour 1→A→B→C→11 \to A \to B \to C \to 1 completes.

6.5.7 Optimal Tour & Minimum Cost​

  • Optimal tour cost: 35\mathbf{35}
Unit - 7

String Matching & NP-Completeness​

7.1 Naive String Matching​

7.1.1 Problem Strings (Text & Pattern)​

  • Text: T="AABAACAADAABAABA"(n=16)T = \text{"AABAACAADAABAABA"} \quad (n = 16)
  • Pattern: P="AABA"(m=4)P = \text{"AABA"} \quad (m = 4)
  • Possible shifts: s=0s = 0 to n−m=16−4=12n - m = 16 - 4 = 12

7.1.2 Shift-by-Shift Character Comparison Trace​

Shift s=0s = 0:​
  • Substring T[0…3]="AABA"T[0 \dots 3] = \text{"AABA"}
  • Compare with P="AABA"P = \text{"AABA"}
  • All 44 characters match.
  • Match found at index 00!
Shift s=1s = 1:​
  • Substring T[1…4]="ABAA"T[1 \dots 4] = \text{"ABAA"}
  • Compare: T[1]=′A′==P[0]T[1] = 'A' == P[0], but T[2]=′B′≠P[1](′A′)T[2] = 'B' \ne P[1]('A').
  • Mismatch after 11 comparison.
Shift s=2s = 2:​
  • Substring T[2…5]="BAAC"T[2 \dots 5] = \text{"BAAC"}
  • Compare: T[2]=′B′≠P[0](′A′)T[2] = 'B' \ne P[0]('A').
  • Immediate mismatch.
Shift s=9s = 9:​
  • Substring T[9…12]="AABA"T[9 \dots 12] = \text{"AABA"}
  • Compare with PP: All characters match.
  • Match found at index 99!
Shift s=12s = 12:​
  • Substring T[12…15]="AABA"T[12 \dots 15] = \text{"AABA"}
  • Compare with PP: All characters match.
  • Match found at index 1212!

7.1.3 Valid Matches & Worst-Case Analysis​

  • Valid match shifts: s∈{0,9,12}\mathbf{s \in \{0, 9, 12\}}
  • Time Complexity:
    • Best Case: O(n)O(n)
    • Worst Case: O((n−m+1)m)\mathbf{O((n - m + 1) m)}

7.2 Rabin-Karp Algorithm (Rolling Hash)​

7.2.1 Problem Parameters​

  • Text: T="31415926535"T = \text{"31415926535"}
  • Pattern: P="26"P = \text{"26"}
  • Pattern length: m=2m = 2
  • Radix / Base: d=10d = 10
  • Prime modulus: q=11q = 11
  • High-order multiplier: h=dm−1(modq)=102−1(mod11)=10h = d^{m-1} \pmod q = 10^{2-1} \pmod{11} = 10

7.2.2 Pattern Hash Calculation​

  • Direct value: 2626
  • Hash: p=26(mod11)=4p = 26 \pmod{11} = \mathbf{4}

7.2.3 Window-by-Window Rolling Hash Trace​

  • Window 0 ("31"): t0=31(mod11)=9≠4t_0 = 31 \pmod{11} = 9 \ne 4
  • Window 1 ("14"): t1=14(mod11)=3≠4t_1 = 14 \pmod{11} = 3 \ne 4
  • Window 2 ("41"): t2=41(mod11)=8≠4t_2 = 41 \pmod{11} = 8 \ne 4
  • Window 3 ("15"): t3=15(mod11)=4==pt_3 = 15 \pmod{11} = 4 == p
    • Hash match! Verify characters:
    • String "15" ≠\ne "26"
    • Spurious Hit!
  • Window 4 ("59"): t4=59(mod11)=4==pt_4 = 59 \pmod{11} = 4 == p
    • Hash match! String "59" ≠\ne "26"
    • Spurious Hit!
  • Window 5 ("92"): t5=92(mod11)=4==pt_5 = 92 \pmod{11} = 4 == p
    • Hash match! String "92" ≠\ne "26"
    • Spurious Hit!
  • Window 6 ("26"): t6=26(mod11)=4==pt_6 = 26 \pmod{11} = 4 == p
    • Hash match! Verify characters:
    • String "26" ==== "26"
    • Valid Match found at Shift 66!

7.2.4 Rolling Hash Formula Calculation Step-by-Step​

  • Shift formula: ts+1=(d(ts−T[s+1]⋅h)+T[s+m+1])(modq)t_{s+1} = \left( d (t_s - T[s+1] \cdot h) + T[s+m+1] \right) \pmod q
  • Example: Transition from Window 0 ("31") to Window 1 ("14"):
    • Outgoing digit: 33
    • Incoming digit: 44
    • Calculation: t1=(10(31−3×10)+4)(mod11)t_1 = (10(31 - 3 \times 10) + 4) \pmod{11} t1=(10(1)+4)(mod11)=14(mod11)=3t_1 = (10(1) + 4) \pmod{11} = 14 \pmod{11} = 3
  • Time Complexity:
    • Average Case: O(n+m)\mathbf{O(n + m)}
    • Worst Case: O((n−m+1)m)\mathbf{O((n - m + 1)m)}

7.3 String Matching with Finite Automata (FA)​

7.3.1 Automaton Model (States & Alphabet)​

  • Pattern: P="aba"P = \text{"aba"}
  • Alphabet: Σ={a,b}\Sigma = \{a, b\}
  • States: {0,1,2,3}\{0, 1, 2, 3\}
  • Initial State: 00
  • Accepting State: 33

7.3.2 Visual Automaton State Diagram​

7.3.3 State Transition Function (δ(q,a)\delta(q, a)) Computation​

  • Definition: δ(q,c)\delta(q, c) is the length of the longest prefix of PP that is a suffix of PqcP_q c.
  • From State 00 (∅\emptyset):
    • On ′a′'a': Longest prefix of "aba" in "a" is "a"   ⟹  \implies State 11.
    • On ′b′'b': Longest prefix in "b" is ∅  ⟹  \emptyset \implies State 00.
  • From State 11 ("a"):
    • On ′a′'a': Suffix of "aa" is "a"   ⟹  \implies State 11.
    • On ′b′'b': Suffix of "ab" is "ab"   ⟹  \implies State 22.
  • From State 22 ("ab"):
    • On ′a′'a': Suffix of "aba" is "aba"   ⟹  \implies State 33.
    • On ′b′'b': Suffix of "abb" is ∅  ⟹  \emptyset \implies State 00.
  • From State 33 ("aba"):
    • On ′a′'a': Suffix of "abaa" is "a"   ⟹  \implies State 11.
    • On ′b′'b': Suffix of "abab" is "ab"   ⟹  \implies State 22.

7.3.4 Complete State Transition Table​

State qqInput 'a'Input 'b'
010
112
230
312

7.3.5 Text Processing State Trace​

  • Input Text: T="ababa"T = \text{"ababa"}
    • Start at state: 00
    • Read T[1]=′a′  ⟹  T[1] = 'a' \implies State 11
    • Read T[2]=′b′  ⟹  T[2] = 'b' \implies State 22
    • Read T[3]=′a′  ⟹  T[3] = 'a' \implies State 33 (Match at index 3!)
    • Read T[4]=′b′  ⟹  T[4] = 'b' \implies State 22
    • Read T[5]=′a′  ⟹  T[5] = 'a' \implies State 33 (Match at index 5!)
  • Matching Time: Θ(n)\mathbf{\Theta(n)}

7.4 Knuth-Morris-Pratt (KMP) Algorithm​

7.4.1 Pattern Definition & Prefix Function Concept​

  • Pattern: P="ababaca"P = \text{"ababaca"}
  • Length: m=7m = 7
  • Prefix function π[i]\pi[i] represents the length of the longest proper prefix of P[1…i]P[1 \dots i] that is also a suffix of P[1…i]P[1 \dots i].

7.4.2 Step-by-Step π\pi (LPS) Array Calculation​

Index i=1i = 1: Substring "a"​
  • No proper prefix exists.
  • π[1]=0\pi[1] = \mathbf{0}
Index i=2i = 2: Substring "ab"​
  • Proper prefixes: {"a"}
  • Proper suffixes: {"b"}
  • Match: None
  • π[2]=0\pi[2] = \mathbf{0}
Index i=3i = 3: Substring "aba"​
  • Proper prefixes: {"a", "ab"}
  • Proper suffixes: {"a", "ba"}
  • Longest match: "a" (length 11)
  • π[3]=1\pi[3] = \mathbf{1}
Index i=4i = 4: Substring "abab"​
  • Proper prefixes: {"a", "ab", "aba"}
  • Proper suffixes: {"b", "ab", "bab"}
  • Longest match: "ab" (length 22)
  • π[4]=2\pi[4] = \mathbf{2}
Index i=5i = 5: Substring "ababa"​
  • Proper prefixes: {"a", "ab", "aba", "abab"}
  • Proper suffixes: {"a", "ba", "aba", "baba"}
  • Longest match: "aba" (length 33)
  • π[5]=3\pi[5] = \mathbf{3}
Index i=6i = 6: Substring "ababac"​
  • New character ′c′'c' mismatches with ′b′'b'.
  • Longest matching proper prefix-suffix: None.
  • π[6]=0\pi[6] = \mathbf{0}
Index i=7i = 7: Substring "ababaca"​
  • Proper prefixes: {"a", ...}
  • Proper suffixes: {"a", ...}
  • Longest match: "a" (length 11)
  • π[7]=1\pi[7] = \mathbf{1}

7.4.3 Complete π\pi Table​

ii1234567
P[i]P[i]ababaca
π[i]\pi[i]0012301

7.4.4 Text Search Walkthrough (No Backtracking on Text)​

  • Text: T="abababaca"T = \text{"abababaca"}
  • Indices 11 to 55:
    • T[1…5]="ababa"T[1 \dots 5] = \text{"ababa"} matches P[1…5]P[1 \dots 5].
  • Index 66:
    • T[6]=′b′T[6] = 'b', but P[6]=′c′P[6] = 'c' (Mismatch).
  • Shift without text backtracking:
    • Current matched length: 55.
    • Lookup π[5]=3\pi[5] = 3.
    • Resume comparison with P[3+1]=P[4]=′b′P[3 + 1] = P[4] = 'b'.
    • Compare T[6](′b′)T[6]('b') with P[4](′b′)P[4]('b')   ⟹  \implies Direct match!
  • Preprocessing Time: Θ(m)\mathbf{\Theta(m)}
  • Matching Time: Θ(n)\mathbf{\Theta(n)}
  • Total Time: Θ(n+m)\mathbf{\Theta(n + m)}

7.5 NP-Completeness Foundations & Polynomial-Time Reduction​

7.5.1 Definitions: P, NP, NP-Hard, NP-Complete​

  • Class P: Problems solvable in polynomial time (O(nk)O(n^k)).
  • Class NP: Decision problems whose solutions are verifiable in polynomial time.
  • NP-Hard: Problems at least as hard as any problem in NP (not necessarily in NP).
  • NP-Complete: Problems that are both in NP and NP-Hard.

7.5.2 3-SAT to CLIQUE Reduction Example​

  • 3-CNF Boolean formula ϕ\phi with kk clauses: ϕ=(x1∨¬x2∨x3)∧(¬x1∨x2∨x4)\phi = (x_1 \lor \neg x_2 \lor x_3) \land (\neg x_1 \lor x_2 \lor x_4)
  • Number of clauses: k=2k = 2

7.5.3 Visual Reduction Graph Diagram​

7.5.4 Graph Transformation Step-by-Step​

  • Clause 1: create vertices for literals v1,1(x1),v1,2(¬x2),v1,3(x3)v_{1,1}(x_1), v_{1,2}(\neg x_2), v_{1,3}(x_3).
  • Clause 2: create vertices for literals v2,1(¬x1),v2,2(x2),v2,3(x4)v_{2,1}(\neg x_1), v_{2,2}(x_2), v_{2,3}(x_4).
  • Edge placement rule:
    • Connect two vertices if they are in different clauses AND are not complementary (i.e. not xix_i and ¬xi\neg x_i).

7.5.5 Equivalence Proof Walkthrough​

  • If ϕ\phi is satisfiable:
    • Choosing assignment x1=True,x2=Truex_1 = \text{True}, x_2 = \text{True}:
    • Literal x1x_1 in Clause 1 is True.
    • Literal x2x_2 in Clause 2 is True.
    • They are in different clauses and not contradictory.
    • An edge exists between them, forming a Clique of size k=2k = 2.
  • If graph has a kk-clique:
    • Exactly one vertex per clause is chosen.
    • Since no edges exist between contradictory literals, setting all selected literals to True satisfies formula ϕ\phi.
  • Proves 3-SAT≤PCLIQUE\text{3-SAT} \le_P \text{CLIQUE}.

8. Master Algorithm Complexity Reference Table​

UnitAlgorithmBest Case TimeAverage Case TimeWorst Case TimeSpace Complexity
U1Karatsuba MultiplicationΘ(n1.585)\Theta(n^{1.585})Θ(n1.585)\Theta(n^{1.585})Θ(n1.585)\Theta(n^{1.585})O(n)O(n)
U2Binary SearchO(1)O(1)O(log⁡n)O(\log n)O(log⁡n)O(\log n)O(1)O(1)
U2Merge SortΘ(nlog⁡n)\Theta(n \log n)Θ(nlog⁡n)\Theta(n \log n)Θ(nlog⁡n)\Theta(n \log n)O(n)O(n)
U2Quick SortO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(n2)O(n^2)O(log⁡n)O(\log n)
U2Strassen Matrix MultΘ(n2.807)\Theta(n^{2.807})Θ(n2.807)\Theta(n^{2.807})Θ(n2.807)\Theta(n^{2.807})O(n2)O(n^2)
U2Modular ExponentiationO(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)
U3Kruskal's MSTO(Elog⁡E)O(E \log E)O(Elog⁡E)O(E \log E)O(Elog⁡E)O(E \log E)O(V)O(V)
U3Prim's MST (Min-Heap)O(Elog⁡V)O(E \log V)O(Elog⁡V)O(E \log V)O(Elog⁡V)O(E \log V)O(V)O(V)
U3Dijkstra Shortest PathO((V+E)log⁡V)O((V+E)\log V)O((V+E)log⁡V)O((V+E)\log V)O((V+E)log⁡V)O((V+E)\log V)O(V)O(V)
U3Fractional KnapsackO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(1)O(1)
U3Activity SelectionO(n)O(n) (sorted)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(1)O(1)
U3Huffman CodingO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(n)O(n)
U40/1 Knapsack (DP)Θ(nW)\Theta(n W)Θ(nW)\Theta(n W)Θ(nW)\Theta(n W)O(nW)O(n W)
U4Binomial Coefficient DPΘ(nk)\Theta(n k)Θ(nk)\Theta(n k)Θ(nk)\Theta(n k)O(k)O(k)
U4Floyd-Warshall APSPΘ(V3)\Theta(V^3)Θ(V3)\Theta(V^3)Θ(V3)\Theta(V^3)Θ(V2)\Theta(V^2)
U4Matrix Chain Mult (MCM)Θ(n3)\Theta(n^3)Θ(n3)\Theta(n^3)Θ(n3)\Theta(n^3)Θ(n2)\Theta(n^2)
U4Longest Common SubseqΘ(m⋅n)\Theta(m \cdot n)Θ(m⋅n)\Theta(m \cdot n)Θ(m⋅n)\Theta(m \cdot n)Θ(m⋅n)\Theta(m \cdot n)
U5Breadth-First SearchΘ(V+E)\Theta(V + E)Θ(V+E)\Theta(V + E)Θ(V+E)\Theta(V + E)O(V)O(V)
U5Depth-First SearchΘ(V+E)\Theta(V + E)Θ(V+E)\Theta(V + E)Θ(V+E)\Theta(V + E)O(V)O(V)
U5Topological Sort (Kahn)Θ(V+E)\Theta(V + E)Θ(V+E)\Theta(V + E)Θ(V+E)\Theta(V + E)O(V)O(V)
U5Kosaraju SCCΘ(V+E)\Theta(V + E)Θ(V+E)\Theta(V + E)Θ(V+E)\Theta(V + E)O(V)O(V)
U5Articulation PointsΘ(V+E)\Theta(V + E)Θ(V+E)\Theta(V + E)Θ(V+E)\Theta(V + E)O(V)O(V)
U64-Queens BacktrackingO(1)O(1)O(N!)O(N!)O(N!)O(N!)O(N)O(N)
U60/1 Knapsack BacktrackingO(n)O(n)O(2n)O(2^n)O(2n)O(2^n)O(n)O(n)
U6TSP Branch & BoundO(n2)O(n^2)O(2n⋅n2)O(2^n \cdot n^2)O(2n⋅n2)O(2^n \cdot n^2)O(n)O(n)
U7Naive String MatchingO(n)O(n)O(n)O(n)O((n−m+1)m)O((n - m + 1)m)O(1)O(1)
U7Rabin-Karp MatcherO(n+m)O(n + m)O(n+m)O(n + m)O((n−m+1)m)O((n - m + 1)m)O(1)O(1)
U7Finite Automaton MatcherΘ(n)\Theta(n)Θ(n)\Theta(n)Θ(n)\Theta(n)$O(m
U7KMP String MatcherΘ(n+m)\Theta(n + m)Θ(n+m)\Theta(n + m)Θ(n+m)\Theta(n + m)O(m)O(m)