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 sub-multiplications for -digit halves.
- Karatsuba's algorithm performs only recursive multiplications.
- The cross-term is obtained via the algebraic identity:
1.1.2 Problem Statement & Input
- Multiply two -digit integers:
- Number of digits:
- Half-length:
1.1.3 Step-by-Step Solved Walkthrough
Step 1: Split the Numbers into Halves
- Number :
- High half:
- Low half:
- Number :
- High half:
- Low half:
Step 2: Compute the Three Primary Products
-
Product 1 (High halves product):
-
Product 2 (Low halves product):
-
Product 3 (Sum of halves product):
Step 3: Compute the Middle Cross-Term
- Cross-term formula:
Step 4: Assemble the Final Product
- Standard assembly formula:
- Substituting values:
- Summation:
Step 5: Verification
- Direct multiplication:
- The result matches exactly.
1.1.4 Complexity Analysis
- Recurrence relation:
- By Master Theorem:
- Time Complexity:
- Space Complexity: due to recursive call stack.
1.2 Master Theorem for Recurrence Relations
1.2.1 Standard Form
- General recurrence:
- Parameters:
- : Number of subproblems.
- : Subproblem reduction factor.
- : Cost of dividing and combining.
- Critical exponent:
1.2.2 Case 1 Example:
- Parameter extraction:
- Calculate critical exponent:
- Compare powers:
- Power in is .
- Critical power is .
- Since , we have for .
- Conclusion:
1.2.3 Case 2 Example: (Merge Sort)
- Parameter extraction:
- Calculate critical exponent:
- Compare powers:
- Power in is .
- Critical power is .
- Since .
- Conclusion:
1.2.4 Case 3 Example:
- Parameter extraction:
- Calculate critical exponent:
- Compare powers:
- Power in is .
- Critical power is .
- Since , we have for .
- Check Regularity Condition:
- Conclusion:
1.3 Substitution Method (Mathematical Induction)
1.3.1 Problem Definition
- Solve the recurrence:
- Base case:
- Target:
- Prove that .
1.3.2 Inductive Hypothesis
- Assume that for all integers :
- Constant will be determined.
1.3.3 Inductive Step Proof
- Start with the recurrence definition:
- Substitute the hypothesis for :
- Simplify the constant factor:
- Apply logarithm quotient rule :
- Expand the bracket:
- Factor out :
- For the bound to hold, we need:
1.3.4 Base Case Verification
- Choose :
- Check against bound:
- Requirement:
- Choosing satisfies both the base case and the inductive step.
- Conclusion:
1.4 Recursion Tree Method
1.4.1 Recurrence Relation
- Recurrence:
1.4.2 Tree Level Costs
- Level 0 (Root node):
- Number of nodes:
- Size of subproblem:
- Cost per node:
- Total level cost:
- Level 1:
- Number of nodes:
- Size of subproblem:
- Cost per node:
- Total level cost:
- Level 2:
- Number of nodes:
- Size of subproblem:
- Cost per node:
- Total level cost:
- Level (General level):
- Number of nodes:
- Size of subproblem:
- Cost per node:
- Total level cost:
1.4.3 Visual Recursion Tree Diagram
1.4.4 Tree Height & Total Work Sum
- Tree depth :
- Total number of levels:
- Total cost across all levels:
- Asymptotic behavior:
Unit - 2
Divide & Conquer Algorithms
2.1 Binary Search
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:
- Indices: to
- Target key:
2.1.3 Iteration-by-Iteration Trace
Iteration 1
- Lower pointer:
- Upper pointer:
- Calculate mid:
- Inspect element:
- Compare:
- Action:
- Target lies in the right half.
- Update:
Iteration 2
- Lower pointer:
- Upper pointer:
- Calculate mid:
- Inspect element:
- Compare:
- Action:
- Match found at index .
- Search terminates.
2.1.4 Complexity
- Comparisons made:
- Time Complexity:
- Best Case:
- Average Case:
- Worst Case:
- Space Complexity: (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:
- Size:
2.2.3 Divide Step Tree
- Level 0:
- Level 1:
- Left:
- Right:
- Level 2:
- From Left: and
- From Right: and
- Level 3 (Base Cases):
2.2.4 Conquer & Merge Step
Sub-Merge 1
- Merge and :
- Compare and
- Result:
Sub-Merge 2
- Merge and :
- Compare and
- Result:
Sub-Merge 3
- Merge and :
- Compare and Take
- Compare and Take
- Compare and Take
- Remaining: Take
- Result:
Sub-Merge 4
- Merge and :
- Compare and Take
- Result:
Sub-Merge 5
- Merge and :
- Compare and Take
- Remaining: Take
- Result:
Final Merge Step
- Left subarray:
- Right subarray:
- Pointer comparison trace:
- Compare and Output
- Compare and Output
- Compare and Output
- Compare and Output
- Compare and Output
- Compare and Output
- Exhausted left subarray Append remaining
2.2.5 Visual Merge Sort Tree Diagram
2.2.6 Final Sorted Output & Complexity
- Sorted array:
- Time Complexity:
- Best Case:
- Average Case:
- Worst Case:
- Auxiliary Space: .
2.3 Quick Sort (Lomuto Partitioning)
2.3.1 Concept & Partition Logic
- Chooses the last element as the pivot: .
- Maintains index tracking elements smaller than or equal to .
- Traverses with index : whenever , increment and swap with .
- Finally places pivot at .
2.3.2 Numerical Problem
- Input array:
- Indices: to
- Pivot:
2.3.3 Step-by-Step Index Swap Trace
- Initialize:
Step
- Value:
- Test: (True)
- Increment :
- Swap with (no movement):
- State:
Step
- Value:
- Test: (True)
- Increment :
- Swap with :
- State:
Step
- Value:
- Test: (False)
- No swap, remains .
- State:
Step
- Value:
- Test: (True)
- Increment :
- Swap with Swap with :
- State:
Step
- Value:
- Test: (False)
- No swap, remains .
- State:
Pivot Placement Step
- End of loop reached.
- Swap pivot with :
- Swap with
- Final partitioned array:
- Pivot index:
- Subarrays formed:
- Left:
- Right:
2.3.4 Complexity
- Time Complexity:
- Best Case:
- Average Case:
- Worst Case: (when array is already sorted or reverse sorted)
- Space Complexity: recursion stack.
2.4 Strassen's Matrix Multiplication ()
2.4.1 Concept & Matrix Blocks
- Standard multiplication uses scalar multiplications.
- Strassen uses products, saving computational overhead on large matrices.
2.4.2 Numerical Input Matrices
-
Matrix :
-
Matrix :
2.4.3 The 7 Auxiliary Products ( to )
-
Product :
-
Product :
-
Product :
-
Product :
-
Product :
-
Product :
-
Product :
2.4.4 Result Matrix Assembly ()
-
Entry :
-
Entry :
-
Entry :
-
Entry :
-
Resultant Matrix :
2.4.5 Verification & Complexity
- Standard multiplication check:
- Time Complexity: (Standard multiplication is ).
2.5 Divide and Conquer Modular Exponentiation
2.5.1 Recursive Exponentiation Rule
- For base and exponent :
- If :
- If is even:
- If is odd:
2.5.2 Numerical Problem
- Compute:
2.5.3 Step-by-Step Computation
- Step 1: Break down (even power):
- Step 2: Break down (odd power):
- Step 3: Compute :
- Step 4: Compute :
- Step 5: Compute :
- Step 6: Compute :
- Step 7: Apply modulo :
2.5.4 Complexity Comparison
- Sequential multiplication multiplications: multiplications
- Divide and conquer multiplications: multiplications
- Time Complexity:
Unit - 3
Greedy Algorithms
3.1 Kruskal's Algorithm (Minimum Spanning Tree)
3.1.1 Graph Problem Input
- Vertices:
- Total Vertices:
- Target MST Edges:
- Edges with weights:
3.1.2 Visual Graph Representation
3.1.3 Edge Sorting Step
- Sorted list of edges in non-decreasing order:
- with weight
- with weight
- with weight
- with weight
- with weight
- with weight
- with weight
3.1.4 Edge-by-Edge Disjoint Set (DSU) Trace
- Initialize disjoint sets:
Consideration 1: Edge with weight
- Set of :
- Set of :
- Check:
- Decision: Accept edge
- Union:
- MST Edges:
Consideration 2: Edge with weight
- Set of :
- Set of :
- Check:
- Decision: Accept edge
- Union:
- MST Edges:
Consideration 3: Edge with weight
- Set of :
- Set of :
- Check:
- Decision: Accept edge
- Union:
- MST Edges:
Consideration 4: Edge with weight
- Set of :
- Set of :
- Check: (Both in same set)
- Decision: Reject edge (Creates cycle )
Consideration 5: Edge with weight
- Set of :
- Set of :
- Check:
- Decision: Reject edge (Creates cycle )
Consideration 6: Edge with weight
- Set of :
- Set of :
- Check:
- Decision: Accept edge
- Union:
- MST Edges:
3.1.5 Final MST Visual Graph & Weight
- Total edges chosen: ()
- Final MST Tree Graph:
- Total weight calculation:
- Time Complexity: or
3.2 Prim's Algorithm (Minimum Spanning Tree)
3.2.1 Graph Problem Input & Starting Vertex
- Same graph:
- Starting root vertex:
- Target MST vertices: all vertices
3.2.2 Step-by-Step Cut Set Growth
Iteration 0 (Initialization)
- Spanning tree set:
- Unvisited set:
- Initial cost:
Iteration 1
- Crossing edges from :
- : weight
- : weight
- Minimum cut edge: with weight
- Add to :
- Current cost:
Iteration 2
- Crossing edges from :
- : weight
- : weight
- : weight
- Minimum cut edge: with weight
- Add to :
- Current cost:
Iteration 3
- Crossing edges from :
- : weight
- : weight
- : weight
- Minimum cut edge: with weight
- Add to :
- Current cost:
Iteration 4
- Crossing edges from :
- : weight
- : weight
- Minimum cut edge: with weight
- Add to :
- Current cost:
3.2.3 Final MST & Complexity
- Selected tree edges:
- Total weight:
- Time Complexity:
- With Adjacency Matrix:
- With Min-Heap & Adjacency List:
3.3 Dijkstra's Single-Source Shortest Path
3.3.1 Directed Graph & Edge Weights
- Vertices:
- Source:
- Edges:
3.3.2 Visual Input Graph
3.3.3 Initialization
- Distance array:
- Visited set:
3.3.4 Step-by-Step Node Selection & Relaxation
Step 1: Process Node
- Select minimum unvisited: with
- Mark as visited:
- Relax edge :
- Relax edge :
- Current distances:
Step 2: Process Node
- Select minimum unvisited: with
- Mark as visited:
- Relax edge :
- Relax edge :
- Relax edge :
- Current distances:
Step 3: Process Node
- Select minimum unvisited: with
- Mark as visited:
- Relax edge :
- Current distances:
Step 4: Process Node
- Select minimum unvisited: with
- Mark as visited:
- Relax edge :
- Current distances:
Step 5: Process Node
- Select minimum unvisited: with
- Mark as visited:
- No outgoing edges from .
3.3.5 Shortest Path Tree Visual Diagram
- Shortest paths from :
- To : Cost
- To : Cost , Path:
- To : Cost , Path:
- To : Cost , Path:
- To : Cost , Path:
- Time Complexity:
3.4 Fractional Knapsack Problem
3.4.1 Problem Definition & Capacity
- Knapsack capacity:
- Item list:
- Item 1: Profit , Weight
- Item 2: Profit , Weight
- Item 3: Profit , Weight
3.4.2 Ratio Calculation ()
- Ratio for Item 1:
- Ratio for Item 2:
- Ratio for Item 3:
3.4.3 Sorted Ratio Order
- Descending order:
- Item 1 ()
- Item 2 ()
- Item 3 ()
3.4.4 Greedy Item Selection Walkthrough
Take Item 1
- Current capacity:
- Item 1 weight:
- Action: Take full item ()
- Profit added:
- Remaining capacity:
- Current total profit:
Take Item 2
- Current capacity:
- Item 2 weight:
- Action: Take full item ()
- Profit added:
- Remaining capacity:
- Current total profit:
Take Fraction of Item 3
- Current capacity:
- Item 3 weight: (Cannot take completely)
- Action: Take fractional part:
- Profit added:
- Remaining capacity:
3.4.5 Final Solution Vector & Max Profit
- Selection fractions:
- Total optimal profit:
- Time Complexity: (sorting dominant).
3.5 Activity Selection Problem
3.5.1 Problem Data (Start & Finish Times)
- Activities with :
- : Start , Finish
- : Start , Finish
- : Start , Finish
- : Start , Finish
- : Start , Finish
- : Start , Finish
3.5.2 Sorting by Finish Time
- Finish times are already sorted:
3.5.3 Compatibility Check Trace
Consider Activity
- First activity is always selected.
- Action: Select
- Selected set:
- Last finish time:
Consider Activity
- Start time:
- Test: (Overlap)
- Action: Reject
Consider Activity
- Start time:
- Test: (Compatible)
- Action: Select
- Selected set:
- Last finish time:
Consider Activity
- Start time:
- Test:
- Action: Reject
Consider Activity
- Start time:
- Test:
- Action: Reject
Consider Activity
- Start time:
- Test: (Compatible)
- Action: Select
- Selected set:
- Last finish time:
3.5.4 Selected Activities & Complexity
- Maximum set of mutually compatible activities:
- Total count:
- Time Complexity: if unsorted; if sorted.
3.6 Huffman Coding
3.6.1 Character Frequencies Input
- Character set with frequencies:
3.6.2 Step-by-Step Min-Heap Tree Merge
Merge 1
- Two smallest frequencies: and
- Create parent node :
- Remaining nodes:
Merge 2
- Two smallest frequencies: and
- Create parent node :
- Remaining nodes:
Merge 3
- Two smallest frequencies: and
- Create parent node :
- Remaining nodes:
Merge 4
- Two smallest frequencies: and
- Create parent node :
- Remaining nodes:
Merge 5
- Two remaining nodes: and
- Create root node:
3.6.3 Visual Huffman Tree Diagram
3.6.4 Prefix Code Generation Table
- Traverse left as , right as :
- Character : Code (Length )
- Character : Path (Length )
- Character : Path (Length )
- Character : Path (Length )
- Character : Path (Length )
- Character : Path (Length )
3.6.5 Total Bit Length Calculation & Ratio
- Bits required per character:
- Total encoded message size:
- Fixed-length comparison ( bits per char for chars):
- Space saved:
- Time Complexity:
Unit - 4
Dynamic Programming
4.1 0/1 Knapsack Problem (Tabulation)
4.1.1 Problem Parameters & Recurrence
- Knapsack capacity:
- Number of items:
- Items:
- Item 1:
- Item 2:
- Item 3:
- Item 4:
- Recurrence relation:
4.1.2 DP Table Construction Walkthrough
Row (No Items)
- For all capacities to :
Row (Item 1: )
- :
- :
- :
- :
- :
- :
Row (Item 2: )
- :
- :
- :
- :
- :
- :
Row (Item 3: )
- :
- :
- :
- :
- :
- :
Row (Item 4: )
- :
- :
- :
- :
- :
- :
4.1.3 Complete DP Matrix Table
| 0 | 0 | 0 | 0 | 0 | 0 | |
| 0 | 0 | 3 | 3 | 3 | 3 | |
| 0 | 0 | 3 | 4 | 4 | 7 | |
| 0 | 0 | 3 | 4 | 5 | 7 | |
| 0 | 0 | 3 | 4 | 5 | 7 |
4.1.4 Item Backtracking Trace
- Check Item 4 at :
- Item 4 is NOT selected.
- Check Item 3 at :
- Item 3 is NOT selected.
- Check Item 2 at :
- Item 2 is SELECTED ().
- Remaining capacity: .
- Check Item 1 at :
- Item 1 is SELECTED ().
- Remaining capacity: .
4.1.5 Optimal Subset & Complexity
- Selected items:
- Total weight:
- Total max profit:
- Time Complexity:
- Space Complexity: (reducible to ).
4.2 Binomial Coefficient ()
4.2.1 Recurrence & Base Cases
- Pascal's identity:
- Base cases:
4.2.2 Line-by-Line DP Table Calculation for
- Row :
- Row :
- Row :
- Row :
- Row :
- Row :
4.2.3 Final Value & Space Optimization
- Result:
- Time Complexity:
- Space Complexity: using 1D array.
4.3 Floyd-Warshall All-Pairs Shortest Path
4.3.1 Problem Graph & Initial Matrix
- Directed graph with vertices:
4.3.2 Visual Directed Graph
4.3.3 Recurrence Formula
4.3.4 Intermediate Matrices
Pass (Intermediate Node )
- Column and Row remain unchanged.
- Matrix :
Pass (Intermediate Node )
- Matrix :
Pass (Intermediate Node )
- Matrix :
Pass (Intermediate Node )
4.3.5 Final All-Pairs Distance Matrix & Complexity
- Final matrix :
- Time Complexity:
- Space Complexity:
4.4 Matrix Chain Multiplication (MCM)
4.4.1 Matrix Chain Dimensions
- Three matrices:
- : dimension
- : dimension
- : dimension
- Dimension array:
4.4.2 MCM Recurrence Formula
4.4.3 Chain Length (Base Cases)
- Cost to multiply a single matrix:
4.4.4 Chain Length (Individual Calculations)
-
Multiplying ():
-
Multiplying ():
4.4.5 Chain Length (Split Minimization Trace)
-
Multiply entire chain: ()
-
Option : Split as
-
Option : Split as
-
Minimum cost choice:
4.4.6 Optimal Parenthesization & Multiplications Count
- Optimal parenthesization from split table:
- Minimum scalar multiplications required:
- Time Complexity:
- Space Complexity:
4.5 Longest Common Subsequence (LCS)
4.5.1 Input Sequences & Recurrence
- Sequences:
- ()
- ()
- Recurrence:
4.5.2 DP Table Construction
- Step-by-step matching logic:
- If : take diagonal value plus .
- If : take maximum of top cell and left cell .
4.5.3 Complete Cell Matrix
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | |
| 0 | 0 | 0 | 0 | 1 | 1 | 1 | |
| 0 | 1 | 1 | 1 | 1 | 2 | 2 | |
| 0 | 1 | 1 | 2 | 2 | 2 | 2 | |
| 0 | 1 | 1 | 2 | 2 | 3 | 3 | |
| 0 | 1 | 2 | 2 | 2 | 3 | 3 | |
| 0 | 1 | 2 | 2 | 3 | 3 | 4 | |
| 0 | 1 | 2 | 2 | 3 | 4 | 4 |
4.5.4 Backtracking the Common Subsequence
- Start at :
- Mismatch. Take max(top, left) move up to with value .
- Match! Add to LCS. Move diagonal to with value .
- Mismatch. Move up to with value .
- Follow up to : Match! Add to LCS. Move diagonal to with value .
- Follow up to : Match! Add to LCS. Move diagonal to with value .
- Follow to : Match! Add to LCS. Move diagonal to with value .
4.5.5 Final LCS String & Length
- Reverse the matched characters:
- Sequence:
- LCS String: (or )
- LCS Length:
- Time Complexity:
- Space Complexity:
Unit - 5
Exploring Graphs
5.1 Breadth-First Search (BFS)
5.1.1 Graph Structure & Starting Vertex
- Vertices:
- Undirected edges:
- Starting source vertex:
5.1.2 Visual Graph & Level Frontiers
5.1.3 Step-by-Step Queue & Distance Updates
Initialization
- Visited:
- Queue:
[1] - Distance array:
Step 1: Dequeue
- Dequeued vertex:
- Unvisited neighbors:
- Updates:
- Enqueue:
- Queue:
[2, 3] - Visited:
Step 2: Dequeue
- Dequeued vertex:
- Unvisited neighbors:
- Updates:
- Enqueue:
- Queue:
[3, 4, 5] - Visited:
Step 3: Dequeue
- Dequeued vertex:
- Neighbors: (already visited), (already visited)
- No new vertices enqueued.
- Queue:
[4, 5]
Step 4: Dequeue
- Dequeued vertex:
- Unvisited neighbors:
- Updates:
- Enqueue:
- Queue:
[5, 6] - Visited:
Step 5: Dequeue
- Dequeued vertex:
- Neighbors: (all visited)
- Queue:
[6]
Step 6: Dequeue
- Dequeued vertex:
- Queue:
[](Empty) - Traversal complete.
5.1.4 Final BFS Traversal Sequence & Tree Edges
- BFS Node Visitation Order:
- BFS Tree Edges:
- Time Complexity:
- Space Complexity: (Queue).
5.2 Depth-First Search (DFS) & Edge Classification
5.2.1 Graph Structure & Initialization
- Directed graph with vertices :
- Global timer:
5.2.2 Visual DFS Edge Classification Graph
5.2.3 Step-by-Step Recursion Stack & Timestamp Trace ()
- Step 1: Visit node :
- Discovery time:
- Step 2: Traverse tree edge , visit node :
- Discovery time:
- Step 3: Traverse tree edge , visit node :
- Discovery time:
- Step 4: Explore edge :
- Node is currently in the active recursion stack (GRAY).
- This indicates an ancestor relationship.
- Classification: Back Edge (Cycle detected!)
- Step 5: Finish node :
- Finishing time:
- Step 6: Backtrack to node and finish:
- Finishing time:
- Step 7: Backtrack to node , explore tree edge , visit node :
- Discovery time:
- Step 8: Explore edge :
- Node is already completely processed (BLACK) and is not an ancestor.
- Classification: Cross Edge
- Step 9: Finish node :
- Finishing time:
- Step 10: Finish node :
- Finishing time:
5.2.4 Edge Classification Summary
- Tree Edges:
- Back Edge:
- Cross Edge:
- Time Complexity:
5.3 Topological Sorting
5.3.1 DAG Definition & Visual Graph
- Directed Acyclic Graph (DAG) with vertices :
5.3.2 Kahn's Algorithm Trace (In-Degree Elimination)
Step 1: In-Degree Calculation
- Node :
- Node :
- Node :
- Node :
- Node :
Step 2: Initialize Queue
- Enqueue nodes with in-degree :
Step 3: Dequeue
- Output:
- Decrement neighbor in-degrees:
- Enqueue
- Enqueue
Step 4: Dequeue
- Output:
- Decrement neighbor in-degrees:
Step 5: Dequeue
- Output:
- Decrement neighbor in-degrees:
- Enqueue
Step 6: Dequeue
- Output:
- Decrement neighbor in-degrees:
- Enqueue
Step 7: Dequeue
- Output:
- Decrement neighbors: None
5.3.3 Linear Topological Order Flow
- Topological ordering:
- Time Complexity:
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 :
- Start at
- Finish Push
- Finish Push
- Finish Push
- Finish Push
- Finish Push
- Resulting Stack (top to bottom):
5.4.3 Pass 2: Transpose Graph Construction
- Reverse the direction of all edges:
5.4.4 Pass 3: Reverse DFS & SCC Extraction
- Pop from Stack:
- DFS on from visits:
- Component 1:
- Next unvisited on Stack is :
- Pop from Stack
- DFS on from visits:
- Component 2:
- Strongly Connected Components:
- Time Complexity:
5.5 Articulation Points & Bridges
5.5.1 Graph Problem Input & Visual Diagram
- Undirected graph with vertices:
5.5.2 Discovery Times and Low Values ()
- DFS traversal starting at node :
- Visit :
- Visit :
- Visit :
- Back edge :
- Propagate back to :
- Propagate back to :
- From , explore tree edge :
- Visit :
- Explore tree edge :
- Visit :
5.5.3 Cut Vertex Condition Testing
- Non-root condition: Vertex is an articulation point if it has a child such that:
- Test Node with child :
- Test Node with child :
5.5.4 Bridge Condition Testing & Output
- Bridge condition: Edge is a bridge if:
- Test edge :
- Test edge :
- Articulation Points:
- Bridges:
- Time Complexity:
Unit - 6
Backtracking & Branch and Bound
6.1 4-Queens Problem (Backtracking)
6.1.1 Problem Statement & Board Model
- Place queens on a chessboard such that no two queens attack each other.
- Representation: array
col[1..4]wherecol[i]is the column of the queen in row .
6.1.2 Non-Attacking Constraints
- Two queens in rows and conflict if:
- Same column:
- Same diagonal:
6.1.3 Visual State-Space Search Tree
6.1.4 Step-by-Step Exploration & Pruning
Row 1: Place Queen 1
- Try Column 1:
- State:
[1, _, _, _]
Row 2: Place Queen 2
- Try Column 1: Conflict with (same column).
- Try Column 2: Conflict with ( diagonal).
- Try Column 3: Safe!
- State:
[1, 3, _, _]
Row 3: Place Queen 3
- Try Column 1: Conflict with (same column).
- Try Column 2: Conflict with ( diagonal).
- Try Column 3: Conflict with (same column).
- Try Column 4: Conflict with ( diagonal).
- Dead end! No safe column in Row 3.
- Action: Backtrack to Row 2.
Row 2 (Re-try):
- Try Column 4: Safe!
- State:
[1, 4, _, _]
Row 3:
- Try Column 1: Conflict with .
- Try Column 2: Safe!
- State:
[1, 4, 2, _]
Row 4:
- Try Column 1: Conflict with ().
- Try Column 2: Conflict with (same column).
- Try Column 3: Conflict with ().
- Try Column 4: Conflict with (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:
- State:
[2, _, _, _]
Row 2:
- Try Column 1: Conflict with diagonal.
- Try Column 2: Conflict with column.
- Try Column 3: Conflict with diagonal.
- Try Column 4: Safe!
- State:
[2, 4, _, _]
Row 3:
- Try Column 1: Safe!
- State:
[2, 4, 1, _]
Row 4:
- Try Column 1: Conflict with column.
- Try Column 2: Conflict with column.
- Try Column 3: Safe!
- State:
[2, 4, 1, 3]
6.1.5 Final Solution Placement & Vector
- Solution Vector:
- 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:
6.2 0/1 Knapsack using Backtracking
6.2.1 Problem Parameters & Items
- Capacity:
- Items sorted by :
- : (Ratio )
- : (Ratio )
- : (Ratio )
6.2.2 State-Space Tree Exploration
- Root: weight , profit , best profit .
Branch Left (Include ):
- Weight:
- Profit:
- Branch Left (Include ):
- Weight:
- Profit:
- Update best profit:
- Branch Left (Include ):
- Weight: (Over capacity!)
- Prune: Infeasible branch.
- Branch Right (Exclude ):
- Leaf reached with profit .
- Branch Left (Include ):
- Branch Right (Exclude ):
- Weight:
- Profit:
- Maximum possible profit with remaining :
- Since :
- Prune: Promising check fails.
- Branch Left (Include ):
Branch Right (Exclude ):
- Weight:
- Profit:
- Maximum possible profit with :
- Branch Left (Include ):
- Weight: , Profit:
- Try include : Weight Infeasible.
- Exclude : Profit is .
- Branch Right (Exclude ):
- Only left Max profit Prune.
- Branch Left (Include ):
6.2.3 Pruning Checks & Best Profit Updates
- Optimal solution:
- Max profit:
- Weight used:
6.3 0/1 Knapsack using Branch & Bound (LC-BB)
6.3.1 Problem Instance & Relaxation Model
- Capacity:
- Sorted items:
- : ()
- : ()
- : ()
- : ()
6.3.2 Upper Bound () Formula via Fractional Knapsack
- Upper bound formula at any node:
6.3.3 State-Space Tree Expansion & Priority Queue State
- Root Node (Node 1):
- Current weight:
- Current profit:
- Take (), (), ()
- Total weight: , Total profit:
- Remaining capacity:
- Fractional part of :
- Upper Bound:
6.3.4 Node Pruning & Optimal Leaf Finding
- Branch Left (Include ):
- Current weight: , Profit:
- Upper Bound remains .
- Branch Right (Exclude ):
- Upper bound drops below .
- Expanding promising nodes:
- Take :
- Weight:
- Profit:
- Take :
- Any node with is pruned.
- Final optimal profit:
6.4 Minimax Principle & Alpha-Beta Pruning
6.4.1 Game Tree Layout & Visual Cutoff Diagram
6.4.2 Alpha () and Beta () Boundary Definitions
- : Best score that Maximizer can guarantee so far ( initially).
- : Best score that Minimizer can guarantee so far ( initially).
- Prune condition:
6.4.3 Step-by-Step Node Evaluations & Cutoffs
Subtree Under
- Leaf 1 under : value
- Leaf 2 under : value
- Node (MIN) selects:
- Node (MIN) updates beta:
- Subtree :
- Leaf 1 under : value
- Since , MIN at node will never select a value from .
- Node returns value .
Root Node
- Node (MAX) receives from child .
- Update alpha:
Subtree Under
- Node inherits .
- Subtree :
- Leaf 1 under : value
- Leaf 2 under : value
- Node evaluates to:
- Node (MIN) updates beta:
- Pruning Check at Node :
- Condition Met: Cutoff / Prune Subtree entirely!
- Leaves under ( and ) are never evaluated.
6.4.4 Final Root Optimal Decision
- Optimal minimax value at root:
6.5 Travelling Salesperson Problem (TSP) using Branch & Bound
6.5.1 Cost Matrix Definition
- Initial cost matrix:
6.5.2 Visual City Graph
6.5.3 Row Reductions Step-by-Step
- Row 1: minimum is
- Subtract :
- Reduction
- Row 2: minimum is
- Subtract :
- Reduction
- Row 3: minimum is
- Subtract :
- Reduction
- Row 4: minimum is
- Subtract :
- Reduction
- Sum of row reductions:
6.5.4 Column Reductions Step-by-Step
- Reduced matrix after row reduction:
- Column 1: has
- Column 2: has
- Column 3: minimum is
- Subtract :
- Reduction
- Column 4: minimum is
- Subtract :
- Reduction
- Sum of column reductions:
6.5.5 Initial Lower Bound Calculation
- Root Lower Bound:
6.5.6 Branching & Child Bound Computations
- Child bound formula for moving from city to city :
- Set row to
- Set column to
- Set cell to
- The branch with the minimum lower bound is explored until the full tour completes.
6.5.7 Optimal Tour & Minimum Cost
- Optimal tour cost:
Unit - 7
String Matching & NP-Completeness
7.1 Naive String Matching
7.1.1 Problem Strings (Text & Pattern)
- Text:
- Pattern:
- Possible shifts: to
7.1.2 Shift-by-Shift Character Comparison Trace
Shift :
- Substring
- Compare with
- All characters match.
- Match found at index !
Shift :
- Substring
- Compare: , but .
- Mismatch after comparison.
Shift :
- Substring
- Compare: .
- Immediate mismatch.
Shift :
- Substring
- Compare with : All characters match.
- Match found at index !
Shift :
- Substring
- Compare with : All characters match.
- Match found at index !
7.1.3 Valid Matches & Worst-Case Analysis
- Valid match shifts:
- Time Complexity:
- Best Case:
- Worst Case:
7.2 Rabin-Karp Algorithm (Rolling Hash)
7.2.1 Problem Parameters
- Text:
- Pattern:
- Pattern length:
- Radix / Base:
- Prime modulus:
- High-order multiplier:
7.2.2 Pattern Hash Calculation
- Direct value:
- Hash:
7.2.3 Window-by-Window Rolling Hash Trace
- Window 0 (
"31"): - Window 1 (
"14"): - Window 2 (
"41"): - Window 3 (
"15"):- Hash match! Verify characters:
- String
"15""26" - Spurious Hit!
- Window 4 (
"59"):- Hash match! String
"59""26" - Spurious Hit!
- Hash match! String
- Window 5 (
"92"):- Hash match! String
"92""26" - Spurious Hit!
- Hash match! String
- Window 6 (
"26"):- Hash match! Verify characters:
- String
"26""26" - Valid Match found at Shift !
7.2.4 Rolling Hash Formula Calculation Step-by-Step
- Shift formula:
- Example: Transition from Window 0 (
"31") to Window 1 ("14"):- Outgoing digit:
- Incoming digit:
- Calculation:
- Time Complexity:
- Average Case:
- Worst Case:
7.3 String Matching with Finite Automata (FA)
7.3.1 Automaton Model (States & Alphabet)
- Pattern:
- Alphabet:
- States:
- Initial State:
- Accepting State:
7.3.2 Visual Automaton State Diagram
7.3.3 State Transition Function () Computation
- Definition: is the length of the longest prefix of that is a suffix of .
- From State ():
- On : Longest prefix of
"aba"in"a"is"a"State . - On : Longest prefix in
"b"is State .
- On : Longest prefix of
- From State (
"a"):- On : Suffix of
"aa"is"a"State . - On : Suffix of
"ab"is"ab"State .
- On : Suffix of
- From State (
"ab"):- On : Suffix of
"aba"is"aba"State . - On : Suffix of
"abb"is State .
- On : Suffix of
- From State (
"aba"):- On : Suffix of
"abaa"is"a"State . - On : Suffix of
"abab"is"ab"State .
- On : Suffix of
7.3.4 Complete State Transition Table
| State | Input 'a' | Input 'b' |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 1 | 2 |
| 2 | 3 | 0 |
| 3 | 1 | 2 |
7.3.5 Text Processing State Trace
- Input Text:
- Start at state:
- Read State
- Read State
- Read State (Match at index 3!)
- Read State
- Read State (Match at index 5!)
- Matching Time:
7.4 Knuth-Morris-Pratt (KMP) Algorithm
7.4.1 Pattern Definition & Prefix Function Concept
- Pattern:
- Length:
- Prefix function represents the length of the longest proper prefix of that is also a suffix of .
7.4.2 Step-by-Step (LPS) Array Calculation
Index : Substring "a"
- No proper prefix exists.
Index : Substring "ab"
- Proper prefixes:
{"a"} - Proper suffixes:
{"b"} - Match: None
Index : Substring "aba"
- Proper prefixes:
{"a", "ab"} - Proper suffixes:
{"a", "ba"} - Longest match:
"a"(length )
Index : Substring "abab"
- Proper prefixes:
{"a", "ab", "aba"} - Proper suffixes:
{"b", "ab", "bab"} - Longest match:
"ab"(length )
Index : Substring "ababa"
- Proper prefixes:
{"a", "ab", "aba", "abab"} - Proper suffixes:
{"a", "ba", "aba", "baba"} - Longest match:
"aba"(length )
Index : Substring "ababac"
- New character mismatches with .
- Longest matching proper prefix-suffix: None.
Index : Substring "ababaca"
- Proper prefixes:
{"a", ...} - Proper suffixes:
{"a", ...} - Longest match:
"a"(length )
7.4.3 Complete Table
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|
a | b | a | b | a | c | a | |
| 0 | 0 | 1 | 2 | 3 | 0 | 1 |
7.4.4 Text Search Walkthrough (No Backtracking on Text)
- Text:
- Indices to :
- matches .
- Index :
- , but (Mismatch).
- Shift without text backtracking:
- Current matched length: .
- Lookup .
- Resume comparison with .
- Compare with Direct match!
- Preprocessing Time:
- Matching Time:
- Total Time:
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 ().
- 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 with clauses:
- Number of clauses:
7.5.3 Visual Reduction Graph Diagram
7.5.4 Graph Transformation Step-by-Step
- Clause 1: create vertices for literals .
- Clause 2: create vertices for literals .
- Edge placement rule:
- Connect two vertices if they are in different clauses AND are not complementary (i.e. not and ).
7.5.5 Equivalence Proof Walkthrough
- If is satisfiable:
- Choosing assignment :
- Literal in Clause 1 is True.
- Literal in Clause 2 is True.
- They are in different clauses and not contradictory.
- An edge exists between them, forming a Clique of size .
- If graph has a -clique:
- Exactly one vertex per clause is chosen.
- Since no edges exist between contradictory literals, setting all selected literals to True satisfies formula .
- Proves .
8. Master Algorithm Complexity Reference Table
| Unit | Algorithm | Best Case Time | Average Case Time | Worst Case Time | Space Complexity |
|---|---|---|---|---|---|
| U1 | Karatsuba Multiplication | ||||
| U2 | Binary Search | ||||
| U2 | Merge Sort | ||||
| U2 | Quick Sort | ||||
| U2 | Strassen Matrix Mult | ||||
| U2 | Modular Exponentiation | ||||
| U3 | Kruskal's MST | ||||
| U3 | Prim's MST (Min-Heap) | ||||
| U3 | Dijkstra Shortest Path | ||||
| U3 | Fractional Knapsack | ||||
| U3 | Activity Selection | (sorted) | |||
| U3 | Huffman Coding | ||||
| U4 | 0/1 Knapsack (DP) | ||||
| U4 | Binomial Coefficient DP | ||||
| U4 | Floyd-Warshall APSP | ||||
| U4 | Matrix Chain Mult (MCM) | ||||
| U4 | Longest Common Subseq | ||||
| U5 | Breadth-First Search | ||||
| U5 | Depth-First Search | ||||
| U5 | Topological Sort (Kahn) | ||||
| U5 | Kosaraju SCC | ||||
| U5 | Articulation Points | ||||
| U6 | 4-Queens Backtracking | ||||
| U6 | 0/1 Knapsack Backtracking | ||||
| U6 | TSP Branch & Bound | ||||
| U7 | Naive String Matching | ||||
| U7 | Rabin-Karp Matcher | ||||
| U7 | Finite Automaton Matcher | $O(m | |||
| U7 | KMP String Matcher |