Ald Assignment 5 & 6: Divide and Conquer
Ald Assignment 5 & 6: Divide and Conquer
Ald Assignment 5 & 6: Divide and Conquer
Ritvik Gupta(2018407)
Ans 1)
Let the 2 n-bit numbers be X and Y respectively. We are given that addition X+Y is O(n).
For efficient multiplication, we will use the Karatsuba Algorithm, which is a divide and conquer
approach.
Note: At any step during dividing, If n is odd, add 0 in front of the number and proceed.
Divide both numbers into 2 equal parts. Let X divide into X1 and X2. Y divides into Y1 and Y2.
All the new numbers are n/2 bits.
The product XY can be computed as:
X*Y=(X1*2n/2 + X2)*(Y1*2n/2 + Y2)
= X1*Y1*2n + 2n/2(X1*Y2 + Y1*X2) + X2*Y2 ___(1)
In the above case, we need to perform 4 multiplications.
Recurrence Relation:
T(n) = 3*T(n/2) + O(n)
By Master’s Theorem, we get the time complexity for following relation as the following :
T(n) = O(n log23 ) = O(n1.58)
Proof of correctness:
By induction:
Base Case:
power(a,0): a0=1
Inductive Hypothesis:
Let power(a,k) returns ak
Induction Step:
We need to prove power(a,k+1) returns ak+1.
If k+1 is even:
k+1 = 2m for integer m
(k+1)/2 = m
m is in the range 0 through k, by the inductive hypothesis,
power(a, m) returns am
power(a, k+1) returns [power(a, m)]2
k+1 is odd:
k+1 = 2m+1 for integer m
(k+1)/2 = m
Therefore this becomes similar to the previous case.
Ans 5)
The time complexity of the above algo is same as that of binary search O(log n)
Ans 7 )
Algorithm for finding convex hull.
Before calling the method to compute the convex hull, we sort the points by x-coordinate.
This step takes O(nlogn) time.
Divide Step: Find the point with median x-coordinate.
Since the input points are already sorted by x-coordinate, this step should take constant time.
This can be done in O(n) time.
Conquer Step: Call the above divide procedure recursively on both the halves and continue till
you are left with only one point on each of the divisions.
Merge Step:
Merge the two convex hulls computed by two recursive calls in the conquer step. The merge
procedure should take O(n) time. Find the min in sorted order and the max one now divides into
two halves and now recursively finds the most away element from the line joining them.
Recursively do this again and again to find the convex hull.
Hence the time complexity of our algorithm is O(n logn) due to the sorting step.
Note:
mid = low + (high - low)/2 is better to use instead of mid = (high + low)/2 as it can avoid integer
overflow which is caused by the latter one for large values.
DYNAMIC PROGRAMMING
Ans 2)
Find length of the longest alternating subsequence(LAS) starting from increasing number given
array a[ ] :
Make a (n x 2) matrix dp[ ][ ].
For 1 =< i < n, each dp[ i ][ 0 ] contains the length of LAS starting from 1 to i, such that the last
element of the sequence is greater than its previous element.
Similarly, For 1 =< i < n, each dp[ i ][ 1 ] contains the length of LAS starting from 1 to i, such that
the last element of the sequence is lesser than its previous element.
Recurrence Relation:
dp[ i ][ 0 ] = Maxk =ik=1(dp[ k ][ 1 ] + 1) where a[k]<a[i] ----(1)
dp[ i ][ 1 ] = Maxk =ik=1(dp[ k ][ 0 ] + 1) where a[k]>a[i] ----(2)
For the first recurrence, If no value of k is valid in the above case, dp[ i ][ 0 ]=0, here we can’t
say the answer to be 1 as the constraint that the resultant subsequence must start from
increasing number would be violated.
For the second recurrence, If no value of k is valid in the above case, dp[ i ][ 0 ]=1,because we
have now considered it as a sequence that ends with decreasing relation at its end. We can add
a greater element next time and satisfy the property.
Time Complexity:
T(n)=O(n2)
Space Complexity=O(2*n)
Ans 3)
Algorithm:
Make a dp[] array.
Now Let dp[i] be a value that is the minimum cost to reach n from i such that (1 < i <= n). Here
dp[n]=0
So we try all the possible paths and find the minimum out of that.
So the optimal solution for this problem would be dp[1].
Optimal Cost of travelling from point i is given by :
dp[i]= minj: i< j <= n (dp[j] + fi,j) where fi,j is the cost of going from i to j.
Proof of Optimality:
Canoe starts from station 1 and then we have considered all possible cases(i+1,i+2… ,n) of
canoe to reach n and then found the minimum out of it. Therefore, this approach leads to an
optimal solution.
Time Complexity:
Cost of calculating each dp[i] subproblem is O(n) hence the overall time complexity for n
subproblems is O(n2).
Ans 5)
Time Complexity: O(n*k) Due to the 2 for loops. For loop of length k is nested inside loop of
length n.
Space Complexity: Made 2-D dp array so its cost is O(n*k)
Ans 7)
This problem is based on the Longest Increasing subsequence problem.
DP Algorithm:
1) Generate a new dimensions array containing the length width and height of the boxes.
Sort the above generated array on the basis of the base area of all n boxes(i.e. Length
and width dimensions). Give priority in Area of base> Length > width in order to resolve
collisions
2) Now we just need to find the longest increasing subsequence(LIS) for the dimensions
array based on the priority.
Time Complexity: O(n2) due to 2 for loops. For each point in msh[], we need to do a
maximum of O(n) work for each entry and there are n entries.
Ans 1)
a.)Yes (B1:G1, B2:G2, B3:G3, B4:G4) will be a stable matching.
This is because there are no blocking pairs, that implies there is no leverage for a man and
woman in different relationships to break their current relationships respectively and form one
itself.
b)
Yes they are not man optimal and man pessimal as they are not formed according to the stable
marriage algorithm.
Giving G1 and G2 their first choices, that means marrying (B1, G2) and (B2, G1)
would also be stable. But with this switch, B1 does worse.
So the stable matching above is not man-pessimal.
The correct man pessimal match given in part ( c )
Likewise, after marrying off the first two men and women, giving B3 and B4 their best remaining
choices, that is, marrying (B3, G4),(B4, G3), will also be stable. But after this switch, B3 does
better. So the stable matching above is not man-optimal.
The correct man optimal match is given below.
c)
Pairs according to stable marriage algorithm should have been formed as:
Man optimal:
B1 : G1
B2 : G2
B3 : G4
B4 : G3
Man pessimal:
G1 : B2
G2 : B1
G3 : B3
G4 : B4
Ans 2) Given a string and an integer k, find out whether on removing k characters from the
string, it becomes a palindrome or not.
Pseudocode for the recursive algorithm:
#Helper recursive function
def kPalcompare(s1, s2, int m, int n):
#s1 and s2 are 2 strings. m and n are lengths respectively
if(m==0):
return n
elif(n==0):
return m
if (s1[m-1] == s2[n-1]):
return kPalcompare(s1, s2, m-1, n-1)
return (1+min(kPalcompare(s1, s2, m-1, n),kPalcompare(s1, s2, m, n-1)))
#boolean function
def kPal(str,k):
rev=str[: :-1]
x=len(str)
return (kPalcompare(str, rev, x, x) <=( k * 2))
This is an inefficient algorithm having time complexity of O(2n) and a DP approach would give
an efficient solution.
Ans 4)
We can solve this problem by modifying the longest common subsequence algo a bit.
Longest Repeating Subsequence:
Algorithm:
Find LCS(str,str) keeping care when both the characters are same, their index should not be at
the same position in the 2 strings.
if (m == 0 or n == 0):
dp[m][n] = 0
return dp[m][n]
Ans 5)
Ans 1)
We are going to solve this problem using a greedy approach. We are given n points in the
Set A : (a1,a2,....a) on the real line in ascending order. Consider the interval [a1 , a1+1] first
check whether a2 lies within the same interval and keep moving till you get a point that lies
outside the current interval. Remove all those points which lie in the considered interval. Now
move to the next point present in the set and follow the same approach till all the points are
removed from the set.
The overall time complexity for this algo is O(n).
Proof of Correctness:
Ans 2)
Algo:
Start at A.
Our intuitive greedy approach would be to travel as far as we can without stopping at a gas
station.
We are given a list of distances di for a city ci and the maximum miles m the car can cover after
refueling.
So, stop at gas station ci such that di<=m and di+1>m.
Let the corresponding distance for each stop si be ti.
Pseudocode:
S={ }
last =0
For i in range(1,n):
If (di-last)>m :
S.append(ci-1)
last=ti-1
The above algorithm is O(n).
Proof Of Correctness:
Let an optimal solution be S. Suppose the stops of S are in the list S: {s1,s2, . . . . . sk} and let the
corresponding distance for each stop be ti. Suppose g is the first stop made which is made by
the algorithm. We need to show that there is an optimal solution with first stop at g. If s1=g, then
S is a solution. Let’s assume (s1!=g) , so as per our greedy algo s1 comes before g. The total
distance in S and S’ is the same. We now argue that S’={g,s2, . . . . . sk} is an optimal solution.
Since we never ran out of gas, S’ is valid. Since S is optimal and the distance between g and s2
is not more than s1 and s2, there is enough gas to get from g to s2. Rest of S and S’ are similar.
Let P be the original problem with an optimal solution S. S. Then after stopping at the station g
at distance di the subproblem that is left over is given by {di+1,di+2 . . . . dn}. Let S’ be an optimal
solution to P’.
Since, cost(S) = cost(S’) + 1, clearly an optimal solution to P includes within it an optimal
solution to P’.
Ans 3)
We can give a counterexample for this to prove this wrong.
Let m = 41, using the given algorithm, we get m-25=16, 16-10=6,(25*1 + 10*1 + 6*1) So we get
a total (1+1+6)=8 coins. But this is not the optimal solution, As we can achieve this in (4*10 +
1*1) i.e. using 5 coins, which would be the optimal solution.
Ans 4)
Algo:
Our greedy algo for this problem would be to put as many songs as possible(song 1 to j) on the
1st CD without exceeding the time limit of m minutes.
After that recursively do this for all the CDs till the songs are finished.
The time complexity for our algorithm is O(n), because n songs are simply added to the CDs
one by one.
Proof of Correctness:
ASYMPTOTIC ANALYSIS
Ans 3)
Given f(n) and g(n) are monotonically increasing functions.
So if m<=n,
Then f(m)<=f(n) __(1)
and g(m)<=g(n) __(2)
By definition of monotonicity.
Therefore, adding both equations: f(m)+g(m) <= f(n)+g(n), hence f(n)+g(n) is monotonically
increasing.
Replace both m and n with g(m) and g(n) in equation (1) the inequality does not get affected as f
is non negative and f and g are both monotonic.
So we get f(g(m)) <= f(g(n))
Ans 4)
a) Due to one for loop running time of this code segment is Θ(n)
Maintenance:
After the ith iteration,
n−(i+1)
y=ai + x ∑ ak+i+1xk
k=0
n−(i+1)
= ai x0 + ∑ ak+i+1 xk+1
k=0
n−i
= ai x0 + ∑ ak+i xk
k=1
n−i
= ∑ ak+i xk --(1)
k=0
Termination:
The following loop eqn (1) will terminate when i=0
n
Therefore, y = ∑ ak xk
k=0
d)
The given code fragment correctly evaluates a polynomial characterized by the
coefficients as the invariant of the loop is a sum which equals a polynomial with the
given coefficients.
Ans 7)
n
Therefore, ln n = Θ (k)
Ans 8)
a) In order to show this, when k >= d, we have to show there exists constants c,n0 >
0
k
such that 0 <= p(n) <= c * (n ) for all n>=n0
Now as k >= d, for all possible values of i, (i−k) <= 0, which implies that all ni-k <= 1 for all
d
n >= 1. There we can say that p(n) <= ∑ ak by equation (1).
k=0
d
Hence we can say that 0 <= p(n) <= c * (nk) where c = ∑ ak and n0 =
1.
k=0
k
Hence p(n)=O(n ).
b) In order to show this, when k <= d, we have to show there exists constants c , n0 >
0
k
such that 0 <= p(n) <= c * (n ) for all n>=n0
c) In part (a) and (b), we proved that when k=d, p(n)=O(nk) and p(n)= Ω (nk) respectively.
Hence we can also say that p(n)= Θ (nk)
Now as k > d, for all possible values of i, (i−k) < 0, which implies that all ni-k < 1 for all
d
n >= 1. There we can say that p(n) < ∑ ak by equation (1).
k=0
d
Hence we can say that 0 <= p(n) < c * (nk) where c = ∑ ak and n0 =
1.
k=0
Hence p(n) = o(nk).
See the proof of inequality (b). We simply need to remove inequality there. From there
we find:
p(n) = a0 + a1n1 + 2 d
a2n + . . . . .+adn ---(1)
Hence we can say that 0 <= c * (nk) < p(n) where c = ak and n0 =
1.