Lecture 2
Divide and conquer
Review of CSE 247
- Divide the problem into (generally equal) smaller subproblems
- Recursively solve the subproblems
- Combine the solutions of subproblems to get the solution of the original problem
- Examples: Merge Sort, Binary Search
Recurrence
Master Method:
Example 1: Multiplying 2 numbers
Normal Algorithm:
def multiply(x,y):
p=0
for i in y:
p+=x*y
return p
divide and conquer approach
def multiply(x,y):
n=max(len(x),len(y))
if n==1:
return x*y
xh,xl=x>>(n/2),x&((1<<n/2)-1)
yh,yl=y>>(n/2),y&((1<<n/2)-1)
return (multiply(xh,yh)<<n)+((multiply(xh,yl)+multiply(yh,xl))<<(n/2))+multiply(xl,yl)
Not a useful optimization
But,
def multiply(x,y):
n=max(len(x),len(y))
if n==1:
return x*y
xh,xl=x>>(n/2),x&((1<<n/2)-1)
yh,yl=y>>(n/2),y&((1<<n/2)-1)
zhh=multiply(xh,yh)
zll=multiply(xl,yl)
return (zhh<<n)+((multiply(xh-xl,yh-yl)+zhh+zll)<<(n/2))+zll
Example 2: Closest Pairs
Input: is a set of points in the plane.
Goal: Find the distance between the closest pair of points.
Naive algorithm: iterate all pairs ().
Divide and conquer algorithm:
Preprocessing: Sort by coordinate to get .
Base case:
- 1 point: clostest d = inf
- 2 points: clostest d = d(p_1,p_2)
Divide Step:
Compute mid point and get .
Recursive step:
- closest pair in
- closest pair in
Combine step:
Calculate closest point such that one point is on the left side and the other is on the right.
return
Total runtime:
Still no change.
Important Insight: Can reduce the number of checks
Lemma: If all points within this square are at least apart, there are at most 4 points in this square.
A better algorithm:
- Divide into 2 halves using the mid point
- Recursively computer the and , take .
- Filter points into y-strip: points which are within
- Sort y-strip by y coordinate. For every point , we look at this y-strip in sorted order starting at this point and stop when we see a point with y coordinate
# d is distance function
def closestP(P,d):
Px=sorted(P,key=lambda x:x[0])
def closestPRec(P,d):
n=len(P)
if n==1:
return float('inf')
if n==2:
return d(P[0],P[1])
Q,R=Px[:n//2],Px[n//2:]
midx=R[0][0]
dl,dr=closestP(Q),closestP(R)
dc=min(dl,dr)
ys=[i if midx-dc<i[0]<midx+dc for i in P]
ys.sort()
yn=len(ys)
# this step below checks at most 4 points, (but still runs O(n))
for i in range(yn):
for j in range(i,yn):
curd=d(ys[i],ys[j])
if curd>dc:
break
dc=min(dc,curd)
return dc
return closestPRec(Px,d):
Runtime analysis:
We can do even better by presorting Y
- Divide into 2 halves using the mid point
- Recursively computer the and , take .
- Filter points into y-strip: points which are within by visiting presorted
# d is distance function
def closestP(P,d):
Px=sorted(P,key=lambda x:x[0])
Py=sorted(P,key=lambda x:x[1])
def closestPRec(P,d):
n=len(P)
if n==1:
return float('inf')
if n==2:
return d(P[0],P[1])
Q,R=Px[:n//2],Px[n//2:]
midx=R[0][0]
dl,dr=closestP(Q),closestP(R)
dc=min(dl,dr)
ys=[i if midx-dc<i[0]<midx+dc for i in Py]
yn=len(ys)
# this step below checks at most 4 points, (but still runs O(n))
for i in range(yn):
for j in range(i,yn):
curd=d(ys[i],ys[j])
if curd>dc:
break
dc=min(dc,curd)
return dc
return closestPRec(Px,d):
Runtime analysis:
In-person lectures
is number of sub problems, is size of subproblems, is the cost of divide and combine cost.
Example 3: Max Contiguous Subsequence Sum (MCSS)
Given: array of integers (positive or negative),
Return:
Trivial solution:
brute force
A bit better solution:
use prefix sum to reduce cost for sum.
Divide and conquer solution.
def MCSS(S):
def MCSSMid(S,i,j,mid):
res=S[j]
for l in range(i,j):
curS=0
for r in range(l,j):
curS+=S[r]
res=max(res,curS)
return res
def MCSSRec(i,j):
if i==j:
return S[i]
mid=(i+j)//2
L,R=MCSSRec(i,mid),MCSSRec(mid,j)
C=MCSSMid(i,j)
return min([L,C,R])
return MCSSRec(0,len(S))
If MCSSMid(S,i,j,mid)
use trivial solution, the running time is:
and we did nothing.
Observations: Any contiguous subsequence that starts on the left and ends on the right can be split into two parts as sum(S[i:j])=sum(S[i:mid])+sum(S[mid,j])
and let be the subsequence that has the largest sum that ends at mid, and be the subsequence that has the largest sum on the right that starts at mid.
Lemma: Biggest subsequence that contains S[mid]
is
Proof:
By contradiction,
Assume for the sake of contradiction that is a sum of such a subsequence that is larger than ().
Let , since , by definition of , then , WOLG, , , which contradicts that .
Optimized function as follows:
def MCSS(S):
def MCSSMid(S,i,j,mid):
res=S[mid]
LS,RS=0,0
cl,cr=0,0
for l in range(mid-1,i-1,-1):
cl+=S[l]
LS=max(LS,cl)
for r in range(mid+1,j):
cr+=S[r]
RS=max(RS,cr)
return res+LS+RS
def MCSSRec(i,j):
if i==j:
return S[i]
mid=(i+j)//2
L,R=MCSSRec(i,mid),MCSSRec(mid,j)
C=MCSSMid(i,j)
return min([L,C,R])
return MCSSRec(0,len(S))
The running time is:
Strengthening the recusions:
def MCSS(S):
def MCSSRec(i,j):
if i==j:
return S[i],S[i],S[i],S[i]
mid=(i+j)//2
L,lp,ls,sl=MCSSRec(i,mid)
R,rp,rs,sr=MCSSRec(mid,j)
return min([L,R,ls+rp]),max(lp,sl+rp),max(rs,sr+ls),sl+sr
return MCSSRec(0,len(S))
Pre-computer version:
def MCSS(S):
pfx,sfx=[0],[S[-1]]
n=len(S)
for i in range(n-1):
pfx.append(pfx[-1]+S[i])
sfx.insert(sfx[0]+S[n-i-2],0)
def MCSSRec(i,j):
if i==j:
return S[i],pfx[i],sfx[i]
mid=(i+j)//2
L,lp,ls=MCSSRec(i,mid)
R,rp,rs=MCSSRec(mid,j)
return min([L,R,ls+rp]),max(lp,sfx[mid]-sfx[i]+rp),max(rs,sfx[j]-sfx[mid]+ls)
return MCSSRec(0,n)