text stringlengths 17 2.11k | code stringlengths 82 3.44k |
|---|---|
Count of subsets of integers from 1 to N having no adjacent elements | Function to count subsets ; Driver Code | def count_subsets(N):
"""
Count of subsets of integers from 1 to N having no adjacent elements
"""
if (N <= 2):
return N
if (N == 3):
return 2
DP = [0] * (N + 1)
DP[0] = 0
DP[1] = 1
DP[2] = 2
DP[3] = 2
for i in range(4, N + 1):
DP[i] = DP[i - 2] + DP[i... |
Count the Arithmetic sequences in the Array of size at least 3 | Function to find all arithmetic sequences of size atleast 3 ; If array size is less than 3 ; Finding arithmetic subarray length ; To store all arithmetic subarray of length at least 3 ; Check if current element makes arithmetic sequence with previous two ... | def number_of_arithmetic_sequences(L, N):
"""
Count the Arithmetic sequences in the Array of size at least 3
"""
if (N <= 2):
return 0
count = 0
res = 0
for i in range(2, N):
if ((L[i] - L[i - 1]) == (L[i - 1] - L[i - 2])):
count += 1
else:
cou... |
Count triplet of indices ( i , j , k ) such that XOR of elements between [ i , j ) equals [ j , k ] | Function return the count of triplets having subarray XOR equal ; XOR value till i ; Count and ways array as defined above ; Using the formula stated ; Increase the frequency of x ; Add i + 1 to ways [ x ] for upcoming... | def count_of_triplets(a, n):
"""
Count triplet of indices ( i , j , k ) such that XOR of elements between [ i , j ) equals [ j , k ]
"""
answer = 0
x = 0
count = [0 for i in range(100005)]
ways = [0 for i in range(100005)]
for i in range(n):
x ^= a[i]
answer += count[x] *... |
Count maximum occurrence of subsequence in string such that indices in subsequence is in A . P . | Python3 implementation to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Function to find the maximum occurrence of the subsequence such that the indices... | import sys
def maximum_occurrence(s):
"""
Count maximum occurrence of subsequence in string such that indices in subsequence is in A . P .
"""
n = len(s)
freq = [0] * (26)
dp = [[0 for i in range(26)]for j in range(26)]
for i in range(n):
c = (ord(s[i]) - ord('a'))
for j in... |
Shortest path with exactly k edges in a directed and weighted graph | Set 2 | Python3 implementation of the above approach ; Function to find the smallest path with exactly K edges ; Array to store dp ; Loop to solve DP ; Initialising next state ; Recurrence relation ; Returning final answer ; Driver code ; Input edges... | inf = 100000000
def sm_path(s, d, ed, n, k):
"""
Shortest path with exactly k edges in a directed and weighted graph
"""
dis = [inf] * (n + 1)
dis[s] = 0
for i in range(k):
dis1 = [inf] * (n + 1)
for it in ed:
dis1[it[1]] = min(dis1[it[1]], dis[it[0]] + it[2])
... |
Path with smallest product of edges with weight > 0 | Python3 implementation of the approach . ; Function to return the smallest product of edges ; If the source is equal to the destination ; Array to store distances ; Initialising the array ; Bellman ford algorithm ; Loop to detect cycle ; Returning final answer ; Dri... | import sys
inf = sys .maxsize
def bellman(s, d, ed, n):
"""
Path with smallest product of edges with weight > 0
"""
if (s == d):
return 0
dis = [0] * (n + 1)
for i in range(1, n + 1):
dis[i] = inf
dis[s] = 1
for i in range(n - 1):
for it in ed:
dis[i... |
Find Maximum Length Of A Square Submatrix Having Sum Of Elements At | Python3 implementation of the above approach ; Function to return maximum length of square submatrix having sum of elements at - most K ; Matrix to store prefix sum ; Current maximum length ; Variable for storing maximum length of square ; Calculatin... | import numpy as np
def max_length_square(row, column, arr, k):
"""
Find Maximum Length Of A Square Submatrix Having Sum Of Elements At
"""
sum = np.zeros((row + 1, column + 1))
cur_max = 1
max = 0
for i in range(1, row + 1):
for j in range(1, column + 1):
sum[i][j] = su... |
Sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times | Python3 program to find sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times ; exactsum [ i ] [ j ] [ k ] stores the sum of all the numbers having exact i 4 ' s , ▁ j ▁ 5' s and k 6 's ; exac... | import numpy as np
N = 101
mod = int(1e9) + 7
exactsum = np.zeros((N, N, N))
exactnum = np.zeros((N, N, N))
def get_sum(x, y, z):
"""
Sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times
"""
ans = 0
exactnum[0][0][0] = 1
for i in range(x + 1):
for j... |
Maximum value obtained by performing given operations in an Array | Python3 implementation of the above approach ; A function to calculate the maximum value ; basecases ; Loop to iterate and add the max value in the dp array ; Driver Code | import numpy as np
def find_max(a, n):
"""
Maximum value obtained by performing given operations in an Array
"""
dp = np.zeros((n, 2))
dp[0][0] = a[0] + a[1]
dp[0][1] = a[0] * a[1]
for i in range(1, n - 1):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]) + a[i + 1]
dp[i][1] = dp... |
Find the minimum difference path from ( 0 , 0 ) to ( N | Python3 implementation of the approach ; Function to return the minimum difference path from ( 0 , 0 ) to ( N - 1 , M - 1 ) ; Terminating case ; Base case ; If it is already visited ; Recursive calls ; Return the value ; Driver code ; Function call | import numpy as np
import sys
MAXI = 50
INT_MAX = sys .maxsize
dp = np.ones((MAXI, MAXI, MAXI * MAXI))
dp *= -1
def min_difference(x, y, k, b, c):
"""
Find the minimum difference path from ( 0 , 0 ) to ( N
"""
if (x >= n or y >= m):
return INT_MAX
if (x == n - 1 and y == m - 1):
di... |
Maximum possible array sum after performing the given operation | Function to return the maximum possible sum after performing the given operation ; Dp vector to store the answer ; Base value ; Return the maximum sum ; Driver code | def max_sum(a, n):
"""
Maximum possible array sum after performing the given operation
"""
dp = [[0 for i in range(2)]for j in range(n + 1)]
dp[0][0] = 0
dp[0][1] = -999999
for i in range(0, n):
dp[i + 1][0] = max(dp[i][0] + a[i], dp[i][1] - a[i])
dp[i + 1][1] = max(dp[i][0] ... |
Find the number of ways to reach Kth step in stair case | Python3 implementation of the approach ; Function to return the number of ways to reach the kth step ; Create the dp array ; Broken steps ; Calculate the number of ways for the rest of the positions ; If it is a blocked position ; Number of ways to get to the it... | MOD = 1000000007
def number_of_ways(arr, n, k):
"""
Find the number of ways to reach Kth step in stair case
"""
if (k == 1):
return 1
dp = [-1] * (k + 1)
for i in range(n):
dp[arr[i]] = 0
dp[0] = 1
dp[1] = 1 if (dp[1] == -1)else dp[1]
for i in range(2, k + 1):
... |
Minimum number of coins that can generate all the values in the given range | Python3 program to find minimum number of coins ; Function to find minimum number of coins ; Driver code | import math
def find_count(n):
"""
Minimum number of coins that can generate all the values in the given range
"""
return int(math.log(n, 2)) + 1
N = 10
print(find_count(N))
|
Count number of ways to arrange first N numbers | Python3 implementation of the approach ; Function to return the count of required arrangements ; Create a vector ; Store numbers from 1 to n ; To store the count of ways ; Initialize flag to true if first element is 1 else false ; Checking if the current permutation sat... | from itertools import permutations
def count_ways(n):
"""
Count number of ways to arrange first N numbers
"""
a = []
i = 1
while (i <= n):
a.append(i)
i += 1
ways = 0
flag = 1 if (per[0] == 1)else 0
for i in range(1, n):
if (abs(per[i] - per[i - 1])... |
Count number of ways to arrange first N numbers | Function to return the count of required arrangements ; Create the dp array ; Initialize the base cases as explained above ; ( 12 ) as the only possibility ; Generate answer for greater values ; dp [ n ] contains the desired answer ; Driver code | def count_ways(n):
"""
Count number of ways to arrange first N numbers
"""
dp = [0 for i in range(n + 1)]
dp[0] = 0
dp[1] = 1
dp[2] = 1
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 3] + 1
return dp[n]
n = 6
print(count_ways(n))
|
Number of shortest paths to reach every cell from bottom | Function to find number of shortest paths ; Compute the grid starting from the bottom - left corner ; Print the grid ; Driver code ; Function call | def number_of_shortest_paths(n, m):
"""
Number of shortest paths to reach every cell from bottom
"""
a = [[0 for i in range(m)]for j in range(n)]
for i in range(n):
for j in range(m):
a[i][j] = 0
i = n - 1
while (i >= 0):
for j in range(m):
if (j == 0 ... |
Maximum sum combination from two arrays | Function to maximum sum combination from two arrays ; To store dp value ; For loop to calculate the value of dp ; Return the required answer ; Driver code ; Function call | def max__sum(arr1, arr2, n):
"""
Maximum sum combination from two arrays
"""
dp = [[0 for i in range(2)]for j in range(n)]
for i in range(n):
if (i == 0):
dp[i][0] = arr1[i]
dp[i][1] = arr2[i]
continue
else:
dp[i][0] = max(dp[i - 1][0],... |
Maximum sum of non | Python3 program to implement above approach ; Variable to store states of dp ; Variable to check if a given state has been solved ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Variable to store prefix sum fo... | maxLen = 10
dp = [0] * maxLen
visit = [0] * maxLen
def max_sum(arr, i, n, k):
"""
Maximum sum of non
"""
if (i >= n):
return 0
if (visit[i]):
return dp[i]
visit[i] = 1
tot = 0
dp[i] = max_sum(arr, i + 1, n, k)
j = i
while (j < i + k and j < n):
tot += ar... |
Minimize the sum after choosing elements from the given three arrays | Python3 implementation of the above approach ; Function to return the minimized sum ; If all the indices have been used ; If this value is pre - calculated then return its value from dp array instead of re - computing it ; If A [ i - 1 ] was chosen ... | import numpy as np
SIZE = 3
N = 3
def min_sum(A, B, C, i, n, curr, dp):
"""
Minimize the sum after choosing elements from the given three arrays
"""
if (n <= 0):
return 0
if (dp[n][curr] != -1):
return dp[n][curr]
if (curr == 0):
dp[n][curr] = min(
B[i] +
... |
Find maximum topics to prepare in order to pass the exam | Python3 implementation of the approach ; Function to return the maximum marks by considering topics which can be completed in the given time duration ; If we are given 0 time then nothing can be done So all values are 0 ; If we are given 0 topics then the time ... | import numpy as np
def maximum_marks(marksarr, timearr, h, n, p):
"""
Find maximum topics to prepare in order to pass the exam
"""
no_of_topics = n + 1
total_time = h + 1
T = np.zeros((no_of_topics, total_time))
for i in range(no_of_topics):
T[i][0] = 0
for j in range(total_tim... |
Minimize the number of steps required to reach the end of the array | Python3 implementation of the above approach ; variable to store states of dp ; variable to check if a given state has been solved ; Function to find the minimum number of steps required to reach the end of the array ; base case ; to check if a state... | maxLen = 10
maskLen = 130
dp = [[0 for i in range(maskLen)]for i in range(maxLen)]
v = [[False for i in range(maskLen)]for i in range(maxLen)]
def min_steps(arr, i, mask, n):
"""
Minimize the number of steps required to reach the end of the array
"""
if (i == n - 1):
return 0
if (i > n - 1... |
Minimum number of cubes whose sum equals to given number N | Function to return the minimum number of cubes whose sum is k ; If k is less than the 2 ^ 3 ; Initialize with the maximum number of cubes required ; Driver code | def min_of_cubed(k):
"""
Minimum number of cubes whose sum equals to given number N
"""
if (k < 8):
return k
res = k
for i in range(1, k + 1):
if ((i * i * i) > k):
return res
res = min(res, min_of_cubed(k - (i * i * i)) + 1)
return res
num = 15
print(mi... |
Minimum number of cubes whose sum equals to given number N | Python implementation of the approach ; Function to return the minimum number of cubes whose sum is k ; While current perfect cube is less than current element ; If i is a perfect cube ; i = ( i - 1 ) + 1 ^ 3 ; Next perfect cube ; Re - initialization for next... | import sys
def min_of_cubed_dp(k):
"""
Minimum number of cubes whose sum equals to given number N
"""
DP = [0] * (k + 1)
j = 1
t = 1
DP[0] = 0
for i in range(1, k + 1):
DP[i] = sys .maxsize
while (j <= i):
if (j == i):
DP[i] = 1
e... |
Maximum Subarray Sum after inverting at most two elements | Function to return the maximum required sub - array sum ; Creating one based indexing ; 2d array to contain solution for each step ; Case 1 : Choosing current or ( current + previous ) whichever is smaller ; Case 2 : ( a ) Altering sign and add to previous cas... | def max_sum(a, n):
"""
Maximum Subarray Sum after inverting at most two elements
"""
ans = 0
arr = [0] * (n + 1)
for i in range(1, n + 1):
arr[i] = a[i - 1]
dp = [[0 for i in range(3)]for j in range(n + 1)]
for i in range(0, n + 1):
dp[i][0] = max(arr[i], dp[i - 1][0] + a... |
Maximum sum possible for a sub | Function to return the maximum sum possible ; dp [ i ] represent the maximum sum so far after reaching current position i ; Initialize dp [ 0 ] ; Initialize the dp values till k since any two elements included in the sub - sequence must be atleast k indices apart , and thus first elemen... | def max_sum(arr, k, n):
"""
Maximum sum possible for a sub
"""
if (n == 0):
return 0
if (n == 1):
return arr[0]
if (n == 2):
return max(arr[0], arr[1])
dp = [0] * n
dp[0] = arr[0]
for i in range(1, k + 1):
dp[i] = max(arr[i], dp[i - 1])
for i in ra... |
Minimum cost to form a number X by adding up powers of 2 | Function to return the minimum cost ; Re - compute the array ; Add answers for set bits ; If bit is set ; Increase the counter ; Right shift the number ; Driver code | def minimum_cost(a, n, x):
"""
Minimum cost to form a number X by adding up powers of 2
"""
for i in range(1, n, 1):
a[i] = min(a[i], 2 * a[i - 1])
ind = 0
sum = 0
while (x):
if (x & 1):
sum += a[ind]
ind += 1
x = x >> 1
return sum
if __name_... |
Ways to form an array having integers in given range such that total sum is divisible by 2 | Function to return the number of ways to form an array of size n such that sum of all elements is divisible by 2 ; Represents first and last numbers of each type ( modulo 0 and 1 ) ; Count of numbers of each type between range ... | def count_ways(n, l, r):
"""
Ways to form an array having integers in given range such that total sum is divisible by 2
"""
tL, tR = l, r
L = [0 for i in range(2)]
R = [0 for i in range(2)]
L[l % 2] = l
R[r % 2] = r
l += 1
r -= 1
if (l <= tR and r >= tL):
L[l % 2], R[... |
Color N boxes using M colors such that K boxes have different color from the box on its left | Python3 Program to Paint N boxes using M colors such that K boxes have color different from color of box on its left ; This function returns the required number of ways where idx is the current index and diff is number of box... | M = 1001
MOD = 998244353
dp = [[-1] * M] * M
def solve(idx, diff, N, M, K):
"""
Color N boxes using M colors such that K boxes have different color from the box on its left
"""
if (idx > N):
if (diff == K):
return 1
return 0
if (dp[idx][diff] != -1):
return dp[i... |
Maximum path sum in an Inverted triangle | SET 2 | Python program implementation of Max sum problem in a triangle ; Function for finding maximum sum ; Loop for bottom - up calculation ; For each element , check both elements just below the number and below left to the number add the maximum of them to it ; Return the m... | N = 3
def max_path_sum(tri):
"""
Maximum path sum in an Inverted triangle
"""
ans = 0
for i in range(N - 2, -1, -1):
for j in range(0, N - i):
if (j - 1 >= 0):
tri[i][j] += max(tri[i + 1][j], tri[i + 1][j - 1])
else:
tri[i][j] += tri[... |
Count no . of ordered subsets having a particular XOR value | Python 3 implementation of the approach ; Returns count of ordered subsets of arr [ ] with XOR value = K ; Find maximum element in arr [ ] ; Maximum possible XOR value ; The value of dp [ i ] [ j ] [ k ] is the number of subsets of length k having XOR of the... | from math import log2
def subset_xor(arr, n, K):
"""
Count no . of ordered subsets having a particular XOR value
"""
max_ele = arr[0]
for i in range(1, n):
if (arr[i] > max_ele):
max_ele = arr[i]
m = (1 << int(log2(max_ele) + 1)) - 1
dp = [[[0 for i in range(n + 1)]for ... |
Possible cuts of a number such that maximum parts are divisible by 3 | Python3 program to find the maximum number of numbers divisible by 3 in a large number ; This will contain the count of the splits ; This will keep sum of all successive integers , when they are indivisible by 3 ; This is the condition of finding a ... | def get_max_splits(num_string):
"""
Possible cuts of a number such that maximum parts are divisible by 3
"""
count = 0
running_sum = 0
for i in range(len(num_string)):
current_num = int(num_string[i])
running_sum += current_num
if current_num % 3 == 0 or (running_sum != 0... |
Count of Numbers in Range where first digit is equal to last digit of the number | Python3 program to implement the above approach ; Base Case ; Calculating the last digit ; Calculating the first digit ; Driver Code | def solve(x):
"""
Count of Numbers in Range where first digit is equal to last digit of the number
"""
ans, temp = 0, x
if (x < 10):
return x
last = x % 10
while (x):
first = x % 10
x = x // 10
if (first <= last):
ans = 9 + temp // 10
else:
ans... |
Form N | function returns the minimum cost to form a n - copy string Here , x -> Cost to add / remove a single character ' G ' and y -> cost to append the string to itself ; base case : ro form a 1 - copy string we need tp perform an operation of type 1 ( i , e Add ) ; case1 . Perform a Add operation on ( i - 1 ) copy ... | def find_minimum_cost(n, x, y):
"""
Form N
"""
dp = [0 for i in range(n + 1)]
dp[1] = x
for i in range(2, n + 1):
if i & 1:
dp[i] = min(dp[i - 1] + x, dp[(i + 1) // 2] + y + x)
else:
dp[i] = min(dp[i - 1] + x, dp[i // 2] + y)
return dp[n]
n, x, y = 4... |
Number of ways to partition a string into two balanced subsequences | For maximum length of input string ; Declaring the DP table ; Declaring the prefix array ; Function to calculate the number of valid assignments ; Return 1 if X is balanced . ; Increment the count if it is an opening bracket ; Decrement the count if ... | MAX = 10
F = [[-1 for i in range(MAX)]for j in range(MAX)]
C = [None] * MAX
def no_of_assignments(S, n, i, c_x):
"""
Number of ways to partition a string into two balanced subsequences
"""
if F[i][c_x] != -1:
return F[i][c_x]
if i == n:
F[i][c_x] = not c_x
return F[i][c_x]
... |
Minimum sum falling path in a NxN grid | Python3 Program to minimum required sum ; Function to return minimum path falling sum ; R = Row and C = Column We begin from second last row and keep adding maximum sum . ; best = min ( A [ R + 1 ] [ C - 1 ] , A [ R + 1 ] [ C ] , A [ R + 1 ] [ C + 1 ] ) ; Driver code ; function ... | import sys
n = 3
def min_falling_path_sum(A):
"""
Minimum sum falling path in a NxN grid
"""
for R in range(n - 2, -1, -1):
for C in range(n):
best = A[R + 1][C]
if C > 0:
best = min(best, A[R + 1][C - 1])
if C + 1 < n:
best =... |
Find the maximum sum of Plus shape pattern in a 2 | Python 3 program to find the maximum value of a + shaped pattern in 2 - D array ; Function to return maximum Plus value ; Initializing answer with the minimum value ; Initializing all four arrays ; Initializing left and up array . ; Initializing right and down array .... | N = 100
n = 3
m = 4
def max_plus(arr):
"""
Find the maximum sum of Plus shape pattern in a 2
"""
ans = 0
left = [[0 for x in range(N)]for y in range(N)]
right = [[0 for x in range(N)]for y in range(N)]
up = [[0 for x in range(N)]for y in range(N)]
down = [[0 for x in range(N)]for y in ... |
Total number of different staircase that can made from N boxes | Function to find the total number of different staircase that can made from N boxes ; DP table , there are two states . First describes the number of boxes and second describes the step ; Initialize all the elements of the table to zero ; Base case ; When... | def count_staircases(N):
"""
Total number of different staircase that can made from N boxes
"""
memo = [[0 for x in range(N + 5)]for y in range(N + 5)]
for i in range(N + 1):
for j in range(N + 1):
memo[i][j] = 0
memo[3][2] = memo[4][2] = 1
for i in range(5, N + 1):
... |
Find maximum points which can be obtained by deleting elements from array | function to return maximum cost obtained ; find maximum element of the array . ; create and initialize count of all elements to zero . ; calculate frequency of all elements of array . ; stores cost of deleted elements . ; selecting minimum rang... | def max_cost(a, n, l, r):
"""
Find maximum points which can be obtained by deleting elements from array
"""
mx = 0
for i in range(n):
mx = max(mx, a[i])
count = [0] * (mx + 1)
for i in range(n):
count[a[i]] += 1
res = [0] * (mx + 1)
res[0] = 0
l = min(l, r)
fo... |
Count the number of ways to traverse a Matrix | Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Return 1 if it is the first row or first column ; Recursively find the no of way to reach the last cell . ; Driver code | def count_paths(m, n):
"""
Count the number of ways to traverse a Matrix
"""
if m == 1 or n == 1:
return 1
return (count_paths(m - 1, n) + count_paths(m, n - 1))
if __name__ == "__main__":
n = 5
m = 5
print(count_paths(n, m))
|
Count the number of ways to traverse a Matrix | Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Driver code | def count_paths(m, n):
"""
Count the number of ways to traverse a Matrix
"""
dp = [[0 for i in range(m + 1)]for j in range(n + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if (i == 1 or j == 1):
dp[i][j] = 1
else:
dp[i][j] = ... |
Alternate Fibonacci Numbers | Alternate Fibonacci Series using Dynamic Programming ; 0 th and 1 st number of the series are 0 and 1 ; Driver Code | def alternate_fib(n):
"""
Alternate Fibonacci Numbers
"""
if (n < 0):
return -1
f1 = 0
f2 = 1
print(f1, end=" ")
for i in range(2, n + 1):
f3 = f2 + f1
if (i % 2 == 0):
print(f3, end=" ")
f1 = f2
f2 = f3
N = 15
alternate_fib(N)
|
Number of ways to form an array with distinct adjacent elements | Returns the total ways to form arrays such that every consecutive element is different and each element except the first and last can take values from 1 to M ; define the dp [ ] [ ] array ; if the first element is 1 ; there is only one way to place a 1 a... | def total_ways(N, M, X):
"""
Number of ways to form an array with distinct adjacent elements
"""
dp = [[0 for i in range(2)]for j in range(N + 1)]
if (X == 1):
dp[0][0] = 1
else:
dp[0][1] = 0
if (X == 1):
dp[1][0] = 0
dp[1][1] = M - 1
else:
dp[1][0... |
Memoization ( 1D , 2D and 3D ) | Fibonacci Series using Recursion ; Base case ; recursive calls ; Driver Code | def fib(n):
"""
Memoization ( 1D , 2D and 3D )
"""
if (n <= 1):
return n
return fib(n - 1) + fib(n - 2)
if __name__ == '__main__':
n = 6
print(fib(n))
|
Memoization ( 1D , 2D and 3D ) | Python program to find the Nth term of Fibonacci series ; Fibonacci Series using memoized Recursion ; base case ; if fib ( n ) has already been computed we do not do further recursive calls and hence reduce the number of repeated work ; store the computed value of fib ( n ) in an array ... | term = [0 for i in range(1000)]
def fib(n):
"""
Memoization ( 1D , 2D and 3D )
"""
if n <= 1:
return n
if term[n] != 0:
return term[n]
else:
term[n] = fib(n - 1) + fib(n - 2)
return term[n]
n = 6
print(fib(n))
|
Memoization ( 1D , 2D and 3D ) | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Driver Code | def lcs(X, Y, m, n):
"""
Memoization ( 1D , 2D and 3D )
"""
if (m == 0 or n == 0):
return 0
if (X[m - 1] == Y[n - 1]):
return 1 + lcs(X, Y, m - 1, n - 1)
else:
return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n))
if __name__ == '__main__':
X = "AGGTAB"
Y = "GXTX... |
Print Fibonacci sequence using 2 variables | Simple Python3 Program to print Fibonacci sequence ; Driver code | def fib(n):
"""
Print Fibonacci sequence using 2 variables
"""
a = 0
b = 1
if (n >= 0):
print(a, end=' ')
if (n >= 1):
print(b, end=' ')
for i in range(2, n + 1):
c = a + b
print(c, end=' ')
a = b
b = c
fib(9)
|
Maximum sum increasing subsequence from a prefix and a given element after prefix is must | Python3 program to find maximum sum increasing subsequence till i - th index and including k - th index . ; Initializing the first row of the dp [ ] [ ] ; Creating the dp [ ] [ ] matrix . ; To calculate for i = 4 and k = 6. ; Dr... | def pre_compute(a, n, index, k):
"""
Maximum sum increasing subsequence from a prefix and a given element after prefix is must
"""
dp = [[0 for i in range(n)]for i in range(n)]
for i in range(n):
if a[i] > a[0]:
dp[0][i] = a[i] + a[0]
else:
dp[0][i] = a[i]
... |
Longest Common Substring ( Space optimized DP solution ) | Space optimized Python3 implementation of longest common substring . ; Function to find longest common substring . ; Find length of both the strings . ; Variable to store length of longest common substring . ; Matrix to store result of two consecutive rows at a... | import numpy as np
def lc_sub_str(X, Y):
"""
Longest Common Substring ( Space optimized DP solution )
"""
m = len(X)
n = len(Y)
result = 0
len_mat = np.zeros((2, n))
currRow = 0
for i in range(m):
for j in range(n):
if (i == 0 j == 0):
len_mat[cu... |
Minimal moves to form a string by adding characters or appending string itself | Python program to print the Minimal moves to form a string by appending string and adding characters ; function to return the minimal number of moves ; initializing dp [ i ] to INT_MAX ; initialize both strings to null ; base case ; check ... | INT_MAX = 100000000
def minimal_steps(s, n):
"""
Minimal moves to form a string by adding characters or appending string itself
"""
dp = [INT_MAX for i in range(n)]
s1 = ""
s2 = ""
dp[0] = 1
s1 += s[0]
for i in range(1, n):
s1 += s[i]
s2 = s[i + 1:i + 1 + i + 1]
... |
Check if any valid sequence is divisible by M | Function to check if any valid sequence is divisible by M ; DEclare mod array ; Calculate the mod array ; Check if sum is divisible by M ; Check if sum is not divisible by 2 ; Remove the first element from the ModArray since it is not possible to place minus on the first ... | def func(n, m, A):
"""
Check if any valid sequence is divisible by M
"""
ModArray = [0] * n
Sum = 0
for i in range(n):
ModArray[i] = A[i] % m
Sum += ModArray[i]
Sum = Sum % m
if (Sum % m == 0):
print("True")
return
if (Sum % 2 != 0):
print("Fal... |
Golomb sequence | Print the first n term of Golomb Sequence ; base cases ; Finding and pring first n terms of Golomb Sequence . ; Driver Code | def golomb(n):
"""
golomb sequence
"""
dp = [0] * (n + 1)
dp[1] = 1
print(dp[1], end=" ")
for i in range(2, n + 1):
dp[i] = 1 + dp[i - dp[dp[i - 1]]]
print(dp[i], end=" ")
n = 9
golomb(n)
|
Balanced expressions such that given positions have opening brackets | Python 3 code to find number of ways of arranging bracket with proper expressions ; function to calculate the number of proper bracket sequence ; hash array to mark the positions of opening brackets ; dp 2d array ; mark positions in hash array ; fir... | N = 1000
def arrange_braces(n, pos, k):
"""
Balanced expressions such that given positions have opening brackets
"""
h = [False for i in range(N)]
dp = [[0 for i in range(N)]for i in range(N)]
for i in range(k):
h[pos[i]] = 1
dp[0][0] = 1
for i in range(1, 2 * n + 1):
f... |
Maximum difference of zeros and ones in binary string | Set 2 ( O ( n ) time ) | Returns the length of substring with maximum difference of zeroes and ones in binary string ; traverse a binary string from left to right ; add current value to the current_sum according to the Character if it ' s ▁ ' 0 ' add 1 else -1 ; u... | def find_length(string, n):
"""
Maximum difference of zeros and ones in binary string
"""
current_sum = 0
max_sum = 0
for i in range(n):
current_sum += (1 if string[i] == '0'else -1)
if current_sum < 0:
current_sum = 0
max_sum = max(current_sum, max_sum)
r... |
Number of decimal numbers of length k , that are strict monotone | Python3 program to count numbers of k digits that are strictly monotone . ; DP [ i ] [ j ] is going to store monotone numbers of length i + 1 considering j + 1 digits ( 1 , 2 , 3 , . .9 ) ; Unit length numbers ; Building dp [ ] in bottom up ; Driver cod... | DP_s = 9
def get_num_strict_monotone(ln):
"""
Number of decimal numbers of length k , that are strict monotone
"""
DP = [[0] * DP_s for _ in range(ln)]
for i in range(DP_s):
DP[0][i] = i + 1
for i in range(1, ln):
for j in range(1, DP_s):
DP[i][j] = DP[i - 1][j - 1]... |
Count ways to divide circle using N non | python code to count ways to divide circle using N non - intersecting chords . ; n = no of points required ; dp array containing the sum ; returning the required number ; driver code | def chord_cnt(A):
"""
Count ways to divide circle using N non
"""
n = 2 * A
dpArray = [0] * (n + 1)
dpArray[0] = 1
dpArray[2] = 1
for i in range(4, n + 1, 2):
for j in range(0, i - 1, 2):
dpArray[i] += (dpArray[j] * dpArray[i - 2 - j])
return int(dpArray[n])
N =... |
Check for possible path in 2D matrix | Python3 program to find if there is path from top left to right bottom ; to find the path from top left to bottom right ; set arr [ 0 ] [ 0 ] = 1 ; Mark reachable ( from top left ) nodes in first row and first column . ; Mark reachable nodes in remaining matrix . ; return yes if r... | row = 5
col = 5
def is_path(arr):
"""
Check for possible path in 2D matrix
"""
arr[0][0] = 1
for i in range(1, row):
if (arr[i][0] != -1):
arr[i][0] = arr[i - 1][0]
for j in range(1, col):
if (arr[0][j] != -1):
arr[0][j] = arr[0][j - 1]
for i in rang... |
Newmanâ €“ Shanksâ €“ Williams prime | return nth NewmanaShanksaWilliams prime ; Base case ; Recursive step ; Driven Program | def nswp(n):
"""
Newmanâ €" Shanksâ €" Williams prime
"""
if n == 0 or n == 1:
return 1
return 2 * nswp(n - 1) + nswp(n - 2)
n = 3
print(nswp(n))
|
Newman Shanks Williams prime | return nth Newman Shanks Williams prime ; Base case ; Finding nth Newman Shanks Williams prime ; Driver Code | def nswp(n):
"""
Newman Shanks Williams prime
"""
dp = [1 for x in range(n + 1)]
for i in range(2, n + 1):
dp[i] = (2 * dp[i - 1] + dp[i - 2])
return dp[n]
n = 3
print(nswp(n))
|
Number of ways to insert a character to increase the LCS by one | Python Program to Number of ways to insert a character to increase LCS by one ; Return the Number of ways to insert a character to increase the Longest Common Subsequence by one ; Insert all positions of all characters in string B ; Longest Common Subseq... | MAX = 256
def numberofways(A, B, N, M):
"""
Number of ways to insert a character to increase the LCS by one
"""
pos = [[]for _ in range(MAX)]
for i in range(M):
pos[ord(B[i])].append(i + 1)
dpl = [[0] * (M + 2)for _ in range(N + 2)]
for i in range(1, N + 1):
for j in range(... |
Given a large number , check if a subsequence of digits is divisible by 8 | Function to calculate any permutation divisible by 8. If such permutation exists , the function will return that permutation else it will return - 1 ; Generating all possible permutations and checking if any such permutation is divisible by 8 ;... | def is_sub_seq_divisible(st):
"""
Given a large number , check if a subsequence of digits is divisible by 8
"""
l = len(st)
arr = [int(ch)for ch in st]
for i in range(0, l):
for j in range(i, l):
for k in range(j, l):
if (arr[i] % 8 == 0):
... |
Length of Longest Balanced Subsequence | Python3 program to find length of the longest balanced subsequence ; Considering all balanced substrings of length 2 ; Considering all other substrings ; Driver Code | def max_length(s, n):
"""
Length of Longest Balanced Subsequence
"""
dp = [[0 for i in range(n)]for i in range(n)]
for i in range(n - 1):
if (s[i] == '(' and s[i + 1] == ')'):
dp[i][i + 1] = 2
for l in range(2, n):
i = -1
for j in range(l, n):
i +=... |
Maximum sum bitonic subarray | Function to find the maximum sum bitonic subarray . ; to store the maximum sum bitonic subarray ; Find the longest increasing subarray starting at i . ; Now we know that a [ i . . j ] is an increasing subarray . Remove non - positive elements from the left side as much as possible . ; Fin... | def max_sum_bitonic_sub_arr(arr, n):
"""
Maximum sum bitonic subarray
"""
max_sum = -10 ** 9
i = 0
while (i < n):
j = i
while (j + 1 < n and arr[j] < arr[j + 1]):
j += 1
while (i < j and arr[i] <= 0):
i += 1
k = j
while (k + 1 < n a... |
Smallest sum contiguous subarray | Python program to find the smallest sum contiguous subarray ; function to find the smallest sum contiguous subarray ; to store the minimum value that is ending up to the current index ; to store the minimum value encountered so far ; traverse the array elements ; if min_ending_here > ... | import sys
def smallest_sum_subarr(arr, n):
"""
Smallest sum contiguous subarray
"""
min_ending_here = sys .maxsize
min_so_far = sys .maxsize
for i in range(n):
if (min_ending_here > 0):
min_ending_here = arr[i]
else:
min_ending_here += arr[i]
mi... |
Paper Cut into Minimum Number of Squares | Set 2 | Python3 program to find minimum number of squares to cut a paper using Dynamic Programming ; Returns min number of squares needed ; Initializing max values to vertical_min and horizontal_min ; N = 11 & M = 13 is a special case ; If the given rectangle is already a squa... | MAX = 300
dp = [[0 for i in range(MAX)]for i in range(MAX)]
def minimum_square(m, n):
"""
Paper Cut into Minimum Number of Squares
"""
vertical_min = 10000000000
horizontal_min = 10000000000
if n == 13 and m == 11:
return 6
if m == 13 and n == 11:
return 6
if m == n:
... |
Painting Fence Algorithm | Returns count of ways to color k posts using k colors ; There are k ways to color first post ; There are 0 ways for single post to violate ( same color_ and k ways to not violate ( different color ) ; Fill for 2 posts onwards ; Current same is same as previous diff ; We always have k - 1 choi... | def count_ways(n, k):
"""
Painting Fence Algorithm
"""
total = k
mod = 1000000007
same, diff = 0, k
for i in range(2, n + 1):
same = diff
diff = total * (k - 1)
diff = diff % mod
total = (same + diff) % mod
return total
if __name__ == "__main__":
n, ... |
Sum of all substrings of a string representing a number | Set 2 ( Constant Extra Space ) | Returns sum of all substring of num ; Initialize result ; Here traversing the array in reverse order . Initializing loop from last element . mf is multiplying factor . ; Each time sum is added to its previous sum . Multiplying th... | def sum_of_substrings(num):
"""
Sum of all substrings of a string representing a number
"""
sum = 0
mf = 1
for i in range(len(num) - 1, -1, -1):
sum = sum + (int(num[i])) * (i + 1) * mf
mf = mf * 10 + 1
return sum
if __name__ == '__main__':
num = "6759"
... |
Largest sum subarray with at | Returns maximum sum of a subarray with at - least k elements . ; maxSum [ i ] is going to store maximum sum till index i such that a [ i ] is part of the sum . ; We use Kadane 's algorithm to fill maxSum[] Below code is taken from method3 of https:www.geeksforgeeks.org/largest-sum-conti... | def max_sum_with_k(a, n, k):
"""
Largest sum subarray with at
"""
maxSum = [0 for i in range(n)]
maxSum[0] = a[0]
curr_max = a[0]
for i in range(1, n):
curr_max = max(a[i], curr_max + a[i])
maxSum[i] = curr_max
sum = 0
for i in range(k):
sum += a[i]
result... |
Sequences of given length where every element is more than or equal to twice of previous | Recursive function to find the number of special sequences ; A special sequence cannot exist if length n is more than the maximum value m . ; If n is 0 , found an empty special sequence ; There can be two possibilities : ( 1 ) Re... | def get_total_number_of_sequences(m, n):
"""
Sequences of given length where every element is more than or equal to twice of previous
"""
if m < n:
return 0
if n == 0:
return 1
res = (get_total_number_of_sequences(m - 1, n) +
get_total_number_of_sequences(m // 2, n - 1... |
Sequences of given length where every element is more than or equal to twice of previous | DP based function to find the number of special sequence ; define T and build in bottom manner to store number of special sequences of length n and maximum value m ; Base case : If length of sequence is 0 or maximum value is 0 , ... | def get_total_number_of_sequences(m, n):
"""
Sequences of given length where every element is more than or equal to twice of previous
"""
T = [[0 for i in range(n + 1)]for i in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
T[i][j... |
Clustering / Partitioning an array such that sum of square differences is minimum | Python3 program to find minimum cost k partitions of array . ; Returns minimum cost of partitioning a [ ] in k clusters . ; Create a dp [ ] [ ] table and initialize all values as infinite . dp [ i ] [ j ] is going to store optimal parti... | inf = 1000000000
def min_cost(a, n, k):
"""
Clustering / Partitioning an array such that sum of square differences is minimum
"""
dp = [[inf for i in range(k + 1)]for j in range(n + 1)]
dp[0][0] = 0
for i in range(1, n + 1):
for j in range(1, k + 1):
for m in range(i - 1, -... |
Temple Offerings | Returns minimum offerings required ; Go through all templs one by one ; Go to left while height keeps increasing ; Go to right while height keeps increasing ; This temple should offer maximum of two values to follow the rule . ; Driver Code | def offering_number(n, templeHeight):
"""
Temple Offerings
"""
for i in range(n):
left = 0
right = 0
for j in range(i - 1, -1, -1):
if (templeHeight[j] < templeHeight[j + 1]):
left += 1
else:
break
for j in range(i +... |
Subset with sum divisible by m | Returns true if there is a subset of arr [ ] with sum divisible by m ; This array will keep track of all the possible sum ( after modulo m ) which can be made using subsets of arr [ ] initialising boolean array with all false ; we 'll loop through all the elements of arr[] ; anytime we ... | def modular_sum(arr, n, m):
"""
Subset with sum divisible by m
"""
if (n > m):
return True
DP = [False for i in range(m)]
for i in range(n):
if (DP[0]):
return True
temp = [False for i in range(m)]
for j in range(m):
if (DP[j]):
... |
Maximum sum of a path in a Right Number Triangle | tri [ ] [ ] is a 2D array that stores the triangle , n is number of lines or rows . ; Adding the element of row 1 to both the elements of row 2 to reduce a step from the loop ; Traverse remaining rows ; Loop to traverse columns ; tri [ i ] would store the possible comb... | def max_sum(tri, n):
"""
Maximum sum of a path in a Right Number Triangle
"""
if n > 1:
tri[1][1] = tri[1][1] + tri[0][0]
tri[1][0] = tri[1][0] + tri[0][0]
for i in range(2, n):
tri[i][0] = tri[i][0] + tri[i - 1][0]
tri[i][i] = tri[i][i] + tri[i - 1][i - 1]
fo... |
Modify array to maximize sum of adjacent differences | Returns maximum - difference - sum with array modifications allowed . ; Initialize dp [ ] [ ] with 0 values . ; for [ i + 1 ] [ 0 ] ( i . e . current modified value is 1 ) , choose maximum from dp [ i ] [ 0 ] + abs ( 1 - 1 ) = dp [ i ] [ 0 ] and dp [ i ] [ 1 ] + ab... | def maximum_difference_sum(arr, N):
"""
Modify array to maximize sum of adjacent differences
"""
dp = [[0, 0]for i in range(N)]
for i in range(N):
dp[i][0] = dp[i][1] = 0
for i in range(N - 1):
dp[i + 1][0] = max(dp[i][0], dp[i][1] + abs(1 - arr[i]))
dp[i + 1][1] = max(dp... |
Count of subarrays whose maximum element is greater than k | Return number of subarrays whose maximum element is less than or equal to K . ; To store count of subarrays with all elements less than or equal to k . ; Traversing the array . ; If element is greater than k , ignore . ; Counting the subarray length whose eac... | def count_subarray(arr, n, k):
"""
Count of subarrays whose maximum element is greater than k
"""
s = 0
i = 0
while (i < n):
if (arr[i] > k):
i = i + 1
continue
count = 0
while (i < n and arr[i] <= k):
i = i + 1
count = coun... |
Maximum subsequence sum such that no three are consecutive | Python3 program to find the maximum sum such that no three are consecutive using recursion . ; Returns maximum subsequence sum such that no three elements are consecutive ; 3 Base cases ( process first three elements ) ; Process rest of the elements We have t... | arr = [100, 1000, 100, 1000, 1]
sum = [-1] * 10000
def max_sum_wo3_consec(n):
"""
Maximum subsequence sum such that no three are consecutive
"""
if (sum[n] != -1):
return sum[n]
if (n == 0):
sum[n] = 0
return sum[n]
if (n == 1):
sum[n] = arr[0]
return su... |
Maximum sum of pairs with specific difference | Method to return maximum sum we can get by finding less than K difference pairs ; Sort elements to ensure every i and i - 1 is closest possible pair ; To get maximum possible sum , iterate from largest to smallest , giving larger numbers priority over smaller numbers . ; ... | def max_sum_pair_with_difference_less_than_k(arr, N, k):
"""
Maximum sum of pairs with specific difference
"""
maxSum = 0
arr.sort()
i = N - 1
while (i > 0):
if (arr[i] - arr[i - 1] < k):
maxSum += arr[i]
maxSum += arr[i - 1]
i -= 1
i -= 1
... |
Count digit groupings of a number with given constraints | Function to find the subgroups ; Terminating Condition ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as pre... | def count_groups(position, previous_sum, length, num):
"""
Count digit groupings of a number with given constraints
"""
if (position == length):
return 1
res = 0
sum = 0
for i in range(position, length):
sum = sum + int(num[i])
if (sum >= previous_sum):
re... |
Count digit groupings of a number with given constraints | Maximum length of input number string ; A memoization table to store results of subproblems length of string is 40 and maximum sum will be 9 * 40 = 360. ; Function to find the count of splits with given condition ; Terminating Condition ; If already evaluated f... | MAX = 40
dp = [[-1 for i in range(9 * MAX + 1)]for i in range(MAX)]
def count_groups(position, previous_sum, length, num):
"""
Count digit groupings of a number with given constraints
"""
if (position == length):
return 1
if (dp[position][previous_sum] != -1):
return dp[position][p... |
A Space Optimized DP solution for 0 | val [ ] is for storing maximum profit for each weight wt [ ] is for storing weights n number of item W maximum capacity of bag dp [ W + 1 ] to store final result ; initially profit with 0 to W KnapSack capacity is 0 ; iterate through all items ; traverse dp array from right to left... | def knap_sack(val, wt, n, W):
"""
A Space Optimized DP solution for 0
"""
dp = [0] * (W + 1)
for i in range(n):
for j in range(W, wt[i], -1):
dp[j] = max(dp[j], val[i] + dp[j - wt[i]])
return dp[W]
val = [7, 8, 4]
wt = [3, 8, 6]
W = 10
n = 3
print(knap_sack(val, wt, n, W))
|
Find number of times a string occurs as a subsequence in given string | Iterative DP function to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; Create a table to store results of sub - problems ; If first string is empty ; If second string is empty ; Fill l... | def count(a, b):
"""
Find number of times a string occurs as a subsequence in given string
"""
m = len(a)
n = len(b)
lookup = [[0] * (n + 1)for i in range(m + 1)]
for i in range(n + 1):
lookup[0][i] = 0
for i in range(m + 1):
lookup[i][0] = 1
for i in range(1, m + 1):... |
Longest Geometric Progression | Returns length of the longest GP subset of sett [ ] ; Base cases ; let us sort the sett first ; An entry L [ i ] [ j ] in this table stores LLGP with sett [ i ] and sett [ j ] as first two elements of GP and j > i . ; Initialize result ( A single element is always a GP ) ; Initialize val... | def len_of_longest_gp(sett, n):
"""
Longest Geometric Progression
"""
if n < 2:
return n
if n == 2:
return 2 if (sett[1] % sett[0] == 0)else 1
sett.sort()
L = [[0 for i in range(n)]for i in range(n)]
llgp = 1
for i in range(0, n - 1):
if sett[n - 1] % sett[i] ... |
A Space Optimized Solution of LCS | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Find lengths of two strings ; Binary index , used to index current row and previous row . ; Compute current binary index ; Last filled entry contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; Driver Code | def lcs(X, Y):
"""
A Space Optimized Solution of LCS
"""
m = len(X)
n = len(Y)
L = [[0 for i in range(n + 1)]for j in range(2)]
bi = bool
for i in range(m):
bi = i & 1
for j in range(n + 1):
if (i == 0 or j == 0):
L[bi][j] = 0
elif ... |
Count number of subsets having a particular XOR value | Python 3 arr dynamic programming solution to finding the number of subsets having xor of their elements as k ; Returns count of subsets of arr [ ] with XOR value equals to k . ; Find maximum element in arr [ ] ; Maximum possible XOR value ; Initializing all the va... | import math
def subset_xor(arr, n, k):
"""
Count number of subsets having a particular XOR value
"""
max_ele = arr[0]
for i in range(1, n):
if arr[i] > max_ele:
max_ele = arr[i]
m = (1 << (int)(math.log2(max_ele) + 1)) - 1
if (k > m):
return 0
dp = [[0 for i in ... |
Partition a set into two subsets such that the difference of subset sums is minimum | A Recursive Python3 program to solve minimum sum partition problem . ; Returns the minimum value of the difference of the two sets . ; Calculate sum of all elements ; Create an 2d list to store results of subproblems ; Initialize firs... | import sys
def find_min(a, n):
"""
Partition a set into two subsets such that the difference of subset sums is minimum
"""
su = 0
su = sum(a)
dp = [[0 for i in range(su + 1)]for j in range(n + 1)]
for i in range(n + 1):
dp[i][0] = True
for j in range(1, su + 1):
dp[0][j... |
Find number of solutions of a linear equation of n variables | Recursive function that returns count of solutions for given rhs value and coefficients coeff [ stat ... end ] ; Base case ; Initialize count of solutions ; One by one subtract all smaller or equal coefficients and recur ; Driver Code | def count_sol(coeff, start, end, rhs):
"""
Find number of solutions of a linear equation of n variables
"""
if (rhs == 0):
return 1
result = 0
for i in range(start, end + 1):
if (coeff[i] <= rhs):
result += count_sol(coeff, i, end, rhs - coeff[i])
return result
... |
Minimum steps to reach a destination | python program to count number of steps to reach a point ; source -> source vertex step -> value of last step taken dest -> destination vertex ; base cases ; if we go on positive side ; if we go on negative side ; minimum of both cases ; Driver Code | import sys
def steps(source, step, dest):
"""
Minimum steps to reach a destination
"""
if (abs(source) > (dest)):
return sys .maxsize
if (source == dest):
return step
pos = steps(source + step + 1, step + 1, dest)
neg = steps(source - step - 1, step + 1, dest)
return mi... |
Longest Common Substring | DP | Function to find the length of the longest LCS ; Create DP table ; Driver Code ; Function call | def lc_sub_str(s, t, n, m):
"""
Longest Common Substring
"""
dp = [[0 for i in range(m + 1)]for j in range(2)]
res = 0
for i in range(1, n + 1):
for j in range(1, m + 1):
if (s[i - 1] == t[j - 1]):
dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1
if (... |
Longest Common Substring | DP | Returns length of function for longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Driver code | def lcs(i, j, count):
"""
Longest Common Substring
"""
if (i == 0 or j == 0):
return count
if (X[i - 1] == Y[j - 1]):
count = lcs(i - 1, j - 1, count + 1)
count = max(count, max(lcs(i, j - 1, 0), lcs(i - 1, j, 0)))
return count
if __name__ == "__main__":
X = "abcdxyz"
... |
Make Array elements equal by replacing adjacent elements with their XOR | Function to check if it is possible to make all the array elements equal using the given operation ; Stores the XOR of all elements of array A [ ] ; Case 1 , check if the XOR of the array A [ ] is 0 ; Maintains the XOR till the current element ; ... | def possible_equal_array(A, N):
"""
Make Array elements equal by replacing adjacent elements with their XOR
"""
tot_XOR = 0
for i in range(N):
tot_XOR ^= A[i]
if (tot_XOR == 0):
print("YES")
return
cur_XOR = 0
cnt = 0
for i in range(N):
cur_XOR ^= A[i]... |
Count of palindromes that can be obtained by concatenating equal length prefix and substrings | Function to calculate the number of palindromes ; Calculation of Z - array ; Calculation of sigma ( Z [ i ] + 1 ) ; return the count ; Given String | def count_palindrome(S):
"""
Count of palindromes that can be obtained by concatenating equal length prefix and substrings
"""
N = len(S)
Z = [0] * N
l = 0
r = 0
for i in range(1, N):
if i <= r:
Z[i] = min(r - i + 1, Z[i - 1])
while ((i + Z[i]) < N and (S[Z[i]... |
Extract substrings between any pair of delimiters | Function to print strings present between any pair of delimeters ; Stores the indices ; If opening delimeter is encountered ; If closing delimeter is encountered ; Extract the position of opening delimeter ; Length of substring ; Extract the substring ; Driver Code | def print_subs_in_delimeters(string):
"""
Extract substrings between any pair of delimiters
"""
dels = []
for i in range(len(string)):
if (string[i] == '['):
dels.append(i)
elif (string[i] == ']' and len(dels) != 0):
pos = dels[-1]
dels.pop()
... |
Print matrix elements from top | Function to traverse the matrix diagonally upwards ; Store the number of rows ; Initialize queue ; Push the index of first element i . e . , ( 0 , 0 ) ; Get the front element ; Pop the element at the front ; Insert the element below if the current element is in first column ; Insert the... | def print_diagonal_traversal(nums):
"""
Print matrix elements from top
"""
m = len(nums)
q = []
q.append([0, 0])
while (len(q) != 0):
p = q[0]
q.pop(0)
print(nums[p[0]][p[1]], end=" ")
if (p[1] == 0 and p[0] + 1 < m):
q.append([p[0] + 1, p[1]])
... |
Check if a number starts with another number or not | Function to check if B is a prefix of A or not ; Convert numbers into strings ; Find the length of s1 and s2 ; Base case ; Traverse the string s1 and s2 ; If at any index characters are unequal then return False ; Return true ; Driver code ; Given numbers ; Function... | def checkprefix(A, B):
"""
Check if a number starts with another number or not
"""
s1 = str(A)
s2 = str(B)
n1 = len(s1)
n2 = len(s2)
if n1 < n2:
return False
for i in range(0, n2):
if s1[i] != s2[i]:
return False
return True
if __name__ == '__main__'... |
Check if it is possible to reach ( x , y ) from origin in exactly Z steps using only plus movements | Function to check if it is possible to reach ( x , y ) from origin in exactly z steps ; Condition if we can 't reach in Z steps ; Driver Code ; Destination pocoordinate ; Number of steps allowed ; Function call | def possible_to_reach(x, y, z):
"""
Check if it is possible to reach ( x , y ) from origin in exactly Z steps using only plus movements
"""
if (z < abs(x) + abs(y) or (z - abs(x) - abs(y)) % 2):
print("Not Possible")
else:
print("Possible")
if __name__ == '__main__':
x = 5
... |
Number of cycles in a Polygon with lines from Centroid to Vertices | Function to find the Number of Cycles ; Driver code | def n_cycle(N):
"""
Number of cycles in a Polygon with lines from Centroid to Vertices
"""
return (N) * (N - 1) + 1
N = 4
print(n_cycle(N))
|
Count of total Heads and Tails after N flips in a coin | Function to find count of head and tail ; Check if initially all the coins are facing towards head ; Check if initially all the coins are facing towards tail ; Driver Code | import math
def count_ht(s, N):
"""
Count of total Heads and Tails after N flips in a coin
"""
if s == "H":
h = math.floor(N / 2)
t = math.ceil(N / 2)
elif s == "T":
h = math.ceil(N / 2)
t = math.floor(N / 2)
return [h, t]
if __name__ == "__main__":
C = "H... |
Find Nth term of the series 2 , 3 , 10 , 15 , 26. ... | Function to find Nth term ; Nth term ; Driver Method | def nth_term(N):
"""
Find Nth term of the series 2 , 3 , 10 , 15 , 26. ...
"""
nth = 0
if (N % 2 == 1):
nth = (N * N) + 1
else:
nth = (N * N) - 1
return nth
if __name__ == "__main__":
N = 5
print(nth_term(N))
|
Find the Nth term in series 12 , 35 , 81 , 173 , 357 , ... | Function to find Nth term ; Nth term ; Driver Method | def nth_term(N):
"""
Find the Nth term in series 12 , 35 , 81 , 173 , 357 , ...
"""
nth = 0
first_term = 12
nth = (first_term * (pow(2, N - 1))) + 11 * ((pow(2, N - 1)) - 1)
return nth
if __name__ == "__main__":
N = 5
print(nth_term(N))
|
Find Nth term of the series 4 , 2 , 2 , 3 , 6 , ... | Function to find Nth term ; Nth term ; Driver code | def nth_term(N):
"""
Find Nth term of the series 4 , 2 , 2 , 3 , 6 , ...
"""
nth = 0
first_term = 4
pi = 1
po = 1
n = N
while (n > 1):
pi *= n - 1
n -= 1
po *= 2
nth = (first_term * pi) // po
return nth
if __name__ == "__main__":
N = 5
print(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.