text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Minimum count of indices to be skipped for every index of Array to keep sum till that index at most T | Function to calculate minimum indices to be skipped so that sum till i remains smaller than T ; Store the sum of all indices before i ; Store the elements that can be skipped ; Traverse the array , A [ ] ; Store the total sum of elements that needs to be skipped ; Store the number of elements need to be removed ; Traverse from the back of map so as to take bigger elements first ; Update sum ; Update map with the current element ; Driver code ; Given Input ; Function Call
def skipIndices ( N , T , arr ) : NEW_LINE INDENT sum = 0 NEW_LINE count = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT d = sum + arr [ i ] - T NEW_LINE k = 0 NEW_LINE if ( d > 0 ) : NEW_LINE INDENT for u in list ( count . keys ( ) ) [ : : - 1 ] : NEW_LINE INDENT j = u NEW_LINE x = j * count [ j ] NEW_LINE if ( d <= x ) : NEW_LINE INDENT k += ( d + j - 1 ) // j NEW_LINE break NEW_LINE DEDENT k += count [ j ] NEW_LINE d -= x NEW_LINE DEDENT DEDENT sum += arr [ i ] NEW_LINE count [ arr [ i ] ] = count . get ( arr [ i ] , 0 ) + 1 NEW_LINE print ( k , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE T = 15 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] NEW_LINE skipIndices ( N , T , arr ) NEW_LINE DEDENT
Count triplets ( a , b , c ) such that a + b , b + c and a + c are all divisible by K | Set 2 | Function to count the number of triplets from the range [ 1 , N - 1 ] having sum of all pairs divisible by K ; If K is even ; Otherwise ; Driver Code
def countTriplets ( N , K ) : NEW_LINE INDENT if ( K % 2 == 0 ) : NEW_LINE INDENT x = N // K NEW_LINE y = ( N + ( K // 2 ) ) // K NEW_LINE return x * x * x + y * y * y NEW_LINE DEDENT else : NEW_LINE INDENT x = N // K NEW_LINE return x * x * x NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE K = 2 NEW_LINE print ( countTriplets ( N , K ) ) NEW_LINE DEDENT
Maximize count of 3 | Function to count the maximum number of palindrome subsequences of length 3 considering the same index only once ; Index of the S ; Stores the frequency of every character ; Stores the pair of frequency containing same characters ; Number of subsequences having length 3 ; Counts the frequency ; Counts the pair of frequency ; Returns the minimum value ; Driver Code
def maxNumPalindrome ( S ) : NEW_LINE INDENT i = 0 NEW_LINE freq = [ 0 ] * 26 NEW_LINE freqPair = 0 NEW_LINE ln = len ( S ) // 3 NEW_LINE while ( i < len ( S ) ) : NEW_LINE INDENT freq [ ord ( S [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE i += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT freqPair += ( freq [ i ] // 2 ) NEW_LINE DEDENT return min ( freqPair , ln ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " geeksforg " NEW_LINE print ( maxNumPalindrome ( S ) ) NEW_LINE DEDENT
Minimum Bipartite Groups | ''Function to find the height sizeof the current component with vertex s ; Visit the current Node ; Call DFS recursively to find the maximum height of current CC ; If the node is not visited then the height recursively for next element ; Function to find the minimum Groups ; Initialise with visited array ; To find the minimum groups ; Traverse all the non visited Node and calculate the height of the tree with current node as a head ; If the current is not visited therefore , we get another CC ; Return the minimum bipartite matching ; Function that adds the current edges in the given graph ; Driver code ; Adjacency List ; Adding edges to List
import sys NEW_LINE def height ( s , adj , visited ) : NEW_LINE INDENT visited [ s ] = 1 NEW_LINE h = 0 NEW_LINE for child in adj [ s ] : NEW_LINE INDENT if ( visited [ child ] == 0 ) : NEW_LINE INDENT h = max ( h , 1 + height ( child , adj , visited ) ) NEW_LINE DEDENT DEDENT return h NEW_LINE DEDENT def minimumGroups ( adj , N ) : NEW_LINE INDENT visited = [ 0 for i in range ( N + 1 ) ] NEW_LINE groups = - sys . maxsize NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( visited [ i ] == 0 ) : NEW_LINE INDENT comHeight = height ( i , adj , visited ) NEW_LINE groups = max ( groups , comHeight ) NEW_LINE DEDENT DEDENT return groups NEW_LINE DEDENT def addEdge ( adj , u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE adj = [ [ ] for i in range ( N + 1 ) ] NEW_LINE addEdge ( adj , 1 , 2 ) NEW_LINE addEdge ( adj , 3 , 2 ) NEW_LINE addEdge ( adj , 4 , 3 ) NEW_LINE print ( minimumGroups ( adj , N ) ) NEW_LINE DEDENT
Sum of subsets of all the subsets of an array | O ( 2 ^ N ) | store the answer ; Function to sum of all subsets of a given array ; Function to generate the subsets ; Base - case ; Finding the sum of all the subsets of the generated subset ; Recursively accepting and rejecting the current number ; Driver code
c = [ ] NEW_LINE ans = 0 NEW_LINE def subsetSum ( ) : NEW_LINE INDENT global ans NEW_LINE L = len ( c ) NEW_LINE mul = pow ( 2 , L - 1 ) NEW_LINE i = 0 NEW_LINE while ( i < len ( c ) ) : NEW_LINE INDENT ans += c [ i ] * mul NEW_LINE i += 1 NEW_LINE DEDENT DEDENT def subsetGen ( arr , i , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT subsetSum ( ) NEW_LINE return NEW_LINE DEDENT subsetGen ( arr , i + 1 , n ) NEW_LINE c . append ( arr [ i ] ) NEW_LINE subsetGen ( arr , i + 1 , n ) NEW_LINE c . pop ( ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE subsetGen ( arr , 0 , n ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Find the maximum possible value of a [ i ] % a [ j ] over all pairs of i and j | Function that returns the second largest element in the array if exists , else 0 ; There must be at least two elements ; To store the maximum and the second maximum element from the array ; If current element is greater than first then update both first and second ; If arr [ i ] is in between first and second then update second ; No second maximum found ; Driver code
def getMaxValue ( arr , arr_size ) : NEW_LINE INDENT if ( arr_size < 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT first = - sys . maxsize - 1 NEW_LINE second = - sys . maxsize - 1 NEW_LINE for i in range ( arr_size ) : NEW_LINE INDENT if ( arr [ i ] > first ) : NEW_LINE INDENT second = first NEW_LINE first = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > second and arr [ i ] != first ) : NEW_LINE INDENT second = arr [ i ] NEW_LINE DEDENT DEDENT if ( second == - sys . maxsize - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return second NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 5 , 1 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( getMaxValue ( arr , n ) ) NEW_LINE DEDENT
Maximize the value of the given expression | Function to return the maximum result ; To store the count of negative integers ; Sum of all the three integers ; Product of all the three integers ; To store the smallest and the largest among all the three integers ; Calculate the count of negative integers ; When all three are positive integers ; For single negative integer ; For two negative integers ; For three negative integers ; Driver Code
def maximumResult ( a , b , c ) : NEW_LINE INDENT countOfNegative = 0 NEW_LINE Sum = a + b + c NEW_LINE product = a * b * c NEW_LINE largest = max ( a , b , c ) NEW_LINE smallest = min ( a , b , c ) NEW_LINE if a < 0 : NEW_LINE INDENT countOfNegative += 1 NEW_LINE DEDENT if b < 0 : NEW_LINE INDENT countOfNegative += 1 NEW_LINE DEDENT if c < 0 : NEW_LINE INDENT countOfNegative += 1 NEW_LINE DEDENT if countOfNegative == 0 : NEW_LINE INDENT return ( Sum - largest ) * largest NEW_LINE DEDENT elif countOfNegative == 1 : NEW_LINE INDENT return ( product // smallest ) + smallest NEW_LINE DEDENT elif countOfNegative == 2 : NEW_LINE INDENT return ( product // largest ) + largest NEW_LINE DEDENT elif countOfNegative == 3 : NEW_LINE INDENT return ( Sum - smallest ) * smallest NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a , b , c = - 2 , - 1 , - 4 NEW_LINE print ( maximumResult ( a , b , c ) ) NEW_LINE DEDENT
Maximum students to pass after giving bonus to everybody and not exceeding 100 marks | Function to return the number of students that can pass ; maximum marks ; maximum bonus marks that can be given ; counting the number of students that can pass ; Driver code
def check ( n , marks ) : NEW_LINE INDENT x = max ( marks ) NEW_LINE bonus = 100 - x NEW_LINE c = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( marks [ i ] + bonus >= 50 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT return c NEW_LINE DEDENT n = 5 NEW_LINE marks = [ 0 , 21 , 83 , 45 , 64 ] NEW_LINE print ( check ( n , marks ) ) NEW_LINE
Sum of first N natural numbers which are not powers of K | Function to return the sum of first n natural numbers which are not positive powers of k ; sum of first n natural numbers ; subtract all positive powers of k which are less than n ; next power of k ; Driver code
def find_sum ( n , k ) : NEW_LINE INDENT total_sum = ( n * ( n + 1 ) ) // 2 NEW_LINE power = k NEW_LINE while power <= n : NEW_LINE INDENT total_sum -= power NEW_LINE power *= k NEW_LINE DEDENT return total_sum NEW_LINE DEDENT n = 11 ; k = 2 NEW_LINE print ( find_sum ( n , k ) ) NEW_LINE
Minimum number of operations required to delete all elements of the array | Python 3 implementation of the above approach ; function to find minimum operations ; sort array ; prepare hash of array ; Driver Code
MAX = 10000 NEW_LINE hashTable = [ 0 ] * MAX NEW_LINE def minOperations ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT hashTable [ arr [ i ] ] += 1 NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( hashTable [ arr [ i ] ] ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if ( arr [ j ] % arr [ i ] == 0 ) : NEW_LINE INDENT hashTable [ arr [ j ] ] = 0 NEW_LINE DEDENT DEDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 6 , 2 , 8 , 7 , 21 , 24 , 49 , 44 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minOperations ( arr , n ) ) NEW_LINE DEDENT
Sorting array with reverse around middle | Python 3 program to find possibility to sort by multiple subarray reverse operarion ; making the copy of the original array ; sorting the copied array ; checking mirror image of elements of sorted copy array and equivalent element of original array ; Driver code
def ifPossible ( arr , n ) : NEW_LINE INDENT cp = [ 0 ] * n NEW_LINE cp = arr NEW_LINE cp . sort ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( not ( arr [ i ] == cp [ i ] ) and not ( arr [ n - 1 - i ] == cp [ i ] ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 1 , 7 , 6 , 4 , 5 , 3 , 2 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE if ( ifPossible ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Program for Shortest Job First ( SJF ) scheduling | Set 2 ( Preemptive ) | Function to find the waiting time for all processes ; Copy the burst time into rt [ ] ; Process until all processes gets completed ; Find process with minimum remaining time among the processes that arrives till the current time ` ; Reduce remaining time by one ; Update minimum ; If a process gets completely executed ; Increment complete ; Find finish time of current process ; Calculate waiting time ; Increment time ; Function to calculate turn around time ; Calculating turnaround time ; Function to calculate average waiting and turn - around times . ; Function to find waiting time of all processes ; Function to find turn around time for all processes ; Display processes along with all details ; Driver code ; Process id 's
def findWaitingTime ( processes , n , wt ) : NEW_LINE INDENT rt = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT rt [ i ] = processes [ i ] [ 1 ] NEW_LINE DEDENT complete = 0 NEW_LINE t = 0 NEW_LINE minm = 999999999 NEW_LINE short = 0 NEW_LINE check = False NEW_LINE while ( complete != n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ( processes [ j ] [ 2 ] <= t ) and ( rt [ j ] < minm ) and rt [ j ] > 0 ) : NEW_LINE INDENT minm = rt [ j ] NEW_LINE short = j NEW_LINE check = True NEW_LINE DEDENT DEDENT if ( check == False ) : NEW_LINE INDENT t += 1 NEW_LINE continue NEW_LINE DEDENT rt [ short ] -= 1 NEW_LINE minm = rt [ short ] NEW_LINE if ( minm == 0 ) : NEW_LINE INDENT minm = 999999999 NEW_LINE DEDENT if ( rt [ short ] == 0 ) : NEW_LINE INDENT complete += 1 NEW_LINE check = False NEW_LINE fint = t + 1 NEW_LINE wt [ short ] = ( fint - proc [ short ] [ 1 ] - proc [ short ] [ 2 ] ) NEW_LINE if ( wt [ short ] < 0 ) : NEW_LINE INDENT wt [ short ] = 0 NEW_LINE DEDENT DEDENT t += 1 NEW_LINE DEDENT DEDENT def findTurnAroundTime ( processes , n , wt , tat ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT tat [ i ] = processes [ i ] [ 1 ] + wt [ i ] NEW_LINE DEDENT DEDENT def findavgTime ( processes , n ) : NEW_LINE INDENT wt = [ 0 ] * n NEW_LINE tat = [ 0 ] * n NEW_LINE findWaitingTime ( processes , n , wt ) NEW_LINE findTurnAroundTime ( processes , n , wt , tat ) NEW_LINE print ( " Processes ▁ Burst ▁ Time ▁ Waiting " , " Time ▁ Turn - Around ▁ Time " ) NEW_LINE total_wt = 0 NEW_LINE total_tat = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT total_wt = total_wt + wt [ i ] NEW_LINE total_tat = total_tat + tat [ i ] NEW_LINE print ( " ▁ " , processes [ i ] [ 0 ] , " TABSYMBOL TABSYMBOL " , processes [ i ] [ 1 ] , " TABSYMBOL TABSYMBOL " , wt [ i ] , " TABSYMBOL TABSYMBOL " , tat [ i ] ) NEW_LINE DEDENT print ( " Average waiting time = % .5 f " % ( total_wt / n ) ) NEW_LINE print ( " Average ▁ turn ▁ around ▁ time ▁ = ▁ " , total_tat / n ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT proc = [ [ 1 , 6 , 1 ] , [ 2 , 8 , 1 ] , [ 3 , 7 , 2 ] , [ 4 , 3 , 3 ] ] NEW_LINE n = 4 NEW_LINE findavgTime ( proc , n ) NEW_LINE DEDENT
Count N | Function to count N - length strings consisting of vowels only sorted lexicographically ; Initializing vector to store count of strings . ; Summing up the total number of combinations . ; Return the result ; Function Call
def findNumberOfStrings ( N ) : NEW_LINE INDENT counts = [ ] NEW_LINE for i in range ( 5 ) : NEW_LINE INDENT counts . append ( 1 ) NEW_LINE DEDENT for i in range ( 2 , N + 1 ) : NEW_LINE INDENT for j in range ( 3 , - 1 , - 1 ) : NEW_LINE INDENT counts [ j ] += counts [ j + 1 ] NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for c in counts : NEW_LINE INDENT ans += c NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 2 NEW_LINE print ( findNumberOfStrings ( N ) ) NEW_LINE
Count N | Stores the value of overlapping states ; Function to check whether a number have only digits X or Y or not ; Until sum is positive ; If any digit is not X or Y then return 0 ; Return 1 ; Function to find the count of numbers that are formed by digits X and Y and whose sum of digit also have digit X or Y ; Initialize dp array ; Base Case ; Check if sum of digits formed by only X or Y ; Return the already computed ; Place the digit X at the current position ; Place the digit Y at the current position ; Update current state result ; Driver Code ; Function Call
dp = [ [ - 1 for x in range ( 9000 + 5 ) ] for y in range ( 1000 + 5 ) ] NEW_LINE mod = 1000000007 NEW_LINE def check ( sum , x , y ) : NEW_LINE INDENT while ( sum > 0 ) : NEW_LINE INDENT ln = sum % 10 NEW_LINE if ( ln != x and ln != y ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT sum //= 10 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def countNumbers ( n , x , y , sum ) : NEW_LINE INDENT global dp NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return check ( sum , x , y ) NEW_LINE DEDENT if ( dp [ n ] [ sum ] != - 1 ) : NEW_LINE INDENT return dp [ n ] [ sum ] % mod NEW_LINE DEDENT option1 = countNumbers ( n - 1 , x , y , sum + x ) % mod NEW_LINE option2 = countNumbers ( n - 1 , x , y , sum + y ) % mod NEW_LINE dp [ n ] [ sum ] = ( option1 + option2 ) % mod NEW_LINE return dp [ n ] [ sum ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE X = 1 NEW_LINE Y = 5 NEW_LINE print ( countNumbers ( N , X , Y , 0 ) % mod ) NEW_LINE DEDENT
Minimum cost to generate any permutation of the given string | Function to find the minimum cost to form any permutation of string s ; Base Case ; Return the precomputed state ; Iterate over the string and check all possible characters available for current position ; Check if character can be placed at current position ; As there is no previous character so the cost for 1 st character is 0 ; Find the cost of current character and move to next position ; Store the answer for each current state ; Function that returns True if the current bit is set ; Function that generates any permutation of the given string with minimum cost ; Initialize dp table ; Set all the bits of the current character id ; Minimum cost of generating the permutation ; Driver Code ; Function Call
def solve ( a , s , n , prev , mask , dp ) : NEW_LINE INDENT if ( mask == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ mask ] [ prev + 1 ] != - 1 ) : NEW_LINE INDENT return dp [ mask ] [ prev + 1 ] ; NEW_LINE DEDENT ans = 10000 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT id = ord ( s [ i ] ) - ord ( ' a ' ) ; NEW_LINE if ( check ( mask , id ) ) : NEW_LINE INDENT if ( prev == - 1 ) : NEW_LINE INDENT ans = min ( ans , solve ( a , s , n , id , mask ^ ( 1 << id ) , dp ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT ans = min ( ans , a [ prev ] [ id ] + solve ( a , s , n , id , mask ^ ( 1 << id ) , dp ) ) ; NEW_LINE DEDENT DEDENT DEDENT dp [ mask ] [ prev + 1 ] = ans ; NEW_LINE return ans ; NEW_LINE DEDENT def check ( mask , i ) : NEW_LINE INDENT c = ( mask & ( 1 << i ) ) ; NEW_LINE return c != 0 ; NEW_LINE DEDENT def generatePermutation ( mask , n , a , s ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( n + 5 ) ] for j in range ( ( 1 << n ) + 5 ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT id = ord ( s [ i ] ) - ord ( ' a ' ) ; NEW_LINE mask |= ( 1 << id ) ; NEW_LINE DEDENT print ( solve ( a , s , n , - 1 , mask , dp ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE str = " abcde " ; NEW_LINE mat = [ [ 0 , 5 , 1 , 5 , 3 ] , [ 4 , 0 , 9 , 4 , 2 ] , [ 7 , 9 , 0 , 10 , 7 ] , [ 1 , 2 , 8 , 0 , 2 ] , [ 3 , 9 , 7 , 7 , 0 ] ] ; NEW_LINE generatePermutation ( 0 , N , mat , str ) ; NEW_LINE DEDENT
Minimize Cost to reduce the Array to a single element by given operations | Python3 program for the above approach ; Function to minimize the cost to add the array elements to a single element ; Check if the value is already stored in the array ; Compute left subproblem ; Compute left subproblem ; Calculate minimum cost ; Store the answer to avoid recalculation ; Function to generate the cost using Prefix Sum Array technique ; Function to combine the sum of the two subproblems ; Driver Code ; Initialise dp array ; Preprocessing the array
inf = 10000000 NEW_LINE def minCost ( a , i , j , k , prefix , dp ) : NEW_LINE INDENT if ( i >= j ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT best_cost = inf NEW_LINE for pos in range ( i , j ) : NEW_LINE INDENT left = minCost ( a , i , pos , k , prefix , dp ) NEW_LINE right = minCost ( a , pos + 1 , j , k , prefix , dp ) NEW_LINE best_cost = min ( best_cost , left + right + ( k * Combine ( prefix , i , j ) ) ) NEW_LINE DEDENT dp [ i ] [ j ] = best_cost NEW_LINE return dp [ i ] [ j ] NEW_LINE DEDENT def preprocess ( a , n ) : NEW_LINE INDENT p = [ 0 ] * n NEW_LINE p [ 0 ] = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT p [ i ] = p [ i - 1 ] + a [ i ] NEW_LINE DEDENT return p NEW_LINE DEDENT def Combine ( p , i , j ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT return p [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT return p [ j ] - p [ i - 1 ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE a = [ 4 , 5 , 6 , 7 ] NEW_LINE k = 3 NEW_LINE dp = [ [ - 1 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE prefix = preprocess ( a , n ) NEW_LINE print ( minCost ( a , 0 , n - 1 , k , prefix , dp ) ) NEW_LINE DEDENT
Minimize operations required to obtain N | ''Function to find the minimum number of operations ; Storing the minimum operations to obtain all numbers up to N ; Initial state ; Iterate for the remaining numbers ; If the number can be obtained by multiplication by 2 ; If the number can be obtained by multiplication by 3 ; Obtaining the number by adding 1 ; Return the minimum operations to obtain n ; Driver code
import NEW_LINE def minOperations ( n ) : NEW_LINE INDENT dp = [ sys . maxsize ] * ( n + 1 ) NEW_LINE dp [ 1 ] = 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT x = dp [ i // 2 ] NEW_LINE if x + 1 < dp [ i ] : NEW_LINE INDENT dp [ i ] = x + 1 NEW_LINE DEDENT DEDENT if i % 3 == 0 : NEW_LINE INDENT x = dp [ i // 3 ] NEW_LINE if x + 1 < dp [ i ] : NEW_LINE INDENT dp [ i ] = x + 1 NEW_LINE DEDENT DEDENT x = dp [ i - 1 ] NEW_LINE if x + 1 < dp [ i ] : NEW_LINE INDENT dp [ i ] = x + 1 NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT n = 15 NEW_LINE print ( minOperations ( n ) ) NEW_LINE
Longest Reverse Bitonic Sequence | Function to return the length of the Longest Reverse Bitonic Subsequence in the array ; Allocate memory for LIS [ ] and initialize LIS values as 1 for all indexes ; Compute LIS values from left to right ; Allocate memory for LDS and initialize LDS values for all indexes ; Compute LDS values from right to left Loop from n - 2 downto 0 ; Loop from n - 1 downto i - 1 ; Return the maximum value of ( lis [ i ] + lds [ i ] - 1 ) ; Driver code
def ReverseBitonic ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE lds = [ 1 for i in range ( N + 1 ) ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 0 , i ) : NEW_LINE INDENT if ( ( arr [ i ] < arr [ j ] ) and ( lds [ i ] < lds [ j ] + 1 ) ) : NEW_LINE INDENT lds [ i ] = lds [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT lis = [ 1 for i in range ( N + 1 ) ] NEW_LINE for i in reversed ( range ( N - 1 ) ) : NEW_LINE INDENT for j in reversed ( range ( i - 1 , N ) ) : NEW_LINE INDENT if ( arr [ i ] < arr [ j ] and lis [ i ] < lis [ j ] + 1 ) : NEW_LINE INDENT lis [ i ] = lis [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT maximum = lis [ 0 ] + lds [ 0 ] - 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT maximum = max ( ( lis [ i ] + lds [ i ] - 1 ) , maximum ) NEW_LINE DEDENT return maximum NEW_LINE DEDENT arr = [ 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 ] NEW_LINE print ( " Length ▁ of ▁ LBS ▁ is " , ReverseBitonic ( arr ) ) NEW_LINE
Maze With N doors and 1 Key | Recursive function to check whether there is a path from the top left cell to the bottom right cell of the maze ; Check whether the current cell is within the maze ; If key is required to move further ; If the key hasn 't been used before ; If current cell is the destination ; Either go down or right ; Key has been used before ; If current cell is the destination ; Either go down or right ; Driver code ; If there is a path from the cell ( 0 , 0 )
def findPath ( maze , xpos , ypos , key ) : NEW_LINE INDENT if xpos < 0 or xpos >= len ( maze ) or ypos < 0 or ypos >= len ( maze ) : NEW_LINE INDENT return False NEW_LINE DEDENT if maze [ xpos ] [ ypos ] == '1' : NEW_LINE INDENT if key == True : NEW_LINE INDENT if xpos == len ( maze ) - 1 and ypos == len ( maze ) - 1 : NEW_LINE INDENT return True NEW_LINE DEDENT return findPath ( maze , xpos + 1 , ypos , False ) or findPath ( maze , xpos , ypos + 1 , False ) NEW_LINE DEDENT return False NEW_LINE DEDENT if xpos == len ( maze ) - 1 and ypos == len ( maze ) - 1 : NEW_LINE INDENT return True NEW_LINE DEDENT return findPath ( maze , xpos + 1 , ypos , key ) or findPath ( maze , xpos , ypos + 1 , key ) NEW_LINE DEDENT def mazeProb ( maze , xpos , ypos ) : NEW_LINE INDENT key = True NEW_LINE if findPath ( maze , xpos , ypos , key ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT maze = [ [ '0' , '0' , '1' ] , [ '1' , '0' , '1' ] , [ '1' , '1' , '0' ] ] NEW_LINE n = len ( maze ) NEW_LINE if mazeProb ( maze , 0 , 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Minimum cost to reach end of array array when a maximum jump of K index is allowed | Python 3 implementation of the approach ; Function to return the minimum cost to reach the last index ; If we reach the last index ; Already visited state ; Initially maximum ; Visit all possible reachable index ; If inside range ; We cannot move any further ; Memoize ; Driver Code
import sys NEW_LINE def FindMinimumCost ( ind , a , n , k , dp ) : NEW_LINE INDENT if ( ind == ( n - 1 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( dp [ ind ] != - 1 ) : NEW_LINE INDENT return dp [ ind ] NEW_LINE DEDENT else : NEW_LINE INDENT ans = sys . maxsize NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT if ( ind + i < n ) : NEW_LINE INDENT ans = min ( ans , abs ( a [ ind + i ] - a [ ind ] ) + FindMinimumCost ( ind + i , a , n , k , dp ) ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT dp [ ind ] = ans NEW_LINE return ans NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 10 , 30 , 40 , 50 , 20 ] NEW_LINE k = 3 NEW_LINE n = len ( a ) NEW_LINE dp = [ - 1 for i in range ( n ) ] NEW_LINE print ( FindMinimumCost ( 0 , a , n , k , dp ) ) NEW_LINE DEDENT
Sum of all even factors of numbers in the range [ l , r ] | Function to calculate the prefix sum of all the even factors ; Add i to all the multiples of i ; Update the prefix sum ; Function to return the sum of all the even factors of the numbers in the given range ; Driver code
def sieve_modified ( ) : NEW_LINE INDENT for i in range ( 2 , MAX , 2 ) : NEW_LINE INDENT for j in range ( i , MAX , i ) : NEW_LINE INDENT prefix [ j ] += i NEW_LINE DEDENT DEDENT for i in range ( 1 , MAX ) : NEW_LINE INDENT prefix [ i ] += prefix [ i - 1 ] NEW_LINE DEDENT DEDENT def sumEvenFactors ( L , R ) : NEW_LINE INDENT return ( prefix [ R ] - prefix [ L - 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT MAX = 100000 NEW_LINE prefix = [ 0 ] * MAX NEW_LINE sieve_modified ( ) NEW_LINE l , r = 6 , 10 NEW_LINE print ( sumEvenFactors ( l , r ) ) NEW_LINE DEDENT
Count of numbers between range having only non | Function to return the count of required numbers from 0 to num ; Last position ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current digit is zero and nonz is 1 , we can 't place it ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver code ; n is the sum of digits and number should be divisible by m ; States - position , sum , rem , tight sum can have values upto 162 , if we are dealing with numbers upto 10 ^ 18 when all 18 digits are 9 , then sum is 18 * 9 = 162
def count ( pos , Sum , rem , tight , nonz , num ) : NEW_LINE INDENT if pos == len ( num ) : NEW_LINE INDENT if rem == 0 and Sum == n : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if dp [ pos ] [ Sum ] [ rem ] [ tight ] != - 1 : NEW_LINE INDENT return dp [ pos ] [ Sum ] [ rem ] [ tight ] NEW_LINE DEDENT ans = 0 NEW_LINE if tight : NEW_LINE INDENT limit = 9 NEW_LINE DEDENT else : NEW_LINE INDENT limit = num [ pos ] NEW_LINE DEDENT for d in range ( 0 , limit + 1 ) : NEW_LINE INDENT if d == 0 and nonz : NEW_LINE INDENT continue NEW_LINE DEDENT currSum = Sum + d NEW_LINE currRem = ( rem * 10 + d ) % m NEW_LINE currF = int ( tight or ( d < num [ pos ] ) ) NEW_LINE ans += count ( pos + 1 , currSum , currRem , currF , nonz or d , num ) NEW_LINE DEDENT dp [ pos ] [ Sum ] [ rem ] [ tight ] = ans NEW_LINE return ans NEW_LINE DEDENT def solve ( x ) : NEW_LINE INDENT num = [ ] NEW_LINE global dp NEW_LINE while x > 0 : NEW_LINE INDENT num . append ( x % 10 ) NEW_LINE x //= 10 NEW_LINE DEDENT num . reverse ( ) NEW_LINE dp = [ [ [ [ - 1 , - 1 ] for i in range ( M ) ] for j in range ( 165 ) ] for k in range ( M ) ] NEW_LINE return count ( 0 , 0 , 0 , 0 , 0 , num ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L , R = 1 , 100 NEW_LINE n , m , M = 8 , 2 , 20 NEW_LINE dp = [ ] NEW_LINE print ( solve ( R ) - solve ( L ) ) NEW_LINE DEDENT
Count of Numbers in Range where the number does not contain more than K non zero digits | This function returns the count of required numbers from 0 to num ; Last position ; If count of non zero digits is less than or equal to K ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current digit is nonzero increment currCnt ; At this position , number becomes smaller ; Next recursive call ; This function converts a number into its digit vector and uses above function to compute the answer ; Initialize dp ; Driver Code ; states - position , count , tight ; K is the number of non zero digits
def countInRangeUtil ( pos , cnt , tight , num ) : NEW_LINE INDENT if pos == len ( num ) : NEW_LINE INDENT if cnt <= K : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if dp [ pos ] [ cnt ] [ tight ] != - 1 : NEW_LINE INDENT return dp [ pos ] [ cnt ] [ tight ] NEW_LINE DEDENT ans = 0 NEW_LINE limit = 9 if tight else num [ pos ] NEW_LINE for dig in range ( limit + 1 ) : NEW_LINE INDENT currCnt = cnt NEW_LINE if dig != 0 : NEW_LINE INDENT currCnt += 1 NEW_LINE DEDENT currTight = tight NEW_LINE if dig < num [ pos ] : NEW_LINE INDENT currTight = 1 NEW_LINE DEDENT ans += countInRangeUtil ( pos + 1 , currCnt , currTight , num ) NEW_LINE DEDENT dp [ pos ] [ cnt ] [ tight ] = ans NEW_LINE return dp [ pos ] [ cnt ] [ tight ] NEW_LINE DEDENT def countInRange ( x ) : NEW_LINE INDENT global dp , K , M NEW_LINE num = [ ] NEW_LINE while x : NEW_LINE INDENT num . append ( x % 10 ) NEW_LINE x //= 10 NEW_LINE DEDENT num . reverse ( ) NEW_LINE dp = [ [ [ - 1 , - 1 ] for i in range ( M ) ] for j in range ( M ) ] NEW_LINE return countInRangeUtil ( 0 , 0 , 0 , num ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT dp = [ ] NEW_LINE M = 20 NEW_LINE K = 0 NEW_LINE L = 1 NEW_LINE R = 1000 NEW_LINE K = 3 NEW_LINE print ( countInRange ( R ) - countInRange ( L - 1 ) ) NEW_LINE L = 9995 NEW_LINE R = 10005 NEW_LINE K = 2 NEW_LINE print ( countInRange ( R ) - countInRange ( L - 1 ) ) NEW_LINE DEDENT
Balanced expressions such that given positions have opening brackets | Set 2 | Python3 implementation of above approach using memoization ; Open brackets at position 1 ; Function to find Number of proper bracket expressions ; If open - closed brackets < 0 ; If index reaches the end of expression ; If brackets are balanced ; If already stored in dp ; If the current index has assigned open bracket ; Move forward increasing the length of open brackets ; Move forward by inserting open as well as closed brackets on that index ; return the answer ; DP array to precompute the answer ; Calling the find function to calculate the answer
N = 1000 ; NEW_LINE dp = [ [ - 1 for x in range ( N ) ] for y in range ( N ) ] ; NEW_LINE adj = [ 1 , 0 , 0 , 0 ] ; NEW_LINE def find ( index , openbrk , n ) : NEW_LINE INDENT if ( openbrk < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( index == n ) : NEW_LINE INDENT if ( openbrk == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( dp [ index ] [ openbrk ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ openbrk ] ; NEW_LINE DEDENT if ( adj [ index ] == 1 ) : NEW_LINE INDENT dp [ index ] [ openbrk ] = find ( index + 1 , openbrk + 1 , n ) ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ index ] [ openbrk ] = ( find ( index + 1 , openbrk + 1 , n ) + find ( index + 1 , openbrk - 1 , n ) ) ; NEW_LINE DEDENT return dp [ index ] [ openbrk ] ; NEW_LINE DEDENT n = 2 ; NEW_LINE print ( find ( 0 , 0 , 2 * n ) ) ; NEW_LINE
Maximize array elements upto given number | variable to store maximum value that can be obtained . ; If entire array is traversed , then compare current value in num to overall maximum obtained so far . ; Case 1 : Subtract current element from value so far if result is greater than or equal to zero . ; Case 2 : Add current element to value so far if result is less than or equal to maxLimit . ; def to find maximum possible value that can be obtained using array elements and given number . ; variable to store current index position . ; call to utility def to find maximum possible value that can be obtained . ; Driver code
ans = 0 ; NEW_LINE def findMaxValUtil ( arr , n , num , maxLimit , ind ) : NEW_LINE INDENT global ans NEW_LINE if ( ind == n ) : NEW_LINE INDENT ans = max ( ans , num ) NEW_LINE return NEW_LINE DEDENT if ( num - arr [ ind ] >= 0 ) : NEW_LINE INDENT findMaxValUtil ( arr , n , num - arr [ ind ] , maxLimit , ind + 1 ) NEW_LINE DEDENT if ( num + arr [ ind ] <= maxLimit ) : NEW_LINE INDENT findMaxValUtil ( arr , n , num + arr [ ind ] , maxLimit , ind + 1 ) NEW_LINE DEDENT DEDENT def findMaxVal ( arr , n , num , maxLimit ) : NEW_LINE INDENT global ans NEW_LINE ind = 0 NEW_LINE findMaxValUtil ( arr , n , num , maxLimit , ind ) NEW_LINE return ans NEW_LINE DEDENT num = 1 NEW_LINE arr = [ 3 , 10 , 6 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE maxLimit = 15 NEW_LINE print ( findMaxVal ( arr , n , num , maxLimit ) ) NEW_LINE
Print equal sum sets of array ( Partition problem ) | Set 1 | Function to print the equal sum sets of the array . ; Print set 1. ; Print set 2. ; Utility function to find the sets of the array which have equal sum . ; If entire array is traversed , compare both the sums . ; If sums are equal print both sets and return true to show sets are found . ; If sums are not equal then return sets are not found . ; Add current element to set 1. ; Recursive call after adding current element to set 1. ; If this inclusion results in an equal sum sets partition then return true to show desired sets are found . ; If not then backtrack by removing current element from set1 and include it in set 2. ; Recursive call after including current element to set 2 and removing the element from set 2 if it returns False ; Return true if array arr can be partitioned into two equal sum sets or not . ; Calculate sum of elements in array . ; If sum is odd then array cannot be partitioned . ; Declare vectors to store both the sets . ; Find both the sets . ; Driver code
def printSets ( set1 , set2 ) : NEW_LINE INDENT for i in range ( 0 , len ( set1 ) ) : NEW_LINE INDENT print ( " { } ▁ " . format ( set1 [ i ] ) , end = " " ) ; NEW_LINE DEDENT print ( " " ) NEW_LINE for i in range ( 0 , len ( set2 ) ) : NEW_LINE INDENT print ( " { } ▁ " . format ( set2 [ i ] ) , end = " " ) ; NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT def findSets ( arr , n , set1 , set2 , sum1 , sum2 , pos ) : NEW_LINE INDENT if ( pos == n ) : NEW_LINE INDENT if ( sum1 == sum2 ) : NEW_LINE INDENT printSets ( set1 , set2 ) NEW_LINE return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT set1 . append ( arr [ pos ] ) NEW_LINE res = findSets ( arr , n , set1 , set2 , sum1 + arr [ pos ] , sum2 , pos + 1 ) NEW_LINE if ( res ) : NEW_LINE INDENT return res NEW_LINE DEDENT set1 . pop ( ) NEW_LINE set2 . append ( arr [ pos ] ) NEW_LINE res = findSets ( arr , n , set1 , set2 , sum1 , sum2 + arr [ pos ] , pos + 1 ) NEW_LINE if not res : NEW_LINE INDENT set2 . pop ( ) NEW_LINE DEDENT return res NEW_LINE DEDENT def isPartitionPoss ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum % 2 != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT set1 = [ ] NEW_LINE set2 = [ ] NEW_LINE return findSets ( arr , n , set1 , set2 , 0 , 0 , 0 ) NEW_LINE DEDENT arr = [ 5 , 5 , 1 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE if ( isPartitionPoss ( arr , n ) == False ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT
Maximum subarray sum in O ( n ) using prefix sum | Python3 program to find out maximum subarray sum in linear time using prefix sum . ; Function to compute maximum subarray sum in linear time . ; Initialize minimum prefix sum to 0. ; Initialize maximum subarray sum so far to - infinity . ; Initialize and compute the prefix sum array . ; loop through the array keep track of minimum prefix sum so far and maximum subarray sum . ; Test case 1 ; Test case 2
import math NEW_LINE def maximumSumSubarray ( arr , n ) : NEW_LINE INDENT min_prefix_sum = 0 NEW_LINE res = - math . inf NEW_LINE prefix_sum = [ ] NEW_LINE prefix_sum . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix_sum . append ( prefix_sum [ i - 1 ] + arr [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT res = max ( res , prefix_sum [ i ] - min_prefix_sum ) NEW_LINE min_prefix_sum = min ( min_prefix_sum , prefix_sum [ i ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr1 = [ - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE print ( maximumSumSubarray ( arr1 , n1 ) ) NEW_LINE arr2 = [ 4 , - 8 , 9 , - 4 , 1 , - 8 , - 1 , 6 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE print ( maximumSumSubarray ( arr2 , n2 ) ) NEW_LINE
Counting numbers of n digits that are monotone | Considering all possible digits as { 1 , 2 , 3 , . .9 } ; DP [ i ] [ j ] is going to store monotone numbers of length i + 1 considering j + 1 digits . ; Unit length numbers ; Single digit numbers ; Filling rest of the entries in bottom up manner . ; Driver code
DP_s = 9 NEW_LINE def getNumMonotone ( ln ) : NEW_LINE INDENT DP = [ [ 0 ] * DP_s for i in range ( ln ) ] NEW_LINE for i in range ( DP_s ) : NEW_LINE INDENT DP [ 0 ] [ i ] = i + 1 NEW_LINE DEDENT for i in range ( ln ) : NEW_LINE INDENT DP [ i ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , ln ) : NEW_LINE INDENT for j in range ( 1 , DP_s ) : NEW_LINE INDENT DP [ i ] [ j ] = DP [ i - 1 ] [ j ] + DP [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT return DP [ ln - 1 ] [ DP_s - 1 ] NEW_LINE DEDENT print ( getNumMonotone ( 10 ) ) NEW_LINE
Newman | To declare array import module array ; To store values of sequence in array ; Driver code
import array NEW_LINE def sequence ( n ) : NEW_LINE INDENT f = array . array ( ' i ' , [ 0 , 1 , 1 ] ) NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT r = f [ f [ i - 1 ] ] + f [ i - f [ i - 1 ] ] NEW_LINE f . append ( r ) ; NEW_LINE DEDENT return r NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT n = 10 NEW_LINE print sequence ( n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Hosoya 's Triangle | Python3 code to print Hosoya 's triangle of height n. ; Base case ; Recursive step ; Print the Hosoya triangle of height n . ; Driven Code
def Hosoya ( n , m ) : NEW_LINE INDENT if ( ( n == 0 and m == 0 ) or ( n == 1 and m == 0 ) or ( n == 1 and m == 1 ) or ( n == 2 and m == 1 ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n > m : NEW_LINE INDENT return Hosoya ( n - 1 , m ) NEW_LINE INDENT + Hosoya ( n - 2 , m ) NEW_LINE DEDENT DEDENT elif m == n : NEW_LINE INDENT return Hosoya ( n - 1 , m - 1 ) NEW_LINE INDENT + Hosoya ( n - 2 , m - 2 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def printHosoya ( n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT print ( Hosoya ( i , j ) , end = " ▁ " ) NEW_LINE DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE printHosoya ( n ) NEW_LINE
Eulerian Number | Return euleriannumber A ( n , m ) ; Driver code
def eulerian ( n , m ) : NEW_LINE INDENT if ( m >= n or n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( m == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return ( ( n - m ) * eulerian ( n - 1 , m - 1 ) + ( m + 1 ) * eulerian ( n - 1 , m ) ) NEW_LINE DEDENT n = 3 NEW_LINE m = 1 NEW_LINE print ( eulerian ( n , m ) ) NEW_LINE
Largest divisible pairs subset | ''function to find the longest Subsequence ; dp [ i ] is going to store size of largest divisible subset beginning with a [ i ] . ; Since last element is largest , d [ n - 1 ] is 1 ; Fill values for smaller elements ; Find all multiples of a [ i ] and consider the multiple that has largest subset beginning with it . ; Return maximum value from dp [ ] ; Driver Code
def largestSubset ( a , n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n ) ] NEW_LINE dp [ n - 1 ] = 1 ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT mxm = 0 ; NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if a [ j ] % a [ i ] == 0 or a [ i ] % a [ j ] == 0 : NEW_LINE INDENT mxm = max ( mxm , dp [ j ] ) NEW_LINE DEDENT DEDENT dp [ i ] = 1 + mxm NEW_LINE DEDENT return max ( dp ) NEW_LINE DEDENT a = [ 1 , 3 , 6 , 13 , 17 , 18 ] NEW_LINE n = len ( a ) NEW_LINE print ( largestSubset ( a , n ) ) NEW_LINE
How to solve a Dynamic Programming Problem ? | This function returns the number of arrangements to form 'n ; lookup dictionary / hashmap is initialized ; Base cases negative number can 't be produced, return 0 ; 0 can be produced by not taking any number whereas 1 can be produced by just taking 1 ; Checking if number of way for producing n is already calculated or not if calculated , return that , otherwise calulcate and then return
' NEW_LINE def solve ( n , lookup = { } ) : NEW_LINE INDENT if n < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n not in lookup : NEW_LINE INDENT lookup [ n ] = ( solve ( n - 1 ) + solve ( n - 3 ) + solve ( n - 5 ) ) NEW_LINE DEDENT return lookup [ n ] NEW_LINE DEDENT
Friends Pairing Problem | Returns count of ways n people can remain single or paired up . ; Filling dp [ ] in bottom - up manner using recursive formula explained above . ; Driver code
def countFriendsPairings ( n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( i <= 2 ) : NEW_LINE INDENT dp [ i ] = i NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + ( i - 1 ) * dp [ i - 2 ] NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT n = 4 NEW_LINE print ( countFriendsPairings ( n ) ) NEW_LINE
Friends Pairing Problem | Returns count of ways n people can remain single or paired up . ; Driver code
def countFriendsPairings ( n ) : NEW_LINE INDENT a , b , c = 1 , 2 , 0 ; NEW_LINE if ( n <= 2 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT for i in range ( 3 , n + 1 ) : NEW_LINE INDENT c = b + ( i - 1 ) * a ; NEW_LINE a = b ; NEW_LINE b = c ; NEW_LINE DEDENT return c ; NEW_LINE DEDENT n = 4 ; NEW_LINE print ( countFriendsPairings ( n ) ) ; NEW_LINE
Check whether row or column swaps produce maximum size binary sub | Python3 program to find maximum binary sub - matrix with row swaps and column swaps . ; Precompute the number of consecutive 1 below the ( i , j ) in j - th column and the number of consecutive 1 s on right side of ( i , j ) in i - th row . ; Travesing the 2d matrix from top - right . ; If ( i , j ) contain 0 , do nothing ; Counting consecutive 1 on right side ; Travesing the 2d matrix from bottom - left . ; If ( i , j ) contain 0 , do nothing ; Counting consecutive 1 down to ( i , j ) . ; Return maximum size submatrix with row swap allowed . ; Copying the column ; Sort the copied array ; Find maximum submatrix size . ; Return maximum size submatrix with column swap allowed . ; Copying the row . ; Sort the copied array ; Find maximum submatrix size . ; Solving for row swap and column swap ; Comparing both . ; Driver Code
R , C = 5 , 3 NEW_LINE def precompute ( mat , ryt , dwn ) : NEW_LINE INDENT for j in range ( C - 1 , - 1 , - 1 ) : NEW_LINE INDENT for i in range ( 0 , R ) : NEW_LINE INDENT if mat [ i ] [ j ] == 0 : NEW_LINE INDENT ryt [ i ] [ j ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT ryt [ i ] [ j ] = ryt [ i ] [ j + 1 ] + 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( R - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( 0 , C ) : NEW_LINE INDENT if mat [ i ] [ j ] == 0 : NEW_LINE INDENT dwn [ i ] [ j ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT dwn [ i ] [ j ] = dwn [ i + 1 ] [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def solveRowSwap ( ryt ) : NEW_LINE INDENT b = [ 0 ] * R NEW_LINE ans = 0 NEW_LINE for j in range ( 0 , C ) : NEW_LINE INDENT for i in range ( 0 , R ) : NEW_LINE INDENT b [ i ] = ryt [ i ] [ j ] NEW_LINE DEDENT b . sort ( ) NEW_LINE for i in range ( 0 , R ) : NEW_LINE INDENT ans = max ( ans , b [ i ] * ( R - i ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def solveColumnSwap ( dwn ) : NEW_LINE INDENT b = [ 0 ] * C NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , R ) : NEW_LINE INDENT for j in range ( 0 , C ) : NEW_LINE INDENT b [ j ] = dwn [ i ] [ j ] NEW_LINE DEDENT b . sort ( ) NEW_LINE for i in range ( 0 , C ) : NEW_LINE INDENT ans = max ( ans , b [ i ] * ( C - i ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def findMax1s ( mat ) : NEW_LINE INDENT ryt = [ [ 0 for i in range ( C + 2 ) ] for j in range ( R + 2 ) ] NEW_LINE dwn = [ [ 0 for i in range ( C + 2 ) ] for j in range ( R + 2 ) ] NEW_LINE precompute ( mat , ryt , dwn ) NEW_LINE rswap = solveRowSwap ( ryt ) NEW_LINE cswap = solveColumnSwap ( dwn ) NEW_LINE if rswap > cswap : print ( " Row Swap " , rswap ) NEW_LINE else : print ( " Column Swap " , cswap ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 0 , 0 , 0 ] , [ 1 , 1 , 0 ] , [ 1 , 1 , 0 ] , [ 0 , 0 , 0 ] , [ 1 , 1 , 0 ] ] NEW_LINE findMax1s ( mat ) NEW_LINE DEDENT
LCS ( Longest Common Subsequence ) of three strings | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] and Z [ 0. . o - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] [ o + 1 ] in bottom up fashion . Note that L [ i ] [ j ] [ k ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] and Z [ 0. . ... k - 1 ] ; L [ m ] [ n ] [ o ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] and Z [ 0. . o - 1 ] ; Driver program to test above function
def lcsOf3 ( X , Y , Z , m , n , o ) : NEW_LINE INDENT L = [ [ [ 0 for i in range ( o + 1 ) ] for j in range ( n + 1 ) ] for k in range ( m + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT for k in range ( o + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 or k == 0 ) : NEW_LINE INDENT L [ i ] [ j ] [ k ] = 0 NEW_LINE DEDENT elif ( X [ i - 1 ] == Y [ j - 1 ] and X [ i - 1 ] == Z [ k - 1 ] ) : NEW_LINE INDENT L [ i ] [ j ] [ k ] = L [ i - 1 ] [ j - 1 ] [ k - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] [ k ] = max ( max ( L [ i - 1 ] [ j ] [ k ] , L [ i ] [ j - 1 ] [ k ] ) , L [ i ] [ j ] [ k - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return L [ m ] [ n ] [ o ] NEW_LINE DEDENT X = ' AGGT12' NEW_LINE Y = '12TXAYB ' NEW_LINE Z = '12XBA ' NEW_LINE m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE o = len ( Z ) NEW_LINE print ( ' Length ▁ of ▁ LCS ▁ is ' , lcsOf3 ( X , Y , Z , m , n , o ) ) NEW_LINE
Longest subsequence such that difference between adjacents is one | ''Driver code
def longestSubsequence ( A , N ) : NEW_LINE INDENT L = [ 1 ] * N NEW_LINE hm = { } NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if abs ( A [ i ] - A [ i - 1 ] ) == 1 : NEW_LINE INDENT L [ i ] = 1 + L [ i - 1 ] NEW_LINE DEDENT elif hm . get ( A [ i ] + 1 , 0 ) or hm . get ( A [ i ] - 1 , 0 ) : NEW_LINE INDENT L [ i ] = 1 + max ( hm . get ( A [ i ] + 1 , 0 ) , hm . get ( A [ i ] - 1 , 0 ) ) NEW_LINE DEDENT hm [ A [ i ] ] = L [ i ] NEW_LINE DEDENT return max ( L ) NEW_LINE DEDENT A = [ 1 , 2 , 3 , 4 , 5 , 3 , 2 ] NEW_LINE N = len ( A ) NEW_LINE print ( longestSubsequence ( A , N ) ) NEW_LINE
Printing Shortest Common Supersequence | returns shortest supersequence of X and Y ; dp [ i ] [ j ] contains length of shortest supersequence for X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; Fill table in bottom up manner ; Below steps follow recurrence relation ; string to store the shortest supersequence ; Start from the bottom right corner and one by one push characters in output string ; If current character in X and Y are same , then current character is part of shortest supersequence ; Put current character in result ; reduce values of i , j and index ; If current character in X and Y are different ; Put current character of Y in result ; reduce values of j and index ; Put current character of X in result ; reduce values of i and index ; If Y reaches its end , put remaining characters of X in the result string ; If X reaches its end , put remaining characters of Y in the result string ; reverse the string and return it ; Driver Code
def printShortestSuperSeq ( x , y ) : NEW_LINE INDENT m = len ( x ) NEW_LINE n = len ( y ) NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if i == 0 : NEW_LINE INDENT dp [ i ] [ j ] = j NEW_LINE DEDENT elif j == 0 : NEW_LINE INDENT dp [ i ] [ j ] = i NEW_LINE DEDENT elif x [ i - 1 ] == y [ j - 1 ] : NEW_LINE INDENT dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 1 + min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT string = " " NEW_LINE i = m NEW_LINE j = n NEW_LINE while i > 0 and j > 0 : NEW_LINE INDENT if x [ i - 1 ] == y [ j - 1 ] : NEW_LINE INDENT string += x [ i - 1 ] NEW_LINE i -= 1 NEW_LINE j -= 1 NEW_LINE DEDENT elif dp [ i - 1 ] [ j ] > dp [ i ] [ j - 1 ] : NEW_LINE INDENT string += y [ j - 1 ] NEW_LINE j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT string += x [ i - 1 ] NEW_LINE i -= 1 NEW_LINE DEDENT DEDENT while i > 0 : NEW_LINE INDENT string += x [ i - 1 ] NEW_LINE i -= 1 NEW_LINE DEDENT while j > 0 : NEW_LINE INDENT string += y [ j - 1 ] NEW_LINE j -= 1 NEW_LINE DEDENT string = list ( string ) NEW_LINE string . reverse ( ) NEW_LINE return ' ' . join ( string ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = " AGGTAB " NEW_LINE y = " GXTXAYB " NEW_LINE print ( printShortestSuperSeq ( x , y ) ) NEW_LINE DEDENT
Longest Repeating Subsequence | This function mainly returns LCS ( str , str ) with a condition that same characters at same index are not considered . ; Create and initialize DP table ; Fill dp table ( similar to LCS loops ) ; If characters match and indexes are not same ; If characters do not match ; Driver Program
def findLongestRepeatingSubSeq ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( str [ i - 1 ] == str [ j - 1 ] and i != j ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " aabb " NEW_LINE print ( " The ▁ length ▁ of ▁ the ▁ largest ▁ subsequence ▁ that ▁ repeats ▁ itself ▁ is ▁ : ▁ " , findLongestRepeatingSubSeq ( str ) ) NEW_LINE DEDENT
Count total number of N digit numbers such that the difference between sum of even and odd digits is 1 | Memoization based recursive function to count numbers with even and odd digit sum difference as 1. This function considers leading zero as a digit ; Base Case ; If current subproblem is already computed ; Initialize result ; If the current digit is odd , then add it to odd sum and recur ; Add to even sum and recur ; Store current result in lookup table and return the same ; This is mainly a wrapper over countRec . It explicitly handles leading digit and calls countRec ( ) for remaining digits . ; Initialize number digits considered so far ; Initialize all entries of lookup table ; Initialize final answer ; Initialize even and odd sums ; Explicitly handle first digit and call recursive function countRec for remaining digits . Note that the first digit is considered as even digit ; Driver Code ; A lookup table used for memoization .
def countRec ( digits , esum , osum , isOdd , n ) : NEW_LINE INDENT if digits == n : NEW_LINE INDENT return ( esum - osum == 1 ) NEW_LINE DEDENT if lookup [ digits ] [ esum ] [ osum ] [ isOdd ] != - 1 : NEW_LINE INDENT return lookup [ digits ] [ esum ] [ osum ] [ isOdd ] NEW_LINE DEDENT ans = 0 NEW_LINE if isOdd : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT ans += countRec ( digits + 1 , esum , osum + i , False , n ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT ans += countRec ( digits + 1 , esum + i , osum , True , n ) NEW_LINE DEDENT DEDENT lookup [ digits ] [ esum ] [ osum ] [ isOdd ] = ans NEW_LINE return ans NEW_LINE DEDENT def finalCount ( n ) : NEW_LINE INDENT global lookup NEW_LINE digits = 0 NEW_LINE lookup = [ [ [ [ - 1 , - 1 ] for i in range ( 500 ) ] for j in range ( 500 ) ] for k in range ( 50 ) ] NEW_LINE ans = 0 NEW_LINE esum = 0 NEW_LINE osum = 0 NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT ans += countRec ( digits + 1 , esum + i , osum , True , n ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT lookup = [ ] NEW_LINE n = 3 NEW_LINE print ( " Count ▁ of ▁ % d ▁ digit ▁ numbers ▁ is ▁ % d " % ( n , finalCount ( n ) ) ) NEW_LINE DEDENT
Count all possible paths from top left to bottom right of a mXn matrix | Returns count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; Create a 1D array to store results of subproblems ; Driver Code
def numberOfPaths ( p , q ) : NEW_LINE INDENT dp = [ 1 for i in range ( q ) ] NEW_LINE for i in range ( p - 1 ) : NEW_LINE INDENT for j in range ( 1 , q ) : NEW_LINE INDENT dp [ j ] += dp [ j - 1 ] NEW_LINE DEDENT DEDENT return dp [ q - 1 ] NEW_LINE DEDENT print ( numberOfPaths ( 3 , 3 ) ) NEW_LINE
Longest Arithmetic Progression | DP | Returns length of the longest AP subset in a given set ; Driver program to test above function
class Solution : NEW_LINE INDENT def Solve ( self , A ) : NEW_LINE INDENT ans = 2 NEW_LINE n = len ( A ) NEW_LINE if n <= 2 : NEW_LINE INDENT return n NEW_LINE DEDENT llap = [ 2 ] * n NEW_LINE A . sort ( ) NEW_LINE for j in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT i = j - 1 NEW_LINE k = j + 1 NEW_LINE while ( i >= 0 and k < n ) : NEW_LINE INDENT if A [ i ] + A [ k ] == 2 * A [ j ] : NEW_LINE INDENT llap [ j ] = max ( llap [ k ] + 1 , llap [ j ] ) NEW_LINE ans = max ( ans , llap [ j ] ) NEW_LINE i -= 1 NEW_LINE k += 1 NEW_LINE DEDENT elif A [ i ] + A [ k ] < 2 * A [ j ] : NEW_LINE INDENT k += 1 NEW_LINE DEDENT else : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT DEDENT obj = Solution ( ) NEW_LINE a = [ 9 , 4 , 7 , 2 , 10 ] NEW_LINE print ( obj . Solve ( a ) ) NEW_LINE
Minimum numbers to be appended such that mean of Array is equal to 1 | Function to calculate minimum Number of operations ; Storing sum of array arr [ ] ; Driver Code ; Function Call
def minumumOperation ( N , arr ) : NEW_LINE INDENT sum_arr = sum ( arr ) NEW_LINE if sum_arr >= N : NEW_LINE INDENT print ( sum_arr - N ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT DEDENT N = 4 NEW_LINE arr = [ 8 , 4 , 6 , 2 ] NEW_LINE minumumOperation ( N , arr ) NEW_LINE
Find Nth term of series 1 , 4 , 15 , 72 , 420. . . | Function to find factorial of N with recursion ; base condition ; use recursion ; calculate Nth term of series ; Driver code
def factorial ( N ) : NEW_LINE INDENT if N == 0 or N == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return N * factorial ( N - 1 ) NEW_LINE DEDENT def nthTerm ( N ) : NEW_LINE INDENT return ( factorial ( N ) * ( N + 2 ) // 2 ) NEW_LINE DEDENT N = 6 NEW_LINE print ( nthTerm ( N ) ) NEW_LINE
Check if a string is substring of another | Python program for the above approach ; Iterate from 0 to Len - 1 ; Driver code
def Substr ( Str , target ) : NEW_LINE INDENT t = 0 NEW_LINE Len = len ( Str ) NEW_LINE i = 0 NEW_LINE for i in range ( Len ) : NEW_LINE INDENT if ( t == len ( target ) ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( Str [ i ] == target [ t ] ) : NEW_LINE INDENT t += 1 NEW_LINE DEDENT else : NEW_LINE INDENT t = 0 NEW_LINE DEDENT DEDENT if ( t < len ( target ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( i - t ) NEW_LINE DEDENT DEDENT print ( Substr ( " GeeksForGeeks " , " Fr " ) ) NEW_LINE print ( Substr ( " GeeksForGeeks " , " For " ) ) NEW_LINE
Count anagrams having first character as a consonant and no pair of consonants or vowels placed adjacently | ''Python 3 program for the above approach include <bits/stdc++.h> ; ''Function to compute factorials till N ; '' Iterate in the range [1, N] ; '' Update ans to ans*i ; ''Store the value of ans in fac[i] ; ''Function to check whether the current character is a vowel or not ; ''Function to count the number of anagrams of S satisfying the given condition ; '' Store the factorials upto N ; '' Function Call to generate all factorials upto n ; '' Create a hashmap to store frequencies of all characters ; '' Store the count of vowels and consonants ; '' Iterate through all characters in the string ; ''Update the frequency of current character ; ''Check if the character is vowel or consonant ; '' Check if C==V+1 or C==V ; ''Store the denominator ; '' Calculate the denominator of the expression ; '' Multiply denominator by factorial of counts of all letters ; '' Store the numerator ; '' Store the answer by dividing numerator by denominator ; '' Print the answer ; ''Otherwise, print 0 ; ''Driver Code
mod = 1000000007 NEW_LINE N = 1000001 NEW_LINE fac = { } NEW_LINE def Precomputefact ( ) : NEW_LINE INDENT global fac NEW_LINE DEDENT ans = 1 NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT ans = ( ans * i ) % mod NEW_LINE DEDENT fac [ i ] = ans NEW_LINE INDENT return NEW_LINE DEDENT def isVowel ( a ) : NEW_LINE INDENT if ( a == ' A ' or a == ' E ' or a == ' I ' or a == ' O ' or a == ' U ' ) : NEW_LINE DEDENT return True NEW_LINE INDENT else : NEW_LINE DEDENT return False NEW_LINE def countAnagrams ( s , n ) : NEW_LINE global fac NEW_LINE INDENT Precomputefact ( ) NEW_LINE count = { } NEW_LINE DEDENT vo = 0 NEW_LINE co = 0 NEW_LINE for i in range ( n ) : NEW_LINE if s [ i ] in count : NEW_LINE INDENT count [ s [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ s [ i ] ] = 1 NEW_LINE DEDENT if ( isVowel ( s [ i ] ) ) : NEW_LINE INDENT vo += 1 NEW_LINE else : NEW_LINE DEDENT co += 1 NEW_LINE INDENT if ( ( co == vo + 1 ) or ( co == vo ) ) : NEW_LINE deno = 1 NEW_LINE DEDENT for key , value in count . items ( ) : NEW_LINE deno = ( deno * fac [ value ] ) % mod NEW_LINE INDENT nume = fac [ co ] % mod NEW_LINE DEDENT nume = ( nume * fac [ vo ] ) % mod NEW_LINE ans = nume // deno NEW_LINE INDENT print ( ans ) NEW_LINE else : NEW_LINE print ( 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " GADO " NEW_LINE l = len ( S ) NEW_LINE countAnagrams ( S , l ) NEW_LINE DEDENT
Modify string by increasing each character by its distance from the end of the word | Function to transform and return the transformed word ; Stores resulting word ; Iterate over the word ; Add the position value to the letter ; Convert it back to character ; Add it to the string ; Function to transform the given string ; Size of string ; Stores resultant string ; Iterate over given string ; End of word is reached ; print ( s [ j : j + i ] ) Append the word ; For the last word ; Driver code ; Given string ; Function call
def util ( sub ) : NEW_LINE INDENT n = len ( sub ) NEW_LINE i = 0 NEW_LINE ret = " " NEW_LINE while i < n : NEW_LINE INDENT t = ( ord ( sub [ i ] ) - 97 ) + n - 1 - i NEW_LINE ch = chr ( t % 26 + 97 ) NEW_LINE ret = ret + ch NEW_LINE i = i + 1 NEW_LINE DEDENT return ret NEW_LINE DEDENT def manipulate ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE res = " " NEW_LINE while i < n : NEW_LINE INDENT if s [ i ] == ' ▁ ' : NEW_LINE INDENT res += util ( s [ j : j + i ] ) NEW_LINE res = res + " ▁ " NEW_LINE j = i + 1 NEW_LINE i = j + 1 NEW_LINE DEDENT else : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT DEDENT res = res + util ( s [ j : j + i ] ) NEW_LINE print ( res ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " acm ▁ fkz " NEW_LINE manipulate ( s ) NEW_LINE DEDENT
Check if given words are present in a string | Helper Function to the Finding bigString ; Initialize leftBigIdx and rightBigIdx and leftSmallIdx variables ; Iterate until leftBigIdx variable reaches less than or equal to rightBigIdx ; Check if bigString [ leftBigIdx ] is not equal to smallString [ leftSmallIdx ] or Check if bigString [ rightBigIdx ] is not equal to smallString [ rightSmallIdx ] than return false otherwise increment leftBigIdx and leftSmallIdx decrement rightBigIdx and rightSmallIdx ; Function to the bigString ; iterate in the bigString ; Check if length of smallString + i is greater than the length of bigString ; call the function isInBigStringHelper ; Function to the multiStringSearch ; iterate in the smallString ; calling the isInBigString Function ; Driver code ; initialize string ; initialize vector string ; Function call ; Print answers ; Check if ans [ i ] is equal to 1 then Print true otherwise print false
def isInBigStringHelper ( bigString , smallString , startIdx ) : NEW_LINE INDENT leftBigIdx = startIdx NEW_LINE rightBigIdx = startIdx + len ( smallString ) - 1 NEW_LINE leftSmallIdx = 0 NEW_LINE rightSmallIdx = len ( smallString ) - 1 NEW_LINE while ( leftBigIdx <= rightBigIdx ) : NEW_LINE INDENT if ( bigString [ leftBigIdx ] != smallString [ leftSmallIdx ] or bigString [ rightBigIdx ] != smallString [ rightSmallIdx ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT leftBigIdx += 1 NEW_LINE rightBigIdx -= 1 NEW_LINE leftSmallIdx += 1 NEW_LINE rightSmallIdx -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def isInBigString ( bigString , smallString ) : NEW_LINE INDENT for i in range ( len ( bigString ) ) : NEW_LINE INDENT if ( i + len ( smallString ) > len ( bigString ) ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( isInBigStringHelper ( bigString , smallString , i ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def multiStringSearch ( bigString , smallStrings ) : NEW_LINE INDENT solution = [ ] NEW_LINE for smallString in smallStrings : NEW_LINE INDENT solution . append ( isInBigString ( bigString , smallString ) ) NEW_LINE DEDENT return solution NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " this ▁ is ▁ a ▁ big ▁ string " NEW_LINE substr = [ " this " , " yo " , " is " , " a " , " bigger " , " string " , " kappa " ] NEW_LINE ans = multiStringSearch ( str1 , substr ) NEW_LINE for i in range ( len ( ans ) ) : NEW_LINE INDENT if ( ans [ i ] == 1 ) : NEW_LINE INDENT print ( " true " , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " false " , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT
Count of lexicographically smaller characters on right | Function to count the smaller characters on the right of index i ; store the length of String ; initialize each elements of arr to zero ; array to store count of smaller characters on the right side of that index ; initialize the variable to store the count of characters smaller than that at index i ; adding the count of characters smaller than index i ; print the count of characters smaller than index i stored in ans array ; Driver Code
def countSmaller ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE arr = [ 0 ] * 26 ; NEW_LINE ans = [ 0 ] * n ; NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT arr [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE ct = 0 ; NEW_LINE for j in range ( ord ( str [ i ] ) - ord ( ' a ' ) ) : NEW_LINE INDENT ct += arr [ j ] ; NEW_LINE DEDENT ans [ i ] = ct ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " edcbaa " ; NEW_LINE countSmaller ( str ) ; NEW_LINE DEDENT
Find the longest sub | Z - algorithm function ; bit update function which updates values from index " idx " to last by value " val " ; Query function in bit ; Driver Code ; BIT array ; Making the z array ; update in the bit array from index z [ i ] by increment of 1 ; if the value in z [ i ] is not equal to ( n - i ) then no need to move further ; queryng for the maximum length substring from bit array
def z_function ( s ) : NEW_LINE INDENT global z , n NEW_LINE n = len ( s ) NEW_LINE z = [ 0 ] * n NEW_LINE l , r = 0 , 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if i <= r : NEW_LINE INDENT z [ i ] = min ( r - i + 1 , z [ i - 1 ] ) NEW_LINE DEDENT while ( i + z [ i ] < n and s [ z [ i ] ] == s [ i + z [ i ] ] ) : NEW_LINE INDENT z [ i ] += 1 NEW_LINE DEDENT if ( i + z [ i ] - 1 > r ) : NEW_LINE INDENT l = i NEW_LINE r = i + z [ i ] - 1 NEW_LINE DEDENT DEDENT return z NEW_LINE DEDENT def update ( idx , val ) : NEW_LINE INDENT global bit NEW_LINE if idx == 0 : NEW_LINE INDENT return NEW_LINE DEDENT while idx <= n : NEW_LINE INDENT bit [ idx ] += val NEW_LINE idx += ( idx & - idx ) NEW_LINE DEDENT DEDENT def pref ( idx ) : NEW_LINE INDENT global bit NEW_LINE ans = 0 NEW_LINE while idx > 0 : NEW_LINE INDENT ans += bit [ idx ] NEW_LINE idx -= ( idx & - idx ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 0 NEW_LINE length = 0 NEW_LINE bit = [ 0 ] * 1000005 NEW_LINE z = [ ] NEW_LINE m = dict ( ) NEW_LINE s = " geeksisforgeeksinplatformgeeks " NEW_LINE z = z_function ( s ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT update ( z [ i ] , 1 ) NEW_LINE DEDENT for i in range ( n - 1 , 1 , - 1 ) : NEW_LINE INDENT if z [ i ] != n - i : NEW_LINE INDENT continue NEW_LINE DEDENT if ( pref ( n ) - pref ( z [ i ] - 1 ) ) >= 2 : NEW_LINE INDENT length = max ( length , z [ i ] ) NEW_LINE DEDENT DEDENT if not length : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( s [ : length ] ) NEW_LINE DEDENT DEDENT
Count of words ending at the given suffix in Java | Function declared to return the count of words in the given sentence that end with the given suffix ; Variable to store count ; split function used to extract words from sentence in form of list ; using for loop with ' in ' to extract elements of list ; returning the count ; Driver Code ; printing the final cde
def endingWith ( str , suff ) : NEW_LINE INDENT c = 0 NEW_LINE wrd = str . split ( " ▁ " ) NEW_LINE for l in wrd : NEW_LINE INDENT if l . endswith ( suff ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT return c NEW_LINE DEDENT str = " GeeksForGeeks ▁ is ▁ a ▁ computer ▁ science ▁ portal ▁ for ▁ geeks " NEW_LINE suff = " ks " NEW_LINE print ( endingWith ( str , suff ) ) NEW_LINE
Character whose frequency is equal to the sum of frequencies of other characters of the given string | Function that returns true if some character exists in the given string whose frequency is equal to the sum frequencies of other characters of the string ; If string is of odd length ; To store the frequency of each character of the string ; Update the frequencies of the characters ; No such character exists ; Driver code
def isFrequencyEqual ( string , length ) : NEW_LINE INDENT if length % 2 == 1 : NEW_LINE INDENT return False NEW_LINE DEDENT freq = [ 0 ] * 26 NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT freq [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 0 , 26 ) : NEW_LINE INDENT if freq [ i ] == length // 2 : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " NEW_LINE length = len ( string ) NEW_LINE if isFrequencyEqual ( string , length ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Minimum replacements to make adjacent characters unequal in a ternary string | Function to count the number of minimal replacements ; Find the length of the string ; Iterate in the string ; Check if adjacent is similar ; If not the last pair ; Check for character which is not same in i + 1 and i - 1 ; Last pair ; Check for character which is not same in i - 1 index ; Driver Code
def countMinimalReplacements ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE cnt = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] == s [ i - 1 ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE if ( i != ( n - 1 ) ) : NEW_LINE INDENT s = list ( s ) NEW_LINE for j in "012" : NEW_LINE INDENT if ( j != s [ i + 1 ] and j != s [ i - 1 ] ) : NEW_LINE INDENT s [ i ] = j NEW_LINE break NEW_LINE DEDENT DEDENT s = ' ' . join ( s ) NEW_LINE DEDENT else : NEW_LINE INDENT s = list ( s ) NEW_LINE for k in "012" : NEW_LINE INDENT if ( k != s [ i - 1 ] ) : NEW_LINE INDENT s [ i ] = k NEW_LINE break NEW_LINE DEDENT DEDENT s = ' ' . join ( s ) NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "201220211" NEW_LINE print ( countMinimalReplacements ( s ) ) NEW_LINE DEDENT
Check whether the frequencies of all the characters in a string are prime or not | Python3 implementation of above approach ; function that returns true if n is prime else false ; 1 is not prime ; check if there is any factor or not ; function that returns true if the frequencies of all the characters of s are prime ; create a map to store the frequencies of characters ; update the frequency ; check whether all the frequencies are prime or not ; Driver code ; if all the frequencies are prime
import math as mt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT i = 2 NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , mt . ceil ( mt . sqrt ( n ) ) ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def check_frequency ( s ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if s [ i ] in m . keys ( ) : NEW_LINE INDENT m [ s [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ s [ i ] ] = 1 NEW_LINE DEDENT DEDENT for ch in m : NEW_LINE INDENT if m [ ch ] > 0 and isPrime ( m [ ch ] ) == False : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE if ( check_frequency ( s ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Find the count of substrings in alphabetic order | Function to find number of substrings ; Iterate over string length ; if any two chars are in alphabetic order ; find next char not in order ; return the result ; Driver Code
def findSubstringCount ( str ) : NEW_LINE INDENT result = 0 NEW_LINE n = len ( str ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( ord ( str [ i ] ) + 1 == ord ( str [ i + 1 ] ) ) : NEW_LINE INDENT result += 1 NEW_LINE while ( ord ( str [ i ] ) + 1 == ord ( str [ i + 1 ] ) ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " alphabet " NEW_LINE print ( findSubstringCount ( str ) ) NEW_LINE DEDENT
First non | '' Python3 implementation to find non repeating character using 1D array and one traversal ; The function returns index of the first non - repeating character in a string . If all characters are repeating then returns INT_MAX ; initialize all character as absent ; After below loop , the value of arr [ x ] is going to be index of of x if x appears only once . Else the value is going to be either - 1 or - 2. ; If this character occurs only once and appears before the current result , then update the result ; Driver prohram to test above function
import math as mt NEW_LINE NO_OF_CHARS = 256 NEW_LINE def firstNonRepeating ( string ) : NEW_LINE INDENT arr = [ - 1 for i in range ( NO_OF_CHARS ) ] NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if arr [ ord ( string [ i ] ) ] == - 1 : NEW_LINE INDENT arr [ ord ( string [ i ] ) ] = i NEW_LINE DEDENT else : NEW_LINE INDENT arr [ ord ( string [ i ] ) ] = - 2 NEW_LINE DEDENT DEDENT res = 10 ** 18 NEW_LINE for i in range ( NO_OF_CHARS ) : NEW_LINE INDENT if arr [ i ] >= 0 : NEW_LINE INDENT res = min ( res , arr [ i ] ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT string = " geeksforgeeks " NEW_LINE index = firstNonRepeating ( string ) NEW_LINE if index == 10 ** 18 : NEW_LINE INDENT print ( " Either ▁ all ▁ characters ▁ are ▁ repeating ▁ or ▁ string ▁ is ▁ empty " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " First ▁ non - repeating ▁ character ▁ is " , string [ index ] ) NEW_LINE DEDENT
Character replacement after removing duplicates from a string | Function to minimize string ; Duplicate characters are removed ; checks if character has previously occurred or not if not then add it to the minimized string 'mstr ; Utility function to print the minimized , replaced string ; Creating final string by replacing character ; index calculation ; Driver program
def minimize ( string ) : NEW_LINE INDENT mstr = " ▁ " NEW_LINE flagchar = [ 0 ] * 26 NEW_LINE l = len ( string ) NEW_LINE for i in range ( 0 , len ( string ) ) : NEW_LINE INDENT ch = string [ i ] NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if flagchar [ ord ( ch ) - 97 ] == 0 : NEW_LINE INDENT mstr = mstr + ch NEW_LINE flagchar [ ord ( ch ) - 97 ] = 1 NEW_LINE DEDENT DEDENT def replaceMinimizeUtil ( string ) : NEW_LINE INDENT finalStr = " " NEW_LINE l = len ( string ) NEW_LINE for i in range ( 0 , len ( minimizedStr ) ) : NEW_LINE INDENT ch = ord ( minimizedStr [ i ] ) NEW_LINE index = ( ch * ch ) % l NEW_LINE finalStr = finalStr + string [ index ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeks " NEW_LINE replaceMinimizeUtil ( string ) NEW_LINE DEDENT
Latin alphabet cipher | function for calculating the encryption ; Driver Code
def cipher ( str ) : NEW_LINE INDENT for i in range ( len ( str ) ) : NEW_LINE INDENT if str [ i ] . isalpha ( ) == 0 and str [ i ] != " ▁ " : NEW_LINE INDENT print ( " Enter ▁ only ▁ alphabets ▁ and ▁ space " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " Encrypted ▁ Code ▁ using ▁ Latin ▁ Alphabet " ) NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if str [ i ] >= " A " and str [ i ] <= " Z " : NEW_LINE INDENT print ( ord ( str [ i ] ) - ord ( " A " ) + 1 , end = " ▁ " ) NEW_LINE DEDENT elif str [ i ] >= " a " and str [ i ] <= ' z ' : NEW_LINE INDENT print ( ord ( str [ i ] ) - ord ( " a " ) + 1 , end = " ▁ " ) NEW_LINE DEDENT if str [ i ] == " ▁ " : NEW_LINE INDENT print ( str [ i ] ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE cipher ( str ) NEW_LINE DEDENT
Count palindrome words in a sentence | Function to check if a word is palindrome ; Function to count palindrome words ; splitting each word as spaces as delimiter and storing it into a list ; Iterating every element from list and checking if it is a palindrome . ; if the word is a palindrome increment the count . ; Driver code
def checkPalin ( word ) : NEW_LINE INDENT if word . lower ( ) == word . lower ( ) [ : : - 1 ] : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT def countPalin ( str ) : NEW_LINE INDENT count = 0 NEW_LINE listOfWords = str . split ( " ▁ " ) NEW_LINE for elements in listOfWords : NEW_LINE INDENT if ( checkPalin ( elements ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT countPalin ( " Madam ▁ Arora ▁ teaches ▁ malayalam " ) NEW_LINE countPalin ( " Nitin ▁ speaks ▁ malayalam " ) NEW_LINE
Remove the forbidden strings | pre [ ] keeps record of the characters of w that need to be changed ; stores the forbidden strings ; Function to check if the particula r substring is present in w at position ; If length of substring from this position is greater than length of w then return ; n and n1 are used to check for substring without considering the case of the letters in w by comparing the difference of ASCII values ; If same == true then it means a substring was found starting at position therefore all characters from position to length of substring found need to be changed therefore they needs to be marked ; Function implementing logic ; To verify if any substring is starting from index i ; Modifying the string w according to th rules ; This condition checks if w [ i ] = upper ( letter ) ; This condition checks if w [ i ] is any lowercase letter apart from letter . If true replace it with letter ; This condition checks if w [ i ] is any uppercase letter apart from letter . If true then replace it with upper ( letter ) . ; number of forbidden strings ; given string ; letter to replace and occur max number of times ; Calling function
pre = [ False ] * 100 NEW_LINE s = [ None ] * 110 NEW_LINE def verify ( position , index ) : NEW_LINE INDENT l = len ( w ) NEW_LINE k = len ( s [ index ] ) NEW_LINE if ( position + k > l ) : NEW_LINE INDENT return NEW_LINE DEDENT same = True NEW_LINE for i in range ( position , position + k ) : NEW_LINE INDENT ch = w [ i ] NEW_LINE ch1 = s [ index ] [ i - position ] NEW_LINE if ( ch >= ' a ' and ch <= ' z ' ) : NEW_LINE INDENT n = ord ( ch ) - ord ( ' a ' ) NEW_LINE DEDENT else : NEW_LINE INDENT n = ord ( ch ) - ord ( ' A ' ) NEW_LINE DEDENT if ( ch1 >= ' a ' and ch1 <= ' z ' ) : NEW_LINE INDENT n1 = ord ( ch1 ) - ord ( ' a ' ) NEW_LINE DEDENT else : NEW_LINE INDENT n1 = ord ( ch1 ) - ord ( ' A ' ) NEW_LINE DEDENT if ( n != n1 ) : NEW_LINE INDENT same = False NEW_LINE DEDENT DEDENT if ( same == True ) : NEW_LINE INDENT for i in range ( position , position + k ) : NEW_LINE INDENT pre [ i ] = True NEW_LINE DEDENT return NEW_LINE DEDENT DEDENT def solve ( ) : NEW_LINE INDENT l = len ( w ) NEW_LINE p = ord ( letter ) - ord ( ' a ' ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT verify ( i , j ) NEW_LINE DEDENT DEDENT for i in range ( l ) : NEW_LINE INDENT if ( pre [ i ] == True ) : NEW_LINE INDENT if ( w [ i ] == letter ) : NEW_LINE INDENT w [ i ] = ' b ' if ( letter == ' a ' ) else ' a ' NEW_LINE DEDENT elif ( w [ i ] == str ( ord ( ' A ' ) + p ) ) : NEW_LINE INDENT w [ i ] = ' B ' if ( letter == ' a ' ) else ' A ' NEW_LINE DEDENT elif ( w [ i ] >= ' a ' and w [ i ] <= ' z ' ) : NEW_LINE INDENT w [ i ] = letter NEW_LINE DEDENT elif ( w [ i ] >= ' A ' and w [ i ] <= ' Z ' ) : NEW_LINE INDENT w [ i ] = chr ( ord ( ' A ' ) + p ) NEW_LINE DEDENT DEDENT DEDENT print ( ' ' . join ( w ) ) NEW_LINE DEDENT n = 3 NEW_LINE s [ 0 ] = " etr " NEW_LINE s [ 1 ] = " ed " NEW_LINE s [ 2 ] = " ied " NEW_LINE w = " PEtrUnited " NEW_LINE w = list ( w ) NEW_LINE letter = ' d ' NEW_LINE solve ( ) NEW_LINE
Round the given number to nearest multiple of 10 | function to round the number ; Smaller multiple ; Larger multiple ; Return of closest of two ; driver code
def round ( n ) : NEW_LINE INDENT a = ( n // 10 ) * 10 NEW_LINE b = a + 10 NEW_LINE return ( b if n - a > b - n else a ) NEW_LINE DEDENT n = 4722 NEW_LINE print ( round ( n ) ) NEW_LINE
Breaking a number such that first part is integral division of second by a power of 10 | Python3 program to count ways to divide a string in two parts a and b such that b / pow ( 10 , p ) == a ; substring representing int a ; no of digits in a ; consider only most significant l1 characters of remaining string for int b ; if any of a or b contains leading 0 s discard this ; if both are equal ; driver code to test above function
def calculate ( N ) : NEW_LINE INDENT length = len ( N ) NEW_LINE l = int ( ( length ) / 2 ) NEW_LINE count = 0 NEW_LINE for i in range ( l + 1 ) : NEW_LINE INDENT s = N [ 0 : 0 + i ] NEW_LINE l1 = len ( s ) NEW_LINE t = N [ i : l1 + i ] NEW_LINE try : NEW_LINE INDENT if s [ 0 ] == '0' or t [ 0 ] == '0' : NEW_LINE INDENT continue NEW_LINE DEDENT DEDENT except : NEW_LINE INDENT continue NEW_LINE DEDENT if s == t : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT N = str ( "2202200" ) NEW_LINE print ( calculate ( N ) ) NEW_LINE
Program to check Strength of Password | Python3 program to check if a given password is strong or not . ; Checking lower alphabet in string ; Strength of password ; Driver code
def printStrongNess ( input_string ) : NEW_LINE INDENT n = len ( input_string ) NEW_LINE hasLower = False NEW_LINE hasUpper = False NEW_LINE hasDigit = False NEW_LINE specialChar = False NEW_LINE normalChars = " abcdefghijklmnopqrstu " NEW_LINE for i in range ( n ) : NEW_LINE INDENT if input_string [ i ] . islower ( ) : NEW_LINE INDENT hasLower = True NEW_LINE DEDENT if input_string [ i ] . isupper ( ) : NEW_LINE INDENT hasUpper = True NEW_LINE DEDENT if input_string [ i ] . isdigit ( ) : NEW_LINE INDENT hasDigit = True NEW_LINE DEDENT if input_string [ i ] not in normalChars : NEW_LINE INDENT specialChar = True NEW_LINE DEDENT DEDENT print ( " Strength ▁ of ▁ password : - " , end = " " ) NEW_LINE if ( hasLower and hasUpper and hasDigit and specialChar and n >= 8 ) : NEW_LINE INDENT print ( " Strong " ) NEW_LINE DEDENT elif ( ( hasLower or hasUpper ) and specialChar and n >= 6 ) : NEW_LINE INDENT print ( " Moderate " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Weak " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input_string = " GeeksforGeeks ! @12" NEW_LINE printStrongNess ( input_string ) NEW_LINE DEDENT
String with k distinct characters and no same characters adjacent | Function to find a string of length n with k distinct characters . ; Initialize result with first k Latin letters ; Fill remaining n - k letters by repeating k letters again and again . ; Driver code
def findString ( n , k ) : NEW_LINE INDENT res = " " NEW_LINE for i in range ( k ) : NEW_LINE INDENT res = res + chr ( ord ( ' a ' ) + i ) NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( n - k ) : NEW_LINE INDENT res = res + chr ( ord ( ' a ' ) + count ) NEW_LINE count += 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT count = 0 ; NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE k = 2 NEW_LINE print ( findString ( n , k ) ) NEW_LINE DEDENT
Find substrings that contain all vowels | Returns true if x is vowel . ; Function to check whether a character is vowel or not ; Function to FindSubstrings of string ; hash = set ( ) ; To store vowels ; If current character is vowel then insert into hash ; If all vowels are present in current substring ; Driver Code
def isVowel ( x ) : NEW_LINE INDENT return ( x == ' a ' or x == ' e ' or x == ' i ' or x == ' o ' or x == ' u ' ) ; NEW_LINE DEDENT def FindSubstring ( str ) : NEW_LINE INDENT start = 0 ; NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( isVowel ( str [ i ] ) == True ) : NEW_LINE INDENT hash . add ( str [ i ] ) ; NEW_LINE if ( len ( hash ) == 5 ) : NEW_LINE INDENT print ( str [ start : i + 1 ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT start = i + 1 ; NEW_LINE hash . clear ( ) ; NEW_LINE DEDENT DEDENT DEDENT str = " aeoibsddaeiouudb " ; NEW_LINE FindSubstring ( str ) ; NEW_LINE
Concatenated string with uncommon characters of two strings | Python3 program Find concatenated string with uncommon characters of given strings ; res = " " result ; store all characters of s2 in map ; Find characters of s1 that are not present in s2 and append to result ; Find characters of s2 that are not present in s1 . ; Driver Code
def concatenetedString ( s1 , s2 ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( 0 , len ( s2 ) ) : NEW_LINE INDENT m [ s2 [ i ] ] = 1 NEW_LINE DEDENT for i in range ( 0 , len ( s1 ) ) : NEW_LINE INDENT if ( not s1 [ i ] in m ) : NEW_LINE INDENT res = res + s1 [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT m [ s1 [ i ] ] = 2 NEW_LINE DEDENT DEDENT for i in range ( 0 , len ( s2 ) ) : NEW_LINE INDENT if ( m [ s2 [ i ] ] == 1 ) : NEW_LINE INDENT res = res + s2 [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " abcs " NEW_LINE s2 = " cxzca " NEW_LINE print ( concatenetedString ( s1 , s2 ) ) NEW_LINE DEDENT
Null Cipher | Function to decode the message . ; Store the decoded string ; found variable is used to tell that the encoded encoded character is found in that particular word . ; Set found variable to false whenever we find whitespace , meaning that encoded character for new word is not found ; Driver code
def decode ( string ) : NEW_LINE INDENT res = " " NEW_LINE found = False NEW_LINE for character in string : NEW_LINE INDENT if character == ' ▁ ' : NEW_LINE INDENT found = False NEW_LINE continue NEW_LINE DEDENT if not found : NEW_LINE INDENT if character >= ' A ' and character <= ' Z ' or character >= ' a ' and character <= ' z ' : NEW_LINE INDENT res += character NEW_LINE found = True NEW_LINE DEDENT DEDENT DEDENT return res . lower ( ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input = " A ▁ Step ▁ by ▁ Step ▁ Guide ▁ for ▁ Placement ▁ Preparation ▁ by ▁ GeeksforGeeks " NEW_LINE print ( " Enciphered ▁ Message : " , decode ( input ) ) NEW_LINE DEDENT
Program to count vowels in a string ( Iterative and Recursive ) | Function to check the Vowel ; to count total number of vowel from 0 to n ; string object ; Total numbers of Vowel
def isVowel ( ch ) : NEW_LINE INDENT return ch . upper ( ) in [ ' A ' , ' E ' , ' I ' , ' O ' , ' U ' ] NEW_LINE DEDENT def countVovels ( str , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return isVowel ( str [ n - 1 ] ) ; NEW_LINE DEDENT return ( countVovels ( str , n - 1 ) + isVowel ( str [ n - 1 ] ) ) ; NEW_LINE DEDENT str = " abc ▁ de " ; NEW_LINE print ( countVovels ( str , len ( str ) ) ) NEW_LINE
Generate all rotations of a given string | Print all the rotated string . ; Concatenate str with itself ; Print all substrings of size n . Note that size of temp is 2 n ; Driver Code
def printRotatedString ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE temp = string + string NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( temp [ i + j ] , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeks " NEW_LINE printRotatedString ( string ) NEW_LINE DEDENT
Check if frequency of all characters can become same by one removal | Python3 program to get same frequency character string by removal of at most one char ; Utility method to get index of character ch in lower alphabet characters ; Returns true if all non - zero elements values are same ; get first non - zero element ; check equality of each element with variable same ; Returns true if we can make all character frequencies same ; fill frequency array ; if all frequencies are same , then return true ; Try decreasing frequency of all character by one and then check all equality of all non - zero frequencies ; Check character only if it occurs in str ; Driver code
M = 26 NEW_LINE def getIdx ( ch ) : NEW_LINE INDENT return ( ord ( ch ) - ord ( ' a ' ) ) NEW_LINE DEDENT def allSame ( freq , N ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT same = freq [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( freq [ j ] > 0 and freq [ j ] != same ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def possibleSameCharFreqByOneRemoval ( str1 ) : NEW_LINE INDENT l = len ( str1 ) NEW_LINE freq = [ 0 ] * M NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT freq [ getIdx ( str1 [ i ] ) ] += 1 NEW_LINE DEDENT if ( allSame ( freq , M ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 0 , 26 ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT freq [ i ] -= 1 NEW_LINE if ( allSame ( freq , M ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT freq [ i ] += 1 NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " xyyzz " NEW_LINE if ( possibleSameCharFreqByOneRemoval ( str1 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Check if a large number is divisible by 11 or not | Function to find that number divisible by 11 or not ; Compute sum of even and odd digit sums ; When i is even , position of digit is odd ; Check its difference is divisible by 11 or not ; Driver code
def check ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE oddDigSum = 0 NEW_LINE evenDigSum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT oddDigSum = oddDigSum + ( ( int ) ( st [ i ] ) ) NEW_LINE DEDENT else : NEW_LINE INDENT evenDigSum = evenDigSum + ( ( int ) ( st [ i ] ) ) NEW_LINE DEDENT DEDENT return ( ( oddDigSum - evenDigSum ) % 11 == 0 ) NEW_LINE DEDENT st = "76945" NEW_LINE if ( check ( st ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ " ) NEW_LINE DEDENT
Hamming Distance between two strings | Function to calculate Hamming distance ; Driver code ; function call
def hammingDist ( str1 , str2 ) : NEW_LINE INDENT i = 0 NEW_LINE count = 0 NEW_LINE while ( i < len ( str1 ) ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT str1 = " geekspractice " NEW_LINE str2 = " nerdspractise " NEW_LINE print ( hammingDist ( str1 , str2 ) ) NEW_LINE
Check if two strings are k | Python3 program to check if two strings are k anagram or not . ; Function to check that is k - anagram or not ; If both strings are not of equal length then return false ; Store the occurrence of all characters in a hash_array ; Count number of characters that are different in both strings ; Return true if count is less than or equal to k ; Driver Code
MAX_CHAR = 26 NEW_LINE def arekAnagrams ( str1 , str2 , k ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE if ( len ( str2 ) != n ) : NEW_LINE INDENT return False NEW_LINE DEDENT count1 = [ 0 ] * MAX_CHAR NEW_LINE count2 = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( n ) : NEW_LINE INDENT count1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT count2 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( MAX_CHAR ) : NEW_LINE INDENT if ( count1 [ i ] > count2 [ i ] ) : NEW_LINE INDENT count = count + abs ( count1 [ i ] - count2 [ i ] ) NEW_LINE DEDENT DEDENT return ( count <= k ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " anagram " NEW_LINE str2 = " grammar " NEW_LINE k = 2 NEW_LINE if ( arekAnagrams ( str1 , str2 , k ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Remove spaces from a given string | Function to remove all spaces from a given string ; To keep track of non - space character count ; Traverse the given string . If current character is not space , then place it at index 'count++ ; Utility Function ; Driver program
def removeSpaces ( string ) : NEW_LINE INDENT count = 0 NEW_LINE list = [ ] NEW_LINE DEDENT ' NEW_LINE INDENT for i in xrange ( len ( string ) ) : NEW_LINE INDENT if string [ i ] != ' ▁ ' : NEW_LINE INDENT list . append ( string [ i ] ) NEW_LINE DEDENT DEDENT return toString ( list ) NEW_LINE DEDENT def toString ( List ) : NEW_LINE INDENT return ' ' . join ( List ) NEW_LINE DEDENT string = " g ▁ eeks ▁ for ▁ ge ▁ eeks ▁ " NEW_LINE print removeSpaces ( string ) NEW_LINE
Given a binary string , count number of substrings that start and end with 1. | A Python3 program to count number of substrings starting and ending with 1 ; Count of 1 's in input string ; Traverse input string and count of 1 's in it ; Return count of possible pairs among m 1 's ; Driver program to test above function
def countSubStr ( st , n ) : NEW_LINE INDENT m = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( st [ i ] == '1' ) : NEW_LINE INDENT m = m + 1 NEW_LINE DEDENT DEDENT return m * ( m - 1 ) // 2 NEW_LINE DEDENT st = "00100101" ; NEW_LINE list ( st ) NEW_LINE n = len ( st ) NEW_LINE print ( countSubStr ( st , n ) , end = " " ) NEW_LINE
Given a number as a string , find the number of contiguous subsequences which recursively add up to 9 | Python 3 program to count substrings with recursive sum equal to 9 ; count = 0 To store result ; Consider every character as beginning of substring ; sum of digits in current substring ; One by one choose every character as an ending character ; Add current digit to sum , if sum becomes multiple of 5 then increment count . Let us do modular arithmetic to avoid overflow for big strings ; Driver Code
def count9s ( number ) : NEW_LINE INDENT n = len ( number ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = ord ( number [ i ] ) - ord ( '0' ) NEW_LINE if ( number [ i ] == '9' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT sum = ( sum + ord ( number [ j ] ) - ord ( '0' ) ) % 9 NEW_LINE if ( sum == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( count9s ( "4189" ) ) NEW_LINE print ( count9s ( "1809" ) ) NEW_LINE DEDENT
Generate n | Python3 program to generate n - bit Gray codes ; This function generates all n bit Gray codes and prints the generated codes ; base case ; ' arr ' will store all generated codes ; start with one - bit pattern ; Every iteration of this loop generates 2 * i codes from previously generated i codes . ; Enter the prviously generated codes again in arr [ ] in reverse order . Nor arr [ ] has double number of codes . ; append 0 to the first half ; append 1 to the second half ; prcontents of arr [ ] ; Driver Code
import math as mt NEW_LINE def generateGrayarr ( n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT arr = list ( ) NEW_LINE arr . append ( "0" ) NEW_LINE arr . append ( "1" ) NEW_LINE i = 2 NEW_LINE j = 0 NEW_LINE while ( True ) : NEW_LINE INDENT if i >= 1 << n : NEW_LINE INDENT break NEW_LINE DEDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT arr . append ( arr [ j ] ) NEW_LINE DEDENT for j in range ( i ) : NEW_LINE INDENT arr [ j ] = "0" + arr [ j ] NEW_LINE DEDENT for j in range ( i , 2 * i ) : NEW_LINE INDENT arr [ j ] = "1" + arr [ j ] NEW_LINE DEDENT i = i << 1 NEW_LINE DEDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] ) NEW_LINE DEDENT DEDENT generateGrayarr ( 3 ) NEW_LINE
Rat in a Maze Problem when movement in all possible directions is allowed | Python3 implementation of the above approach ; Function returns true if the move taken is valid else it will return false . ; Function to print all the possible paths from ( 0 , 0 ) to ( n - 1 , n - 1 ) . ; This will check the initial point ( i . e . ( 0 , 0 ) ) to start the paths . ; If reach the last cell ( n - 1 , n - 1 ) then store the path and return ; Mark the cell as visited ; Check if downward move is valid ; Check if the left move is valid ; Check if the right move is valid ; Check if the upper move is valid ; Mark the cell as unvisited for other possible paths ; Function to store and print all the valid paths ; vector to store all the possible paths ; Call the utility function to find the valid paths ; Print all possible paths ; Driver code
from typing import List NEW_LINE MAX = 5 NEW_LINE def isSafe ( row : int , col : int , m : List [ List [ int ] ] , n : int , visited : List [ List [ bool ] ] ) -> bool : NEW_LINE INDENT if ( row == - 1 or row == n or col == - 1 or col == n or visited [ row ] [ col ] or m [ row ] [ col ] == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def printPathUtil ( row : int , col : int , m : List [ List [ int ] ] , n : int , path : str , possiblePaths : List [ str ] , visited : List [ List [ bool ] ] ) -> None : NEW_LINE INDENT if ( row == - 1 or row == n or col == - 1 or col == n or visited [ row ] [ col ] or m [ row ] [ col ] == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( row == n - 1 and col == n - 1 ) : NEW_LINE INDENT possiblePaths . append ( path ) NEW_LINE return NEW_LINE DEDENT visited [ row ] [ col ] = True NEW_LINE if ( isSafe ( row + 1 , col , m , n , visited ) ) : NEW_LINE INDENT path += ' D ' NEW_LINE printPathUtil ( row + 1 , col , m , n , path , possiblePaths , visited ) NEW_LINE path = path [ : - 1 ] NEW_LINE DEDENT if ( isSafe ( row , col - 1 , m , n , visited ) ) : NEW_LINE INDENT path += ' L ' NEW_LINE printPathUtil ( row , col - 1 , m , n , path , possiblePaths , visited ) NEW_LINE path = path [ : - 1 ] NEW_LINE DEDENT if ( isSafe ( row , col + 1 , m , n , visited ) ) : NEW_LINE INDENT path += ' R ' NEW_LINE printPathUtil ( row , col + 1 , m , n , path , possiblePaths , visited ) NEW_LINE path = path [ : - 1 ] NEW_LINE DEDENT if ( isSafe ( row - 1 , col , m , n , visited ) ) : NEW_LINE INDENT path += ' U ' NEW_LINE printPathUtil ( row - 1 , col , m , n , path , possiblePaths , visited ) NEW_LINE path = path [ : - 1 ] NEW_LINE DEDENT visited [ row ] [ col ] = False NEW_LINE DEDENT def printPath ( m : List [ List [ int ] ] , n : int ) -> None : NEW_LINE INDENT possiblePaths = [ ] NEW_LINE path = " " NEW_LINE visited = [ [ False for _ in range ( MAX ) ] for _ in range ( n ) ] NEW_LINE printPathUtil ( 0 , 0 , m , n , path , possiblePaths , visited ) NEW_LINE for i in range ( len ( possiblePaths ) ) : NEW_LINE INDENT print ( possiblePaths [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m = [ [ 1 , 0 , 0 , 0 , 0 ] , [ 1 , 1 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 0 , 1 ] , [ 0 , 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 0 , 1 ] ] NEW_LINE n = len ( m ) NEW_LINE printPath ( m , n ) NEW_LINE DEDENT
N Queen in O ( n ) space | Python code to for n Queen placement ; Helper Function to check if queen can be placed ; Function to display placed queen ; Function to check queens placement ; Driver Code
class GfG : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . MAX = 10 NEW_LINE self . arr = [ 0 ] * self . MAX NEW_LINE self . no = 0 NEW_LINE DEDENT def breakLine ( self ) : NEW_LINE INDENT print ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " ) NEW_LINE DEDENT def canPlace ( self , k , i ) : NEW_LINE INDENT for j in range ( 1 , k ) : NEW_LINE INDENT if ( self . arr [ j ] == i or ( abs ( self . arr [ j ] - i ) == abs ( j - k ) ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def display ( self , n ) : NEW_LINE INDENT self . breakLine ( ) NEW_LINE self . no += 1 NEW_LINE print ( " Arrangement ▁ No . " , self . no , end = " ▁ " ) NEW_LINE self . breakLine ( ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if self . arr [ i ] != j : NEW_LINE INDENT print ( " TABSYMBOL _ " , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " TABSYMBOL Q " , end = " ▁ " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT self . breakLine ( ) NEW_LINE DEDENT def nQueens ( self , k , n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if self . canPlace ( k , i ) : NEW_LINE INDENT self . arr [ k ] = i NEW_LINE if k == n : NEW_LINE INDENT self . display ( n ) NEW_LINE DEDENT else : NEW_LINE INDENT self . nQueens ( k + 1 , n ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE obj = GfG ( ) NEW_LINE obj . nQueens ( 1 , n ) NEW_LINE DEDENT
Numbers that are bitwise AND of at least one non | Python3 implementation of the approach ; Set to store all possible AND values . ; Starting index of the sub - array . ; Ending index of the sub - array . res = 2147483647 Integer . MAX_VALUE ; AND value is added to the set . ; The set contains all possible AND values .
A = [ 11 , 15 , 7 , 19 ] NEW_LINE N = len ( A ) NEW_LINE Set = set ( ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i , N ) : NEW_LINE INDENT res &= A [ j ] NEW_LINE Set . add ( res ) NEW_LINE DEDENT DEDENT print ( Set ) NEW_LINE
Collect all coins in minimum number of steps | recursive method to collect coins from height array l to r , with height h already collected ; if l is more than r , no steps needed ; loop over heights to get minimum height index ; choose minimum from , 1 ) collecting coins using all vertical lines ( total r - l ) 2 ) collecting coins using lower horizontal lines and recursively on left and right segments ; method returns minimum number of step to collect coin from stack , with height in height [ ] array ; Driver code
def minStepsRecur ( height , l , r , h ) : NEW_LINE INDENT if l >= r : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT m = l NEW_LINE for i in range ( l , r ) : NEW_LINE INDENT if height [ i ] < height [ m ] : NEW_LINE INDENT m = i NEW_LINE DEDENT DEDENT return min ( r - l , minStepsRecur ( height , l , m , height [ m ] ) + minStepsRecur ( height , m + 1 , r , height [ m ] ) + height [ m ] - h ) NEW_LINE DEDENT def minSteps ( height , N ) : NEW_LINE INDENT return minStepsRecur ( height , 0 , N , 0 ) NEW_LINE DEDENT height = [ 2 , 1 , 2 , 5 , 1 ] NEW_LINE N = len ( height ) NEW_LINE print ( minSteps ( height , N ) ) NEW_LINE
Count of Unique Direct Path Between N Points On a Plane | Function to count the total number of direct paths ; Driver Code
def countDirectPath ( N ) : NEW_LINE INDENT return N + ( N * ( N - 3 ) ) // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE print ( countDirectPath ( N ) ) NEW_LINE DEDENT
Find the coordinate that does not belong to any square | Function to find the point that is not a part of the side of a square ; Traverse each pair of coordinates ; Minimize x - coordinate in all the points except current point ; Maximize x - coordinate in all the points except the current point ; Minimize y - coordinate in all the points except current point ; Maximize y - coordinate in all the points except current point ; If x - coordinate matches with other same line ; If y coordinate matches with other same line ; Check if the condition for square exists or not ; Print the output ; Driver Code
def findPoint ( n , p ) : NEW_LINE INDENT for i in range ( n * 4 + 1 ) : NEW_LINE INDENT x1 = 2e9 NEW_LINE x2 = - 2e9 NEW_LINE y1 = 2e9 NEW_LINE y2 = - 2e9 NEW_LINE for j in range ( n * 4 + 1 ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT x1 = min ( x1 , p [ j ] [ 0 ] ) NEW_LINE x2 = max ( x2 , p [ j ] [ 0 ] ) NEW_LINE y1 = min ( y1 , p [ j ] [ 1 ] ) NEW_LINE y2 = max ( y2 , p [ j ] [ 1 ] ) NEW_LINE DEDENT DEDENT ok = 1 NEW_LINE c1 = 0 NEW_LINE c2 = 0 NEW_LINE c3 = 0 NEW_LINE c4 = 0 NEW_LINE for j in range ( 1 , n * 4 + 1 , 1 ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT if ( ( p [ j ] [ 0 ] == x1 or p [ j ] [ 0 ] == x2 ) or ( p [ j ] [ 1 ] == y1 or p [ j ] [ 1 ] == y2 ) ) : NEW_LINE INDENT if ( p [ j ] [ 0 ] == x1 ) : NEW_LINE INDENT c1 += 1 NEW_LINE DEDENT if ( p [ j ] [ 0 ] == x2 ) : NEW_LINE INDENT c2 += 1 NEW_LINE DEDENT if ( p [ j ] [ 1 ] == y1 ) : NEW_LINE INDENT c3 += 1 NEW_LINE DEDENT if ( p [ j ] [ 1 ] == y2 ) : NEW_LINE INDENT c4 += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT ok = 0 NEW_LINE DEDENT DEDENT DEDENT if ( ok and c1 >= n and c2 >= n and c3 >= n and c4 >= n and x2 - x1 == y2 - y1 ) : NEW_LINE INDENT print ( p [ i ] [ 0 ] , p [ i ] [ 1 ] ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE arr = [ [ 0 , 0 ] , [ 0 , 1 ] , [ 0 , 2 ] , [ 1 , 0 ] , [ 1 , 1 ] , [ 1 , 2 ] , [ 2 , 0 ] , [ 2 , 1 ] , [ 2 , 2 ] ] NEW_LINE findPoint ( N , arr ) NEW_LINE DEDENT
Triacontagon Number | Finding the nth triacontagonal Number ; Driver Code
def triacontagonalNum ( n ) : NEW_LINE INDENT return ( 28 * n * n - 26 * n ) // 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( "3rd ▁ triacontagonal ▁ Number ▁ is ▁ = ▁ " , triacontagonalNum ( n ) ) NEW_LINE
Hexacontagon Number | Finding the nth hexacontagon Number ; Driver Code
def hexacontagonNum ( n ) : NEW_LINE INDENT return ( 58 * n * n - 56 * n ) // 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( "3rd ▁ hexacontagon ▁ Number ▁ is ▁ = ▁ " , hexacontagonNum ( n ) ) ; NEW_LINE
Enneacontagon Number | Finding the nth enneacontagon Number ; Driver Code
def enneacontagonNum ( n ) : NEW_LINE INDENT return ( 88 * n * n - 86 * n ) // 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( "3rd ▁ enneacontagon ▁ Number ▁ is ▁ = ▁ " , enneacontagonNum ( n ) ) NEW_LINE
Triacontakaidigon Number | Finding the nth triacontakaidigon Number ; Driver Code
def triacontakaidigonNum ( n ) : NEW_LINE INDENT return ( 30 * n * n - 28 * n ) // 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( "3rd ▁ triacontakaidigon ▁ Number ▁ is ▁ = ▁ " , triacontakaidigonNum ( n ) ) NEW_LINE
Icosihexagonal Number | Finding the nth Icosihexagonal Number ; Driver Code
def IcosihexagonalNum ( n ) : NEW_LINE INDENT return ( 24 * n * n - 22 * n ) // 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( "3rd ▁ Icosihexagonal ▁ Number ▁ is ▁ = ▁ " , IcosihexagonalNum ( n ) ) NEW_LINE
Icosikaioctagon or Icosioctagon Number | Finding the nth icosikaioctagonal Number ; Driver Code
def icosikaioctagonalNum ( n ) : NEW_LINE INDENT return ( 26 * n * n - 24 * n ) // 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( "3rd ▁ icosikaioctagonal ▁ Number ▁ is ▁ = ▁ " , icosikaioctagonalNum ( n ) ) NEW_LINE
Octacontagon Number | Finding the nth octacontagon number ; Driver code
def octacontagonNum ( n ) : NEW_LINE INDENT return ( 78 * n * n - 76 * n ) // 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( "3rd ▁ octacontagon ▁ Number ▁ is ▁ = ▁ " , octacontagonNum ( n ) ) NEW_LINE
Hectagon Number | Finding the nth hectagon number ; Driver code
def hectagonNum ( n ) : NEW_LINE INDENT return ( 98 * n * n - 96 * n ) // 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( "3rd ▁ hectagon ▁ Number ▁ is ▁ = ▁ " , hectagonNum ( n ) ) NEW_LINE
Tetracontagon Number | Finding the nth tetracontagon Number ; Driver Code
def tetracontagonNum ( n ) : NEW_LINE INDENT return ( 38 * n * n - 36 * n ) // 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( "3rd ▁ tetracontagon ▁ Number ▁ is ▁ = ▁ " , tetracontagonNum ( n ) ) NEW_LINE
Perimeter of an Ellipse | Python3 program to find perimeter of an Ellipse ; Function to find the perimeter of an Ellipse ; Compute perimeter ; Driver code ; Function call
from math import sqrt NEW_LINE def Perimeter ( a , b ) : NEW_LINE INDENT perimeter = 0 NEW_LINE perimeter = ( 2 * 3.14 * sqrt ( ( a * a + b * b ) / ( 2 * 1.0 ) ) ) ; NEW_LINE print ( perimeter ) NEW_LINE DEDENT a = 3 NEW_LINE b = 2 NEW_LINE Perimeter ( a , b ) NEW_LINE
Biggest Reuleaux Triangle within A Square | Function to find the Area of the Reuleaux triangle ; Side cannot be negative ; Area of the Reuleaux triangle ; Driver code
def ReuleauxArea ( a ) : NEW_LINE INDENT if ( a < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT A = 0.70477 * pow ( a , 2 ) ; NEW_LINE return A NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 6 NEW_LINE print ( ReuleauxArea ( a ) ) NEW_LINE DEDENT
Largest hexagon that can be inscribed within a square | Function to return the side of the hexagon ; Side cannot be negative ; Side of the hexagon ; Driver code
def hexagonside ( a ) : NEW_LINE INDENT if ( a < 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT x = 0.5176 * a ; NEW_LINE return x ; NEW_LINE DEDENT a = 6 ; NEW_LINE print ( hexagonside ( a ) ) ; NEW_LINE
Largest hexagon that can be inscribed within an equilateral triangle | function to find the side of the hexagon ; Side cannot be negative ; Side of the hexagon ; Driver code
def hexagonside ( a ) : NEW_LINE INDENT if a < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT x = a // 3 NEW_LINE return x NEW_LINE DEDENT a = 6 NEW_LINE print ( hexagonside ( a ) ) NEW_LINE
Find middle point segment from given segment lengths | Function that returns the segment for the middle point ; the middle point ; stores the segment index ; increment sum by length of the segment ; if the middle is in between two segments ; if sum is greater than middle point ; Driver code
def findSegment ( n , m , segment_length ) : NEW_LINE INDENT meet_point = ( 1.0 * n ) / 2.0 NEW_LINE sum = 0 NEW_LINE segment_number = 0 NEW_LINE for i in range ( 0 , m , 1 ) : NEW_LINE INDENT sum += segment_length [ i ] NEW_LINE if ( sum == meet_point ) : NEW_LINE INDENT segment_number = - 1 NEW_LINE break NEW_LINE DEDENT if ( sum > meet_point ) : NEW_LINE INDENT segment_number = i + 1 NEW_LINE break NEW_LINE DEDENT DEDENT return segment_number NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 13 NEW_LINE m = 3 NEW_LINE segment_length = [ 3 , 2 , 8 ] NEW_LINE ans = findSegment ( n , m , segment_length ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Maximum points of intersection n lines | nC2 = ( n ) * ( n - 1 ) / 2 ; Driver code ; n is number of line
def countMaxIntersect ( n ) : NEW_LINE INDENT return int ( n * ( n - 1 ) / 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 8 NEW_LINE print ( countMaxIntersect ( n ) ) NEW_LINE DEDENT
Program to find volume and surface area of pentagonal prism | function for surface area ; function for VOlume ; Driver Code
def surfaceArea ( a , b , h ) : NEW_LINE INDENT return 5 * a * b + 5 * b * h NEW_LINE DEDENT def volume ( b , h ) : NEW_LINE INDENT return ( 5 * b * h ) / 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 5 NEW_LINE b = 3 NEW_LINE h = 7 NEW_LINE print ( " surface ▁ area ▁ = " , surfaceArea ( a , b , h ) , " , " , " volume ▁ = " , volume ( b , h ) ) NEW_LINE DEDENT