程序代写代做代考 algorithm graph go data structure C EECS 3101

EECS 3101
Prof. Andy Mirzaian

STUDY MATERIAL:
• [CLRS] chapters 2, 4.1-2, 12.1, 31.1-2, 33.4 • Lecture Note 4
2

TOPICS
 The algorithm design process: Central Tools: Iteration & Recursion Partial correctness: Assertions Termination: Measure of Progress
 Iterative Algorithms: Loop Invariant Incremental Method
 Recursive Algorithms:
Recursive Pre- & Post- Condition & strong induction Divide-&-Conquer Method
3

The Algorithm Design Process
We are given the pleasurable task of designing an algorithm for a computational problem.
 Where should we start?
 What design process should we follow?  Are we on the right track?
 Is there a systematic way to convince ourselves, our friends,
and all skeptics, that our algorithm is correct?
 Is our algorithm guaranteed to terminate on every possible input?
 Is there a better algorithm? …
4

Assertions
 An assertion is a true/false logical statement about the state of the variables and data structures of the algorithm.
 Although they appear as inserted comments, assertions are not descriptions of the code’s intended purpose or an explanation of its action.
 Important examples of assertions are:  Pre-Condition
 Post-Condition
 Loop Invariant
 What are assertions good for?
 They guide us along the design process. They should be with us from the
initial design stage; to the middle, keeping us on track; to the end, convincing us that we have a correct algorithm, if we maintain correct assertions.
 The design process might go through a revise-&-repeat cycle. If our assertions show us we are not quite on the right track, they usually also show us what is lacking and suggest ways of correction!
5

Algorithm GuessWhat(n)
Pre-Cond: input n is a natural number
Post-Cond: output is ——————– (fill in the blanks)
Termination:
Measure of Progress:
MP = n – i.
Each iteration reduces MP by 1.
i0
j1
while i < n do i  i +1 j  j + j end-while return j end § What is true about values of i, j & n here? § Any relationship between them? Initial MP = n. Loop exits when Algorithm GuessWhat(n) Pre-Cond: input n is a natural number Post-Cond: output is 2n (how can we be sure?) i  0  1 = 20 & j1 i MP  0. # iterations = n. 0  n loop  Loop-Invariant: j = 2 & i  n Establish LI (induction Base) (induction hypothesis) Maintain LI (induction) & progress towards goal if i  n then exit loop  j = 2 i & i < n i  i +1  2j = 2i+1 & i+1  n j  j+ j end-loop so now: j’= 2i’ & i’ n j=2i & in & in Exit loop, use LI & reach goal end returnj  6 Algorithm ALG(Input) Pre-Cond: Input satisfies problem instance specifications ALG Code Post-Cond: output satisfies problem solution requirements end Pre-Cond & ALG Code  Post-Cond Partial Correctness Warranty: Pre-Cond ALG Code Post-Cond If input satisfies Pre-Cond, and if ALG is executed on that input, and if ALG eventually terminates, then the output is guaranteed to satisfy Post-Cond. Post-Cond is not guaranteed to hold if input does not satisfy Pre-Cond, or if ALG does not terminate on the given input. Total Correctness = Partial Correctness + Termination. 7 ACTIONS ASSERTIONS Assertion0 code fragment Assertion1 Assertion0 & code fragment  Assertion1 Assertion0 code fragment Assertion1 8 Sequential code: Assertion 0 code 1 Assertion 1 code 2 ................. Assertion M-1 code M Assertion M Assertion 0 & code 1  Assertion 1 Assertion 1 & code 2  Assertion 2 Assertion 2 & code 3  Assertion 3 .... Assertion M-1 & code M  Assertion M Assertion0 code 1 Assertion1 code 2 Assertion M-1 code M Assertion M 9 If-then-else: Assertion0 if cond then code+ else code- Assertion1 Assertion0 & cond & code+  Assertion1 and Assertion0 & cond & code-  Assertion1 Assertion0 NO code- YES cond code+ Assertion1 10 Many ... many paths from Pre- to Post- Assertion. Pre-Assertion cond0 NO Don’t trace It suffices to verify each code fragment block only once! YES YES code1+ cond1 NO code1- code2+ all paths one-by-one! YES cond2 NO code2- code4 code3 Post-Assertion 11 Loop Invariant Algorithm ALG(Input) Pre-Cond: Input satisfies problem instance specifications Pre-Loop Code Loop: Loop Invariant if exit-condition then exit loop Loop-Code end-loop Post-Loop-Cond Post-Loop Code Post-Cond: output satisfies problem solution requirements end Pre-Cond & Algorithm Code  Post-Cond Loop-Invariant  induction hypothesis Pre-Cond & Pre-Loop-code  Loop-Invariant  induction base Loop-Invariant & exit-cond & Loop-code  Loop-Invariant  induction Loop-Invariant & exit-cond  Post-Loop-Cond Post-Loop-Cond & Post-Loop-code  Post-Cond  clean up loose ends 12 ACTIONS ASSERTIONS ALGORITHM ALG (Input) Pre-Cond: Input satisfies problem instance specifications Pre-Cond & Pre-Loop-code  Loop-Invariant Loop-Invariant & exit-cond  Post-Loop-Cond Post-Loop-Cond & Post-Loop-code  Post-Cond Pre-Loop Code Loop Invariant Loop-Invariant & exit-cond & Loop-code  Loop-Invariant exit-cond Post-Loop-Cond NO YES Loop Code Post-Loop Code Post-Cond: output satisfies problem solution requirements 13 Pre-Cond : input A[1..n] is an array of numbers, n 0 EXAMPLE PROBLEM: Sum of array items. Pre-Loop Code Incremental Method Loop Invariant NO star of the show: YES Loop Code Start with the exit-cond Post-Loop-Cond the Loop Invariant. Post-Loop Code Post-Cond: output is sum of the items in the input array 14 Pre-Cond : input A[1..n] is an array of numbers, n 0 Pre-Loop Code Loop Invariant: S = sum{A[1..t]} &... Incremental Method NO YES Loop Code exit-cond Post-Loop-Cond Post-Loop Code Post-Cond: output is sum of the items in the input array 15 Pre-Cond : input A[1..n] is an array of numbers, n 0 Pre-Loop Code Loop Invariant: S = sum{A[1..t]} &... Incremental Method NO YES Loop Code return S Post-Cond: output is sum of the items in the input array exit-cond S = sum{A[1..n]} Post-Loop-Cond & Post-Loop-code  Post-Cond 16 Pre-Cond : input A[1..n] is an array of numbers, n 0 Incremental Method Loop Code return S Post-Cond: output is sum of the items in the input array Pre-Cond & Pre-Loop-code  Loop-Invariant S0; t0 Loop Invariant: S = sum{A[1..t]} &... Let’s not use “t = n”. Loop won’t terminate with bad input, e.g., n < 0. NO YES exit-cond S = sum{A[1..n]} Post-Loop-Cond & Post-Loop-code  Post-Cond 17 Pre-Cond : input A[1..n] is an array of numbers, n 0 Incremental Method Loop Code return S Post-Cond: output is sum of the items in the input array Pre-Cond & Pre-Loop-code  Loop-Invariant S0; t0 Loop Invariant: S = sum{A[1..t]} &... Let’s not use “t = n”. Loop won’t terminate with bad input, e.g.,n < 0. NO YES tn S = sum{A[1..n]} Post-Loop-Cond & Post-Loop-code  Post-Cond 18 Pre-Cond : input A[1..n] is an array of numbers, n 0 Pre-Cond & Pre-Loop-code  Loop-Invariant S0; t0 Incremental Method Loop Invariant: S = sum{A[1..t]} &... tn S = sum{A[1..n]} NO YES t  t+1 S  S + A[t] Loop-Invariant & exit-cond & Loop-code  Loop-Invariant Post-Loop-Cond & Post-Loop-code  Post-Cond return S Post-Cond: output is sum of the items in the input array 19 Pre-Cond : input A[1..n] is an array of numbers, n 0 Pre-Cond & Pre-Loop-code  Loop-Invariant S0; t0 Incremental Method Strengthen LI Loop Invariant: S = sum{A[1..t]} &... Loop-Invariant & exit-cond  Post-Loop-Cond NO YES t  t+1 S  S + A[t] tn S = sum{A[1..n]} Loop-Invariant & exit-cond & Loop-code  Loop-Invariant Post-Loop-Cond & Post-Loop-code  Post-Cond return S Post-Cond: output is sum of the items in the input array 20 Pre-Cond : input A[1..n] is an array of numbers, n 0 Pre-Cond & Pre-Loop-code  Loop-Invariant S0; t0 LI changed. Needtorevise Pre-Loop Code or Loop Code ? No revision needed. Lucky this time! Loop Invariant: S = sum{A[1..t]} & t  n t  t+1 S  S + A[t] Loop-Invariant & exit-cond & Loop-code  Loop-Invariant Loop-Invariant & exit-cond  Post-Loop-Cond NO YES tn S = sum{A[1..n]} Post-Loop-Cond & Post-Loop-code  Post-Cond return S Post-Cond: output is sum of the items in the input array 21 Pre-Cond : input A[1..n] is an array of numbers, n 0 Termination: Measure of Progress: MP = n – t. Each iteration reduces MP by 1. Pre-Cond & Pre-Loop-code  Loop-Invariant S0; t0 Loop Invariant: Initial MP = n. Loop exits when S = sum{A[1..t]} &tn t  t+1 S  S + A[t] Loop-Invariant & exit-cond & Loop-code  Loop-Invariant We certify this is a correct algorithm! Loop-Invariant & exit-cond  Post-Loop-Cond NO YES MP  0. # iterations = tn S = sum{A[1..n]} max{n,0}. Post-Loop-Cond & Post-Loop-code  Post-Cond return S Post-Cond: output is sum of the items in the input array 22 Algorithm SUM(A[1..n]) Pre-Cond: input A[1..n] is an array of numbers, n 0 S0; t0 Loop: Loop Invariant: S = sum{A[1..t]} & tn if t  n then exit loop t  t+1; S  S + A[t] end-loop S = sum{A[1..n]} return S Post-Cond: output is sum of the items in the input array end Pre-Cond & Algorithm Code  Post-Cond Loop-Invariant  induction hypothesis Pre-Cond & Pre-Loop-code  Loop-Invariant  induction base Loop-Invariant & exit-cond & Loop-code  Loop-Invariant  induction Loop-Invariant & exit-cond  Post-Loop-Cond Post-Loop-Cond & Post-Loop-code  Post-Cond  clean up loose ends 23 ACTIONS ASSERTIONS Loop Invariant may need revision If LI is too strong, it may require too much effort to either establish or maintain it. Pre-Cond & Pre-Loop-code  Loop-Invariant Loop-Invariant & exit-cond & Loop-code  Loop-Invariant Loop-Invariant & exit-cond  Post-Loop-Cond Post-Loop-Cond & Post-Loop-code  Post-Cond If LI is too weak, it may not imply the induction, or may not imply the desired end goal. 24 INCREMENTAL ALGORITHMS Incremental progress over time is an exponential multiplier. -Michael Erik Water droplets gathered incrementally bring about a sea. -Persian proverb 25 TOPICS  Incremental Method & its Loop Invariant  Problems:  VLSI Chip Testing  In-place Tri-Partition  Maximum Sum Sub-Array  Longest Smooth Sub-Array 26 Pre-Cond: S is a set of input objects C  ; Obtain Sol() Loop Invariant: CS & Sol(C) is solution to C Incremental Method This is generic. It may need to be strengthened in a given application. return Sol(C) Post-Cond: output is solution to S x  a selected object from S – C; C  C  {x}; Update Sol(C); On-Line: Items are given to you one-by-one. You need to update solution before next object is given. Examples: SUM and on-line Insertion Sort. Off-Line: CS C=S & Sol(C) is solution to C NO YES You are given all input objects in advance of any computation. You may choose any previously unselected input object. Example: Selection Sort. 27 Problem: VLSI Chip Testing [CLRS Problem 4-5, page 109]  Pre-Condition: Input is a set S of VLSI chips, each chip is either good or bad (unknown to us). Strictly more than half of these chips are good. (Note: this implies S  .)  Post-Condition: Output is one of the good chips from the input.  Notation: MTHG(S) = “More Than Half of the chips in S are Good”.  Primitive operation: Boolean Test(x,y) on any pair of chips x and y. Test(x,y) = True  x & y are either both good or both bad False  at least one of x or y is bad  Use this primitive operation to solve the problem.  Comment: If good and bad chips are 50-50, Test would be unable to break the good-bad symmetry. If less than 50% are good, that’s even worse! 28 Where to start? • Brute Force: Compare each chip against every other chip. This requires O(n2) Tests. Can we do it faster, incrementally? • Incremental method could be quite effective! How? Suppose we pick a pair of chips x and y from S and invoke Test(x,y). • If Test(x,y) = False, then at least one of x or y is bad (the other is good or bad). We can discard both x & y (S  S – {x,y}, and proceed with what’s left). We still have MTHG(S). So, S still contains a good chip. There is hope !!! • If Test(x,y) = True, then what? If x & y both happen to be bad, then discarding both is still safe. But x & y could both be good. It’s unsafe to discard them both. Why? You no longer have the guarantee that MTHG(S)! You may have inadvertently discarded all the good chips! • How should we “repair” this shortcoming? Strengthen the Loop Invariant. ............................................ P.T.O. 29 Strengthen the Loop Invariant • Notation: MTHG(S) = “More Than Half of the chips in S are Good”. AllGood(C) = “chips in set C are all good”. Uniform(C) = “chips in set C are either all good or all bad”. Note: [MTHG(C) & Uniform(C)]  [AllGood(C) & C]. • Strengthen Loop Invariant: In addition to MTHG(S), maintain a candidate subset C of the chips with the guarantee: Uniform(C). • Now, how can you maintain LI and make progress? Idea: pick xS – C and yC, then Test(x,y). What happens? What if S – C is empty? What if C is empty? yx C non-candidate tested chips “discarded” S 30 Pre-Cond: input is a set S of n VLSI chips & MTHG(S). Pre-Cond & Pre-Loop-code  Loop-Invariant C Incremental Method Loop-Invariant & exit-cond & Loop-code  Loop-Invariant Loop Invariant: C  S & Uniform(C) & MTHG(S) Loop-Invariant & exit-cond  Post-Loop-Cond Post-Loop-Cond & Post-Loop-code  Post-Cond NO YES xanarbitrarychipin S–C if C =  then C  C  {x} else do y  an arbitrary chip in C if Test(x,y) then CC{x} else CC–{y}; CS C   & AllGood(C) end-do S  S – {x,y} return any one chip from C Post-Cond: output is a good chip from the input Measure of Progress: MP = |S – C| . # iterations  n. 31 Algorithm VLSIChipTesting( S ) § takes O(n) Tests Pre-Cond: input is a set S of n VLSI chips & MTHG(S). C Loop: Loop Invariant: C  S & Uniform(C) & MTHG(S) if C = S then exit loop xanarbitrarychipin S–C if C =  then C  C  {x} else do y  an arbitrary chip in C if Test(x,y) then CC{x} else CC–{y}; SS–{x,y} end-do end-loop C   & AllGood(C) return any one chip from C Post-Cond: output is a good chip from the input end 32 INPUT: OUTPUT: INPUT: OUTPUT: Problem: In-Place Tri-Partition An array A[1..n], where each item A[i]  {red, green, blue}, i=1..n. A permutation of A[1..n] so that all red items appear first, then all green items, then all blue items. Same colour items can appear in any order within their colour group. 1 2 3 4 5 6 7 8 9 10 11 12 3 10 7 11 8 4 5 2 6 1 9 12 Restriction: This has to be done in-place, within array A. We are allowed to use only O(1) additional scalar variables (e.g., array indices). [We cannot use O(n) additional memory cells such as lists.] Applications: Partitioning in QuickSort & QuickSelect, In-place bucketing, etc. CLAIM: We can do this partitioning in O(n) time incrementally. 33 The Loop Invariant not processed yet A 1RG Bn Loop Invariant: • A[1..R-1] are all reds. • A[R..G-1] are all greens. • A[B+1..n] are all blues. • 1RGB+1n+1. Measure of Progress: # unprocessed items. MP = B – G +1. Exit Condition: G > B. (i.e., all items processed)
Establish Loop Invariant:
(R, G, B)  (1, 1, n).
i.e., all n items are unprocessed.
Maintain LI & Make Progress:
Reduce MP while maintaining LI? How? Process A[G]. What’s its colour?
If A[G] = green then G++
If A[G] = blue
then A[G]  A[B]; B–
If A[G] = red
then A[G]  A[R]; R++; G++
34

Another Loop Invariant
not processed yet
A
1RG
Exercise 1:
Bn
Solve the 3-partition problem in-place in O(n) time, using the alternative Loop Invariant shown above.
Exercise 2:
Generalize the 3-partition problem to 4-partition, 5-partition, …
In general, for any integer C, 2  C  n, show that the C-partition problem can be solved in O(Cn) time, using O(C) extra memory cells.
Therefore, if C is any constant, the C-partition problem can be solved in O(n) time, using O(1) extra memory cells.
35

Problem: Maximum Sum Sub-Array
 INPUT: an array A[1..n] of arbitrary real numbers (positive, zero, negative). OUTPUT: a contiguous sub-array, say A[i+1..j], of A[1..n] with max element
sum (i.e., A[i+1] + A[i+2] + ··· + A[j] is max possible).
 Example: [ 2, 1, -6, -3, 2, -4, 6, -2, -1, 1, 3, -4, 7, -5, 2, -3, 2, 1 ].
 Brute Force Method: Try every sub-array A[i+1..j], for all 0  i  j  n. This can be done in O(n2) time. How?
We can obtain sum(A[i+1..j]) in O(1) time if we first spend O(n) pre-processing time to obtain PrefixSum[0..n], where
PrefixSum[t] = sum(A[1..t]), for t=0,1,…,n, (computed incrementally):
PrefixSum[0]  0; for t  1..n do PrefixSum[t] PrefixSum[t-1]+A[t] Now, sum(A[i+1..j]) = PrefixSum[j] – PrefixSum[i].
 Can we solve the problem in sub-quadratic time incrementally?
Let’s try ………………………………………………………………………. P.T.O.
36

Incremental Solution
 A[1..t] = prefix of A considered incrementally so far.
 Suppose maximum sum subarray of A[1..t] is A[i+1..j], Let’s denote that solution by:
BestSol(t) = A[i+1..j], and SolSum(t) = sum(A[i+1..j]).
 Loop Invariant: BestSol(t) = A[i+1..j], tn, SolSum(t) = sum(A[i+1..j]),
and … (?)
0  i  j  t  n.
1i jtt+1 n A BestSol(t) A[t+1]
?
BestSol(t) & SolSum(t) & A[t+1]  BestSol(t+1) & SolSum(t+1)
Enough info in Loop Invariant?
37

Examine the Loop Invariant
LI(t) & A[t+1]
BestSol(t) = A[i+1..j], SolSum(t) = sum(A[i+1..j]), A[t+1]
Maintain LI
& progress
LI(t+1)
BestSol(t+1) = ?, SolSum(t+1) = ?
which case are we in?
Case 1: A[t+1] is not part of BestSol(t+1): BestSol(t+1) = BestSol(t) and
SolSum(t+1) = SolSum(t).
Case 2: A[t+1] is part of BestSol(t+1): BestSol(t+1) = a suffix of A[1..t+1].
Which suffix?
LI is not strong enough. It should also tell us what is the
maximum sum suffix of A[1..t] and its element sum.
1 Best Solution t t+1 n A
Best Suffix
38

1
Revise the Loop Invariant
Best Solution t t+1 n
A
Best Suffix
BestSol(t) = A[i+1..j], tn, SolSum(t) = sum(A[i+1..j]),
maintain LI & progress
LI(t+1) (the one with bigger sum):
1) A[t+1] excluded:
BestSuffix(t+1) = A[t+2..t+1] (i.e., nil) SuffixSum(t+1) = 0
2) A[t+1] included:
BestSuffix(t+1) = (BestSuffix(t) , A[t+1]) SuffixSum(t+1) = SuffixSum(t) + A[t+1]
BestSol(t+1) = BestSol(t) or BestSuffix(t+1), whichever has bigger sum.
Loop Invariant:
LI(t) & A[t+1]
BestSuffix(t) = A[k+1..t], SuffixSum(t) = sum(A[k+1..t])
SuffixSum(t+1) is better of two choices
BestSol(0) SolSum(0)
 A[1..0] (nil)  0
LI(0)
establish LI
BestSuffix(0)  A[1..0] SuffixSum(0)  0
39

Pre-Cond: input is an array A[1..n] of arbitrary integers.
(i, j, k, t)  (0, 0, 0, 0) SolSum  SuffixSum  0
Loop Invariant:
BestSol(t) = A[i+1..j], tn, SolSum = sum(A[i+1..j]), BestSuffix(t) = A[k+1..t], SuffixSum = sum(A[k+1..t])
Incremental Method
t  t+1
if SuffixSum + A[t] > 0
NO YES
BestSol(n) = A[i+1..j]
return A[i+1..j]
Post-Cond: output is max-sum-subarray of input
tn
then SuffixSum  SuffixSum + A[t] else SuffixSum  0; k  t
if SolSum < SuffixSum then SolSum  SuffixSum; (i, j)  (k, t) MP = n – t. # iterations  n. 40 Algorithm MaxSumSubArray( A[1..n] ) § takes O(n) time Pre-Cond: input is an array A[1..n] of arbitrary integers. (i, j, k)  (0, 0, 0) § t  0 SolSum  SuffixSum  0 for t  1 .. n do Loop Invariant: BestSol(t) = A[i+1..j], SolSum = sum(A[i+1..j]), BestSuffix(t) = A[k+1..t], SuffixSum = sum(A[k+1..t]) if SuffixSum + A[t] > 0
then SuffixSum  SuffixSum + A[t] else SuffixSum  0; k  t
if SolSum < SuffixSum then SolSum  SuffixSum; (i, j)  (k, t) end-for BestSol(n) = A[i+1..j] return A[i+1..j] Post-Cond: output is max-sum-subarray of input end 41 BestSol BestSuffix 3 3 3 3 3 Example run of the algorithm 2 1 -6-32 -46 -46 -4 6 -4 6 -4 6 -4 6 -2-11 3 -2-11 3 -2 -1 1 3 -2 -1 1 3 -2 -1 1 3 -2 -1 1 3 -2 -1 1 3 -47 -47 -4 7 -4 7 -4 7 -4 7 -4 7 -52 -3 -52 -3 -5 2 -3 -5 2 -3 -5 2 -3 -5 2 -3 -5 2 -3 21 3 2 2 2 2 2 -6-32 1 -6 -3 2 0 1 -6 -3 2 0 1 -6 -3 1 -6 -3 1 -6 -3 2 2 2 2 0 6 -4 6 6 42 2 1 2 1 2 1 2 1 2 1 2 1 2 1 -6-32 -4 -6 -3 2 -4 -6 -3 2 -4 -6 -3 2 -4 -6 -3 2 -4 -6 -3 2 -4 -6-32 -4 6 6 6 4 6 6 3 6 6 4 6 6 -2 -1 -2 -1 -2 -1 -2 -1 7 -2 -1 7 7 -2 -1 3 10 Example run of the algorithm 6 6 13-47 1 3 -4 7 1 3 -4 7 1 3 -4 7 1 3 -4 7 1 3 -4 7 -52 -3 -5 2 -3 -5 2 -3 -5 2 -3 -5 2 -3 -5 2 -3 -52 -3 6 -2 -1 1 3 -4 7 10 43 2 1 2 1 2 1 2 1 2 1 -6-32 -6 -3 2 -6 -3 2 -6 -3 2 -6 -3 2 10 -4 -52 -3 10 -4 6 -2 -1 1 3 -4 7 -5 2 -3 5 10 -4 6 -2 -1 1 3 -4 7 -5 2 -3 7 10 -4 6 -2 -1 1 3 -4 7 -5 2 -3 4 -4 6 -2 -1 1 3 -4 7 -5 2 -3 Maximum Sum Sub-Array Example run of the algorithm 6 -2 -1 1 3 -4 7 10 44 Problem: Longest Smooth Sub-Array  Consider a real number D > 0.
An array S of numbers is said to be D-smooth, if no pair of items in S have a difference more than D, i.e., max(S) – min(S)  D.
Example: S = [3, 4, 9, 5, 3, 6] is 7-smooth because max(S) – min(S) = 9-3  7.
 Longest Smooth Subarray (LSS) Problem:
INPUT: OUTPUT:
 Example: A[t]
an array A[1..n] of numbers, and a number D > 0. the longest contiguous D-smooth subarray of A[1..n].
D = 8 , A = [ 4, -3, 7, 9, 12, 5, 9, 10, 6, 1, 6 ] .
max – min  D
t
1
i A[i..j] = LSS(A[1..n]) j n
45

Where to start?
 Brute Force Method: Try every subarray A[i..j], for all 1  i  j  n. This can be done in O(n2) time. How?
 Can we solve the problem in sub-quadratic time? By the Incremental Method?
 Start with the obvious incremental LI and gradually strengthen it till it’s right. LSS(A[1..t]) denotes the Longest D-Smooth Subarray of A[1..t].
 Our Loop Invariant so far includes:
LI(a): A[i..j] = LSS(A[1..t]), i  j  t  n.
 How do we maintain LI(a) going from A[1..t-1] to A[1..t]?
Like MaxSumSubArray, we see we need the best suffix info too.
 LSX(A[1..t]) denotes the Longest D-Smooth Suffix of A[1..t].
46

Strengthen the Incremental Loop Invariant
 LI(a): A[i..j] = LSS(A[1..t]), i  j  t  n.
 LSS(A[1..t]) = LSS(A[1..t-1]) if A[t] is not part of LSS(A[1..t])
LSS(A[1..t]) = LSX(A[1..t]) if A[t] is part of LSS(A[1..t])
 Strengthen Loop Invariant:
LI(b): A[k..t] = LSX(A[1..t]), k  t.
 How do we maintain LI(b)?
 Suppose LSX(A[1..t-1]) = A[k’ ..t-1]. This is D-smooth.
Add A[t] to it to get A[k’ ..t].
If A[k’..t] is D-smooth, then LSX(A[1..t]) = A[k’ ..t]. Why?
What if A[k’ ..t] is not D-smooth?
…………………………………………………………………………………… P.T.O.
47

Further Strengthen the Loop Invariant
LI(a): A[i..j] = LSS(A[1..t]), i  j  t  n. LI(b): A[k..t] = LSX(A[1..t]), k  t.
 A[min1] = rightmost minimum of A[k’ ..t-1] & A[max1] = rightmost maximum of A[k’ ..t-1].
 A[k’..t-1] is D-smooth but A[k’..t] is not.
1 1
k’ min1 t-1 t k’ max1 t-1 t
So, either
A[t] – D > A[min1]
or A[t] + D < A[max1], but not both. D D t  If A[t] - D > A[min1], then no part of A[k’.. min1] can be in LSX(A[1..t]). If A[t] + D < A[max1], then no part of A[k’.. max1] can be in LSX(A[1..t]).  To get to k, we upgrade k’ to 1+ min1 or 1+max1, whichever is appropriate. But we may not be done yet! ........................................................ P.T.O. t 48 A[t] LSX(A[1..t-1]) D max - min  D 1k’cut t-1tn off min k LSX(A[1..t]) min2 3 t min1 index m1 while A[t] - D > A[minm]
do k  1 + minm ; m++
49

max1 max2 LSX(A[1..t]) k
cut off
max – min  D D
A[t] t-1 t
t
1
k’ LSX(A[1..t-1])
n
m1
while A[t]+D A[minm], we need to upgrade lowest index in LSX. 2. MaxUpgrade: While A[t] + D < A[maxm], we need to upgrade lowest index in LSX. 3. FrontCleanUp: t is part of the new suffix & must be pushed to the front of both lists. Before doing that, remove front items in MinL (MaxL) that would no longer be rightmost minima (maxima) after t is added. Procedure MinUpgrade while MinL   & A[t] - D > A[Rear(MinL)] do k  1 + PopRear(MinL) while MaxL   & Rear(MaxL) < k do PopRear(MaxL) Procedure MaxUpgrade while MaxL   & A[t] + D < A[Rear(MaxL)] do k  1 + PopRear(MaxL) while MinL   & Rear(MinL) < k do PopRear(MinL) Procedure FrontCleanUp while MinL   & A[t]  A[Front(MinL)] do PopFront(MinL) while MaxL   & A[t]  A[Front(MaxL)] do PopFront(MaxL) PushFront(t, MinL) PushFront(t, MaxL) only 2 pushes all Pops 53 Pre-Cond: input is an array A[1..n] of numbers & D > 0.
Pre-Cond & Pre-Loop-code  Loop-Invariant
(i, j, k, t)  (0, 0, 0, 0) (MinL, MaxL)  (, )
Incremental Method
Loop-Invariant & exit-cond & Loop-code  Loop-Invariant
LOOP INVARIANT:
LI(a): A[i..j] = LSS(A[1..t]),
LI(b): A[k..t] = LSX(A[1..t]),
LI(c): MinL and MaxL as described.
i  j  t n. k  t.
Loop-Invariant & exit-cond  Post-Loop-Cond
Post-Loop-Cond
t  n YES
NO
t  t+1 MinUpgrade MaxUpgrade FrontCleanUp
if j – i < t – k then (i, j)  (k, t) Nested loops. Quadratic time ??? LSS(A[1..n]) = A[i..j] & Post-Loop-code  Post-Cond MP = 3(n – t) + |MinL| + |MaxL|. return A[i..j] Post-Cond: output is longest D-smooth subarray of A[1..n] Total iterations in all loops  3n. 54 Algorithm LongestSmoothSubArray(A[1..n], D) § takes O(n) time Pre-Cond: input is an array A[1..n] of numbers and D > 0.
(i, j, k)  (0, 0, 0); (MinL, MaxL)  (, ) § t  0
for t  1 .. n do Loop Invariant: LI(a): A[i..j] = LSS(A[1..t]), i  j  t  n.
§ maintain LI(b) and LI(c): § MinUpgrade:
LI(b): A[k..t] = LSX(A[1..t]), k  t. LI(c): MinL and MaxL as described.
while MinL   & A[t] -D > A[Rear(MinL)] do k  1 + PopRear(MinL) while MaxL   & Rear(MaxL) < k do PopRear(MaxL) § MaxUpgrade: while MaxL   & A[t]+ D < A[Rear(MaxL)] do k  1 + PopRear(MaxL) while MinL   & Rear(MinL) < k do PopRear(MinL) § FrontCleanUp: while MinL   & A[t]  A[Front(MinL)] do PopFront(MinL) while MaxL   & A[t]  A[Front(MaxL)] do PopFront(MaxL) PushFront(t, MinL); PushFront(t, MaxL) § maintain LI(a): if j – i < t – k then (i, j)  (k, t) end-for LSS(A[1..n]) = A[i..j] return A[i..j] Post-Cond: output is longest D-smooth subarray of A[1..n]. end 55 Algorithm LongestSmoothSubArray(A[1..n], D) § takes O(n) time (i, j, k)  (0, 0, 0); (MinL, MaxL)  (, ) for t  1 .. n do MP = 3(n – t) + |MinL| + |MaxL| while MinL   & A[t] -D > A[Rear(MinL)] do k  1 + PopRear(MinL) while MaxL   & Rear(MaxL) < k do PopRear(MaxL) while MaxL   & A[t]+ D < A[Rear(MaxL)] do k  1 + PopRear(MaxL) while MinL   & Rear(MinL) < k do PopRear(MinL) while MinL   & A[t]  A[Front(MinL)] do PopFront(MinL) while MaxL   & A[t]  A[Front(MaxL)] do PopFront(MaxL) PushFront(t, MinL); PushFront(t, MaxL) if j – i < t – k then (i, j)  (k, t) end-for return A[i..j] end 56 RECURSION 57 TOPICS  Recursive Pre- & Post- Conditions  Correctness through Strong Induction  Divide-&-Conquer:  Recursive Doubling: • Exponentiation • Fibonacci Numbers  Euclid’s GCD algorithm  Integer & Matrix Multiplication  Closest Pair of Points in the plane  Algorithms on Binary Trees 58 Algorithm ALG(I) Pre-Cond(I) ALG code on instance I: Code A Assertion0 recursive call to ALG(I0) Assertion1 Code B Post-Cond(I) size(I0) < size(I) recursive call to ALG(I0) Pre-Cond(I0) ALG code on instance I0 Post-Cond(I0) GOAL: I: Pre-Cond & ALG Code  Post-Cond Assume strong induction hypothesis: Pre-Cond(I0) & ALG code(I0)  Post-Cond(I0) Prove for an arbitrary instance I:  Pre-Cond & ALG code Base case  Post-Cond Pre-Cond & CodeA Assertion0 Assertion0  Pre-Cond(I0) Post-Cond(I0)  Assertion1 Assertion1 & Code B  Post-Cond induction base 59 Pre-Cond, Post- Cond, or code may need revision Post-Cond not too weak Post-Cond not too strong Pre-Cond & ALG code  Post-Cond Base case Pre-Cond & CodeA Assertion0 Assertion0  Pre-Cond(I0) Post-Cond(I0)  Assertion1 Assertion1 & Code B  Post-Cond Pre-Cond not too weak Pre-Cond not too strong Algorithm ALG(I) Pre-Cond(I) ALG code on instance I: Code A Assertion0 call ALG(I0) Assertion1 Code B Post-Cond(I) 60 DIVIDE & CONQUER Divide et impera. - Niccolò Machiavelli [1469-1527] 61 The Divide-&-Conquer Method MergeSort is the prototypical divide-&-conquer algorithm. Algorithm ALG(I) Pre-Condition: input is instance I Post-Condition: output is Sol(I) Base: Divide: Conquer: Combine: Output: end if |I| = O(1) then return Sol(I) by the base method Divide I into sub-instances I1, I2, ..., Ia, each of size |I|/b for i  1 .. a do Soli  ALG(Ii) Sol  Combine(Sol1, Sol2, ..., Sola ) return Sol TnaTbnfn n1 1 n  O1 62 What Number did I guess? Problem 1: I guess an integer x between 1 and n. You find x. You can ask me questions of the form “is x=a?”, “is x > a?”, “is x < a?”, for any number a you choose. What’s your method? How many questions do you need to ask? Do binary search on integers between 1 and n. O(log n) questions. Problem 2: I guess a positive integer x. You find x. You can ask me questions of the form “is x=a?”, “is x > a?”, “is x < a?”, for any number a you choose. What’s your method? How many questions do you need to ask? Starting from 1, repeatedly double to get an upper-bound n on x. Then binary search between 1 and n. O(log x) questions. 63 Recursive Doubling Example: Given X - {0} and nN , compute Xn using arithmetic. Method 1: Multiply n copies of X: X ·X ·X ··· X ·X ·X. That takes O(n) arithmetic operations. That’s exponential in the bit length of input n. Method 2: Starting with X, repeatedly multiply the result by itself. We get: X, X2, X4, X8, X16, X32, ... Suppose we want to compute X13. 13 = 8 + 4 + 1. So, X13 = X8 ·X4 ·X. Xn can be computed this way in O(log n) arithmetic operations. How? Just figure out n in binary bits. It’s simpler to look backwards. Divide n by 2 and let r be the remainder: n2nr, r{0,1}. 2 n 2n2r 2 n2 r m r x  x  x   x  y  x w h e r e y  x  x a n d m   n2  . 64 Xn by Recursive Doubling Algorithm EXP(X, n) Pre-Cond:X-{0},nN. if n=0 then return 1 YX·X Z  EXP(Y, n/2) if n mod 2 = 1 then Z  Z · X return Z Post-Cond: returns Xn. end n n2r, r{0,1}. xn x2n2r yn2xr y  x2 r  n mod 2. T(n)T(n2)(1) n0  T(n)(logn). (1) n0 2 65 Fibonacci Numbers Fibonacci Numbers: F0 =0, F1 =1, Fn+2 =Fn+1 +Fn foralln0. n: 0 1 2 3 4 5 6 7 8 9 10 11 12 ... Fn:01123581321 34 55 89144... xn2 xn1 xn,x0 x2 x1. Two roots : golden ratio   1 5 1.61803, 2 1 n n Fn  5 φ  φˆ  F φn n ˆ and 1 5 0.61803. 2 nˆn Fn aφ bφ Now choose a and b to satisfy the boundary conditions F  0, F  1. 01 66 Method 1: the recurrence formula Algorithm Fib(n) if n{0,1} then return n return Fib(n-1) + Fib(n-2) end T ( n )   T ( n  1 )  T ( n  2 )   ( 1 ) (1) n  2 n  0,1  T(n)(Fn )(φn ). [use guess-&-verify] Cons: This is double-exponential time in the input n’s bit length! 67 Method 2: incremental Algorithm Fib(n) (x,y)  (0,1) § (x,y)= (F0,F1 ) for t  2 .. n do zx+y xy yz LI: (x, y) = (Ft-1, Ft ) end-for return y end T ( n )  ( n ). Cons: This is exponential time in the input n’s bit length! 68 Method 3: recursive doubling F  1 φn  φˆ n  Algorithm Fib(n) n 5 X EXP( (1 +5)/2 , n) Y EXP( (1 –5)/2 , n) return (X –Y)/5 end T ( n )  (log n ). Pros: This is linear in the input n’s bit length! Cons: • What if we didn’t know the formula? • It uses non-integer real arithmetic &  even though Fn is always an integer! Is there a way to do integer-only arithmetic to avoid “round off” errors? 69 Method 4: An recursive doubling Fn1 1 1Fn  Fn1 Fn Fn1 Fn Fn F 1 0F  n n1 Fn1 Fn  1 1Fn Fn1        n1  n2 FF 1 1 Fn Fn1 1 0Fn1Fn2 G ( 1 )   F F    1 10 0   A Fn11Fn1 F 1 0F  21 A G(n-1) G(n)=A·G(n-1)=A2 ·G(n-2)=···=An-1 ·G(1)=An . G(n) EXP(A , n) on 2-by-2 matrices! O(log n) time integer-only arithmetic! 70 Greatest Common Divisor Input: a, b N, not both zero. Output: Greatest Common Divisor of a and b: GCD(a,b) = max { dN : d|a and d|b }. d|a means “d divides a”, i.e., a is an integer multiple of d. Elementary School Method: if min{a,b} = 0 then return max{a,b} for d  min{a,b} down-to 1 do if d|a & d|b then return d end Running time = O( 1 + min{a,b} ). This is exponential time in the # bits in the input. Try GCD(1000,000,000,001, 1000,000,000,000). 71 Euclid’s GCD Algorithm FACT 0: d|a & d|b  d|GCD(a,b). FACT 1: b = 0  GCD(a,b) = a. Now suppose b  0. Divide a by b. Let q = quotient, r = remainder: a = q·b +r, 0rb-1. FACT 2: GCD(a,b) = GCD(b,r). Proof: d: d|a & d|b  d|b & d|r. FACT 3: (a) a < b  q = 0, r = a. So, (b,r) = (b,a). (b) a = b  q = 1, r = 0. So, (b,r) = (b,0). (c) a > b  a  b + r > 2r.
r0 = a, r1 = b,
For all i, such that ri+1  0:
ri = qi ri+1 + ri+2 , 0  ri+2  ri+1 –1.
Algorithm GCD(a,b)
if b=0 then return a return GCD(b, a mod b)
end
(r0 , r1)=(a,b) (r1 , r2)
(r2 , r3)
(r3 , r4)
···
(rk-1 , rk), (rk , rk+1),
ri 0,ik rk+1 = 0
rk = GCD(a,b)
FACT 4:
(a) For all i>0: ri+2 < 1⁄2 ri. (b) k < 2 + 2 log min{a,b}. (c) Running time of GCD = O(1 + log min{a,b}). 72 More on GCD FACT 5: The following are equivalent: (1) D = GCD(a,b) (2) D=max{dN: d|aandd|b}. (3) D = min {ax + by > 0 : x & y are integers}.
Proof: (1)  (2) by definition. We show (1)  (3) as follows: Let D = GCD(a,b) and D’ = min {ax + by > 0 : x & y are integers}. D|a & D|b  D|(ax+by)  D|D’  D  D’.
D  D’ is implied by the Claim below. Therefore, D = D’.
CLAIM: D = GCD(a,b) = ax + by, for some integers x and y.
Proof of Claim: By induction on the recursion depth of Euclid’s algorithm. Basis: If b=0, then GCD(a,b) = a = 1a + 0b.
Induction: If b 0, let a = qb+r.
By induction hypothesis GCD(b, r) = bx’+ ry’, for some integers x’ & y’. Therefore, GCD(a,b) = bx’+ry’ = bx’+(a-qb)y’ = ay’+(x’ –qy’)b = ax+by with x = y’ and y = x’ – qy’.
73

More on GCD
FACT 5: The following are equivalent: (1) D = GCD(a,b)
(2) D = max {dN : d|a and d|b }.
(3) D = min {ax + by > 0 : x & y are integers}.
FACT 6: For (possibly negative) integers a and b, GCD(a,b) = GCD( |a| , |b| ).
FACT 7: The equation ax + by = 1
with given non-zero integers a and b, has integer solutions for x and y if and only if a and b are relatively prime, i.e., GCD(a,b) = 1.
FACT 8: The equation ax + by = c
with given non-zero integers a, b, c, has integer solutions for x and y if and only if GCD(a,b)|c.
Exercise:
Show that Euclid’s algorithm can be adapted to produce such a solution.
74

n-bit Integer Addition vs Multiplication xxn1xn2 x1x0 compute xy
yyn1yn2 y1y0 and x*y
FACT 0: The bit-complexity of n-bit addition or multiplication is (n).
Proof: A correct algorithm must “look” at every input bit.
Suppose on non-zero inputs, input bit b is not looked at by the algorithm. Adversary gives the algorithm the same input, but with bit b flipped. Algorithm is oblivious to b, so it will give the same answer.
It can’t be correct both times!
Elementary School Addition Algorithm has O(n) bit-complexity:
XXXXXXXXXX + XXXXXXXXXX
XXXXXXXXXXX
FACT 1: The bit-complexity of n-bit addition is (n).
75

n-bit Integer Multiplication xxn1xn2 x1x0 compute xy
yyn1yn2 y1y0 and x*y Elementary School Multiplication Algorithm has O(n2) bit-complexity:
QUESTION:
XXXX * XXXX
XXXXX XXXXX
XXXXX XXXXX
XXXXXXXXX
What is the bit-complexity of n-bit multiplication?
76

n-bit Integer Multiplication by Divide-&-Conquer
xxn1xn2 x1x0 compute xy yyn1yn2 y1y0 and x*y
31 59
41 27
X= Y=
X*Y = 18,616,707
X=3100+41 = a•100+b Y=5900+27 = c•100+d
X*Y =(a*c) • 10000 + (a*d + b*c) • 100 + b*d
= (31*59) • 10000 + (31*27 + 41*59) • 100 + 41*27
=1829•10000 + (837+2419)•100 = 1829•10000 + 3256•100
= 18290000 + 325600
= 18,616,707
+ 1107 + 1107
+ 1107
77

n-bit Integer Multiplication by Divide-&-Conquer
xxn1xn2 x1x0 yyn1yn2 y1y0
compute xy and x*y
n/2
n/2
n
a
b
x= y=
c
d
x*y(a*c)22n2 (a*dc*b)2n2 (b*d) Shift/Add/Subtract (n) time
T(n)4T(n2)(n) T(n)nlog2 4n2
78

n-bit Integer Multiplication by Divide-&-Conquer
xxn1xn2 x1x0 yyn1yn2 y1y0
compute xy and x*y
n/2
n
n/2
a
b
x= y=
c
d
x*y(a*c)22n2 (a*dc*b)2n2 (b*d) Shift/Add/Subtract (n) time
(ab)*(cd)  (a*c)(a*dc*b)(b*d) T(n)4T( 2)(n) T(n)nlog2 4n2
n
79

n-bit Integer Multiplication by Divide-&-Conquer xxn1xn2 x1x0 compute xy
yyn1yn2 y1y0 and x*y n
n/2 n/2
x= y=
Divide-&-Conquer Multiplication by Karatsuba, Ofman [1962]:
a
b
c
d
u  (a + b) * (c + d)
va*c
w b*d
xy  v • 22 n/2 + (u – v – w) • 2 n/2 + w return xy
Karatsuba-Ofman’s discovery disproved Andrey Kolmogorov’s 1956 conjecture that multiplication requires (n2) bit operations.
T(n)  3T(n 2)  (n)  T(n)  nlog2 3   n1.585 
80

n-bit Integer Multiplication by Divide-&-Conquer
xxn1xn2 x1x0 compute xy yyn1yn2 y1y0 and x*y
X = 3141 Y = 5927
X*Y = 18,616,707
X=3100+41 = a•100+b Y=5900+27 = c•100+d
u = (a+b)*(c+d) = (31+41)*(59+27) = 72 * 86 = 6,192 v = a*c = 31 * 59 = 1,829
w = b*d = 41 * 27 = 1,107
X*Y = v • 10000 + (u – v – w) • 100 + w
= 1829 • 10000 + (6192 –1829 –1107) • 100 + 1107 = 18,616,707
81

Complexity of n-bit Integer Multiplication
Known Upper Bounds:
 O(n log 3 ) = O(n1.59 )  O(n log n log log n)  O(n log n 8 log*n )
Known Lower Bound:
by divide-&-conquer [Karatsuba-Ofman, 1962]
by FFT
[Schönhage-Strassen, 1971] [David Harvey et al., 2016]
 ( n log n / log log n)
FFT = Fast Fourier Transform [CLRS chapter 30]
[Fischer-Meyer, 1974]
82

Matrix Multiplication
stt ri=ir
A
B
s
j
j
Cs AB fori1..r,j1..t.
ij k1 ik kj ( rst ) time.
(n3) time,if rstn.
C
83

Matrix Multiplication by Divide-&-Conquer
A11
A12
A21
A22
B11
B12
B21
B22
C11
C12
C21
C22
n/2
n/2
n/2 n/2

=
C11  A11B11  A12B21 C21  A21B11  A22B21
C12  A11B12  A12B22 C22  A21B12  A22B22
T(n)8T(n2)(n2) T(n)nlog28n3
84

Strassen’s Matrix Multiplication Algorithm
A11
A12
A21
A22
B11
B12
B21
B22
C11
C12
C21
C22

m (A A )(B B ) 1 11 22 21 22
m (A A )(B B ) 2 11 22 11 22
m (A A )(B B ) 3 11 21 11 12
m(AA)B 4 11 12 22
=
m
A (B B ) 11 12 22
A (B B ) 22 21 11
(A A )B 21 22 11
C m m m m 11 1 2 4 6
C m m 12 4 5
C m m 21 6 7
C mmmm 22 2 3 5 7
Srassen’s discovery broke the (n3) barrier. There has been further recent improvements.
m
m
5
6
7
T(n)7T(n2)(n2) T(n)nlog27On2.81…
85

The Closest Pair of Points
Input: A set P = {p1 , p2 , … , pn } of n points in the plane.
Each point is given by its x & y coordinates pi=(xi, yi), i=1..n.
Output: The closest pair of points in P, i.e., the pair (pi, pj) in P, i  j ,
with minimum Euclidean distance d(pi, pj) = ((xi – xj)2 +(yi – yj)2 )1⁄2 .
y
x
In 1 dimension: The Min-Gap Problem.
Known lower bound on time complexity: (n log n). Discussed later.
Matching upper bound (by sorting first): O(n log n).
In 2 dimensions it is at least as hard.
Brute Force: Try every pair. That takes (n2) time. Divide-&-Conquer ………………………………………… P.T.O.
86

CP: Divide-&-Conquer
Py n points
CP(P):
CP(L)
CP(R)
x
LR
n/2 points n/2 points
x-median
3 possible cases for the closest pair of points:
a) both in the left half L,
b) both in the right half R,
c) one in L and the other in R.
[recursive call on L] [recursive call on R] [Combine L & R]
87

Divide-&-Conquer template
Algorithm ClosestPair(P)
Pre-Condition: P is a finite set of points in the plane Post-Condition: Output is the closest pair of points in P
1. Pre-Sort points in P on their x-coordinates (lexicographically next on y)
2. return CP(P)
end
Procedure CP(P)
Pre-Condition: P is a x-sorted finite set of points Post-Condition: Output is the closest pair of points in P
3.Base: 4.Divide: 5.Conquer: 6.Combine: 7.Output: end
if |P| < 10 then return answer by brute-force in (1) time Partition P at its x-median value into sets L and R, |L| |R| |P|/2 SolL  CP(L); SolR  CP(R) Sol  MERGE(SolL , SolR ) return Sol 88 Divide-&-Conquer template Post-Cond of MERGE must imply Post-Cond of CP(P). Algorithm ClosestPair(P) Pre-Condition: P is a finite set of points in the plane On the other hand, Post-Condition: Output is the closest pair of points in P 2. return CP(P) Post-Cond’s of CP(L) and CP(R) must imply 1. Pre-Sort points in P on their x-coordinates (lexicographically next on y) Pre-Cond of MERGE. end Procedure CP(P) Pre-Condition: P is a x-sorted finite set of points Post-Condition: Output is the closest pair of points in P Strengthen Post-Cond of CP ( CP(L) & CP(R) ) to help reduce the burden on MERGE! 3.Base: 4.Divide: 5.Conquer: 6.Combine: 7.Output: end if |P| < 10 then return answer by brute-force in (1) time Partition P at its x-median value into sets L and R, |L| |R| |P|/2 SolL  CP(L); SolR  CP(R) Sol  MERGE(SolL , SolR ) return Sol Our aim T(n) = 2T(n/2) + (n)  T(n) = (n log n) time. 89 Strengthen CP Post-Condition Procedure CP(P) Pre-Condition: P is a x-sorted finite set of points Post-Condition: Output is the closest pair of points in P, and 3.Base: 4.Divide: 5.Conquer: 6.Combine: 7.Output: end P is rearranged into y-sorted order. if |P| < 10 then return answer by brute-force in (1) time Partition P at its x-median value into sets L and R, |L| |R| |P|/2 §Now L & R are x-sorted. SolL  CP(L); SolR  CP(R) § Now L & R are y-sorted. § MERGE can y-merge L & R, and ... Sol  MERGE(SolL , SolR ) § Now P = L  R is y-sorted, and ... return Sol 90 MERGE Py n points dL dR x LddR x-median MERGE(L, R): d=min{dL ,dR} ... ... end Canwedoit in O(n) time? 91 MERGE y L&R are y-sorted LddR x-median MERGE(L, R): d=min{dL ,dR} ... ... Canwedoit in O(n) time? x end 92 MERGE p y p is the latest point merged so far. If p is in the 2d vertical slab: is p too close to a merged point on the opposite side? MERGE can’t afford checking p against every merged point! Is there a short-cut? y-merged so far x LddR x-median MERGE(L, R): d=min{dL ,dR} y-merge L & R ... Canwedoit in O(n) time? end 93 FACT: MERGE There can be at most 7 points (excluding p) in the shaded 2d-by-d rectangle shown below. Why? d p 7 = O(1)  p is the latest point merged so far. d d x-median • Maintain the (up to) 7 latest merged points that fall within the 2d vertical slab. MERGE: • If next point p being merged falls within this slab then compare p against the “7 points”; update closest pair; add p to the “7 point” list (remove the now lowest 8th from the list). • Add p to the merged list and move up to the next point. • Each point is y-merged in O(1) time. MERGE takes O(n) time. Therefore, CP takes O(n log n) time. 94 Binary Trees & Binary Search Trees 95 Binary Trees: A Quick Review root[T] d be acg f external nodes (nil) Node x structure: left[x] left child p[x] parent key[x] right[x] right child n (internal) nodes n-1 (internal) edges n+1 external nodes (nil) n+1 external edges (nil) 96 T: root[T] d be acg f Binary Tree Traversals r LR  Inorder(T):  Preorder(T):  Postorder(T):  Levelorder(T): Inorder(L); r; Inorder(R). r ; Preorder(L); Preorder(R). Postorder(L); Postorder(R); r. non-decreasing depth order (same depth left-to-right) abcdefg dbacegf acbfged dbeacgf graph DFS graph BFS 97 Traversals in O(n) time procedure Inorder(x) 1. if x = nil then return 2. Inorder(left[x]) 3. visit(x) 4. Inorder(right[x]) end r LR Running Time Analysis by Accounting: Line 1: n+1 external nodes (return), n (internal) nodes (continue). Line 3: Assume visit takes O(1) time. Lines 2 & 4: After recursive expansion: Each node x (internal or external) visited exactly once. O(1) time execution of lines 1 & 3 charged to node x. Total n + (n+1) nodes, each charged O(1) time. Total time = O(2n+1) = O(n).  Preorder and Postorder are similar and take O(n) time.  Exercise: Write a simple O(n) time algorithm for Levelorder. [Hint: use a queue.] 98 Running Time Analysis by Recurrence r Time(L)Time(R)1 ifTnil T i m e ( T )   T: 1 if T  nil LR CLAIM: Time(T) = 2 |T| + 1. Proof: By induction on |T|. Basis (|T|=0): Time(T) = 1 = 2 |T| + 1. Induction Step (|T| > 0):
Time(T) = Time(L) + Time(R) + 1 = (2|L|+1) + (2|R|+1) + 1
= 2(|L| + |R| + 1) + 1 = 2 |T| + 1.
[by the recurrence]
[by the Induction Hypothesis]
99

BST from Binary Search on Sorted Array E0 < K1 < E1 < K2 < E2 < K3 < E3 < K4 < E4 < K5 < E5 < K6 < E6 <  < Kn < En E0 E1 E2 E3 K1 K2 K3 K4 K5 K6 E4 E5 E6 100 BST from Binary Search on Sorted Array E0 < K1 < E1 < K2 < E2 < K3 < E3 < K4 < E4 < K5 < E5 < K6 < E6 <  < Kn < En E0 E1 E2 E3 K1 K2 K3 K4 K5 K6 E4 E5 E6 K3 E0 E1 K1 K2 E2 E3 E4 K4 K5 K6 E5 E6 101 BST from Binary Search on Sorted Array E0 < K1 < E1 < K2 < E2 < K3 < E3 < K4 < E4 < K5 < E5 < K6 < E6 <  < Kn < En E0 E1 E2 E3 K1 K2 K3 K4 K5 K6 E4 E5 E6 K3 K1 K6 E0 E6 E1 K2 E2 E3 E4 K4 K5 E5 102 BST from Binary Search on Sorted Array E0 < K1 < E1 < K2 < E2 < K3 < E3 < K4 < E4 < K5 < E5 < K6 < E6 <  < Kn < En E0 E1 E2 E3 K1 K2 K3 K4 K5 K6 E4 E5 E6 K3 K1 K6 E0 K2 K4 E6 E1 E2 E3 E4 K5 E5 103 BST from Binary Search on Sorted Array E0 < K1 < E1 < K2 < E2 < K3 < E3 < K4 < E4 < K5 < E5 < K6 < E6 <  < Kn < En E0 E1 E2 E3 K1 K2 K3 K4 K5 K6 E4 E5 E6 K3 K1 K6 E0 K2 K4 E6 E1 E2 E3 K5 E4 E5 SORTED ORDER  BST INORDER 104 BST Definition BST is a binary tree T with one distinct key per node such that:  Inorder node sequence of T encounters keys in sorted order. Equivalent definition: For all nodes x & y in T:  If x is in the left subtree of y, then key[x] < key[y], and  If x is in the right subtree of y, then key[x] > key[y].
 Wrong definition: For all nodes x & y in T:
 If x is left child of y, then key[x] < key[y], and  If x is right child of y, then key[x] > key[y].
root[T] Not a BST: 4
25
197 3
necessary but not sufficient
105

BST Testing Input: A binary tree T with one key per node.
Output: True, if T is a BST; false otherwise.
Method 1: Do an in-order traversal of T and verify that keys appear in
increasing order. This can be done in O(n) time, n = |T|.
Observation:
BSTs have recursive structure:
T is a BST  L and R are BSTs
This implication is necessary but not sufficient.
To make it sufficient, strengthen the conclusion:
T is a BST  (a) L and R are BSTs, and
(b) max key in L < key[r] < min key in R T: r LR Method 2: Do a post-order traversal of T. How? 106 BST Testing Input: A binary tree T with one key per node. Output: True, if T is a BST; false otherwise. T: r LR Algorithm CorrectBST(T) Pre-Condition: T is a binary tree with one key per node Post-Condition: output is true if T is a BST, false otherwise. return IsBST(root[T]) end Function IsBST(r) Pre-Condition: r is pointer to root of a binary tree with one key per node Post-Condition: output is true if the binary tree is a BST, false otherwise. if r = nil then return true SolL  IsBST(left[r]); SolR  IsBST(right[r]) Sol  MERGE(SolL , SolR ) ??? return Sol Two options: (1) strengthen Pre-Cond or (2) strengthen Post-Cond Base: Conquer: Combine: Output: end 107 Strengthen Pre- & Post-Condition r Algorithm CorrectBST(T) Pre-Condition: T is a binary tree with one key per node. Post-Condition: output is true if T is a BST, false otherwise. return IsBST(root[T], – , + ) end T: L R Function IsBST(r, minKey, maxKey) Pre-Condition: r is pointer to root of a binary tree with one key per node, minKey & maxKey are key values (possibly ±). Post-Condition: output is true if the binary tree is a BST and minKey < maxKey and for every node x in that tree: minKey < key[x] < maxKey; if minKey ≥ maxKey then return false if r = nil then return true SolL  IsBST(left[r], minKey, key[r]); SolR  IsBST(right[r], key[r], maxKey) Sol  SolL & SolR return Sol end false otherwise. 108 Strengthen Post-Condition Algorithm CorrectBST(T) Pre-Condition: T is a binary tree with one key per node Post-Condition: output is true if T is a BST, false otherwise. (isBST, minKey, maxKey)  BSTtest(root[T] ) return isBST end Function BSTtest(r) Pre-Condition: r is pointer to root of a binary tree with one key per node Post-Condition: output is (isBST, minKey, maxKey), where isBST = true if the binary tree is a BST, false otherwise, and isBST  minKey = minimum key in the tree rooted at r, and maxKey = maximum key in the tree rooted at r if r = nil then return (true, +, –) § Note where + & – are (isBSTL, minL, maxL)  BSTtest(left[r]); (isBSTR, minR, maxR)  BSTtest(right[r]) isBST isBSTL & isBSTR & (maxL < key[r] < minR) return (isBST, min{ minL, key[r] }, max{ maxR, key[r] }) end T: r LR 109 Bibliography Additional optional sources: [Edm08] [AHU74] Jeff Edmonds, "How to Think about Algorithms," Cambridge H. Press, 2008. [Parts of chapters 1-4, 6-10: good coverage of the loop-invariant method.] Aho, Hopcroft, Ullman, “The Design and Analysis of Computer Algorithms”, Addison-Wesley, 1974. [A classic text book on algorithms, divide-&-conquer, integer & matrix computations, and more.] Manber, “Introduction to Algorithms: A Creative Approach”, Addison-Wesley, 1989. [Contains interesting induction topics and exercise solutions.] [Man89] 110 Exercises 111 INSTRUCTIONS: In the following problems you are asked to design and analyze efficient iterative or recursive algorithms. Follow the Loop-Invariant design-&-verification method for iterative algorithms, and the strong induction method for recursive algorithms. You should clearly state and explain the proof steps as learned in the course. 1. Double Vision in Sorted Array: Design and analyze an O(n) time in-place algorithm for the following problem. Input: An array A[1..n] of n positive real numbers sorted in increasing order. Output: True if there is a pair of indices i and j such that A[i] = 2A[j] ; false otherwise. 2. The Longest All-Positive Sub-Array Problem: Input: An array A[1..n] of arbitrary integers. Output: The longest contiguous sub-array of A[1..n] with positive entries only. 3. The Maximum-Sum Monotone Sub-Array Problem: Input: An array A[1..n] of arbitrary positive integers. Output: The maximum-element-sum contiguous sub-array of A[1..n] whose entries form a monotone sequence (either ascending or descending). 112 4. The Longest D-Smooth s-Slope Sub-Array Problem: Input: An array A[1..n] of arbitrary integers, and two numbers s, and D > 0. Output: The longest contiguous sub-array, say A[i..j], whose entries fall between
two lines of slope s with vertical separation D. (See the illustrative figure below.)
A[t]
D
1ijn
5. The Largest D-Flat Subset and Sub-Array Problems:
Let D be a positive real number and S be a finite set of real numbers. We say S is D-flat if
max(S)–min(S) D·(|S|-1).
(That is, the average difference between contiguous pairs of elements in the sorted permutation of S is  D.)
Design and analyze efficient algorithms for the following problems:
(a) Given a set A of n elements and a D > 0, compute the largest D-flat subset of A.
(b) Given an array A[1..n] of n elements and a D> 0, compute the longest D-flat contiguous
sub-array of A.
[Note: in part (a) any subset is a potential candidate solution, but in part (b) only those subsets that
correspond to contiguous sub-arrays are allowed.
Hint: for part (b) use an incremental method similar to that of the LSS problem we studied in these slides.] 113
t

6. Design and analyze efficient algorithms for each of the following problems:
a) Input: An array A[1..n], with each element 0 or 1.
Output: the longest contiguous sub-array of A[1..n] that contains at least as many 1’s as 0’s.
b) Input: An array A[1..n], with each element 0 or 1.
Output: The longest contiguous sub-array of A[1..n] with at least twice as many 0’s as 1’s.
c) Input: An array A[1..n], with each element 0 or 1.
Output: The longest contiguous sub-array of A[1..n] such that the number of 0’s minus the number of 1’s
in that sub-array is 2 mod 5.
d) Input: An array A[1..n], with each element 0 or 1.
Output: The Length of longest monotone ascending (not necessarily contiguous) sub-array of A[1..n].
e) Input: An array A[1..n] of integers in strictly increasing order.
Output: Find an index i such that A[i] = i, or report that no such index exists.
f) Input: An array A[1..n] of integer elements, where absolute value of each element is ≤ 5.
Output: Longest contiguous sub-array of the input array, whose sum of elements is non-negative.
7. Inplace Rank Sort: We are given an array A[1..n] of n employee records.
Each employee record A[i] consists of two fields: A[i].info and A[i].rank. The rank of each employee is one of 4 possibilities {1,2,3,4}. Design and analyze a linear-time, in-place incremental algorithm to sort the n employee records in ascending order of rank.
8. Generalize 3-Partition to C-Partition: For any fixed integer C, 2  C  n, show that the C-partition problem can be solved in O(Cn) time, using O(C) extra memory cells.
9. 2SUM & 3SUM in a Sorted Array: We are given a sorted array A[1..n] and a target value X. a) 2SUM: Design & analyze an efficient algorithm to find a pair of array indices (i,j) such that
A[i] + A[j] = X, or report that no such pair exists. [Hint: can be done in O(n) time.]
b) 3SUM: Similar to part (a), find a triple array indices (i,j,k) such that A[i] + A[j] + A[k] = X.
What is the time complexity of your algorithm?
114

10. A Fibonacci Identity: Let n and m be arbitrary natural numbers.
(a) Prove the identity below by induction on n. (Make sure to cover all required base cases.) (b) Prove this identity using the matrix formula G(n) = An we established on page 70 of these slides.
Fnm1  Fn1Fm1  FnFm
11. Euclid & Fibonacci: Prove that GCD of two Fibonacci numbers is a Fibonacci number.
12. Integer Linear Equations: Design and analyze an efficient algorithm that, given integers a, b, c, determines whether the linear equation ax + by = c has an integer solution for variables x and y, and if so it finds one such solution.
13. Modified Fibonacci Sequence:
Define G0 = 0, G1 = 1, G2 = 2, Gn+3 = 3Gn + 2Gn+1 + 5Gn+2 , for all n  0. Design and analyze an O(log n) time algorithm to compute Gn.
14. Closest Red-Blue Pair: We are given a set of n points in the plane, each point is either red or blue. We want to find the closest (red, blue) pair among the input points (if there is any such pair).
Design and analyze an efficient divide-&-conquer algorithm for this problem.
15. Boys&GirlsinaBinarySearchTree(BST):
Each node item in our Binary Search Tree is a record of the form (gender, salary), where gender  {boy, girl}, and salary is a positive integer which is used as the key. Design & analyze an efficient recursive algorithm to find a pair of opposite sex records with closest salary values.
115

16. StrengtheningRecursionPre/PostConditions:
Below we show two algorithms for the following problem:
Given a binary tree T and a height threshold h, return the number of nodes in T of height at least h.
Algorithm CountHighNodes1(T, h) Count  CHN1(root[T], h) return (Count)
end
Function CHN1(r, h)
if r = nil then return (0)
LCount  CHN1(left[r], h)
RCount  CHN1(right[r], h)
Height  ComputeHeight(r)
Count  LCount + RCount
if Height ≥ h then Count  Count + 1 return (Count)
end
Function ComputeHeight(r)
Algorithm CountHighNodes2(T, h)
(Count, RootHeight)  CHN2(root[T], h)
return (Count) end
Function CHN2(r, h)
if r = nil then return (0, -1)
(LCount, LHeight)  CHN2(left[r], h) (RCount, RHeight)  CHN2(right[r], h) Height  1 + max(LHeight, RHeight) Count  LCount + RCount
if Height ≥ h then Count  Count + 1 return (Count, Height)
end
if r = nil then return (-1)
LHeight  ComputeHeight(left[r]) RHeight  ComputeHeight(right[r]) return (1 + max(LHeight, RHeight))
end
a) Give all the Pre- and Post-Conditions, and argue that both algorithms CountHighNodes1 and CountHighNodes2 correctly solve the problem.
b) Analyze the worst-case running times of CountHighNodes1 and CountHighNodes2.
c) Explain the real reason why CountHighNodes1 is less efficient than CountHighNodes2.
116

17. More Recursion on Binary Trees:
The input is a binary tree T with an integer valued key per node.
Design & analyze efficient recursive algorithms for the following tasks.
[If no solution exists, some special value, say null, may be returned. If there are several solutions, choose any one of them and return it.]
a) Find the sum of the keys in all the leaves of T.
b) Find a root-to-leaf path with minimum sum key sequence.
c) Find the root of the largest subtree that contains no more than |T|/10 nodes.
[Note: |T| denotes the number of nodes in T and is not part of the input.]
d) Find a node with maximum imbalance, where imbalance of a node is the difference between the heights of its left and right subtrees. [Note: height of an empty tree is –1.]
e) Find a pair of nodes (x, y) in T such that
(i) y is the successor of x in the inorder sequence of nodes of T, and (ii) | (depth of x) – (depth of y) | is maximum possible.
f) Find a pair of nodes (x,y) in T with longest separation, where the separation between two nodes is the length (number of edges) of the unique path from x to y when thinking of the tree as an undirected graph, i.e., from x up to the lowest common ancestor and back down to y.
[Hint: Look up the previous exercise. Sample Midterm Solutions contain additional examples. You may need to strengthen the Pre- or Post-Conditions of your recursive routines.
For instance, let the recursive routine return extra info in addition to the required output data. Then use the returned extra info in the “combine” step of the recursion.]
117

More Recursion on Binary Trees: 18. The Most Weird Species:
Input: A binary tree T in which each node x contains a field color[x] which is either red or blue.
Define lineage of a node x to be the set of all those nodes in T that are either ancestor or descendant of x (including x). Define weirdness of a node x to be the difference between the number of red nodes and the number of blue nodes in the lineage of x.
Output: A node x in T with maximum weirdness.
19. RichestHeritage:
Input: A binary tree T in which each node x contains a field worth[x], which is a (positive, zero, or negative) monetary value expressed as a real number.
Define (monetary) heritage of a node x to be the total worth of ancestors of x minus the total worth of proper descendants of x.
Output: A node x in T with maximum heritage. 20. SaddlePoint:
Input: A binary tree T in which each node x contains a field value[x] which is a real number. We say a node x in T is a saddle point if x has minimum value among all its ancestors (including
x), but it has maximum value among all its descendants (including x). Output: A saddle point of T if there is one, or null if there isn’t.
118

21. BinaryTreeBisection:
Many divide-&-conquer algorithms that operate on graphs require that the graph be bisected into nearly equal-sized subgraphs by removing a small number of edges. We will discuss graph algorithms later. This problem investigates bisection of binary trees.
a) Prove the following Fact.
Fact: ∀𝑛 ≥ 2: any n-node binary tree T has a balanced edge: an edge whose removal will separate T into two binary trees, each having at most (2n-1)/3 nodes.
b) Design and analyze an efficient algorithm to find a balanced edge of any given binary tree T.
[Hint: O(n) time is possible by a post-order traversal.]
c) Show that the bound in the above Fact is optimal in the worst case by demonstrating that for all n  2 there is an n-node binary tree whose most evenly balanced partition upon removal of a single edge results in one of its two parts having size (2n-1)/3 .
d) Binary Tree Bisection: Using part (a), show that by removing at most O(log n) edges, we can partition the nodes of any n-node binary tree into two sets A and B such that |A| =  n/2 and |B| = n/2, and there is no remaining edge with one end vertex in A and the other in B.
For this part you don’t need to give a detailed algorithm. A high level description will suffice.
119

22. Linked-List Correctness Verification (an IBM interview test question):
We are given the head pointer to a read-only linked list. Each node of this list consists of a single field, namely, a pointer to the next node on the list. For the list to have correct structure, each node should point to its successor, except for the last node that points to nil, as in figure (a) below. However, due to a possible structural error, the list may look like that of figure (b), where a node points to one of the previous nodes (possibly itself). From that node on, we no longer have access to the rest of the nodes on the list. The task is to verify the structural correctness of the list. If we knew n, the number of accessible nodes on the list, we could easily verify the list’s structural correctness, namely, starting from the head pointer, we would follow the list nodes for n steps and see if we reach a nil pointer. However, we have no advance knowledge of the length of the list.
Design & analyze a linear-time in-place algorithm to test the structural correctness of the list. That is, your algorithm should take time linear in the number of accessible nodes, and work in-place, i.e., use only O(1) additional memory cells. So, your algorithm may use a few local scalar variables, but not such things as additional lists or arrays. Also, the nodes on the list do not have any additional fields that you may use for some kind of marking, and your algorithm should not attempt to alter the structure of the list, not even temporarily.
[Hint: use repeated doubling.]
(a) Head nil (b) Head
120

23. A Tiling Problem: The input is a 2𝑛 by 2𝑛 square checkerboard with the unit square at the given coordinates (i,j) marked.
You have a sufficient number of identical tiles of the shape that can cover 3 board squares.
Your task is to place non-overlapping tiles on the board to cover each of the 2𝑛 × 2𝑛 board squares except the marked one. Give a recursive algorithm for this problem.
Further explanation: You need to output the list of tile placements. A tile can cover 3 neighboring squares as mentioned above. So, each tile placement can be given as the set of those 3 squares; each square can be specified by its (x,y) coordinates. See the example below:
Input Output: Tile Placements
Marked
Tile 1
Tile 4
Marked
Tile 2
Tile 3
Tile 5
121

24. [Goodrich-Tamassia C-1.14. pp. 50-53]
Suppose you are given a set of small boxes, numbered 1 to n, identical in every respect except that each of the first i contain a pearl whereas the remaining n  i are empty. You also have two magic wands that can each test if a box is empty or not in a single touch, except that a wand disappears if you test it on an empty box. Show that, without knowing the value of i, you can use the two wands to determine all the boxes containing pearls using at most o(n) wand touches. Express, as a function of n, the asymptotic number of wand touches needed.
25. [Goodrich-Tamassia C-1.25. pp. 50-53]
An evil king has a cellar containing n bottles of expensive wine, and his guards have just caught a spy trying to poison the king’s wine. Fortunately, the guards caught the spy after he succeeded in poisoning only one bottle. Unfortunately, they don’t know which one. To make matters worse, the poison the spy used was very deadly; just one drop diluted even a billion to one will still kill someone. Even so, the poison works slowly; it takes a full month for the person to die. Design a scheme that allows the evil king determine exactly which one of his wine bottles was poisoned in just one month’s time while expending at most O(log n) of his taste testers.
26. [CLRS 2nd edition Problem 4-2, p. 85] Finding the missing integer:
An array A[1..n] contains all the integers from 0 to n except one. It would be easy to determine the missing integer in O(n) time by using an auxiliary array B[0..n] to record which numbers appear in A. In this problem, however, we cannot access an entire integer in A with a single operation. The elements of A are represented in binary, and the only operation we can use to access them is “fetch the jth bit of A[i],” which takes constant time. Show that if we use only this operation, we can still determine the missing integer in O(n) time.
122

27. Polynomialmultiplicationbydivide-&-conquer:
A degree n-1 polynomial 𝑃 𝑥 = 𝑛−1 𝑝 𝑥𝑖 = 𝑝 + 𝑝 𝑥 + 𝑝 𝑥2 … + 𝑝 𝑥𝑛−1 can be 𝑖=0𝑖 012 𝑛−1
represented by an array 𝑝[0. . 𝑛 − 1] of its n coefficients. Suppose P(x) and Q(x) are two polynomials of degree n-1, each given by its coefficient array representation. Their product P(x)Q(x) is a polynomial of degree 2(n-1), and hence can be represented by its coefficient array of length 2n-1. The polynomial multiplication problem is to compute the coefficient array of P(x)Q(x), given the coefficient arrays of P(x) and of Q(x).
There is an obvious Θ 𝑛2 (i.e., quadratic) time algorithm to solve this problem. However, a method similar to the divide-&-conquer integer multiplication algorithm of Karatsuba-Ofman can achieve sub-quadratic time complexity. Design and analyze one such sub-quadratic algorithm for the polynomial multiplication problem.
28. [CLRS Problem 30-2, p. 921] Toeplitz Matrices:
A Toeplitz matrix is an 𝑛𝑛 matrix 𝐴 = (𝑎𝑖𝑗) such that 𝑎𝑖𝑗 = 𝑎𝑖−1,𝑗−1 for 𝑖 = 2. . 𝑛 and
𝑗 = 2..𝑛.
a) Is the sum of two Toeplitz matrices necessarily Toeplitz? What about the product?
b) Describe how to represent a Toeplitz matrix so that you can add two 𝑛𝑛 Toeplitz matrices in 𝑂(𝑛) time.
c) Givean𝑂(𝑛log𝑛)timedivide-&-conqueralgorithmformultiplyingan𝑛𝑛Toeplitz matrix by a vector of length n. Use your representation from part (b).
[Hint: you may need to learn how the Fast Fourier Transform (FFT) algorithm works.]
d) GiveanefficientalgorithmformultiplyingtwoToeplitzmatrices.Analyzeitsrunning time.
123

29. Particle Physics Problem: You have been working with some physicists who need to study, as part of their experimental design, the interaction among large numbers of very small charged particles. Basically, their setup works as follows. They have an inert lattice structure, and they use this for placing charged particles at regular spacing along a straight line. Thus we can model their structure as consisting of the points {1, 2, 3, … , n} on the real line; and at each of these points j, they have a particle with charge qj. (Each charge can be either positive or negative.)
They want to study the total force on each particle, by measuring it and then comparing it to a computational prediction. This computational predictional part is where they need your help. The total net force on particle j, by Coulomb’s Law, is equal to
Fj Cqiqj  Cqiqj  i:ij (ji)2 i:ij (ji)2
They have written the following simple program to compute Fj for all j. for j ← 1..n do
Fj ← 0
for i ← 1 .. j-1 do Fj ← Fj + C qi qj / (j-i)2 for i ← j+1 .. n do Fj ← Fj – C qi qj / (j-i)2 output Fj
end
It is not hard to see that this algorithm takes O(n2 ) time.
The trouble is, for the large values of n they are working with, the program takes several minutes to run. On the other hand, their experimental setup is optimized so that they can throw down n particles, perform the measurements, and be ready to handle n more particles within a few seconds. So they would really like it if there were a way to compute all the forces Fj much more quickly, so as to keep up with the rate of the experiment.
Help them out by designing a divide-&-conquer algorithm that computes all the forces Fj in O(n log n) time. [Hint: use part (c) of the previous problem.]
124

30.
Input: A binary tree 𝑇 in which each node 𝑥 contains a real valued field named 𝑣𝑎𝑙𝑢𝑒[𝑥] . We say a node 𝑥 in 𝑇 is value-balanced if and only if the average value of ancestors of 𝑥 (including 𝑥) equals the average value of descendants of 𝑥 (including 𝑥).
Output: Among value-balanced nodes in 𝑇 return the one with minimum depth (break ties arbitrarily). Return 𝑛𝑖𝑙 if 𝑇 has no value-balanced node.
Note: Apart from the value field and left child and right child pointers, nodes of 𝑇 do not have any additional storage fields.
Design and analyze an efficient algorithm for this.
31. A node 𝑥 in a binary tree is said to be well-oriented if the path from root to 𝑥 follows an equal number of left child branches as right child branches. For example, in the binary tree below, all the well-oriented nodes are shown in solid black.
You may assume that for a node 𝑥, 𝑙𝑒𝑓𝑡[𝑥] is left child of 𝑥, 𝑟𝑖𝑔h𝑡[𝑥] is right child of 𝑥. There are no other storage fields in the nodes of the tree.
Design and analyze an efficient algorithm that returns the number of well-oriented nodes in a given binary tree T.

END
126