Assignment Solution (1)
Assignment Solution (1)
Assignment Solutions
Assignment Solutions
Q1. There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either
1,2,3…m stairs at a time where m is a user given integer. Count the number of ways the person can reach the
top.
Input: n = 5 , m = 3
Output: 7
Approach :
The following recurrence relation has been used : ways(n, m) = ways(n-1, m) + ways(n-2, m) + ... ways(n-m,
m
We create a table res[] in bottom up manner using the following relation: res[i] = res[i] + res[i-j] for every (i-
j) >=
Such that the ith index of the array will contain the number of ways required to reach the ith step
considering all the possibilities of climbing (i.e. from 1 to i).
Output :
Input1: n = 4
Output1: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
Input2: n = 25
Output2: 1389537
Approach :
We use an array to store the calculated values so that repeating values can be fetched without spending all
that computing time on calculating the same thing again.
Output :
Q3. Given a set of positive integers S, partition set S into two subsets, S1 and S2, such that the difference
between the sum of elements in S1 and S2 is minimized. The solution should return the minimum absolute
difference between the sum of elements of two partitions.
We can partition S into two partitions where the minimum absolute difference between the sum of elements
is 5.
S1 = {10, 20, 5}
Note that this solution is not unique. The following is another solution:
S1 = {10, 25}
S2 = {20, 15, 5}
Approach :
The idea is to consider each item in the given set S one by one, and for each item, there are two possibilities:
Include the current item in subset S1 and recur for the remaining items and Include the current item from the
subset S2 and recur for the remaining items
Finally, return the minimum difference we get by including the current item in S1 and S2. When there are no
items left in the set, return the absolute difference between elements of S1 and S2.
Output :
Q4. Given a positive integer K, the task is to find the minimum number of operations of the following two
types, required to change 0 to K:
Add one to the operan
Multiply the operand by 2.
Input1: K = 1
Output1: 1
Explanation:
Step 1: 0 + 1 = 1 = K
Input2: K = 4
Output2: 3
Explanation:
Step 1: 0 + 1 = 1,
Step 2: 1 * 2 = 2,
Step 3: 2 * 2 = 4 = K
Approach :
If K is an odd number, the last step must be adding 1 to it
If K is an even number, the last step is to multiply by 2 to minimize the number of steps
Create a dp[] table that stores in every dp[i], the minimum steps required to reach i.
Observation :
Let us consider an even number
Now we have two options
i) X-
ii)X/
Now if we choose X-1
-> X-1 is an odd number , since X is even
Output :
Q5. Given a positive integer n, count all n–digit binary numbers without any consecutive 1's.
Input 1: n = 5,
Output 1: 13
Explanation : [00000, 00001, 00010, 00100, 00101, 01000, 01001, 01010, 10000, 10001, 10010, 10100, 10101].
Approach :
The idea is to use recursion. We append 0 and 1 to the partially formed number and recur with one less digit
at each point in the recursion
Here, the trick is to append 1 and recur only if the last digit of the partially formed number is 0.
That way, we will never have any consecutive 1's in the output string.
Output :
Q6. Given a distance ‘dist’, count the total number of ways to cover the distance with 1, 2 and 3 steps.
Input1: n = 3
Output1: 4
Explanation:
1 step + 2 step
2 step + 1 step
3 step
Input2: n = 4
Output2: 7
Approach :
Create an array of size n + 1 and initialize the first 3 variables with 1, 1, 2. The base cases.
Output :
Q7. Given an integer n, return the least number of perfect square numbers that sum to n.
A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer
with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.
Input1: n = 12
Output1: 3
Explanation: 12 = 4 + 4 + 4.
Input2: n = 13
Output2: 2
Explanation: 13 = 4 + 9.
Approach
The approach involves breaking down the given integer n into subproblems by considering all possible
square numbers less than or equal to n, and solving the subproblems until we reach the base case of n = 0
To solve this using dynamic programming, follow these steps
We start by defining an array dp of size n+1, where each cell represents the least number of perfect square
numbers that sum to the index value. We initialize the array with the maximum possible value (n itself),
except for the first cell dp[0], which is set to 0
Next, we loop through each index i from 1 to n, and for each index, we loop through all possible square
numbers j*j that are less than or equal to i, and update the value of dp[i] as follows
dp[i] = Math.min(dp[i], dp[i-j*j] + 1) where dp[i-jj] represents the value of dp for the remaining subproblem
after subtracting jj from i, and adding 1 to account for the j*j term
Finally, we return the value of dp[n] as the result.
CODE: https://pastebin.com/vawNMzTv
OUTPUT:
Q8. Given two strings. Find the length of the longest common substring.
Output 1: 3
Approach :
The idea is to find the longest common suffix for all pairs of prefixes of the strings using dynamic
programming using the relation
LCSuffix[i][j] = | LCSuffix[i-1][j-1] + 1 (if X[i-1] = Y[j-1])
|0 (otherwise)
A B A B
0 0 0 0 0
B 0 0 1 0 1
A 0 1 0 2 0
B 0 0 2 0 3
A 0 1 0 3 0
Finally, the longest common substring length would be the maximal of these longest common suffixes of all
possible prefixes.
Output :
Q9. Given an array arr[] of size N, the task is to find the length of the Longest Increasing Subsequence (LIS) i.e.,
the longest possible subsequence in which the elements of the subsequence are sorted in increasing order.
Approach
Intuition: Let L(i) be the length of the LIS ending at index i such that arr[i] is the last element of the LIS. Then,
L(i) can be recursively written as:
L(i) = 1 + max(L(j) ) where 0 < j < i and arr[j] < arr[i]; or
L(i) = 1, if no such j exists.
Formally, the length of LIS ending at index i, is 1 greater than the maximum of lengths of all LIS ending at
some index j such that arr[j] < arr[i] where j < i
Since here we see overlapping subproblems, we use DP to solve this problem
Traverse the array using curr index ( the last index of the LIS ) and the prev index ( from curr-1 to -1 )
For every element we have two options: whether to include it or exclude it
Element is included if and only if arr[curr]>arr[prev] ( next element should be greater than the previous one
for LIS )
Code: https://pastebin.com/9pV0DvUM
Output:
Q10. Given a string s, return the length of the longest palindromic substring in it. A palindromic substring is a
contiguous sequence of characters within a string that reads the same backwards as forwards.
Input1:
s = "babad"
Output1:
Input2:
s = "cbbd"
Output2:
Approach
Intuition: Consider one example “cbebc”. If we already knew that “beb” is a palindrome, it is obvious that
“cbebc” must be a palindrome since the two left and right end letters are the same
We use a boolean 2D array here with number of rows and columns equal to the length of the input string
Keep a variable len to store the longest palindrome’s length
We will be storing true or false values for every cell in the array which will be denoting if the substring from i,j
is a palindrome or not
Initially, since a single character is always a palindrome, we mark all the left to right diagonal cells as true
For every cell, we check if col is just 1 greater than the row number, the character at ith and jth position is the
same else, we also check if cell at diagonally previous location had a palindrome or not
If current cell is true, update len
Return len in the end.
CODE: https://pastebin.com/JsifQjKv
OUTPUT:
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements
without changing the order of the remaining elements.
A palindromic subsequence is the same when read from either left or right.
Input1: s = "bbbab"
Output1: 4
Input2: s = "cbbd"
Output2: 2
Approach
Consider a dp array of size N * N
State is dp[i][j] which denotes the length of the LPS of the string s[i...j]
Fill the table with a start case, dp[i, i] == 1, since all single char in a string is a palindrome, which length is 1
Now we will use the gap strategy to fill the dp table step-by-step using the following logic
Let s be the string of length n, we will start filling the dp table for all substring with gap 0 then with gap 1, and
so on till the gap of n−1
Here gap=k means all substring with gap k i.e., s[i...j] such that j−i=k
Iterate for gap=0 to gap=n−1 and do the following
Declare a variable say i and initialize it to 0
Iterate for j=gap to j=n−1 and do the following - Fill the dp[i][j] as per the state transitions described above.
Increment i by 1, i.e. i++. Now dp[0][n-1] will contain the length of the LPS for string s[0...n−1] i.e. original string.
Hence, we will return it as the answer.
Code: https://pastebin.com/QzRK9MWh
Output:
Q12. Given a string s, partition s such that every substring of the partition is a palindrome. Return the
minimum cuts needed for a palindrome partitioning of s.
Input1: s = "aab"
Output1: 1
Input2: s = "a"
Output2: 0
Approach
If the string is a palindrome, then we simply return 0
Else, we try making cuts at all possible places, calculate the cost for each cut and return the minimum value.
Code: https://pastebin.com/Sxmix75p
Output:
Output1: 7
The seven distinct subsequences are "", "g", "i", "gf", "ig", "gg" and "gig"
Output2: 4
The four distinct subsequences are "", "g", "gg" and "ggg"
Approach
If there are no repetitions, then count becomes double of count for n-1 because we get count(n-1) more
subsequences by adding current character at the end of all subsequences possible with n-1 length.
If there are repetitions, then we find a count of all distinct subsequences ending with the previous
occurrence. This count can be obtained by recursively calling for an index of the previous occurrence.
Since the above recurrence has overlapping subproblems, we can solve it using Dynamic Programming.
Create an array to store index of las
Fill this array with -1
dp[i] is going to store count of distinct subsequences of length i
Empty substring has only one subsequence which is why dp[0] = 1
Traverse through all lengths from 1 to n
Number of subsequences with substring str[0..i-1] = 2 * dp[i-1]
If current character has appeared before, then remove all subsequences ending with previous occurrence
Mark occurrence of current character.
Code: https://pastebin.com/5uWeipzp
Output:
Q14. You have n days of vacation. Each day, you decide to do one of the following activities with the constraint
that you cannot do the same activities for two or more consecutive days. (Homework)
Find the maximum possible total points of happiness that you can gain over the n days.
Input1:
10 40 70
20 50 80
30 60 90
Output1:
210
Input2:
6 7 8
8 8 3
2 5 2
7 8 6
4 6 8
2 3 4
7 5 1
Output2:
46
Approach
Since this problem can be broken down into smaller subproblems(going day by day basis), we use DP to
solve this problem
We create a DP array of the same size as that of the input array, i.e., number of rows = number of days,
number of columns = number of activities
For the first day, each activity will have its own happiness count
For all other days, we try to find the maximum happiness points collected so far, keeping in mind that the
current activity was not done the previous day and add its points to the count
dp[i][0] = Math.max(dp[i-1][1], dp[i-1][2]) + arr[i][0]
dp[i][1] = Math.max(dp[i-1][0], dp[i-1][2]) + arr[i][1]
dp[i][2] = Math.max(dp[i-1][0], dp[i-1][1]) + arr[i][2];
Code: https://pastebin.com/Pd8dKBQu
Output:
Q15. You have n mixtures in front of you, arranged in a row. Each mixture has one of 100 different colors (colors
have numbers from 0 to 99). You want to mix all these mixtures together. At each step, you are going to take
two mixtures that stand next to each other and mix them together, and put the resulting mixture in their
place. When mixing two mixtures of colors a and b, the resulting mixture will have the color (a+b) mod 100.
Also, there will be some smoke in the process. The amount of smoke generated when mixing two mixtures of
colors a and b is a*b.
Find out what is the minimum amount of smoke that you can get when mixing all the mixtures together.
Input1:
n = 2
18 19
Output1:
342
Input2:
n = 3
40 60 20
Output2:
2400
The first scenario is the correct approach since it minimizes the amount of smoke produced.
Approach
To define a state, Let dp[i][j] be the minimum amount of smoke released to collate all mixtures from i to j
(inclusive) into a single mixture.
We soon realize that we also need to maintain the value that this subarray [i,j] attains
More formally, we need to determine 2 values for every range [i,j]
The minimum smoke released to combine said range into 1 mixture
The value of the 1 mixture formed by combining
The former can be done by maintaining a 2d array for each state, where dp[i][j] = min smoke for range [i,j].
The latter can also be an array, where val[i][j] = value of mixture created by [i,j], Or it can be done by
maintaining cumulative sums, and then processing (range_sum)%100 to get the value of the mixture
We know that our answer will be dp[0][n-1]
The basic intuition lies in trying all possibilities, for which we can split every subarray in any way.
The base case lies when size of subarray is 2, we have to compulsorily mix these mixtures, as the mixtures
have to be next to each other.
Code: https://pastebin.com/qiQQrptu
Output: