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 ...
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 ( ...
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 =...
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 ; Co...
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...
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 v...
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...
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 ==...
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 upd...
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 ...
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 thre...
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 ...
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 ( ...
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...
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 = ...
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 remai...
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 ...
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 fo...
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 ; Ini...
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...
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 positio...
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 ] )...
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 cos...
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...
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 ...
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 == ...
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 ...
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_LIN...
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 do...
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 ...
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 ...
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...
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...
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 , otherw...
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 ...
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 pla...
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 =...
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 balan...
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...
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 cur...
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...
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 ...
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 ...
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 pr...
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...
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...
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...
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...
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 (...
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 larg...
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 ( mx...
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 ...
' 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 DE...
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 ...
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 ( countF...
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...
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...
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....
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 ) ...
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 [...
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 ...
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 DEDE...
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 ...
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...
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_...
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 >=...
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_LI...
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] ; ''Fun...
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...
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 strin...
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 I...
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 Che...
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 [ left...
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 ch...
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 ...
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 ) t...
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 ] ...
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 ...
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 ...
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 c...
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 [...
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...
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...
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 ; ...
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_...
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...
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 ] i...
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 els...
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 repl...
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 f...
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 fo...
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 . ; Dri...
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 ( elem...
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 ...
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 [...
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...
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 INDE...
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 ( ) ...
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 IND...
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 [ ...
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 ...
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 [...
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 charac...
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 ] ) ) ; NE...
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 I...
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 ...
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 ) : N...
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 ] ...
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...
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 ...
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 (...
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...
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 ...
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 chara...
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 ( ...
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 t...
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...
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...
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 ...
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_L...
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 ) co...
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 ] ) +...
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 - coordina...
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...
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 DE...
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...