Module 3
Module 3
Dr. Radha Krishna Reddy P, MSc (CS), MTech (CSE), PhD (ECE),
Asst. Prof. in CSE, Manipal Institute of Technology / MAHE,
Research Collaborator - CISTER Research Center, ISEP, Porto, Portugal,
External Research Collaborator - CEDRIC Labs, CNAM, Paris, France.
[Link]@[Link]
Syllabus
Module – 3:
a problem of size n
subproblem 1 subproblem 2
of size n/2 of size n/2
a solution to a solution to
subproblem 1 subproblem 2
a solution to
the original problem
DAA
Divide and Conquer – Examples
The Master Theorem is a tool used to solve recurrence relations that arise in the analysis of
divide-and-conquer algorithms.
The Master Method is used for solving the following types of recurrence
𝑛
𝑇 (𝑛) = 𝑎 𝑇 ( ) + 𝑓 (𝑛)
𝑏
• n is the size of the problem and a is the number of subproblems in the recursion.
• n/b is the size of each subproblem, assuming all subproblems are essentially the same size.
• f (n) is the sum of the work done outside the recursive calls, which includes the sum of
dividing the problem and the sum of combining the solutions to the subproblems.
DAA
Divide and Conquer – Master Method
It is not possible always bound the function according to the requirement, so we make three
cases which will tell us what kind of bound we can apply on the function.
DAA
Divide and Conquer – Master Method
The master method is mainly derived from the recurrence tree method. If we draw the
recurrence tree of T(n) = aT(n/b) + f(n), we can see the root is f(n), and at all leaves is Θ(nc)
where c is 𝒍𝒐𝒈𝒃 𝒂. And the height of the recurrence tree is 𝒍𝒐𝒈𝒃 𝒏.
DAA
Divide and Conquer – Master Method
𝑙𝑜𝑔𝑏𝑎−𝜀 𝑙𝑜𝑔𝑏𝑎
Case1: If 𝑓(𝑛) = 𝑂(𝑛 ) for some constant ε >0, then it follows that 𝑇(𝑛) = Θ (𝑛 )
𝑛
Example: 𝑇 𝑛 = 8 𝑇 + 1000𝑛2 apply master theorem on it.
2
𝑛 𝑛
Solution: Compare 𝑇 𝑛 = 8 𝑇 + 1000𝑛2 with 𝑇 (𝑛) = 𝑎 𝑇 ( ) + 𝑓 (𝑛) a>= 1 and b>1
2 𝑏
1000 𝑛2 = 𝑂 (𝑛3−𝜀 )
Since this equation holds, the first case of the master theorem applies to the given recurrence
𝑙𝑜𝑔𝑏𝑎
relation, thus resulting in the conclusion: 𝑇(𝑛) = Θ (𝑛 )
𝑛
Example: T n = 2𝑇 + 10𝑛 , solve the recurrence by using the master method.
2
DAA
Divide and Conquer – Master Method
𝑛
Solution: As compare the given problem with 𝑇 (𝑛) = 𝑎 𝑇 ( ) + 𝑓 (𝑛) a>= 1 and b>1
𝑏
𝑎
Therefore: T (n) = Θ (𝑛 𝑙𝑜𝑔𝑏 𝑙𝑜𝑔𝑛𝑘+1 )
= Θ (n log n)
DAA
Divide and Conquer – Master Method
𝑎+ ε
Case 3: If it is true 𝑓(𝑛) = Ω (𝑛𝑙𝑜𝑔𝑏 ) for some constant ε >0 and it also true that:
𝑛
𝑎 𝑓( ) ≤ 𝑐𝑓(𝑛) for some constant c<1 for large value of n ,then : 𝑇 (𝑛) = Θ((𝑓 (𝑛))
𝑏
𝑛
Example: Solve the recurrence relation: 𝑇 𝑛 = 2𝑇 + 𝑛2
2
𝑛
Solution: Compare the given problem with 𝑇 (𝑛) = 𝑎 𝑇 ( ) + 𝑓 (𝑛) a>= 1 and b>1
𝑏
𝑛 𝑛2
Now we will also check the second condition: 2( )2 ≤ 𝑐𝑛2 ⇒ ≤ 𝑐𝑛2
2 2
𝑛2 𝑛2
If we will choose c =1/2, it is true: ≤ ∀ n ≥1
2 2
𝑇 (𝑛) = Θ(𝑛2)
DAA
Divide and Conquer – Master Method
8 3 2 9 7 1 5 4
8 3 2 9 71 5 4
8 3 2 9 7 1 5 4
3 8 2 9 1 7 4 5
2 3 8 9 1 4 5 7 85196247
1 2 3 4 5 7 8 9 Homework
DAA
Divide and Conquer – Merge Sort
A[i]p A[i]p
DAA
Divide and Conquer – Quick Sort
DAA
Divide and Conquer – Quick Sort
DAA
Divide and Conquer – Quick Sort
DAA
Divide and Conquer – Quick Sort – Example
Given a pivot, partition the elements of the array that the resulting array consists of:
1. One sub-array that contains elements >= pivot
2. Another sub-array that contains elements < pivot
• The sub-arrays are stored in the original data array.
• Partitioning through loops, swapping elements below/above pivot.
DAA
Divide and Conquer – Quick Sort – Example
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
DAA
Divide and Conquer – Quick Sort – Example
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
DAA
Divide and Conquer – Quick Sort – Example
pivot_index = 0 40 20 10 80 60 50 7 30 100
i j
pivot_index = 0 40 20 10 30 60 50 7 80 100
i j
DAA
Divide and Conquer – Quick Sort – Example
pivot_index = 0 40 20 10 30 60 50 7 80 100
i j
pivot_index = 0 40 20 10 30 60 50 7 80 100
i j
DAA
Divide and Conquer – Quick Sort – Example
pivot_index = 0 40 20 10 30 60 50 7 80 100
i j
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
DAA
Divide and Conquer – Quick Sort – Example
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
DAA
Divide and Conquer – Quick Sort – Example
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
pivot_index = 0 40 20 10 30 7 50 60 80 100
i j
DAA
Divide and Conquer – Quick Sort – Example
pivot_index = 4 7 20 10 30 40 50 60 80 100
i j
7 20 10 30 40 50 60 80 100
Homework
5 3 1 9 8 2 4 7
l = left index
r = right index
s = split position
DAA
Divide and Conquer – Quick Sort – Example
DAA
Divide and Conquer – Quick Sort
Node / Vertex
A Root
B C
Left subtree
Right subtree
D E F G
Edges H I Leaves
J K L M N
DAA
Divide and Conquer – Binary Trees
• A binary tree T is a tree with finite set of nodes that is either empty
• or consists of a root and two disjoint binary trees (the left and right subtrees of
the root).
• A binary tree as a special case of an ordered tree.
T
• Since a binary tree is divided into
• the left subtree and the right subtree,
• many binary trees can be solved by applying DandC..
DAA
Divide and Conquer – Binary Tree
• Special Cases:
DAA
Divide and Conquer – Binary Tree
Recall: height of a tree = longest path from root to leaf (count edges)
DAA
Divide and Conquer – Binary Tree
• min # of leaves:
• min # of nodes:
Internal node
External node
• Modern cryptography, require manipulation of integers that are over 100 decimal
digits long.
• Such integers are too long to fit in a single word of a modern computer, they require
special treatment.
• Need for efficient manipulation of large integers.
• If we use the conventional pen-and-pencil algorithm for multiplying two n-digit
integers, we need a total of n2 digit multiplications.
• Divide-and-conquer can rescue us with fewer than n2 multiplications.
DAA
Divide and Conquer – Multiplication of Large Integers
• Consider the problem of multiplying two (large) n-digit integers represented by arrays
of their digits such as: A = 12345678901357986429 B = 87654321284820912836
• The grade-school algorithm:
• a1 a2 … an
b1 b2 … bn
(d10) d11d12 … d1n
• (d20) d21d22 … d2n
• …………………
• (dn0) dn1dn2 … dnn
• Efficiency: ?? one-digit multiplications n2
DAA
Divide and Conquer – Multiplication of Large Integers
A small example: A B where A = 2135 and B = 4014
A = (21·102 + 35), B = (40 ·102 + 14)
So, A B = (21 ·102 + 35) (40 ·102 + 14) = 21 40 ·104 + (21 14 + 35 40) ·102 + 35 14
In general, if A = A1A2 and B = B1B2 (where A and B are n-digit, and A1, A2, B1, B2 are n / 2-
digit numbers),
A B = A1 B1·10n + (A1 B2 + A2 B1) ·10n/2 + A2 B2
Recurrence for the number of one-digit multiplications M(n): M(n) = 4M(n/2), M(1) = 1
Solution: M(n) = n2
DAA
Divide and Conquer – Multiplication of Large Integers
• which requires only 3 multiplications at the expense of (4-1=3) extra additions and
subtractions (2 adds and 2 subs – 1 add)
• Recurrence for the number of multiplications M(n): M(n) = 3M(n/2), M(1) = 1
• Solution: M(n) = 3log2n = nlog 23 ≈ n1.585
DAA
Divide and Conquer – Strassen’s Matrix Multiplication
Strassen observed [1969] that the product of two matrices can be computed as
follows:
M1 + M4 - M5 + M7 M3 + M5
=
M2 + M4 M1 + M3 - M2 + M6
DAA
Divide and Conquer – Strassen’s Matrix Multiplication
7 .
= (𝑛 𝑙𝑜𝑔2 ) = 𝑂(𝑛2 807).
DAA
Divide and Conquer – Strassen’s Matrix Multiplication
12 34 3 4
𝐴= 𝐵=
22 10 2 1
Syllabus
Module – 3:
• Transformed into:
• a simpler/more convenient instance [e.g. sorted] of the same problem - instance
simplification
• a different representation of the same instance [eg different data structure] -
representation change
• a different problem for which an algorithm is already available - problem reduction
• Solve the problem in the Conquering stage.
DAA
Transform and Conquer Presorting
• Theorem (see Sec. 11.2): log2 n! n log2 n comparisons are necessary in the worst
case to sort a list of size n by any comparison-based algorithm.
• Note: About nlog2 n comparisons are also sufficient to sort array of size n (by
mergesort).
DAA
Transform and Conquer - Presorting
• Presorting-based algorithm
• Stage 1: sort by efficient sorting algorithm (e.g. mergesort)
• Stage 2: scan array to check pairs of adjacent elements
• Efficiency: Θ(nlog n) + O(n) = Θ(nlog n)
• Another 2 algorithms:
• Hashing – frequently useful
• Closest pair
DAA
Transform and Conquer - Presorting
Computing a mode
• A mode is a value that occurs most often in a given list of numbers.
• For example, for 5, 1, 5, 7, 6, 5, 7, the mode is 5.
• The brute-force approach
• Scan the list
• Compute the frequencies of all its distinct values (n),
• then find the value with the largest frequency (n-1)
• Complexity - Θ(𝑛2 )
DAA
Transform and Conquer - Presorting
Hashing
• open hashing (separate chaining)
• closed hashing (open addressing)
DAA
Transform and Conquer – Balanced Search Trees
• Tree searching
• binary search tree
• balanced binary trees:
• AVL trees
• red-black trees
• multiway trees [balanced]:
• 2-3 trees
• 2-3-4 trees, B trees
DAA
Transform and Conquer – Binary Search Trees
Arrange keys in a binary tree with the binary search tree property:
<K >K
Attractiveness of BST is marred by the bad (linear) worst-case efficiency. Two ideas to
overcome it (ie keep BST close to balanced) are:
• To restructure BST to maintain balance when an insertion makes the tree “too
unbalanced”
• AVL trees
• red-black trees
• To allow more than one key per node of a search tree
• 2-3 trees
• 2-3-4 trees
• B-trees
DAA
Transform and Conquer – Balanced Trees – AVL Trees
• Definition - An AVL tree is a BST in which, for every node, the difference between the
heights of its left and right subtrees, called the balance factor, is at most 1
• With the height of an empty tree defined as -1.
1 2
10 10
0 1 0 0
5 20 5 20
1 -1 0 1 -1
4 7 12 4 7
0 0 0 0
2 8 2 8
(a) (b)
Tree (a) is an AVL tree; tree (b) is not an AVL tree
DAA
Transform and Conquer – Balanced Trees – AVL Trees - Rotations
• If a key insertion violates the balance requirement at some node,
• the subtree rooted at that node is transformed via one of the four rotations.
• The rotation is always performed for a subtree rooted at an “unbalanced” node closest
to the new leaf.
2 R
0
3
>
2
A rotation in an AVL tree is a local 1
0 0
transformation of its subtree rooted 2 1 3
at a node whose balance has
become either +2 or −2. 0
1
(a)
Single R-rotation
DAA
Transform and Conquer – Balanced Trees – AVL Trees - Rotations
-2 1 > 0
2
2 0 0
-1
1 3
3
0
(b)
Single L-rotation
DAA
Transform and Conquer – Balanced Trees – AVL Trees - Rotations
LR
2 >
3 0
2
-1
1 0 0
1 3
0
2
(c)
Double LR-rotation
DAA
Transform and Conquer – Balanced Trees – AVL Trees - Rotations
RL
-2 >
1 0
2
1
3
0 0
1 3
0
2
(d)
Double RL-rotation
DAA
Transform and Conquer – Balanced Trees – AVL Trees - Rotations
DAA
Transform and Conquer – Balanced Trees – AVL Trees - Rotations
DAA
Transform and Conquer – Balanced Trees – AVL Trees
0 -1 -2
0
5 5 5 L(5) 6
0 -1
6 6
> 0 0
5 8
0
8
DAA
Transform and Conquer – Balanced Trees – AVL Trees
Construct an AVL tree for the list 5, 6, 8, 3, 2, 4, 7
1 2 1
6 6 6
1 0 2 0 0 0
R (5)
5 8 5 8 > 3 8
0 1 0 0
3 3 2 5
0
2
2 0
6 5
-1 0 0 -1
LR (6)
3 3
8
> 6
0 1 0 0 0
2 5 2 4 8
0
4
DAA
Transform and Conquer – Balanced Trees – AVL Trees
Construct an AVL tree for the list 5, 6, 8, 3, 2, 4, 7
-1 0
5 5
0 0 0
-2
3 RL (6) 3 7
6
0 0
> 0 0 0 0
1
2 4 2 4 6 8
8
0
7
• Definition A multiway search tree is a search tree that allows more than one key in
tree nodes.
• Definition A node of a search tree is called an n-node if it contains n-1 ordered keys.
• Note: Every node in a classical binary search tree is a 2-node
8 3, 8 3, 8
2, 3, 5 9
> >
2 5 9 2 4, 5 9
DAA
Transform and Conquer – Balanced Trees – 2-3 Trees
5
3, 8 3, 5, 8
> > 3 8
2 4, 5, 7 9 2 4 7 9
2 4 7 9
for any 2-3 tree of height h with n nodes, we get the inequality
n ≥ 1+ 2 + . . . + 2h = 2h+1 − 1,
and hence
h ≤ log2(n + 1) − 1.
DAA
Transform and Conquer – Balanced Trees – 2-3 Trees
• What happens when a 2-3 tree of height h with the largest number of keys
• Is a full tree of 3-nodes, each with two keys and three children.
• log3 (n + 1) - 1 h log2 (n + 1) - 1
• Lower and Upper bounds on height h.
• Search, insertion, and deletion are in (log n)
• The idea of 2-3 tree can be generalized by allowing more keys per node
• 2-3-4 trees
• B-trees
• A heap is partially ordered data structure that is especially suitable for implementing
priority queues.
• A priority queue is a multiset of items with an orderable characteristic called an item’s
priority.
• Supporting the following operations:
• finding an item with the highest (i.e., largest) priority
• deleting an item with the highest priority
• adding a new item to the multiset
DAA
Transform and Conquer – Heaps and Heapsort
A heap is a binary tree with keys assigned to its nodes, one key per node, such that they
met:
• The shape property—the binary tree is essentially complete (or simply complete),
i.e., all its levels are full except possibly the last level, where only some rightmost
leaves may be missing.
• The parental dominance or heap property—the key in each node is ≥ the keys in its
children.
DAA
Transform and Conquer – Heaps and Heapsort
First one is not a heap, because the parental dominance fails for the node with key 5.
Second one is not a heap, because the tree’s shape property is violated.
DAA
Transform and Conquer – Heaps and Heapsort - Properties
• Given n, there exists a unique binary tree (structure) with n nodes that is essentially
complete, with h = log2 n
• The root contains the largest key
• Every subtree rooted at every node of a heap is also a heap
• A heap can easily be represented as an array recording the elements in a top-down
and left-to-right fashion.
• The parental node keys will be in the first n/2 positions of the array, while the leaf
keys will occupy the last n/2 positions;
• The children of a key in the array’s parental position i (1≤ i ≤ n/2) will be in
positions 2i and 2i + 1 and the parent of a key in position i (2 ≤ i ≤ n) will be in
position i/2.
DAA
Transform and Conquer – Heaps and Heapsort - Properties
Store heap’s elements in an array (whose elements indexed, for convenience, 1 to n) in
top-down left-to-right order
Example:
• Left child of node j is at 2j
• Right child of node j is at 2j+1
• Parent of node j is at j/2
• Parental (ie interior) nodes are in the first n/2 locations
9 1 2 3 4 5 6
5 3 9 5 3 1 4 2
1 4 2
DAA
Transform and Conquer – Heaps and Heapsort – Construction (bottom-up)
Step 0: Initialize data structure (ie array) with keys in the given order
Step 1: Starting with the last (rightmost) parental (ie interior) node, fix the heap rooted
at it, if it doesn’t satisfy the heap condition: keep exchanging it with its largest
child until the heap condition holds
Bottom up: Adding nodes to heap from bottom to top, pushing elements down, as
needed
DAA
Transform and Conquer – Heaps and Heapsort – Construction (bottom-up)
DAA
Transform and Conquer – Heaps and Heapsort – Construction (bottom-up)
Construct a heap for the list 2, 9, 7, 6, 5, 8 . Insert elements into the array. Process interior
nodes R to L. Why? Before and after each step? Heapify all the way down at each step.
Bottom up?
DAA
Transform and Conquer – Heaps and Heapsort – Construction (bottom-up)
Construct a heap for the list 2, 9, 7, 6, 5, 8 . Insert elements into the array. Process interior
nodes R to L. Why? Before and after each step? Heapify all the way down at each step.
Bottom up?
DAA
Transform and Conquer – Heaps and Heapsort – Construction (bottom-up)
Construct a heap for the list 2, 9, 7, 6, 5, 8 . Insert elements into the array. Process interior
nodes R to L. Why? Before and after each step? Heapify all the way down at each step.
Bottom up?
DAA
Transform and Conquer – Heaps and Heapsort – Construction (top-down)
• Basic operation in building heap in Top-Down order
• Insert the new element at last position in heap (size++)
• Compare new element with its parent and, if it violates heap condition, exchange them
• Continue comparing the new element with nodes up the tree until the heap condition
is satisfied
Example: Insert key 10 into heap of size 6
What order is this? Efficiency: O(log n)
9 9 10
6 8 > 6 10 > 6 9
2 5 7 10 2 5 7 8 2 5 7 8
DAA
Transform and Conquer – Heaps and Heapsort – Construction (top-down)
Deleting a root/maximum key from the heap
Step 1 Exchange the root’s key with the last key K of the heap.
Step 2 Decrease the heap’s size by 1.
Step 3 “Heapify” the smaller tree by sifting K down the tree exactly in the same way we
did it in the bottom-up heap construction algorithm.
• Verify the parental dominance for K: if it holds, we are done;
• if not, swap K with the larger of its children and repeat this operation until the
parental dominance condition holds for K in its new position.
• What order is this? Efficiency: O(log n)
DAA
Transform and Conquer – Heaps and Heapsort – Construction (top-down)
• Deleting a root/maximum key from the heap
8 6
2 5 1
DAA
Transform and Conquer – Heaps and Heapsort – Construction (top-down)
Construct a heap for the list 2, 9, 7, 6, 5, 8 [Start with elements in the array]. Process
interior nodes from L to R. Add nodes from top to bottom. Add each node, and push up
as needed.
2
29
9/ 2
9/ 6 7/ 2 5;
9/ 2 7
9/ 6 7/ 2 5, 8;
9/ 2 7/ 6
9/ 6 8/ 2 5, 7
9/ 6 7/ 2;
Is this a heap??
DAA
Transform and Conquer – Heapsort
Stage 1: Build heap for a given list of n keys (of height h) worst-case
C(n) = σℎ−1
𝑖=0 2 ℎ − 𝑖 2 𝑖
= 2(𝑛 − 𝑙𝑜𝑔2 𝑛 + 1 )𝜖(n)
Stage 2: Repeat operation of root removal n-1 times (fix heap) worst-case
Assume best algorithm for GCD is used. Are these statements true or false?
- The best algorithm for LCM can be faster than best algorithm for GCD.
- The best algorithm for GCD can be faster than best algorithm for LCM.
- Examples:
• Vertices of a graph typically represent possible states of the problem in question, and
edges indicate permitted transitions among such states.
• One of the graph’s vertices represents an initial state and another represents a goal
state of the problem. (There might be several vertices of the latter kind.)
• Such a graph is called a state-space graph.
• Thus, the transformation reduces the problem to the question about a path from the
initial-state vertex to a goal-state vertex.
DAA
Transform and Conquer – Reduction to Graph Problems