text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Maximum sum after rearranging the array for K queries | Function to find maximum sum after rearranging array elements ; Auxiliary array to find the count of each selected elements Initialize with 0 ; Finding count of every element to be selected ; Making it to 0 - indexing ; Prefix sum array concept is used to obtain the count array ; Iterating over the count array to get the final array ; Variable to store the maximum sum ; Sorting both the arrays ; Loop to find the maximum sum ; Driver code | def maxSumArrangement ( A , R , N , M ) : NEW_LINE INDENT count = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT l = R [ i ] [ 0 ] NEW_LINE r = R [ i ] [ 1 ] + 1 NEW_LINE l = l - 1 NEW_LINE r = r - 1 NEW_LINE count [ l ] = count [ l ] + 1 NEW_LINE if ( r < N ) : NEW_LINE INDENT count [ r ] = count [ r ] - 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT count [ i ] = count [ i ] + count [ i - 1 ] NEW_LINE DEDENT ans = 0 NEW_LINE count . sort ( ) NEW_LINE A . sort ( ) NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT ans = ans + A [ i ] * count [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT A = [ 2 , 6 , 10 , 1 , 5 , 6 ] NEW_LINE R = [ [ 1 , 3 ] , [ 4 , 6 ] , [ 3 , 4 ] ] NEW_LINE N = len ( A ) NEW_LINE M = len ( R ) NEW_LINE print ( maxSumArrangement ( A , R , N , M ) ) NEW_LINE |
Sum of M maximum distinct digit sum from 1 to N that are factors of K | Python 3 implementation to find the sum of maximum distinct digit sum of at most M numbers from 1 to N that are factors of K ; Function to find the factors of K in N ; Initialise a vector ; Find out the factors of K less than N ; Find the digit sum of each factor ; Sum of digits for each element in vector ; Find the largest M distinct digit sum from the digitSum vector ; Find the sum of last M numbers . ; Find the at most M numbers from N natural numbers whose digit sum is distinct and those M numbers are factors of K ; Find out the factors of K less than N ; Sum of digits for each element in vector ; Sorting the digitSum vector ; Removing the duplicate elements ; Finding the sum and returning it ; Driver Code ; Function Call | import math NEW_LINE def findFactors ( n , k ) : NEW_LINE INDENT factors = [ ] NEW_LINE sqt = ( int ) ( math . sqrt ( k ) ) NEW_LINE for i in range ( 1 , sqt ) : NEW_LINE INDENT if ( k % i == 0 ) : NEW_LINE INDENT if ( k // i == i and i <= n ) : NEW_LINE INDENT factors . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( i <= n ) : NEW_LINE INDENT factors . append ( i ) NEW_LINE DEDENT if ( k // i <= n ) : NEW_LINE INDENT factors . append ( k // i ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return factors NEW_LINE DEDENT def findDigitSum ( a ) : NEW_LINE INDENT for i in range ( len ( a ) ) : NEW_LINE INDENT c = 0 NEW_LINE while ( a [ i ] > 0 ) : NEW_LINE INDENT c += a [ i ] % 10 NEW_LINE a [ i ] = a [ i ] // 10 NEW_LINE DEDENT a [ i ] = c NEW_LINE DEDENT return a NEW_LINE DEDENT def findMMaxDistinctDigitSum ( distinctDigitSum , m ) : NEW_LINE INDENT sum = 0 NEW_LINE i = len ( distinctDigitSum ) - 1 NEW_LINE while ( i >= 0 and m > 0 ) : NEW_LINE INDENT sum += distinctDigitSum [ i ] NEW_LINE i -= 1 NEW_LINE m -= 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT def findDistinctMnumbers ( n , k , m ) : NEW_LINE INDENT factors = findFactors ( n , k ) NEW_LINE digitSum = findDigitSum ( factors ) NEW_LINE digitSum . sort ( ) NEW_LINE ip = list ( set ( digitSum ) ) NEW_LINE return findMMaxDistinctDigitSum ( ip , m ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 100 NEW_LINE k = 80 NEW_LINE m = 4 NEW_LINE print ( findDistinctMnumbers ( n , k , m ) ) NEW_LINE DEDENT |
Sorting objects using In | Partition function which will partition the array and into two parts ; Compare hash values of objects ; Classic quicksort algorithm ; Function to sort and print the objects ; As the sorting order is blue objects , red objects and then yellow objects ; Quick sort function ; Printing the sorted array ; Let 's represent objects as strings | objects = [ ] NEW_LINE hash = dict ( ) NEW_LINE def partition ( l , r ) : NEW_LINE INDENT global objects , hash NEW_LINE j = l - 1 NEW_LINE last_element = hash [ objects [ r ] ] NEW_LINE for i in range ( l , r ) : NEW_LINE INDENT if ( hash [ objects [ i ] ] <= last_element ) : NEW_LINE INDENT j += 1 NEW_LINE ( objects [ i ] , objects [ j ] ) = ( objects [ j ] , objects [ i ] ) NEW_LINE DEDENT DEDENT j += 1 NEW_LINE ( objects [ j ] , objects [ r ] ) = ( objects [ r ] , objects [ j ] ) NEW_LINE return j NEW_LINE DEDENT def quicksort ( l , r ) : NEW_LINE INDENT if ( l < r ) : NEW_LINE INDENT mid = partition ( l , r ) NEW_LINE quicksort ( l , mid - 1 ) NEW_LINE quicksort ( mid + 1 , r ) NEW_LINE DEDENT DEDENT def sortObj ( ) : NEW_LINE INDENT global objects , hash NEW_LINE hash [ " blue " ] = 1 NEW_LINE hash [ " red " ] = 2 NEW_LINE hash [ " yellow " ] = 3 NEW_LINE quicksort ( 0 , int ( len ( objects ) - 1 ) ) NEW_LINE for i in objects : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT objects = [ " red " , " blue " , " red " , " yellow " , " blue " ] NEW_LINE sortObj ( ) NEW_LINE |
Sort the numbers according to their product of digits | Function to return the product of the digits of n ; Function to sort the array according to the product of the digits of elements ; Vector to store the digit product with respective elements ; Inserting digit product with elements in the vector pair ; Sort the vector , this will sort the pair according to the product of the digits ; Print the sorted vector content ; Driver code | def productOfDigit ( n ) : NEW_LINE INDENT product = 1 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT product *= ( n % 10 ) ; NEW_LINE n = n // 10 ; NEW_LINE DEDENT return product ; NEW_LINE DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT vp = [ ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT vp . append ( ( productOfDigit ( arr [ i ] ) , arr [ i ] ) ) ; NEW_LINE DEDENT vp . sort ( ) ; NEW_LINE for i in range ( len ( vp ) ) : NEW_LINE INDENT print ( vp [ i ] [ 1 ] , end = " β " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , 10 , 102 , 31 , 15 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE sortArr ( arr , n ) ; NEW_LINE DEDENT |
Minimum steps required to reduce all the elements of the array to zero | Function to return the minimum steps required to reduce all the elements to 0 ; Maximum element from the array ; Driver code | def minSteps ( arr , n ) : NEW_LINE INDENT maxVal = max ( arr ) NEW_LINE return maxVal NEW_LINE DEDENT arr = [ 1 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minSteps ( arr , n ) ) NEW_LINE |
Maximum water that can be stored between two buildings | Return the maximum water that can be stored ; Check all possible pairs of buildings ; Maximum so far ; Driver code | def maxWater ( height , n ) : NEW_LINE INDENT maximum = 0 ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT current = min ( height [ i ] , height [ j ] ) * ( j - i - 1 ) ; NEW_LINE maximum = max ( maximum , current ) ; NEW_LINE DEDENT DEDENT return maximum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT height = [ 2 , 1 , 3 , 4 , 6 , 5 ] ; NEW_LINE n = len ( height ) ; NEW_LINE print ( maxWater ( height , n ) ) ; NEW_LINE DEDENT |
Check if the given array contains all the divisors of some integer | Python 3 implementation of the approach ; Function that returns true if arr [ ] contains all the divisors of some integer ; Maximum element from the array ; Vector to store divisors of the maximum element i . e . X ; Store all the divisors of X ; If the lengths of a [ ] and b are different return false ; Sort a [ ] and b ; If divisors are not equal return false ; Driver code | from math import sqrt NEW_LINE def checkDivisors ( a , n ) : NEW_LINE INDENT X = max ( a ) NEW_LINE b = [ ] NEW_LINE for i in range ( 1 , int ( sqrt ( X ) ) + 1 ) : NEW_LINE INDENT if ( X % i == 0 ) : NEW_LINE INDENT b . append ( i ) NEW_LINE if ( X // i != i ) : NEW_LINE INDENT b . append ( X // i ) NEW_LINE DEDENT DEDENT DEDENT if ( len ( b ) != n ) : NEW_LINE INDENT return False NEW_LINE DEDENT a . sort ( reverse = False ) NEW_LINE b . sort ( reverse = False ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( b [ i ] != a [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 1 , 2 , 12 , 48 , 6 , 4 , 24 , 16 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE if ( checkDivisors ( arr , N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Kth largest node among all directly connected nodes to the given node in an undirected graph | Function to print Kth node for each node ; Vector to store nodes directly connected to ith node along with their values ; Add edges to the vector along with the values of the node ; Sort neighbors of every node and find the Kth node ; Get the kth node ; If total nodes are < k ; Driver code | def findKthNode ( u , v , n , val , V , k ) : NEW_LINE INDENT g = [ [ ] for i in range ( V ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT g [ u [ i ] ] . append ( ( val [ v [ i ] ] , v [ i ] ) ) NEW_LINE g [ v [ i ] ] . append ( ( val [ u [ i ] ] , u [ i ] ) ) NEW_LINE DEDENT for i in range ( 0 , V ) : NEW_LINE INDENT if len ( g [ i ] ) > 0 : NEW_LINE INDENT g [ i ] . sort ( ) NEW_LINE DEDENT if k <= len ( g [ i ] ) : NEW_LINE INDENT print ( g [ i ] [ - k ] [ 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT V = 3 NEW_LINE val = [ 2 , 4 , 3 ] NEW_LINE u = [ 0 , 0 , 1 ] NEW_LINE v = [ 2 , 1 , 2 ] NEW_LINE n , k = len ( u ) , 2 NEW_LINE findKthNode ( u , v , n , val , V , k ) NEW_LINE DEDENT |
Minimum length of square to contain at least half of the given Coordinates | Function to Calculate the Minimum value of M ; To store the minimum M for each point in array ; Sort the array ; Index at which atleast required point are inside square of length 2 * M ; Driver Code | def findSquare ( n ) : NEW_LINE INDENT points = [ [ 1 , 2 ] , [ - 3 , 4 ] , [ 1 , 78 ] , [ - 3 , - 7 ] ] NEW_LINE a = [ None ] * n NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT x = points [ i ] [ 0 ] NEW_LINE y = points [ i ] [ 1 ] NEW_LINE a [ i ] = max ( abs ( x ) , abs ( y ) ) NEW_LINE DEDENT a . sort ( ) NEW_LINE index = n // 2 - 1 NEW_LINE print ( " Minimum β M β required β is : " , a [ index ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE findSquare ( N ) NEW_LINE DEDENT |
Eulerian Path in undirected graph | Function to find out the path It takes the adjacency matrix representation of the graph as input ; Find out number of edges each vertex has ; Find out how many vertex has odd number edges ; If number of vertex with odd number of edges is greater than two return " No β Solution " . ; If there is a path find the path Initialize empty stack and path take the starting current as discussed ; Loop will run until there is element in the stack or current edge has some neighbour . ; If current node has not any neighbour add it to path and pop stack set new current to the popped element ; If the current vertex has at least one neighbour add the current vertex to stack , remove the edge between them and set the current to its neighbour . ; Print the path ; Driver Code ; Test case 1 ; Test case 2 ; Test case 3 | def findpath ( graph , n ) : NEW_LINE INDENT numofadj = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT numofadj . append ( sum ( graph [ i ] ) ) NEW_LINE DEDENT startpoint , numofodd = 0 , 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( numofadj [ i ] % 2 == 1 ) : NEW_LINE INDENT numofodd += 1 NEW_LINE startpoint = i NEW_LINE DEDENT DEDENT if ( numofodd > 2 ) : NEW_LINE INDENT print ( " No β Solution " ) NEW_LINE return NEW_LINE DEDENT stack = [ ] NEW_LINE path = [ ] NEW_LINE cur = startpoint NEW_LINE while ( len ( stack ) > 0 or sum ( graph [ cur ] ) != 0 ) : NEW_LINE INDENT if ( sum ( graph [ cur ] ) == 0 ) : NEW_LINE INDENT path . append ( cur ) NEW_LINE cur = stack [ - 1 ] NEW_LINE del stack [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( graph [ cur ] [ i ] == 1 ) : NEW_LINE INDENT stack . append ( cur ) NEW_LINE graph [ cur ] [ i ] = 0 NEW_LINE graph [ i ] [ cur ] = 0 NEW_LINE cur = i NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT for ele in path : NEW_LINE INDENT print ( ele , end = " β - > β " ) NEW_LINE DEDENT print ( cur ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT graph1 = [ [ 0 , 1 , 0 , 0 , 1 ] , [ 1 , 0 , 1 , 1 , 0 ] , [ 0 , 1 , 0 , 1 , 0 ] , [ 0 , 1 , 1 , 0 , 0 ] , [ 1 , 0 , 0 , 0 , 0 ] ] NEW_LINE n = len ( graph1 ) NEW_LINE findpath ( graph1 , n ) NEW_LINE graph2 = [ [ 0 , 1 , 0 , 1 , 1 ] , [ 1 , 0 , 1 , 0 , 1 ] , [ 0 , 1 , 0 , 1 , 1 ] , [ 1 , 1 , 1 , 0 , 0 ] , [ 1 , 0 , 1 , 0 , 0 ] ] NEW_LINE n = len ( graph2 ) NEW_LINE findpath ( graph2 , n ) NEW_LINE graph3 = [ [ 0 , 1 , 0 , 0 , 1 ] , [ 1 , 0 , 1 , 1 , 1 ] , [ 0 , 1 , 0 , 1 , 0 ] , [ 0 , 1 , 1 , 0 , 1 ] , [ 1 , 1 , 0 , 1 , 0 ] ] NEW_LINE n = len ( graph3 ) NEW_LINE findpath ( graph3 , n ) NEW_LINE DEDENT |
Array element with minimum sum of absolute differences | Function to return the minimized sum ; Sort the array ; Median of the array ; Calculate the minimized sum ; Return the required sum ; Driver code | def minSum ( arr , n ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE x = arr [ n // 2 ] ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += abs ( arr [ i ] - x ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 9 , 3 , 6 ] ; NEW_LINE n = len ( arr ) NEW_LINE print ( minSum ( arr , n ) ) ; NEW_LINE DEDENT |
Sort even and odd placed elements in increasing order | function to prin the odd and even indexed digits ; lists to store the odd and even positioned digits ; traverse through all the indexes in the integer ; if the digit is in odd_index position append it to odd_position list ; else append it to the even_position list ; print the elements in the list in sorted order ; Driver Code | def odd_even ( n ) : NEW_LINE INDENT odd_indexes = [ ] NEW_LINE even_indexes = [ ] NEW_LINE for i in range ( len ( n ) ) : NEW_LINE INDENT if i % 2 == 0 : odd_indexes . append ( n [ i ] ) NEW_LINE else : even_indexes . append ( n [ i ] ) NEW_LINE DEDENT for i in sorted ( odd_indexes ) : print ( i , end = " β " ) NEW_LINE for i in sorted ( even_indexes ) : print ( i , end = " β " ) NEW_LINE DEDENT n = [ 3 , 2 , 7 , 6 , 8 ] NEW_LINE odd_even ( n ) NEW_LINE |
Number of pairs whose sum is a power of 2 | Function to return the count of valid pairs ; Storing occurrences of each element ; Sort the array in deceasing order ; Start taking largest element each time ; If element has already been paired ; Find the number which is greater than a [ i ] and power of two ; If there is a number which adds up with a [ i ] to form a power of two ; Edge case when a [ i ] and crr - a [ i ] is same and we have only one occurrence of a [ i ] then it cannot be paired ; Remove already paired elements ; Return the count ; Driver code | def countPairs ( a , n ) : NEW_LINE INDENT mp = dict . fromkeys ( a , 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ a [ i ] ] += 1 NEW_LINE DEDENT a . sort ( reverse = True ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( mp [ a [ i ] ] < 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT cur = 1 NEW_LINE while ( cur <= a [ i ] ) : NEW_LINE INDENT cur = cur << 1 NEW_LINE DEDENT if ( cur - a [ i ] in mp . keys ( ) ) : NEW_LINE INDENT if ( cur - a [ i ] == a [ i ] and mp [ a [ i ] ] == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT count += 1 NEW_LINE mp [ cur - a [ i ] ] -= 1 NEW_LINE mp [ a [ i ] ] -= 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 3 , 11 , 14 , 5 , 13 ] NEW_LINE n = len ( a ) NEW_LINE print ( countPairs ( a , n ) ) NEW_LINE DEDENT |
Maximizing the elements with a [ i + 1 ] > a [ i ] | Returns the number of positions where A ( i + 1 ) is greater than A ( i ) after rearrangement of the array ; Creating a HashMap containing char as a key and occurrences as a value ; Find the maximum frequency ; Driver code | def countMaxPos ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE Map = { } NEW_LINE for x in arr : NEW_LINE INDENT if x in Map : NEW_LINE INDENT Map [ x ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Map [ x ] = 1 NEW_LINE DEDENT DEDENT max_freq = 0 NEW_LINE for entry in Map : NEW_LINE INDENT max_freq = max ( max_freq , Map [ entry ] ) NEW_LINE DEDENT return n - max_freq NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 20 , 30 , 10 , 50 , 40 ] NEW_LINE print ( countMaxPos ( arr ) ) NEW_LINE DEDENT |
Permutation of an array that has smaller values from another array | Function to print required permutation ; Storing elements and indexes ; Filling the answer array ; pair element of A and B ; Fill the remaining elements of answer ; Output required permutation ; Driver Code | def anyPermutation ( A , B , n ) : NEW_LINE INDENT Ap , Bp = [ ] , [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Ap . append ( [ A [ i ] , i ] ) NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT Bp . append ( [ B [ i ] , i ] ) NEW_LINE DEDENT Ap . sort ( ) NEW_LINE Bp . sort ( ) NEW_LINE i , j = 0 , 0 , NEW_LINE ans = [ 0 ] * n NEW_LINE remain = [ ] NEW_LINE while i < n and j < n : NEW_LINE INDENT if Ap [ i ] [ 0 ] > Bp [ j ] [ 0 ] : NEW_LINE INDENT ans [ Bp [ j ] [ 1 ] ] = Ap [ i ] [ 0 ] NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT remain . append ( i ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT j = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ans [ i ] == 0 : NEW_LINE INDENT ans [ i ] = Ap [ remain [ j ] ] [ 0 ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 12 , 24 , 8 , 32 ] NEW_LINE B = [ 13 , 25 , 32 , 11 ] NEW_LINE n = len ( A ) NEW_LINE anyPermutation ( A , B , n ) NEW_LINE DEDENT |
Rearrange all elements of array which are multiples of x in increasing order | Function to sort all the multiples of x from the array in ascending order ; Insert all multiples of 5 to a vector ; Sort the vector ; update the array elements ; Driver code ; Print the result | def sortMultiples ( arr , n , x ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( arr [ i ] % x == 0 ) : NEW_LINE INDENT v . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT v . sort ( reverse = False ) NEW_LINE j = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( arr [ i ] % x == 0 ) : NEW_LINE INDENT arr [ i ] = v [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 125 , 3 , 15 , 6 , 100 , 5 ] NEW_LINE x = 5 NEW_LINE n = len ( arr ) NEW_LINE sortMultiples ( arr , n , x ) NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT |
Minimum increment in the sides required to get non | Function to return the minimum increase in side lengths of the triangle ; push the three sides to a array ; sort the array ; check if sum is greater than third side ; Driver code | def minimumIncrease ( a , b , c ) : NEW_LINE INDENT arr = [ a , b , c ] NEW_LINE arr . sort ( ) NEW_LINE if arr [ 0 ] + arr [ 1 ] >= arr [ 2 ] : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return arr [ 2 ] - ( arr [ 0 ] + arr [ 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a , b , c = 3 , 5 , 10 NEW_LINE print ( minimumIncrease ( a , b , c ) ) NEW_LINE DEDENT |
Minimum sum of differences with an element in an array | function to find min sum after operation ; Sort the array ; Pick middle value ; Sum of absolute differences . ; Driver Code | def absSumDidd ( a , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE midValue = a [ ( int ) ( n // 2 ) ] NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + abs ( a [ i ] - midValue ) NEW_LINE DEDENT return sum NEW_LINE DEDENT arr = [ 5 , 11 , 14 , 10 , 17 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE print ( absSumDidd ( arr , n ) ) NEW_LINE |
Printing frequency of each character just after its consecutive occurrences | Python 3 program to print run length encoding of a string ; Counting occurrences of s [ i ] ; Driver Code | def printRLE ( s ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i < len ( s ) - 1 ) : NEW_LINE INDENT count = 1 NEW_LINE while s [ i ] == s [ i + 1 ] : NEW_LINE INDENT i += 1 NEW_LINE count += 1 NEW_LINE if i + 1 == len ( s ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( str ( s [ i ] ) + str ( count ) , end = " β " ) NEW_LINE i += 1 NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT printRLE ( " GeeeEEKKKss " ) NEW_LINE printRLE ( " cccc0ddEEE " ) NEW_LINE DEDENT |
Word Ladder ( Length of shortest chain to reach a target word ) | Python3 program to find length of the shortest chain transformation from source to target ; Returns length of shortest chain to reach ' target ' from ' start ' using minimum number of adjacent moves . D is dictionary ; If the target is not present in the dictionary ; To store the current chain length and the length of the words ; Push the starting word into the queue ; While the queue is non - empty ; Increment the chain length ; Current size of the queue ; Since the queue is being updated while it is being traversed so only the elements which were already present in the queue before the start of this loop will be traversed for now ; Remove the first word from the queue ; For every character of the word ; Retain the original character at the current position ; Replace the current character with every possible lowercase alphabet ; If the new word is equal to the target word ; Remove the word from the set if it is found in it ; And push the newly generated word which will be a part of the chain ; Restore the original character at the current position ; Driver code ; Make dictionary | from collections import deque NEW_LINE def shortestChainLen ( start , target , D ) : NEW_LINE INDENT if start == target : NEW_LINE return 0 NEW_LINE if target not in D : NEW_LINE INDENT return 0 NEW_LINE DEDENT level , wordlength = 0 , len ( start ) NEW_LINE Q = deque ( ) NEW_LINE Q . append ( start ) NEW_LINE while ( len ( Q ) > 0 ) : NEW_LINE INDENT level += 1 NEW_LINE sizeofQ = len ( Q ) NEW_LINE for i in range ( sizeofQ ) : NEW_LINE INDENT word = [ j for j in Q . popleft ( ) ] NEW_LINE for pos in range ( wordlength ) : NEW_LINE INDENT orig_char = word [ pos ] NEW_LINE for c in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT word [ pos ] = chr ( c ) NEW_LINE if ( " " . join ( word ) == target ) : NEW_LINE INDENT return level + 1 NEW_LINE DEDENT if ( " " . join ( word ) not in D ) : NEW_LINE INDENT continue NEW_LINE DEDENT del D [ " " . join ( word ) ] NEW_LINE Q . append ( " " . join ( word ) ) NEW_LINE DEDENT word [ pos ] = orig_char NEW_LINE DEDENT DEDENT DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT D = { } NEW_LINE D [ " poon " ] = 1 NEW_LINE D [ " plee " ] = 1 NEW_LINE D [ " same " ] = 1 NEW_LINE D [ " poie " ] = 1 NEW_LINE D [ " plie " ] = 1 NEW_LINE D [ " poin " ] = 1 NEW_LINE D [ " plea " ] = 1 NEW_LINE start = " toon " NEW_LINE target = " plea " NEW_LINE print ( " Length β of β shortest β chain β is : β " , shortestChainLen ( start , target , D ) ) NEW_LINE DEDENT |
Find if an array of strings can be chained to form a circle | Set 2 | Python3 code to check if cyclic order is possible among strings under given constrainsts ; Utility method for a depth first search among vertices ; Returns true if all vertices are strongly connected i . e . can be made as loop ; Initialize all vertices as not visited ; Perform a dfs from s ; Now loop through all characters ; I character is marked ( i . e . it was first or last character of some string ) then it should be visited in last dfs ( as for looping , graph should be strongly connected ) ; If we reach that means graph is connected ; return true if an order among strings is possible ; Create an empty graph ; Initialize all vertices as not marked ; Initialize indegree and outdegree of every vertex as 0. ; Process all strings one by one ; Find first and last characters ; Mark the characters ; Increase indegree and outdegree count ; Add an edge in graph ; If for any character indegree is not equal to outdegree then ordering is not possible ; Driver code | M = 26 NEW_LINE def dfs ( g , u , visit ) : NEW_LINE INDENT visit [ u ] = True NEW_LINE for i in range ( len ( g [ u ] ) ) : NEW_LINE INDENT if ( not visit [ g [ u ] [ i ] ] ) : NEW_LINE INDENT dfs ( g , g [ u ] [ i ] , visit ) NEW_LINE DEDENT DEDENT DEDENT def isConnected ( g , mark , s ) : NEW_LINE INDENT visit = [ False for i in range ( M ) ] NEW_LINE dfs ( g , s , visit ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT if ( mark [ i ] and ( not visit [ i ] ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def possibleOrderAmongString ( arr , N ) : NEW_LINE INDENT g = { } NEW_LINE mark = [ False for i in range ( M ) ] NEW_LINE In = [ 0 for i in range ( M ) ] NEW_LINE out = [ 0 for i in range ( M ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT f = ( ord ( arr [ i ] [ 0 ] ) - ord ( ' a ' ) ) NEW_LINE l = ( ord ( arr [ i ] [ - 1 ] ) - ord ( ' a ' ) ) NEW_LINE mark [ f ] = True NEW_LINE mark [ l ] = True NEW_LINE In [ l ] += 1 NEW_LINE out [ f ] += 1 NEW_LINE if f not in g : NEW_LINE INDENT g [ f ] = [ ] NEW_LINE DEDENT g [ f ] . append ( l ) NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT if ( In [ i ] != out [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return isConnected ( g , mark , ord ( arr [ 0 ] [ 0 ] ) - ord ( ' a ' ) ) NEW_LINE DEDENT arr = [ " ab " , " bc " , " cd " , " de " , " ed " , " da " ] NEW_LINE N = len ( arr ) NEW_LINE if ( possibleOrderAmongString ( arr , N ) == False ) : NEW_LINE INDENT print ( " Ordering β not β possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Ordering β is β possible " ) NEW_LINE DEDENT |
Dynamic Connectivity | Set 1 ( Incremental ) | Finding the root of node i ; union of two nodes a and b ; union based on rank ; Returns true if two nodes have same root ; Performing an operation according to query type ; type 1 query means checking if node x and y are connected or not ; If roots of x and y is same then yes is the answer ; type 2 query refers union of x and y ; If x and y have different roots then union them ; Driver Code ; No . of nodes ; The following two arrays are used to implement disjoset data structure . arr [ ] holds the parent nodes while rank array holds the rank of subset ; initializing both array and rank ; number of queries | def root ( arr , i ) : NEW_LINE INDENT while ( arr [ i ] != i ) : NEW_LINE INDENT arr [ i ] = arr [ arr [ i ] ] NEW_LINE i = arr [ i ] NEW_LINE DEDENT return i NEW_LINE DEDENT def weighted_union ( arr , rank , a , b ) : NEW_LINE INDENT root_a = root ( arr , a ) NEW_LINE root_b = root ( arr , b ) NEW_LINE if ( rank [ root_a ] < rank [ root_b ] ) : NEW_LINE INDENT arr [ root_a ] = arr [ root_b ] NEW_LINE rank [ root_b ] += rank [ root_a ] NEW_LINE DEDENT else : NEW_LINE INDENT arr [ root_b ] = arr [ root_a ] NEW_LINE rank [ root_a ] += rank [ root_b ] NEW_LINE DEDENT DEDENT def areSame ( arr , a , b ) : NEW_LINE INDENT return ( root ( arr , a ) == root ( arr , b ) ) NEW_LINE DEDENT def query ( type , x , y , arr , rank ) : NEW_LINE INDENT if ( type == 1 ) : NEW_LINE INDENT if ( areSame ( arr , x , y ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT elif ( type == 2 ) : NEW_LINE INDENT if ( areSame ( arr , x , y ) == False ) : NEW_LINE INDENT weighted_union ( arr , rank , x , y ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 NEW_LINE arr = [ None ] * n NEW_LINE rank = [ None ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = i NEW_LINE rank [ i ] = 1 NEW_LINE DEDENT q = 11 NEW_LINE query ( 1 , 0 , 1 , arr , rank ) NEW_LINE query ( 2 , 0 , 1 , arr , rank ) NEW_LINE query ( 2 , 1 , 2 , arr , rank ) NEW_LINE query ( 1 , 0 , 2 , arr , rank ) NEW_LINE query ( 2 , 0 , 2 , arr , rank ) NEW_LINE query ( 2 , 2 , 3 , arr , rank ) NEW_LINE query ( 2 , 3 , 4 , arr , rank ) NEW_LINE query ( 1 , 0 , 5 , arr , rank ) NEW_LINE query ( 2 , 4 , 5 , arr , rank ) NEW_LINE query ( 2 , 5 , 6 , arr , rank ) NEW_LINE query ( 1 , 2 , 6 , arr , rank ) NEW_LINE DEDENT |
Perfect Binary Tree Specific Level Order Traversal | A binary tree ndoe ; Given a perfect binary tree print its node in specific order ; Let us print root and next level first ; Since it is perfect Binary tree , one of the node is needed to be checked ; Do anythong more if there are nodes at next level in given perfect Binary Tree ; Create a queue and enqueue left and right children of root ; We process two nodes at a time , so we need two variables to stroe two front items of queue ; Traversal loop ; Pop two items from queue ; Print children of first and second in reverse order ; If first and second have grandchildren , enqueue them in reverse order ; Driver program to test above function Perfect Binary Tree of Height 4 | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printSpecificLevelOrder ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT print root . data , NEW_LINE if root . left is not None : NEW_LINE INDENT print root . left . data , NEW_LINE print root . right . data , NEW_LINE DEDENT if root . left . left is None : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root . left ) NEW_LINE q . append ( root . right ) NEW_LINE first = None NEW_LINE second = None NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT first = q . pop ( 0 ) NEW_LINE second = q . pop ( 0 ) NEW_LINE print first . left . data , NEW_LINE print second . right . data , NEW_LINE print first . right . data , NEW_LINE print second . left . data , NEW_LINE if first . left . left is not None : NEW_LINE INDENT q . append ( first . left ) NEW_LINE q . append ( second . right ) NEW_LINE q . append ( first . right ) NEW_LINE q . append ( second . left ) NEW_LINE DEDENT DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . left . left . left = Node ( 8 ) NEW_LINE root . left . left . right = Node ( 9 ) NEW_LINE root . left . right . left = Node ( 10 ) NEW_LINE root . left . right . right = Node ( 11 ) NEW_LINE root . right . left . left = Node ( 12 ) NEW_LINE root . right . left . right = Node ( 13 ) NEW_LINE root . right . right . left = Node ( 14 ) NEW_LINE root . right . right . right = Node ( 15 ) NEW_LINE root . left . left . left . left = Node ( 16 ) NEW_LINE root . left . left . left . right = Node ( 17 ) NEW_LINE root . left . left . right . left = Node ( 18 ) NEW_LINE root . left . left . right . right = Node ( 19 ) NEW_LINE root . left . right . left . left = Node ( 20 ) NEW_LINE root . left . right . left . right = Node ( 21 ) NEW_LINE root . left . right . right . left = Node ( 22 ) NEW_LINE root . left . right . right . right = Node ( 23 ) NEW_LINE root . right . left . left . left = Node ( 24 ) NEW_LINE root . right . left . left . right = Node ( 25 ) NEW_LINE root . right . left . right . left = Node ( 26 ) NEW_LINE root . right . left . right . right = Node ( 27 ) NEW_LINE root . right . right . left . left = Node ( 28 ) NEW_LINE root . right . right . left . right = Node ( 29 ) NEW_LINE root . right . right . right . left = Node ( 30 ) NEW_LINE root . right . right . right . right = Node ( 31 ) NEW_LINE print " Specific β Level β Order β traversal β of β binary β tree β is " NEW_LINE printSpecificLevelOrder ( root ) ; NEW_LINE |
Ford | Python program for implementation of Ford Fulkerson algorithm ; Returns true if there is a path from source ' s ' to sink ' t ' in residual graph . Also fills parent [ ] to store the path ; Mark all the vertices as not visited ; Create a queue for BFS ; Standard BFS Loop ; If we find a connection to the sink node , then there is no point in BFS anymore We just have to set its parent and can return true ; We didn 't reach sink in BFS starting from source, so return false ; Returns tne maximum flow from s to t in the given graph ; This class represents a directed graph using adjacency matrix representation ; This array is filled by BFS and to store path ; There is no flow initially ; Augment the flow while there is path from source to sink ; Find minimum residual capacity of the edges along the path filled by BFS . Or we can say find the maximum flow through the path found . ; update residual capacities of the edges and reverse edges along the path ; Add path flow to overall flow ; Return the overall flow ; Create a graph given in the above diagram | from collections import defaultdict NEW_LINE INDENT def BFS ( self , s , t , parent ) : NEW_LINE INDENT visited = [ False ] * ( self . ROW ) NEW_LINE queue = [ ] NEW_LINE queue . append ( s ) NEW_LINE visited [ s ] = True NEW_LINE while queue : NEW_LINE INDENT u = queue . pop ( 0 ) NEW_LINE for ind , val in enumerate ( self . graph [ u ] ) : NEW_LINE INDENT if visited [ ind ] == False and val > 0 : NEW_LINE INDENT if ind == t : NEW_LINE INDENT visited [ ind ] = True NEW_LINE return True NEW_LINE DEDENT queue . append ( ind ) NEW_LINE visited [ ind ] = True NEW_LINE parent [ ind ] = u NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT def FordFulkerson ( self , source , sink ) : NEW_LINE DEDENT class Graph : NEW_LINE INDENT def __init__ ( self , graph ) : NEW_LINE INDENT self . graph = graph NEW_LINE self . ROW = len ( graph ) NEW_LINE parent = [ - 1 ] * ( self . ROW ) NEW_LINE DEDENT DEDENT max_flow = 0 NEW_LINE INDENT while self . BFS ( source , sink , parent ) : NEW_LINE INDENT path_flow = float ( " Inf " ) NEW_LINE s = sink NEW_LINE while ( s != source ) : NEW_LINE INDENT path_flow = min ( path_flow , self . graph [ parent [ s ] ] [ s ] ) NEW_LINE s = parent [ s ] NEW_LINE DEDENT v = sink NEW_LINE while ( v != source ) : NEW_LINE INDENT u = parent [ v ] NEW_LINE self . graph [ u ] [ v ] -= path_flow NEW_LINE self . graph [ v ] [ u ] += path_flow NEW_LINE v = parent [ v ] NEW_LINE DEDENT max_flow += path_flow NEW_LINE DEDENT return max_flow NEW_LINE DEDENT graph = [ [ 0 , 16 , 13 , 0 , 0 , 0 ] , [ 0 , 0 , 10 , 12 , 0 , 0 ] , [ 0 , 4 , 0 , 0 , 14 , 0 ] , [ 0 , 0 , 9 , 0 , 0 , 20 ] , [ 0 , 0 , 0 , 7 , 0 , 4 ] , [ 0 , 0 , 0 , 0 , 0 , 0 ] ] NEW_LINE g = Graph ( graph ) NEW_LINE source = 0 ; sink = 5 NEW_LINE print ( " The β maximum β possible β flow β is β % d β " % g . FordFulkerson ( source , sink ) ) NEW_LINE |
Channel Assignment Problem | A Depth First Search based recursive function that returns true if a matching for vertex u is possible ; Try every receiver one by one ; If sender u has packets to send to receiver v and receiver v is not already mapped to any other sender just check if the number of packets is greater than '0' because only one packet can be sent in a time frame anyways ; Mark v as visited ; If receiver ' v ' is not assigned to any sender OR previously assigned sender for receiver v ( which is matchR [ v ] ) has an alternate receiver available . Since v is marked as visited in the above line , matchR [ v ] in the following recursive call will not get receiver ' v ' again ; Returns maximum number of packets that can be sent parallely in 1 time slot from sender to receiver ; Initially all receivers are not mapped to any senders ; Count of receivers assigned to senders ; Mark all receivers as not seen for next sender ; Find if the sender ' u ' can be assigned to the receiver ; Driver Code | def bpm ( table , u , seen , matchR ) : NEW_LINE INDENT global M , N NEW_LINE for v in range ( N ) : NEW_LINE INDENT if ( table [ u ] [ v ] > 0 and not seen [ v ] ) : NEW_LINE INDENT seen [ v ] = True NEW_LINE if ( matchR [ v ] < 0 or bpm ( table , matchR [ v ] , seen , matchR ) ) : NEW_LINE INDENT matchR [ v ] = u NEW_LINE return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT def maxBPM ( table ) : NEW_LINE INDENT global M , N NEW_LINE matchR = [ - 1 ] * N NEW_LINE result = 0 NEW_LINE for u in range ( M ) : NEW_LINE INDENT seen = [ 0 ] * N NEW_LINE if ( bpm ( table , u , seen , matchR ) ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT print ( " The β number β of β maximum β packets β sent " , " in β the β time β slot β is " , result ) NEW_LINE for x in range ( N ) : NEW_LINE INDENT if ( matchR [ x ] + 1 != 0 ) : NEW_LINE INDENT print ( " T " , matchR [ x ] + 1 , " - > β R " , x + 1 ) NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT M = 3 NEW_LINE N = 4 NEW_LINE table = [ [ 0 , 2 , 0 ] , [ 3 , 0 , 1 ] , [ 2 , 4 , 0 ] ] NEW_LINE max_flow = maxBPM ( table ) NEW_LINE |
Prim 's algorithm using priority_queue in STL | If v is not in MST and weight of ( u , v ) is smaller than current key of v ; Updating key of v | if ( inMST [ v ] == False and key [ v ] > weight ) : NEW_LINE INDENT key [ v ] = weight NEW_LINE pq . append ( [ key [ v ] , v ] ) NEW_LINE parent [ v ] = u NEW_LINE DEDENT |
Graph implementation using STL for competitive programming | Set 2 ( Weighted graph ) | To add an edge ; Print adjacency list representaion ot graph ; Driver code | def addEdge ( adj , u , v , wt ) : NEW_LINE INDENT adj [ u ] . append ( [ v , wt ] ) NEW_LINE adj [ v ] . append ( [ u , wt ] ) NEW_LINE return adj NEW_LINE DEDENT def printGraph ( adj , V ) : NEW_LINE INDENT v , w = 0 , 0 NEW_LINE for u in range ( V ) : NEW_LINE INDENT print ( " Node " , u , " makes β an β edge β with " ) NEW_LINE for it in adj [ u ] : NEW_LINE INDENT v = it [ 0 ] NEW_LINE w = it [ 1 ] NEW_LINE print ( " TABSYMBOL Node " , v , " with β edge β weight β = " , w ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = 5 NEW_LINE adj = [ [ ] for i in range ( V ) ] NEW_LINE adj = addEdge ( adj , 0 , 1 , 10 ) NEW_LINE adj = addEdge ( adj , 0 , 4 , 20 ) NEW_LINE adj = addEdge ( adj , 1 , 2 , 30 ) NEW_LINE adj = addEdge ( adj , 1 , 3 , 40 ) NEW_LINE adj = addEdge ( adj , 1 , 4 , 50 ) NEW_LINE adj = addEdge ( adj , 2 , 3 , 60 ) NEW_LINE adj = addEdge ( adj , 3 , 4 , 70 ) NEW_LINE printGraph ( adj , V ) NEW_LINE DEDENT |
K Centers Problem | Set 1 ( Greedy Approximate Algorithm ) | Python3 program for the above approach ; index of city having the maximum distance to it 's closest center ; updating the distance of the cities to their closest centers ; updating the index of the city with the maximum distance to it 's closest center ; Printing the maximum distance of a city to a center that is our answer print ( ) ; Printing the cities that were chosen to be made centers ; Driver Code ; Function Call | def maxindex ( dist , n ) : NEW_LINE INDENT mi = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( dist [ i ] > dist [ mi ] ) : NEW_LINE INDENT mi = i NEW_LINE DEDENT DEDENT return mi NEW_LINE DEDENT def selectKcities ( n , weights , k ) : NEW_LINE INDENT dist = [ 0 ] * n NEW_LINE centers = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dist [ i ] = 10 ** 9 NEW_LINE DEDENT max = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT centers . append ( max ) NEW_LINE for j in range ( n ) : NEW_LINE INDENT dist [ j ] = min ( dist [ j ] , weights [ max ] [ j ] ) NEW_LINE DEDENT max = maxindex ( dist , n ) NEW_LINE DEDENT print ( dist [ max ] ) NEW_LINE for i in centers : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE weights = [ [ 0 , 4 , 8 , 5 ] , [ 4 , 0 , 10 , 7 ] , [ 8 , 10 , 0 , 9 ] , [ 5 , 7 , 9 , 0 ] ] NEW_LINE k = 2 NEW_LINE selectKcities ( n , weights , k ) NEW_LINE DEDENT |
Hierholzer 's Algorithm for directed graph | Python3 program to print Eulerian circuit in given directed graph using Hierholzer algorithm ; adj represents the adjacency list of the directed graph edge_count represents the number of edges emerging from a vertex ; find the count of edges to keep track of unused edges ; empty graph Maintain a stack to keep vertices ; vector to store final circuit ; start from any vertex ; Current vertex ; If there 's remaining edge ; Push the vertex ; Find the next vertex using an edge ; and remove that edge ; Move to next vertex ; back - track to find remaining circuit ; Back - tracking ; we 've got the circuit, now print it in reverse ; Driver Code ; Input Graph 1 ; Build the edges ; Input Graph 2 | def printCircuit ( adj ) : NEW_LINE INDENT edge_count = dict ( ) NEW_LINE for i in range ( len ( adj ) ) : NEW_LINE INDENT edge_count [ i ] = len ( adj [ i ] ) NEW_LINE DEDENT if len ( adj ) == 0 : NEW_LINE INDENT return NEW_LINE DEDENT curr_path = [ ] NEW_LINE circuit = [ ] NEW_LINE curr_path . append ( 0 ) NEW_LINE curr_v = 0 NEW_LINE while len ( curr_path ) : NEW_LINE INDENT if edge_count [ curr_v ] : NEW_LINE INDENT curr_path . append ( curr_v ) NEW_LINE next_v = adj [ curr_v ] [ - 1 ] NEW_LINE edge_count [ curr_v ] -= 1 NEW_LINE adj [ curr_v ] . pop ( ) NEW_LINE curr_v = next_v NEW_LINE DEDENT else : NEW_LINE INDENT circuit . append ( curr_v ) NEW_LINE curr_v = curr_path [ - 1 ] NEW_LINE curr_path . pop ( ) NEW_LINE DEDENT DEDENT for i in range ( len ( circuit ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( circuit [ i ] , end = " " ) NEW_LINE if i : NEW_LINE INDENT print ( " β - > β " , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT adj1 = [ 0 ] * 3 NEW_LINE for i in range ( 3 ) : NEW_LINE INDENT adj1 [ i ] = [ ] NEW_LINE DEDENT adj1 [ 0 ] . append ( 1 ) NEW_LINE adj1 [ 1 ] . append ( 2 ) NEW_LINE adj1 [ 2 ] . append ( 0 ) NEW_LINE printCircuit ( adj1 ) NEW_LINE print ( ) NEW_LINE adj2 = [ 0 ] * 7 NEW_LINE for i in range ( 7 ) : NEW_LINE INDENT adj2 [ i ] = [ ] NEW_LINE DEDENT adj2 [ 0 ] . append ( 1 ) NEW_LINE adj2 [ 0 ] . append ( 6 ) NEW_LINE adj2 [ 1 ] . append ( 2 ) NEW_LINE adj2 [ 2 ] . append ( 0 ) NEW_LINE adj2 [ 2 ] . append ( 3 ) NEW_LINE adj2 [ 3 ] . append ( 4 ) NEW_LINE adj2 [ 4 ] . append ( 2 ) NEW_LINE adj2 [ 4 ] . append ( 5 ) NEW_LINE adj2 [ 5 ] . append ( 0 ) NEW_LINE adj2 [ 6 ] . append ( 4 ) NEW_LINE printCircuit ( adj2 ) NEW_LINE print ( ) NEW_LINE DEDENT |
Perfect Binary Tree Specific Level Order Traversal | Set 2 | Linked List node ; Given a perfect binary tree , print its nodes in specific level order ; for level order traversal ; Stack to print reverse ; vector to store the level ; considering size of the level ; push data of the node of a particular level to vector ; push vector containing a level in Stack ; print the Stack ; Finally pop all Nodes from Stack and prints them . ; finally print root ; Driver code | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def specific_level_order_traversal ( root ) : NEW_LINE INDENT q = [ ] NEW_LINE s = [ ] NEW_LINE q . append ( root ) NEW_LINE sz = 0 NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT v = [ ] NEW_LINE sz = len ( q ) NEW_LINE i = 0 NEW_LINE while ( i < sz ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE v . append ( temp . data ) NEW_LINE if ( temp . left != None ) : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right != None ) : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT s . append ( v ) NEW_LINE DEDENT while ( len ( s ) > 0 ) : NEW_LINE INDENT v = s [ - 1 ] NEW_LINE s . pop ( ) NEW_LINE i = 0 NEW_LINE j = len ( v ) - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT print ( v [ i ] , " β " , v [ j ] , end = " β " ) NEW_LINE j = j - 1 NEW_LINE i = i + 1 NEW_LINE DEDENT DEDENT print ( root . data ) NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE print ( " Specific β Level β Order β traversal β of β binary β tree β is " ) NEW_LINE specific_level_order_traversal ( root ) NEW_LINE |
Number of Triangles in an Undirected Graph | Number of vertices in the graph ; Utility function for matrix multiplication ; Utility function to calculate trace of a matrix ( sum ofdiagnonal elements ) ; Utility function for calculating number of triangles in graph ; To Store graph ^ 2 ; To Store graph ^ 3 ; Initialising aux matrices with 0 ; aux2 is graph ^ 2 now printMatrix ( aux2 ) ; after this multiplication aux3 is graph ^ 3 printMatrix ( aux3 ) ; Driver Code | V = 4 NEW_LINE def multiply ( A , B , C ) : NEW_LINE INDENT global V NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT C [ i ] [ j ] = 0 NEW_LINE for k in range ( V ) : NEW_LINE INDENT C [ i ] [ j ] += A [ i ] [ k ] * B [ k ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def getTrace ( graph ) : NEW_LINE INDENT global V NEW_LINE trace = 0 NEW_LINE for i in range ( V ) : NEW_LINE INDENT trace += graph [ i ] [ i ] NEW_LINE DEDENT return trace NEW_LINE DEDENT def triangleInGraph ( graph ) : NEW_LINE INDENT global V NEW_LINE aux2 = [ [ None ] * V for i in range ( V ) ] NEW_LINE aux3 = [ [ None ] * V for i in range ( V ) ] NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT aux2 [ i ] [ j ] = aux3 [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT multiply ( graph , graph , aux2 ) NEW_LINE multiply ( graph , aux2 , aux3 ) NEW_LINE trace = getTrace ( aux3 ) NEW_LINE return trace // 6 NEW_LINE DEDENT graph = [ [ 0 , 1 , 1 , 0 ] , [ 1 , 0 , 1 , 1 ] , [ 1 , 1 , 0 , 1 ] , [ 0 , 1 , 1 , 0 ] ] NEW_LINE print ( " Total β number β of β Triangle β in β Graph β : " , triangleInGraph ( graph ) ) NEW_LINE |
Subsequence queries after removing substrings | arrays to store results of preprocessing ; function to preprocess the strings ; initialize it as 0. ; store subsequence count in forward direction ; store number of matches till now ; store subsequence count in backward direction ; store number of matches till now ; function that gives the output ; length of remaining String A is less than B 's length ; Driver Code ; two queries | fwd = [ 0 ] * 100 NEW_LINE bwd = [ 0 ] * 100 NEW_LINE def preProcess ( a , b ) : NEW_LINE INDENT n = len ( a ) NEW_LINE j = 0 NEW_LINE for i in range ( 1 , len ( a ) + 1 ) : NEW_LINE INDENT if j < len ( b ) and a [ i - 1 ] == b [ j ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT fwd [ i ] = j NEW_LINE DEDENT j = 0 NEW_LINE for i in range ( len ( a ) , 0 , - 1 ) : NEW_LINE INDENT if ( j < len ( b ) and a [ i - 1 ] == b [ len ( b ) - j - 1 ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT bwd [ i ] = j NEW_LINE DEDENT DEDENT def query ( a , b , x , y ) : NEW_LINE INDENT if ( x - 1 + len ( a ) - y ) < len ( b ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT if ( fwd [ x - 1 ] + bwd [ y + 1 ] ) >= len ( b ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = " abcabcxy " NEW_LINE b = " acy " NEW_LINE preProcess ( a , b ) NEW_LINE x = 2 NEW_LINE y = 5 NEW_LINE query ( a , b , x , y ) NEW_LINE x = 3 NEW_LINE y = 6 NEW_LINE query ( a , b , x , y ) NEW_LINE DEDENT |
Count subsequence of length three in a given string | Function to find number of occurrences of a subsequence of length three in a string ; variable to store no of occurrences ; loop to find first character ; loop to find 2 nd character ; loop to find 3 rd character ; increment count if subsequence is found ; Driver Code | def findOccurrences ( str , substr ) : NEW_LINE INDENT counter = 0 NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == substr [ 0 ] ) : NEW_LINE INDENT for j in range ( i + 1 , len ( str ) ) : NEW_LINE INDENT if ( str [ j ] == substr [ 1 ] ) : NEW_LINE INDENT for k in range ( j + 1 , len ( str ) ) : NEW_LINE INDENT if ( str [ k ] == substr [ 2 ] ) : NEW_LINE INDENT counter = counter + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT return counter NEW_LINE DEDENT str = " GFGFGYSYIOIWIN " NEW_LINE substr = " GFG " NEW_LINE print ( findOccurrences ( str , substr ) ) NEW_LINE |
Count subsequence of length three in a given string | Function to find number of occurrences of a subsequence of length three in a string ; calculate length of string ; auxiliary array to store occurrences of first character ; auxiliary array to store occurrences of third character ; calculate occurrences of first character upto ith index from left ; calculate occurrences of third character upto ith index from right ; variable to store total number of occurrences ; loop to find the occurrences of middle element ; if middle character of subsequence is found in the string ; multiply the total occurrences of first character before middle character with the total occurrences of third character after middle character ; Driver code | def findOccurrences ( str1 , substr ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE preLeft = [ 0 for i in range ( n ) ] NEW_LINE preRight = [ 0 for i in range ( n ) ] NEW_LINE if ( str1 [ 0 ] == substr [ 0 ] ) : NEW_LINE INDENT preLeft [ 0 ] += 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( str1 [ i ] == substr [ 0 ] ) : NEW_LINE INDENT preLeft [ i ] = preLeft [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT preLeft [ i ] = preLeft [ i - 1 ] NEW_LINE DEDENT DEDENT if ( str1 [ n - 1 ] == substr [ 2 ] ) : NEW_LINE INDENT preRight [ n - 1 ] += 1 NEW_LINE DEDENT i = n - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( str1 [ i ] == substr [ 2 ] ) : NEW_LINE INDENT preRight [ i ] = preRight [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT preRight [ i ] = preRight [ i + 1 ] NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT counter = 0 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( str1 [ i ] == str1 [ 1 ] ) : NEW_LINE INDENT total = preLeft [ i - 1 ] * preRight [ i + 1 ] NEW_LINE counter += total NEW_LINE DEDENT DEDENT return counter NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " GFGFGYSYIOIWIN " NEW_LINE substr = " GFG " NEW_LINE print ( findOccurrences ( str1 , substr ) ) NEW_LINE DEDENT |
Mirror characters of a string | Function which take the given string and the position from which the reversing shall be done and returns the modified string ; Creating a string having reversed alphabetical order ; The string up to the point specified in the question , the string remains unchanged and from the point up to the length of the string , we reverse the alphabetical order ; Driver function | def compute ( st , n ) : NEW_LINE INDENT reverseAlphabet = " zyxwvutsrqponmlkjihgfedcba " NEW_LINE l = len ( st ) NEW_LINE answer = " " NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT answer = answer + st [ i ] ; NEW_LINE DEDENT for i in range ( n , l ) : NEW_LINE INDENT answer = ( answer + reverseAlphabet [ ord ( st [ i ] ) - ord ( ' a ' ) ] ) ; NEW_LINE DEDENT return answer ; NEW_LINE DEDENT st = " pneumonia " NEW_LINE n = 4 NEW_LINE answer = compute ( st , n - 1 ) NEW_LINE print ( answer ) NEW_LINE |
Lexicographically first alternate vowel and consonant string | Python3 implementation of lexicographically first alternate vowel and consonant string ; ' ch ' is vowel or not ; create alternate vowel and consonant string str1 [ 0. . . l1 - 1 ] and str2 [ start ... l2 - 1 ] ; first adding character of vowel / consonant then adding character of consonant / vowel ; function to find the required lexicographically first alternate vowel and consonant string ; hash table to store frequencies of each character in ' str ' char_freq = [ 0 ] * SIZE initialize all elements of char_freq [ ] to 0 ; count vowels ; count consonants ; update frequency of ' ch ' in char_freq [ ] ; no such string can be formed ; form the vowel string ' vstr ' and consonant string ' cstr ' which contains characters in lexicographical order ; remove first character of vowel string then create alternate string with cstr [ 0. . . nc - 1 ] and vstr [ 1. . . nv - 1 ] ; remove first character of consonant string then create alternate string with vstr [ 0. . . nv - 1 ] and cstr [ 1. . . nc - 1 ] ; if both vowel and consonant strings are of equal length start creating string with consonant ; start creating string with vowel ; Driver Code | SIZE = 26 NEW_LINE def isVowel ( ch ) : NEW_LINE INDENT if ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def createAltStr ( str1 , str2 , start , l ) : NEW_LINE INDENT finalStr = " " NEW_LINE i = 0 NEW_LINE j = start NEW_LINE while j < l : NEW_LINE INDENT finalStr += str1 [ i ] + str2 [ j ] NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return finalStr NEW_LINE DEDENT def findAltStr ( string ) : NEW_LINE INDENT nv = 0 NEW_LINE nc = 0 NEW_LINE vstr = " " NEW_LINE cstr = " " NEW_LINE l = len ( string ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT ch = string [ i ] NEW_LINE if isVowel ( ch ) : NEW_LINE INDENT nv += 1 NEW_LINE DEDENT else : NEW_LINE INDENT nc += 1 NEW_LINE DEDENT char_freq [ ord ( ch ) - 97 ] += 1 NEW_LINE DEDENT if abs ( nv - nc ) >= 2 : NEW_LINE INDENT return " no β such β string " NEW_LINE DEDENT for i in range ( SIZE ) : NEW_LINE INDENT ch = chr ( i + 97 ) NEW_LINE for j in range ( 1 , char_freq [ i ] + 1 ) : NEW_LINE INDENT if isVowel ( ch ) : NEW_LINE INDENT vstr += ch NEW_LINE DEDENT else : NEW_LINE INDENT cstr += ch NEW_LINE DEDENT DEDENT DEDENT if nv > nc : NEW_LINE INDENT return vstr [ 0 ] + createAltStr ( cstr , vstr , 1 , nv ) NEW_LINE DEDENT if nc > nv : NEW_LINE INDENT return cstr [ 0 ] + createAltStr ( vstr , cstr , 1 , nc ) NEW_LINE DEDENT if cstr [ 0 ] < vstr [ 0 ] : NEW_LINE INDENT return createAltStr ( cstr , vstr , 0 , nv ) NEW_LINE DEDENT return createAltStr ( vstr , cstr , 0 , nc ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " aeroplane " NEW_LINE print ( findAltStr ( string ) ) NEW_LINE DEDENT |
Print all possible strings that can be made by placing spaces | Python 3 program to print all strings that can be made by placing spaces ; Function to print all subsequences ; Driver code | from math import pow NEW_LINE def printSubsequences ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE opsize = int ( pow ( 2 , n - 1 ) ) NEW_LINE for counter in range ( opsize ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( str [ j ] , end = " " ) NEW_LINE if ( counter & ( 1 << j ) ) : NEW_LINE INDENT print ( " β " , end = " " ) NEW_LINE DEDENT DEDENT print ( " " , β end β = β " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " ABC " NEW_LINE printSubsequences ( str ) NEW_LINE DEDENT |
Find n | Python3 program to print n - th permutation ; Utility for calculating factorials ; Function for nth permutation ; length of given string ; Count frequencies of all characters ; out string for output string ; iterate till sum equals n ; We update both n and sum in this loop . ; check for characters present in freq [ ] ; Remove character ; calculate sum after fixing a particular char ; if sum > n fix that char as present char and update sum and required nth after fixing char at that position ; if sum < n , add character back ; if sum == n means this char will provide its greatest permutation as nth permutation ; print result ; Driver Code | MAX_CHAR = 26 NEW_LINE MAX_FACT = 20 NEW_LINE fact = [ None ] * ( MAX_FACT ) NEW_LINE def precomputeFactorials ( ) : NEW_LINE INDENT fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , MAX_FACT ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE DEDENT DEDENT def nPermute ( string , n ) : NEW_LINE INDENT precomputeFactorials ( ) NEW_LINE length = len ( string ) NEW_LINE freq = [ 0 ] * ( MAX_CHAR ) NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT freq [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT out = [ None ] * ( MAX_CHAR ) NEW_LINE Sum , k = 0 , 0 NEW_LINE while Sum != n : NEW_LINE INDENT Sum = 0 NEW_LINE for i in range ( 0 , MAX_CHAR ) : NEW_LINE INDENT if freq [ i ] == 0 : NEW_LINE INDENT continue NEW_LINE DEDENT freq [ i ] -= 1 NEW_LINE xsum = fact [ length - 1 - k ] NEW_LINE for j in range ( 0 , MAX_CHAR ) : NEW_LINE INDENT xsum = xsum // fact [ freq [ j ] ] NEW_LINE DEDENT Sum += xsum NEW_LINE if Sum >= n : NEW_LINE INDENT out [ k ] = chr ( i + ord ( ' a ' ) ) NEW_LINE n -= Sum - xsum NEW_LINE k += 1 NEW_LINE break NEW_LINE DEDENT if Sum < n : NEW_LINE INDENT freq [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT i = MAX_CHAR - 1 NEW_LINE while k < length and i >= 0 : NEW_LINE INDENT if freq [ i ] : NEW_LINE INDENT out [ k ] = chr ( i + ord ( ' a ' ) ) NEW_LINE freq [ i ] -= 1 NEW_LINE i += 1 NEW_LINE k += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT print ( ' ' . join ( out [ : k ] ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 NEW_LINE string = " geeksquiz " NEW_LINE nPermute ( string , n ) NEW_LINE DEDENT |
Minimum number of deletions so that no two consecutive are same | Function for counting deletions ; If two consecutive characters are the same , delete one of them . ; Driver code ; Function call to print answer | def countDeletions ( string ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( len ( string ) - 1 ) : NEW_LINE INDENT if ( string [ i ] == string [ i + 1 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT string = " AAABBB " NEW_LINE print countDeletions ( string ) NEW_LINE |
Count words that appear exactly two times in an array of words | Returns count of words with frequency exactly 2. ; Driver code | def countWords ( stri , n ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ stri [ i ] ] = m . get ( stri [ i ] , 0 ) + 1 NEW_LINE DEDENT res = 0 NEW_LINE for i in m . values ( ) : NEW_LINE INDENT if i == 2 : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT s = [ " hate " , " love " , " peace " , " love " , " peace " , " hate " , " love " , " peace " , " love " , " peace " ] NEW_LINE n = len ( s ) NEW_LINE print ( countWords ( s , n ) ) NEW_LINE |
Check whether a given graph is Bipartite or not | Python3 program to find out whether a given graph is Bipartite or not using recursion . ; color this pos as c and all its neighbours and 1 - c ; start is vertex 0 ; two colors 1 and 0 ; Driver Code | V = 4 NEW_LINE def colorGraph ( G , color , pos , c ) : NEW_LINE INDENT if color [ pos ] != - 1 and color [ pos ] != c : NEW_LINE INDENT return False NEW_LINE DEDENT color [ pos ] = c NEW_LINE ans = True NEW_LINE for i in range ( 0 , V ) : NEW_LINE INDENT if G [ pos ] [ i ] : NEW_LINE INDENT if color [ i ] == - 1 : NEW_LINE INDENT ans &= colorGraph ( G , color , i , 1 - c ) NEW_LINE DEDENT if color [ i ] != - 1 and color [ i ] != 1 - c : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if not ans : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isBipartite ( G ) : NEW_LINE INDENT color = [ - 1 ] * V NEW_LINE pos = 0 NEW_LINE return colorGraph ( G , color , pos , 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT G = [ [ 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 0 ] , [ 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 0 ] ] NEW_LINE if isBipartite ( G ) : print ( " Yes " ) NEW_LINE else : print ( " No " ) NEW_LINE DEDENT |
Nth Even length Palindrome | Python3 program to find n = th even length string . ; Function to find nth even length Palindrome ; string r to store resultant palindrome . Initialize same as s ; In this loop string r stores reverse of string s after the string s in consecutive manner . ; Driver code ; Function call | import math as mt NEW_LINE def evenlength ( n ) : NEW_LINE INDENT res = n NEW_LINE for j in range ( len ( n ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT res += n [ j ] NEW_LINE DEDENT return res NEW_LINE DEDENT n = "10" NEW_LINE print ( evenlength ( n ) ) NEW_LINE |
Program for First Fit algorithm in Memory Management | Function to allocate memory to blocks as per First fit algorithm ; Stores block id of the block allocated to a process ; pick each process and find suitable blocks according to its size ad assign to it ; allocate block j to p [ i ] process ; Reduce available memory in this block . ; Driver code | def firstFit ( blockSize , m , processSize , n ) : NEW_LINE INDENT allocation = [ - 1 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if blockSize [ j ] >= processSize [ i ] : NEW_LINE INDENT allocation [ i ] = j NEW_LINE blockSize [ j ] -= processSize [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT print ( " β Process β No . β Process β Size β Block β no . " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( " β " , i + 1 , " β " , processSize [ i ] , " β " , end = " β " ) NEW_LINE if allocation [ i ] != - 1 : NEW_LINE INDENT print ( allocation [ i ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Allocated " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT blockSize = [ 100 , 500 , 200 , 300 , 600 ] NEW_LINE processSize = [ 212 , 417 , 112 , 426 ] NEW_LINE m = len ( blockSize ) NEW_LINE n = len ( processSize ) NEW_LINE firstFit ( blockSize , m , processSize , n ) NEW_LINE DEDENT |
Determine if a string has all Unique Characters | Python program to illustrate string with unique characters using brute force technique ; If at any time we encounter 2 same characters , return false ; If no duplicate characters encountered , return true ; Driver Code | def uniqueCharacters ( str ) : NEW_LINE INDENT for i in range ( len ( str ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == str [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT DEDENT return True ; NEW_LINE DEDENT str = " GeeksforGeeks " ; NEW_LINE if ( uniqueCharacters ( str ) ) : NEW_LINE INDENT print ( " The β String β " , str , " β has β all β unique β characters " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The β String β " , str , " β has β duplicate β characters " ) ; NEW_LINE DEDENT |
Check if given string can be split into four distinct strings | Return if the given string can be split or not . ; We can always break a of size 10 or more into four distinct strings . ; Brute Force ; Making 4 from the given ; Checking if they are distinct or not . ; Driver Code | def check ( s ) : NEW_LINE INDENT if ( len ( s ) >= 10 ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( s ) ) : NEW_LINE INDENT for k in range ( j + 1 , len ( s ) ) : NEW_LINE INDENT s1 = s [ 0 : i ] NEW_LINE s2 = s [ i : j - i ] NEW_LINE s3 = s [ j : k - j ] NEW_LINE s4 = s [ k : len ( s ) - k ] NEW_LINE if ( s1 != s2 and s1 != s3 and s1 != s4 and s2 != s3 and s2 != s4 and s3 != s4 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " aaabb " NEW_LINE print ( " Yes " ) if ( check ( str ) ) else print ( " NO " ) NEW_LINE DEDENT |
Multiply Large Numbers represented as Strings | Multiplies str1 and str2 , and prints result . ; will keep the result number in vector in reverse order ; Below two indexes are used to find positions in result . ; Go from right to left in num1 ; To shift position to left after every multiplication of a digit in num2 ; Go from right to left in num2 ; Take current digit of second number ; Multiply with current digit of first number and add result to previously stored result at current position . ; Carry for next iteration ; Store result ; store carry in next cell ; To shift position to left after every multiplication of a digit in num1 . ; ignore '0' s from the right ; If all were '0' s - means either both or one of num1 or num2 were '0 ; generate the result string ; Driver code | def multiply ( num1 , num2 ) : NEW_LINE INDENT len1 = len ( num1 ) NEW_LINE len2 = len ( num2 ) NEW_LINE if len1 == 0 or len2 == 0 : NEW_LINE INDENT return "0" NEW_LINE DEDENT result = [ 0 ] * ( len1 + len2 ) NEW_LINE i_n1 = 0 NEW_LINE i_n2 = 0 NEW_LINE for i in range ( len1 - 1 , - 1 , - 1 ) : NEW_LINE INDENT carry = 0 NEW_LINE n1 = ord ( num1 [ i ] ) - 48 NEW_LINE i_n2 = 0 NEW_LINE for j in range ( len2 - 1 , - 1 , - 1 ) : NEW_LINE INDENT n2 = ord ( num2 [ j ] ) - 48 NEW_LINE summ = n1 * n2 + result [ i_n1 + i_n2 ] + carry NEW_LINE carry = summ // 10 NEW_LINE result [ i_n1 + i_n2 ] = summ % 10 NEW_LINE i_n2 += 1 NEW_LINE DEDENT if ( carry > 0 ) : NEW_LINE INDENT result [ i_n1 + i_n2 ] += carry NEW_LINE DEDENT i_n1 += 1 NEW_LINE DEDENT i = len ( result ) - 1 NEW_LINE while ( i >= 0 and result [ i ] == 0 ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( i == - 1 ) : NEW_LINE INDENT return "0" NEW_LINE DEDENT s = " " NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT s += chr ( result [ i ] + 48 ) NEW_LINE i -= 1 NEW_LINE DEDENT return s NEW_LINE DEDENT str1 = "1235421415454545454545454544" NEW_LINE str2 = "1714546546546545454544548544544545" NEW_LINE if ( ( str1 [ 0 ] == ' - ' or str2 [ 0 ] == ' - ' ) and ( str1 [ 0 ] != ' - ' or str2 [ 0 ] != ' - ' ) ) : NEW_LINE INDENT print ( " - " , end = ' ' ) NEW_LINE DEDENT if ( str1 [ 0 ] == ' - ' and str2 [ 0 ] != ' - ' ) : NEW_LINE INDENT str1 = str1 [ 1 : ] NEW_LINE DEDENT elif ( str1 [ 0 ] != ' - ' and str2 [ 0 ] == ' - ' ) : NEW_LINE INDENT str2 = str2 [ 1 : ] NEW_LINE DEDENT elif ( str1 [ 0 ] == ' - ' and str2 [ 0 ] == ' - ' ) : NEW_LINE INDENT str1 = str1 [ 1 : ] NEW_LINE str2 = str2 [ 1 : ] NEW_LINE DEDENT print ( multiply ( str1 , str2 ) ) NEW_LINE |
Find an equal point in a string of brackets | Method to find an equal index ; Store the number of opening brackets at each index ; Store the number of closing brackets at each index ; check if there is no opening or closing brackets ; check if there is any index at which both brackets are equal ; Driver Code | def findIndex ( str ) : NEW_LINE INDENT l = len ( str ) NEW_LINE open = [ 0 ] * ( l + 1 ) NEW_LINE close = [ 0 ] * ( l + 1 ) NEW_LINE index = - 1 NEW_LINE open [ 0 ] = 0 NEW_LINE close [ l ] = 0 NEW_LINE if ( str [ 0 ] == ' ( ' ) : NEW_LINE INDENT open [ 1 ] = 1 NEW_LINE DEDENT if ( str [ l - 1 ] == ' ) ' ) : NEW_LINE INDENT close [ l - 1 ] = 1 NEW_LINE DEDENT for i in range ( 1 , l ) : NEW_LINE INDENT if ( str [ i ] == ' ( ' ) : NEW_LINE INDENT open [ i + 1 ] = open [ i ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT open [ i + 1 ] = open [ i ] NEW_LINE DEDENT DEDENT for i in range ( l - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] == ' ) ' ) : NEW_LINE INDENT close [ i ] = close [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT close [ i ] = close [ i + 1 ] NEW_LINE DEDENT DEDENT if ( open [ l ] == 0 ) : NEW_LINE INDENT return len NEW_LINE DEDENT if ( close [ 0 ] == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( l + 1 ) : NEW_LINE INDENT if ( open [ i ] == close [ i ] ) : NEW_LINE INDENT index = i NEW_LINE DEDENT DEDENT return index NEW_LINE DEDENT str = " ( ( ) ) ) ( ( ) ( ) ( ) ) ) ) " NEW_LINE print ( findIndex ( str ) ) NEW_LINE |
Convert decimal fraction to binary number | Function to convert decimal to binary upto k - precision after decimal point ; Fetch the integral part of decimal number ; Fetch the fractional part decimal number ; Conversion of integral part to binary equivalent ; Append 0 in binary ; Reverse string to get original binary equivalent ; Append point before conversion of fractional part ; Conversion of fractional part to binary equivalent ; Find next bit in fraction ; Driver code | def decimalToBinary ( num , k_prec ) : NEW_LINE INDENT binary = " " NEW_LINE Integral = int ( num ) NEW_LINE fractional = num - Integral NEW_LINE while ( Integral ) : NEW_LINE INDENT rem = Integral % 2 NEW_LINE binary += str ( rem ) ; NEW_LINE Integral //= 2 NEW_LINE DEDENT binary = binary [ : : - 1 ] NEW_LINE binary += ' . ' NEW_LINE while ( k_prec ) : NEW_LINE INDENT fractional *= 2 NEW_LINE fract_bit = int ( fractional ) NEW_LINE if ( fract_bit == 1 ) : NEW_LINE INDENT fractional -= fract_bit NEW_LINE binary += '1' NEW_LINE DEDENT else : NEW_LINE INDENT binary += '0' NEW_LINE DEDENT k_prec -= 1 NEW_LINE DEDENT return binary NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4.47 NEW_LINE k = 3 NEW_LINE print ( decimalToBinary ( n , k ) ) NEW_LINE n = 6.986 NEW_LINE k = 5 NEW_LINE print ( decimalToBinary ( n , k ) ) NEW_LINE DEDENT |
Difference of two large numbers | Returns true if str1 is smaller than str2 , else false . ; Calculate lengths of both string ; Function for finding difference of larger numbers ; Before proceeding further , make sure str1 is not smaller ; Take an empty string for storing result ; Calculate lengths of both string ; Initially take carry zero ; Traverse from end of both strings ; Do school mathematics , compute difference of current digits and carry ; Subtract remaining digits of str1 [ ] ; Remove preceding 0 's ; Reverse resultant string ; Driver code ; Function call | def isSmaller ( str1 , str2 ) : NEW_LINE INDENT n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE if ( n1 < n2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n2 < n1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( n1 ) : NEW_LINE INDENT if ( str1 [ i ] < str2 [ i ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( str1 [ i ] > str2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def findDiff ( str1 , str2 ) : NEW_LINE INDENT if ( isSmaller ( str1 , str2 ) ) : NEW_LINE INDENT str1 , str2 = str2 , str1 NEW_LINE DEDENT Str = " " NEW_LINE n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE diff = n1 - n2 NEW_LINE carry = 0 NEW_LINE for i in range ( n2 - 1 , - 1 , - 1 ) : NEW_LINE INDENT sub = ( ( ord ( str1 [ i + diff ] ) - ord ( '0' ) ) - ( ord ( str2 [ i ] ) - ord ( '0' ) ) - carry ) NEW_LINE if ( sub < 0 ) : NEW_LINE INDENT sub += 10 NEW_LINE carry = 1 NEW_LINE DEDENT else : NEW_LINE INDENT carry = 0 NEW_LINE DEDENT Str += chr ( sub + ord ( '0' ) ) NEW_LINE DEDENT for i in range ( n1 - n2 - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( str1 [ i ] == '0' and carry ) : NEW_LINE INDENT Str += '9' NEW_LINE continue NEW_LINE DEDENT sub = ( ord ( str1 [ i ] ) - ord ( '0' ) ) - carry NEW_LINE if ( i > 0 or sub > 0 ) : NEW_LINE INDENT Str += chr ( sub + ord ( '0' ) ) NEW_LINE DEDENT carry = 0 NEW_LINE DEDENT Str = Str [ : : - 1 ] NEW_LINE return Str NEW_LINE DEDENT str1 = "88" NEW_LINE str2 = "1079" NEW_LINE print ( findDiff ( str1 , str2 ) ) NEW_LINE |
Efficiently check if a string has all unique characters without using any additional data structure | Driver code | def unique ( s ) : NEW_LINE INDENT s = list ( s ) NEW_LINE s . sort ( ) NEW_LINE for i in range ( len ( s ) - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE break NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if ( unique ( " abcdd " ) == True ) : NEW_LINE INDENT print ( " String β is β Unique " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " String β is β not β Unique " ) NEW_LINE DEDENT |
Check if two strings are k | Optimized Python3 program to check if two strings are k anagram or not . ; Function to check if str1 and str2 are 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 ; Store the occurrence of all characters in a hash_array ; 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 hash_str1 = [ 0 ] * ( MAX_CHAR ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash_str1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( hash_str1 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] > 0 ) : NEW_LINE INDENT hash_str1 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( count > k ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT str1 = " fodr " ; NEW_LINE str2 = " gork " ; NEW_LINE k = 2 ; NEW_LINE if ( areKAnagrams ( str1 , str2 , k ) == True ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Nth character in Concatenated Decimal String | Method to get dth digit of number N ; Method to return Nth character in concatenated decimal string ; sum will store character escaped till now ; dist will store numbers escaped till now ; loop for number lengths ; nine * len will be incremented characters and nine will be incremented numbers ; restore variables to previous correct state ; get distance from last one digit less maximum number ; d will store dth digit of current number ; method will return dth numbered digit of ( dist + diff ) number ; Driver code to test above methods | def getDigit ( N , d ) : NEW_LINE INDENT string = str ( N ) NEW_LINE return string [ d - 1 ] ; NEW_LINE DEDENT def getNthChar ( N ) : NEW_LINE INDENT sum = 0 NEW_LINE nine = 9 NEW_LINE dist = 0 NEW_LINE for len in range ( 1 , N ) : NEW_LINE INDENT sum += nine * len NEW_LINE dist += nine NEW_LINE if ( sum >= N ) : NEW_LINE INDENT sum -= nine * len NEW_LINE dist -= nine NEW_LINE N -= sum NEW_LINE break NEW_LINE DEDENT nine *= 10 NEW_LINE DEDENT diff = ( N / len ) + 1 NEW_LINE d = N % len NEW_LINE if ( d == 0 ) : NEW_LINE INDENT d = len NEW_LINE DEDENT return getDigit ( dist + diff , d ) ; NEW_LINE DEDENT N = 251 NEW_LINE print getNthChar ( N ) NEW_LINE |
Minimum characters to be added at front to make string palindrome | function for checking string is palindrome or not ; Driver code ; if string becomes palindrome then break ; erase the last element of the string ; print the number of insertion at front | def ispalindrome ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE i = 0 NEW_LINE j = l - 1 NEW_LINE while i <= j : NEW_LINE INDENT if ( s [ i ] != s [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " BABABAA " NEW_LINE cnt = 0 NEW_LINE flag = 0 NEW_LINE while ( len ( s ) > 0 ) : NEW_LINE INDENT if ( ispalindrome ( s ) ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT cnt += 1 NEW_LINE s = s [ : - 1 ] NEW_LINE s . erase ( s . begin ( ) + s . length ( ) - 1 ) ; NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT print ( cnt ) NEW_LINE DEDENT DEDENT |
Count characters at same position as in English alphabet | Function to count the number of characters at same position as in English alphabets ; Traverse the input string ; Check that index of characters of string is same as of English alphabets by using ASCII values and the fact that all lower case alphabetic characters come together in same order in ASCII table . And same is true for upper case . ; Driver Code | def findCount ( str ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( ( i == ord ( str [ i ] ) - ord ( ' a ' ) ) or ( i == ord ( str [ i ] ) - ord ( ' A ' ) ) ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT str = ' AbgdeF ' NEW_LINE print ( findCount ( str ) ) NEW_LINE |
Remove a character from a string to make it a palindrome | Utility method to check if substring from low to high is palindrome or not . ; This method returns - 1 if it is not possible to make string a palindrome . It returns - 2 if string is already a palindrome . Otherwise it returns index of character whose removal can make the whole string palindrome . ; Initialize low and right by both the ends of the string ; loop until low and high cross each other ; If both characters are equal then move both pointer towards end ; If removing str [ low ] makes the whole string palindrome . We basically check if substring str [ low + 1. . high ] is palindrome or not . ; If removing str [ high ] makes the whole string palindrome We basically check if substring str [ low + 1. . high ] is palindrome or not ; We reach here when complete string will be palindrome if complete string is palindrome then return mid character ; Driver Code | def isPalindrome ( string : str , low : int , high : int ) -> bool : NEW_LINE INDENT while low < high : NEW_LINE INDENT if string [ low ] != string [ high ] : NEW_LINE INDENT return False NEW_LINE DEDENT low += 1 NEW_LINE high -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def possiblepalinByRemovingOneChar ( string : str ) -> int : NEW_LINE INDENT low = 0 NEW_LINE high = len ( string ) - 1 NEW_LINE while low < high : NEW_LINE INDENT if string [ low ] == string [ high ] : NEW_LINE INDENT low += 1 NEW_LINE high -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if isPalindrome ( string , low + 1 , high ) : NEW_LINE INDENT return low NEW_LINE DEDENT if isPalindrome ( string , low , high - 1 ) : NEW_LINE INDENT return high NEW_LINE DEDENT return - 1 NEW_LINE DEDENT DEDENT return - 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abecbea " NEW_LINE idx = possiblepalinByRemovingOneChar ( string ) NEW_LINE if idx == - 1 : NEW_LINE INDENT print ( " Not β possible " ) NEW_LINE DEDENT elif idx == - 2 : NEW_LINE INDENT print ( " Possible β without β removing β any β character " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Possible β by β removing β character β at β index " , idx ) NEW_LINE DEDENT DEDENT |
Count number of unique ways to paint a N x 3 grid | Function to count the number of ways to paint N * 3 grid based on given conditions ; Count of ways to pain a row with same colored ends ; Count of ways to pain a row with different colored ends ; Traverse up to ( N - 1 ) th row ; For same colored ends ; For different colored ends ; Print the total number of ways ; Driver Code ; Function call | def waysToPaint ( n ) : NEW_LINE INDENT same = 6 NEW_LINE diff = 6 NEW_LINE for _ in range ( n - 1 ) : NEW_LINE INDENT sameTmp = 3 * same + 2 * diff NEW_LINE diffTmp = 2 * same + 2 * diff NEW_LINE same = sameTmp NEW_LINE diff = diffTmp NEW_LINE DEDENT print ( same + diff ) NEW_LINE DEDENT N = 2 NEW_LINE waysToPaint ( N ) NEW_LINE |
Generate all binary strings from given pattern | Recursive function to generate all binary strings formed by replacing each wildcard character by 0 or 1 ; replace ' ? ' by '0' and recurse ; replace ' ? ' by '1' and recurse ; NOTE : Need to backtrack as string is passed by reference to the function ; Driver code | def _print ( string , index ) : NEW_LINE INDENT if index == len ( string ) : NEW_LINE INDENT print ( ' ' . join ( string ) ) NEW_LINE return NEW_LINE DEDENT if string [ index ] == " ? " : NEW_LINE INDENT string [ index ] = '0' NEW_LINE _print ( string , index + 1 ) NEW_LINE string [ index ] = '1' NEW_LINE _print ( string , index + 1 ) NEW_LINE string [ index ] = ' ? ' NEW_LINE DEDENT else : NEW_LINE INDENT _print ( string , index + 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "1 ? ? 0?101" NEW_LINE string = list ( string ) NEW_LINE _print ( string , 0 ) NEW_LINE DEDENT |
Rearrange array by interchanging positions of even and odd elements in the given array | Function to replace each even element by odd and vice - versa in a given array ; Traverse array ; If current element is even then swap it with odd ; Perform Swap ; Change the sign ; If current element is odd then swap it with even ; Perform Swap ; Change the sign ; Marked element positive ; Print final array ; Driver Code ; Given array arr [ ] ; Function Call | def replace ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] >= 0 and arr [ j ] >= 0 and arr [ i ] % 2 == 0 and arr [ j ] % 2 != 0 ) : NEW_LINE INDENT tmp = arr [ i ] NEW_LINE arr [ i ] = arr [ j ] NEW_LINE arr [ j ] = tmp NEW_LINE arr [ j ] = - arr [ j ] NEW_LINE break NEW_LINE DEDENT elif ( arr [ i ] >= 0 and arr [ j ] >= 0 and arr [ i ] % 2 != 0 and arr [ j ] % 2 == 0 ) : NEW_LINE INDENT tmp = arr [ i ] NEW_LINE arr [ i ] = arr [ j ] NEW_LINE arr [ j ] = tmp NEW_LINE arr [ j ] = - arr [ j ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = abs ( arr [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE replace ( arr , n ) NEW_LINE DEDENT |
Find the most frequent digit without using array / string | Simple function to count occurrences of digit d in x ; count = 0 ; Initialize count of digit d ; Increment count if current digit is same as d ; Returns the max occurring digit in x ; Handle negative number ; Traverse through all digits ; Count occurrences of current digit ; Update max_count and result if needed ; Driver Code | def countOccurrences ( x , d ) : NEW_LINE INDENT while ( x ) : NEW_LINE INDENT if ( x % 10 == d ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT x = int ( x / 10 ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def maxOccurring ( x ) : NEW_LINE INDENT if ( x < 0 ) : NEW_LINE INDENT x = - x ; NEW_LINE DEDENT for d in range ( 10 ) : NEW_LINE INDENT count = countOccurrences ( x , d ) ; NEW_LINE if ( count >= max_count ) : NEW_LINE INDENT max_count = count ; NEW_LINE result = d ; NEW_LINE DEDENT DEDENT return result ; NEW_LINE DEDENT x = 1223355 ; NEW_LINE print ( " Max β occurring β digit β is " , maxOccurring ( x ) ) ; NEW_LINE |
Remove recurring digits in a given number | Removes recurring digits in num [ ] ; Index in modified string ; Traverse digits of given number one by one ; Copy the first occurrence of new digit ; Remove repeating occurrences of digit ; Driver code | def removeRecurringDigits ( num ) : NEW_LINE INDENT l = len ( num ) NEW_LINE ( i , j ) = ( 0 , 0 ) NEW_LINE str = ' ' NEW_LINE while i < l : NEW_LINE INDENT str += num [ i ] NEW_LINE j += 1 NEW_LINE while ( i + 1 < l and num [ i ] == num [ i + 1 ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return str NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num = '1299888833' NEW_LINE print ( ' Modified β number β is β { } ' . format ( removeRecurringDigits ( num ) ) ) NEW_LINE DEDENT |
Find the maximum subarray XOR in a given array | A simple Python program to find max subarray XOR ; Initialize result ; Pick starting points of subarrays ; to store xor of current subarray ; Pick ending points of subarrays starting with i ; Driver code | def maxSubarrayXOR ( arr , n ) : NEW_LINE INDENT ans = - 2147483648 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_xor = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT curr_xor = curr_xor ^ arr [ j ] NEW_LINE ans = max ( ans , curr_xor ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 8 , 1 , 2 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Max β subarray β XOR β is β " , maxSubarrayXOR ( arr , n ) ) NEW_LINE |
Recursive Implementation of atoi ( ) | Recursive function to compute atoi ( ) ; base case , we 've hit the end of the string, we just return the last value ; If more than 1 digits , recur for ( n - 1 ) , multiplu result with 10 and add last digit ; Driver Code | def myAtoiRecursive ( string , num ) : NEW_LINE INDENT if len ( string ) == 1 : NEW_LINE INDENT return int ( string ) + ( num * 10 ) NEW_LINE DEDENT num = int ( string [ 0 : 1 ] ) + ( num * 10 ) NEW_LINE return myAtoiRecursive ( string [ 1 : ] , num ) NEW_LINE DEDENT string = "112" NEW_LINE print ( myAtoiRecursive ( string , 0 ) ) NEW_LINE |
Print string of odd length in ' X ' format | Function to print the given string in respective pattern ; Print characters at corresponding places satisfying the two conditions ; Print blank space at rest of places ; Driver code | def printPattern ( Str , Len ) : NEW_LINE INDENT for i in range ( Len ) : NEW_LINE INDENT for j in range ( Len ) : NEW_LINE INDENT if ( ( i == j ) or ( i + j == Len - 1 ) ) : NEW_LINE INDENT print ( Str [ j ] , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " β " , end = " " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT Str = " geeksforgeeks " NEW_LINE Len = len ( Str ) NEW_LINE printPattern ( Str , Len ) NEW_LINE |
Find the longest substring with k unique characters in a given string | Python program to find the longest substring with k unique characters in a given string ; This function calculates number of unique characters using a associative array count [ ] . Returns true if no . of characters are less than required else returns false . ; Return true if k is greater than or equal to val ; Finds the maximum substring with exactly k unique characters ; Associative array to store the count ; Tranverse the string , fills the associative array count [ ] and count number of unique characters ; If there are not enough unique characters , show an error message . ; Otherwise take a window with first element in it . start and end variables . ; Also initialize values for result longest window ; Initialize associative array count [ ] with zero ; put the first character ; Start from the second character and add characters in window according to above explanation ; Add the character ' s [ i ] ' to current window ; If there are more than k unique characters in current window , remove from left side ; Update the max window size if required ; Driver function | MAX_CHARS = 26 NEW_LINE def isValid ( count , k ) : NEW_LINE INDENT val = 0 NEW_LINE for i in range ( MAX_CHARS ) : NEW_LINE INDENT if count [ i ] > 0 : NEW_LINE INDENT val += 1 NEW_LINE DEDENT DEDENT return ( k >= val ) NEW_LINE DEDENT def kUniques ( s , k ) : NEW_LINE INDENT count = [ 0 ] * MAX_CHARS NEW_LINE for i in range ( n ) : NEW_LINE INDENT if count [ ord ( s [ i ] ) - ord ( ' a ' ) ] == 0 : NEW_LINE INDENT u += 1 NEW_LINE DEDENT count [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT if u < k : NEW_LINE INDENT print ( " Not β enough β unique β characters " ) NEW_LINE return NEW_LINE DEDENT curr_start = 0 NEW_LINE curr_end = 0 NEW_LINE max_window_size = 1 NEW_LINE max_window_start = 0 NEW_LINE count = [ 0 ] * len ( count ) NEW_LINE count [ ord ( s [ 0 ] ) - ord ( ' a ' ) ] += 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT count [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE curr_end += 1 NEW_LINE while not isValid ( count , k ) : NEW_LINE INDENT count [ ord ( s [ curr_start ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE curr_start += 1 NEW_LINE DEDENT if curr_end - curr_start + 1 > max_window_size : NEW_LINE INDENT max_window_size = curr_end - curr_start + 1 NEW_LINE max_window_start = curr_start NEW_LINE DEDENT DEDENT print ( " Max β substring β is β : β " + s [ max_window_start : max_window_start + max_window_size ] + " β with β length β " + str ( max_window_size ) ) NEW_LINE DEDENT s = " aabacbebebe " NEW_LINE k = 3 NEW_LINE kUniques ( s , k ) NEW_LINE |
Check if characters of a given string can be rearranged to form a palindrome | Python3 implementation of above approach . ; bitvector to store the record of which character appear odd and even number of times ; Driver Code | def canFormPalindrome ( s ) : NEW_LINE INDENT bitvector = 0 NEW_LINE for str in s : NEW_LINE INDENT bitvector ^= 1 << ord ( str ) NEW_LINE DEDENT return bitvector == 0 or bitvector & ( bitvector - 1 ) == 0 NEW_LINE DEDENT if canFormPalindrome ( " geeksforgeeks " ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT |
Print all pairs of anagrams in a given array of strings | Python3 program to find best meeting point in 2D array ; function to check whether two strings are anagram of each other ; Create two count arrays and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; See if there is any non - zero value in count array ; This function prints all anagram pairs in a given array of strings ; Driver Code | NO_OF_CHARS = 256 NEW_LINE def areAnagram ( str1 : str , str2 : str ) -> bool : NEW_LINE INDENT count = [ 0 ] * NO_OF_CHARS NEW_LINE i = 0 NEW_LINE while i < len ( str1 ) and i < len ( str2 ) : NEW_LINE INDENT count [ ord ( str1 [ i ] ) ] += 1 NEW_LINE count [ ord ( str2 [ i ] ) ] -= 1 NEW_LINE i += 1 NEW_LINE DEDENT if len ( str1 ) != len ( str2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( NO_OF_CHARS ) : NEW_LINE INDENT if count [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT DEDENT def findAllAnagrams ( arr : list , n : int ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if areAnagram ( arr [ i ] , arr [ j ] ) : NEW_LINE INDENT print ( arr [ i ] , " is β anagram β of " , arr [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " geeksquiz " , " geeksforgeeks " , " abcd " , " forgeeksgeeks " , " zuiqkeegs " ] NEW_LINE n = len ( arr ) NEW_LINE findAllAnagrams ( arr , n ) NEW_LINE DEDENT |
Program to print all palindromes in a given range | A function to check if n is palindrome ; Find reverse of n ; If n and rev are same , then n is palindrome ; prints palindrome between min and max ; Driver Code | def isPalindrome ( n : int ) -> bool : NEW_LINE INDENT rev = 0 NEW_LINE i = n NEW_LINE while i > 0 : NEW_LINE INDENT rev = rev * 10 + i % 10 NEW_LINE i //= 10 NEW_LINE DEDENT return ( n == rev ) NEW_LINE DEDENT def countPal ( minn : int , maxx : int ) -> None : NEW_LINE INDENT for i in range ( minn , maxx + 1 ) : NEW_LINE INDENT if isPalindrome ( i ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT countPal ( 100 , 2000 ) NEW_LINE DEDENT |
Length of the longest substring without repeating characters | Python3 program to find the length of the longest substring without repeating characters ; Result ; Note : Default values in visited are false ; If current character is visited Break the loop ; Else update the result if this window is larger , and mark current character as visited . ; Remove the first character of previous window ; Driver code | def longestUniqueSubsttr ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT visited = [ 0 ] * 256 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT if ( visited [ ord ( str [ j ] ) ] == True ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT res = max ( res , j - i + 1 ) NEW_LINE visited [ ord ( str [ j ] ) ] = True NEW_LINE DEDENT DEDENT visited [ ord ( str [ i ] ) ] = False NEW_LINE DEDENT return res NEW_LINE DEDENT str = " geeksforgeeks " NEW_LINE print ( " The β input β is β " , str ) NEW_LINE len = longestUniqueSubsttr ( str ) NEW_LINE print ( " The β length β of β the β longest β " " non - repeating β character β substring β is β " , len ) NEW_LINE |
Length of the longest substring without repeating characters | Creating a set to store the last positions of occurrence ; starting the initial point of window to index 0 ; Checking if we have already seen the element or not ; If we have seen the number , move the start pointer to position after the last occurrence ; Updating the last seen value of the character ; Driver Code | def longestUniqueSubsttr ( string ) : NEW_LINE INDENT seen = { } NEW_LINE maximum_length = 0 NEW_LINE start = 0 NEW_LINE for end in range ( len ( string ) ) : NEW_LINE INDENT if string [ end ] in seen : NEW_LINE INDENT start = max ( start , seen [ string [ end ] ] + 1 ) NEW_LINE DEDENT seen [ string [ end ] ] = end NEW_LINE maximum_length = max ( maximum_length , end - start + 1 ) NEW_LINE DEDENT return maximum_length NEW_LINE DEDENT string = " geeksforgeeks " NEW_LINE print ( " The β input β string β is " , string ) NEW_LINE length = longestUniqueSubsttr ( string ) NEW_LINE print ( " The β length β of β the β longest β non - repeating β character β substring β is " , length ) NEW_LINE |
Find the smallest window in a string containing all characters of another string | Python solution ; Starting index of ans ; Answer Length of ans ; creating map ; References of Window ; Traversing the window ; Calculating ; Condition matching ; calculating answer . ; Sliding I Calculation for removing I ; Driver code | def smallestWindow ( s , p ) : NEW_LINE INDENT n = len ( s ) NEW_LINE if n < len ( p ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mp = [ 0 ] * 256 NEW_LINE start = 0 NEW_LINE ans = n + 1 NEW_LINE cnt = 0 NEW_LINE for i in p : NEW_LINE INDENT mp [ ord ( i ) ] += 1 NEW_LINE if mp [ ord ( i ) ] == 1 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT j = 0 NEW_LINE i = 0 NEW_LINE while ( j < n ) : NEW_LINE INDENT mp [ ord ( s [ j ] ) ] -= 1 NEW_LINE if mp [ ord ( s [ j ] ) ] == 0 : NEW_LINE INDENT cnt -= 1 NEW_LINE while cnt == 0 : NEW_LINE INDENT if ans > j - i + 1 : NEW_LINE INDENT ans = j - i + 1 NEW_LINE start = i NEW_LINE DEDENT mp [ ord ( s [ i ] ) ] += 1 NEW_LINE if mp [ ord ( s [ i ] ) ] > 0 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT j += 1 NEW_LINE DEDENT if ans > n : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT return s [ start : start + ans ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " ADOBECODEBANC " NEW_LINE p = " ABC " NEW_LINE result = smallestWindow ( s , p ) NEW_LINE print ( " - - > Smallest β window β that β contain β all β character β : " , result ) NEW_LINE DEDENT |
Run Length Encoding | Python3 program to implement run length encoding ; Count occurrences of current character ; Print character and its count ; Driver code | def printRLE ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE i = 0 NEW_LINE while i < n - 1 : NEW_LINE INDENT count = 1 NEW_LINE while ( i < n - 1 and st [ i ] == st [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE i += 1 NEW_LINE DEDENT i += 1 NEW_LINE print ( st [ i - 1 ] + str ( count ) , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " wwwwaaadexxxxxxywww " NEW_LINE printRLE ( st ) NEW_LINE DEDENT |
Print list items containing all characters of a given word | Python program to print the list items containing all characters of a given word ; Prints list items having all characters of word ; Set the values in map ; Get the length of given word ; Check each item of list if has all characters of words ; unset the bit so that strings like sss not printed ; Set the values in map for next item ; Driver program to test the above function | NO_OF_CHARS = 256 NEW_LINE def printList ( list , word , list_size ) : NEW_LINE INDENT map = [ 0 ] * NO_OF_CHARS NEW_LINE for i in word : NEW_LINE INDENT map [ ord ( i ) ] = 1 NEW_LINE DEDENT word_size = len ( word ) NEW_LINE for i in list : NEW_LINE INDENT count = 0 NEW_LINE for j in i : NEW_LINE INDENT if map [ ord ( j ) ] : NEW_LINE INDENT count += 1 NEW_LINE map [ ord ( j ) ] = 0 NEW_LINE DEDENT DEDENT if count == word_size : NEW_LINE INDENT print i NEW_LINE DEDENT for j in xrange ( len ( word ) ) : NEW_LINE INDENT map [ ord ( word [ j ] ) ] = 1 NEW_LINE DEDENT DEDENT DEDENT string = " sun " NEW_LINE list = [ " geeksforgeeks " , " unsorted " , " sunday " , " just " , " sss " ] NEW_LINE printList ( list , string , 5 ) NEW_LINE |
Given a string , find its first non | Python program to print the first non - repeating character ; Returns an array of size 256 containing count of characters in the passed char array ; The function returns index of first non - repeating character in a string . If all characters are repeating then returns - 1 ; Driver program to test above function | NO_OF_CHARS = 256 NEW_LINE def getCharCountArray ( string ) : NEW_LINE INDENT count = [ 0 ] * NO_OF_CHARS NEW_LINE for i in string : NEW_LINE INDENT count [ ord ( i ) ] += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def firstNonRepeating ( string ) : NEW_LINE INDENT count = getCharCountArray ( string ) NEW_LINE index = - 1 NEW_LINE k = 0 NEW_LINE for i in string : NEW_LINE INDENT if count [ ord ( i ) ] == 1 : NEW_LINE INDENT index = k NEW_LINE break NEW_LINE DEDENT k += 1 NEW_LINE DEDENT return index NEW_LINE DEDENT string = " geeksforgeeks " NEW_LINE index = firstNonRepeating ( string ) NEW_LINE if index == 1 : 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 |
Divide a string in N equal parts | Function to print n equal parts of string ; Check if string can be divided in n equal parts ; Calculate the size of parts to find the division points ; Driver program to test the above function Length of string is 28 ; ; Print 4 equal parts of the string | def divideString ( string , n ) : NEW_LINE INDENT str_size = len ( string ) NEW_LINE if str_size % n != 0 : NEW_LINE INDENT print " Invalid β Input : β String β size β is β not β divisible β by β n " NEW_LINE return NEW_LINE DEDENT part_size = str_size / n NEW_LINE k = 0 NEW_LINE for i in string : NEW_LINE INDENT if k % part_size == 0 : NEW_LINE INDENT print " NEW_LINE DEDENT DEDENT DEDENT " , NEW_LINE INDENT print i , NEW_LINE k += 1 NEW_LINE DEDENT string = " a _ simple _ divide _ string _ quest " NEW_LINE / * length od string is 28 * / NEW_LINE divideString ( string , 4 ) NEW_LINE |
Print all paths from a source point to all the 4 corners of a Matrix | Function to check if we reached on of the entry / exit ( corner ) point . ; Function to check if the index is within the matrix boundary . ; Recursive helper function ; If any corner is reached push the string t into ans and return ; For all the four directions ; The new ith index ; The new jth index ; The direction R / L / U / D ; If the new cell is within the matrix boundary and it is not previously visited in same path ; mark the new cell visited ; Store the direction ; Backtrack to explore other paths ; Function to find all possible paths ; Create a direction array for all the four directions ; stores the result ; Initialise variable ; function call ; Print the result | def isCorner ( i , j , M , N ) : NEW_LINE INDENT if ( ( i == 0 and j == 0 ) or ( i == 0 and j == N - 1 ) or ( i == M - 1 and j == N - 1 ) or ( i == M - 1 and j == 0 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def isValid ( i , j , M , N ) : NEW_LINE INDENT if ( i < 0 or i >= M or j < 0 or j >= N ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def solve ( i , j , M , N , Dir , maze , t , ans ) : NEW_LINE INDENT if ( isCorner ( i , j , M , N ) ) : NEW_LINE INDENT ans . append ( t ) NEW_LINE return NEW_LINE DEDENT for k in range ( 4 ) : NEW_LINE INDENT x = i + Dir [ k ] [ 0 ] NEW_LINE y = j + Dir [ k ] [ 1 ] NEW_LINE c = Dir [ k ] [ 2 ] NEW_LINE if ( isValid ( x , y , M , N ) and maze [ x ] [ y ] == 1 ) : NEW_LINE INDENT maze [ x ] [ y ] = 0 NEW_LINE t += c NEW_LINE solve ( x , y , M , N , Dir , maze , t , ans ) NEW_LINE t = t [ : len ( t ) - 1 ] NEW_LINE maze [ x ] [ y ] = 1 NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT def possiblePaths ( src , maze ) : NEW_LINE INDENT Dir = [ [ - 1 , 0 , ' U ' ] , [ 0 , 1 , ' R ' ] , [ 1 , 0 , ' D ' ] , [ 0 , - 1 , ' L ' ] ] NEW_LINE temp = " " NEW_LINE ans = [ ] NEW_LINE solve ( src [ 0 ] , src [ 1 ] , len ( maze ) , len ( maze [ 0 ] ) , Dir , maze , temp , ans ) NEW_LINE return ans NEW_LINE DEDENT maze = [ [ 1 , 0 , 0 , 1 , 0 , 0 , 1 , 1 ] , [ 1 , 1 , 1 , 0 , 0 , 0 , 1 , 0 ] , [ 1 , 0 , 1 , 1 , 1 , 1 , 1 , 0 ] , [ 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 ] , [ 1 , 0 , 1 , 0 , 1 , 0 , 0 , 1 ] , [ 0 , 1 , 1 , 1 , 1 , 0 , 0 , 1 ] , [ 0 , 1 , 0 , 0 , 1 , 1 , 1 , 1 ] , [ 1 , 1 , 0 , 0 , 0 , 0 , 0 , 1 ] ] NEW_LINE src = [ 4 , 2 ] NEW_LINE paths = possiblePaths ( src , maze ) NEW_LINE if ( len ( paths ) == 0 ) : NEW_LINE INDENT print ( " No β Possible β Paths " ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in paths : NEW_LINE INDENT print ( i ) NEW_LINE DEDENT DEDENT |
Remove all subtrees consisting only of even valued nodes from a Binary Tree | Node of the tree ; Function to print tree level wise ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root ; Print front of queue and remove it from queue ; If left child is present ; Otherwise ; If right child is present ; Otherwise ; Function to remove subtrees ; Base Case ; Search for required condition in left and right half ; If the node is even and leaf node ; Driver Code ; Function Call ; Print answer | class node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printLevelOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE print ( temp . data , end = " β " ) NEW_LINE q = q [ 1 : ] NEW_LINE if ( temp . left != None ) : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT elif ( temp . right != None ) : NEW_LINE INDENT print ( " NULL " , end = " β " ) NEW_LINE DEDENT if ( temp . right != None ) : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT elif ( temp . left != None ) : NEW_LINE INDENT print ( " NULL " , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT def pruneTree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT root . left = pruneTree ( root . left ) NEW_LINE root . right = pruneTree ( root . right ) NEW_LINE if ( root . data % 2 == 0 and root . right == None and root . left == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT return root NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = node ( 1 ) NEW_LINE root . left = node ( 2 ) NEW_LINE root . left . left = node ( 8 ) NEW_LINE root . left . right = node ( 10 ) NEW_LINE root . right = node ( 7 ) NEW_LINE root . right . left = node ( 12 ) NEW_LINE root . right . right = node ( 5 ) NEW_LINE newRoot = pruneTree ( root ) NEW_LINE printLevelOrder ( newRoot ) NEW_LINE DEDENT |
Count total ways to reach destination from source in an undirected Graph | Utility Function to count total ways ; Base condition When reach to the destination ; Make vertex visited ; Recursive function , for count ways ; Backtracking Make vertex unvisited ; Return total ways ; Function to count total ways to reach destination ; Loop to make all vertex unvisited , Initially ; Make source visited ; Print total ways | def countWays ( mtrx , vrtx , i , dest , visited ) : NEW_LINE INDENT if ( i == dest ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT total = 0 NEW_LINE for j in range ( vrtx ) : NEW_LINE INDENT if ( mtrx [ i ] [ j ] == 1 and not visited [ j ] ) : NEW_LINE INDENT visited [ j ] = True ; NEW_LINE total += countWays ( mtrx , vrtx , j , dest , visited ) ; NEW_LINE visited [ j ] = False ; NEW_LINE DEDENT DEDENT return total NEW_LINE DEDENT def totalWays ( mtrx , vrtx , src , dest ) : NEW_LINE INDENT visited = [ False ] * vrtx NEW_LINE for i in range ( vrtx ) : NEW_LINE INDENT visited [ i ] = False NEW_LINE DEDENT visited [ src ] = True ; NEW_LINE return countWays ( mtrx , vrtx , src , dest , visited ) NEW_LINE DEDENT print ( totalWays ( mtrx , vrtx , src - 1 , dest - 1 ) ) NEW_LINE |
Print path from given Source to Destination in 2 | Function to print the path ; Base condition ; Pop stores elements ; Recursive call for printing stack In reverse order ; Function to store the path into The stack , if path exist ; Base condition ; Push current elements ; Condition to check whether reach to the Destination or not ; Increment ' x ' ordinate of source by ( 2 * x + y ) Keeping ' y ' constant ; Increment ' y ' ordinate of source by ( 2 * y + x ) Keeping ' x ' constant ; Pop current elements form stack ; If no path exists ; Utility function to check whether path exist or not ; To store x co - ordinate ; To store y co - ordinate ; Function to find the path ; Print - 1 , if path doesn 't exist ; Driver code ; Function call | def printExistPath ( sx , sy , last ) : NEW_LINE INDENT if ( len ( sx ) == 0 or len ( sy ) == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT x = sx [ - 1 ] ; NEW_LINE y = sy [ - 1 ] NEW_LINE sx . pop ( ) ; NEW_LINE sy . pop ( ) ; NEW_LINE printExistPath ( sx , sy , last ) ; NEW_LINE if ( len ( sx ) == last - 1 ) : NEW_LINE INDENT print ( " ( " + str ( x ) + " , β " + str ( y ) + " ) " , end = ' ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " ( " + str ( x ) + " , β " + str ( y ) + " ) β - > β " , end = ' ' ) NEW_LINE DEDENT DEDENT def storePath ( srcX , srcY , destX , destY , sx , sy ) : NEW_LINE INDENT if ( srcX > destX or srcY > destY ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT sx . append ( srcX ) ; NEW_LINE sy . append ( srcY ) ; NEW_LINE if ( srcX == destX and srcY == destY ) : NEW_LINE INDENT printExistPath ( sx , sy , len ( sx ) ) ; NEW_LINE return True ; NEW_LINE DEDENT if ( storePath ( ( 2 * srcX ) + srcY , srcY , destX , destY , sx , sy ) ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( storePath ( srcX , ( 2 * srcY ) + srcX , destX , destY , sx , sy ) ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT sx . pop ( ) ; NEW_LINE sy . pop ( ) ; NEW_LINE return False ; NEW_LINE DEDENT def isPathExist ( srcX , srcY , destX , destY ) : NEW_LINE INDENT sx = [ ] NEW_LINE sy = [ ] NEW_LINE return storePath ( srcX , srcY , destX , destY , sx , sy ) ; NEW_LINE DEDENT def printPath ( srcX , srcY , destX , destY ) : NEW_LINE INDENT if ( not isPathExist ( srcX , srcY , destX , destY ) ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT srcX = 5 NEW_LINE srcY = 8 ; NEW_LINE destX = 83 NEW_LINE destY = 21 ; NEW_LINE printPath ( srcX , srcY , destX , destY ) ; NEW_LINE DEDENT |
Count even paths in Binary Tree | A Tree node ; Utility function to count the even path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is odd ; Increment count when encounter leaf node with all node value even ; Left recursive call , and save the value of count ; Right recursive call , and return value of count ; Function to count the even paths in a given Binary tree ; Function call with count = 0 ; Driver Code ; Tree ; Function call | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . key = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def evenPaths ( node , count ) : NEW_LINE INDENT if ( node == None or ( node . key % 2 != 0 ) ) : NEW_LINE INDENT return count NEW_LINE DEDENT if ( not node . left and not node . right ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT count = evenPaths ( node . left , count ) NEW_LINE return evenPaths ( node . right , count ) NEW_LINE DEDENT def countEvenPaths ( node ) : NEW_LINE INDENT return evenPaths ( node , 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 12 ) NEW_LINE root . left = Node ( 13 ) NEW_LINE root . right = Node ( 12 ) NEW_LINE root . right . left = Node ( 14 ) NEW_LINE root . right . right = Node ( 16 ) NEW_LINE root . right . left . left = Node ( 21 ) NEW_LINE root . right . left . right = Node ( 22 ) NEW_LINE root . right . right . left = Node ( 22 ) NEW_LINE root . right . right . right = Node ( 24 ) NEW_LINE root . right . right . right . left = Node ( 8 ) NEW_LINE print ( countEvenPaths ( root ) ) NEW_LINE DEDENT |
Sum of subsets of all the subsets of an array | O ( 3 ^ N ) | ; Function to sum of all subsets of a given array ; Base case ; Recursively calling subsetSum ; 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 | / * To store the final ans * / NEW_LINE c = [ ] NEW_LINE ans = 0 NEW_LINE def subsetSum ( i , curr ) : NEW_LINE INDENT global ans , c NEW_LINE if ( i == len ( c ) ) : NEW_LINE INDENT ans += curr NEW_LINE return NEW_LINE DEDENT subsetSum ( i + 1 , curr + c [ i ] ) NEW_LINE subsetSum ( i + 1 , curr ) NEW_LINE DEDENT def subsetGen ( arr , i , n ) : NEW_LINE INDENT global ans , c NEW_LINE if ( i == n ) : NEW_LINE INDENT subsetSum ( 0 , 0 ) 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 del c [ - 1 ] NEW_LINE DEDENT arr = [ 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE subsetGen ( arr , 0 , n ) NEW_LINE print ( ans ) NEW_LINE |
Print the DFS traversal step | Python3 program to print the complete DFS - traversal of graph using back - tracking ; Function to print the complete DFS - traversal ; Check if all th node is visited or not and count unvisited nodes ; If all the node is visited return ; Mark not visited node as visited ; Track the current edge ; Print the node ; Check for not visited node and proceed with it . ; Call the DFs function if not visited ; Backtrack through the last visited nodes ; Function to call the DFS function which prints the DFS - traversal stepwise ; Create a array of visited node ; Vector to track last visited road ; Initialize all the node with false ; Call the function ; Function to insert edges in Graph ; Driver Code ; Number of nodes and edges in the graph ; Function call to create the graph ; Call the function to print | N = 1000 NEW_LINE adj = [ [ ] for i in range ( N ) ] NEW_LINE def dfsUtil ( u , node , visited , road_used , parent , it ) : NEW_LINE INDENT c = 0 NEW_LINE for i in range ( node ) : NEW_LINE INDENT if ( visited [ i ] ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( c == node ) : NEW_LINE INDENT return NEW_LINE DEDENT visited [ u ] = True NEW_LINE road_used . append ( [ parent , u ] ) NEW_LINE print ( u , end = " β " ) NEW_LINE for x in adj [ u ] : NEW_LINE INDENT if ( not visited [ x ] ) : NEW_LINE INDENT dfsUtil ( x , node , visited , road_used , u , it + 1 ) NEW_LINE DEDENT DEDENT for y in road_used : NEW_LINE INDENT if ( y [ 1 ] == u ) : NEW_LINE INDENT dfsUtil ( y [ 0 ] , node , visited , road_used , u , it + 1 ) NEW_LINE DEDENT DEDENT DEDENT def dfs ( node ) : NEW_LINE INDENT visited = [ False for i in range ( node ) ] NEW_LINE road_used = [ ] NEW_LINE for i in range ( node ) : NEW_LINE INDENT visited [ i ] = False NEW_LINE DEDENT dfsUtil ( 0 , node , visited , road_used , - 1 , 0 ) NEW_LINE DEDENT def insertEdge ( u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT node = 11 NEW_LINE edge = 13 NEW_LINE insertEdge ( 0 , 1 ) NEW_LINE insertEdge ( 0 , 2 ) NEW_LINE insertEdge ( 1 , 5 ) NEW_LINE insertEdge ( 1 , 6 ) NEW_LINE insertEdge ( 2 , 4 ) NEW_LINE insertEdge ( 2 , 9 ) NEW_LINE insertEdge ( 6 , 7 ) NEW_LINE insertEdge ( 6 , 8 ) NEW_LINE insertEdge ( 7 , 8 ) NEW_LINE insertEdge ( 2 , 3 ) NEW_LINE insertEdge ( 3 , 9 ) NEW_LINE insertEdge ( 3 , 10 ) NEW_LINE insertEdge ( 9 , 10 ) NEW_LINE dfs ( node ) NEW_LINE DEDENT |
Find Maximum number possible by doing at | Python3 program to find maximum integer possible by doing at - most K swap operations on its digits . ; function to find maximum integer possible by doing at - most K swap operations on its digits ; return if no swaps left ; consider every digit ; and compare it with all digits after it ; if digit at position i is less than digit at position j , swap it and check for maximum number so far and recurse for remaining swaps ; swap string [ i ] with string [ j ] ; If current num is more than maximum so far ; recurse of the other k - 1 swaps ; backtrack ; Driver Code | def swap ( string , i , j ) : NEW_LINE INDENT return ( string [ : i ] + string [ j ] + string [ i + 1 : j ] + string [ i ] + string [ j + 1 : ] ) NEW_LINE DEDENT def findMaximumNum ( string , k , maxm ) : NEW_LINE INDENT if k == 0 : NEW_LINE INDENT return NEW_LINE DEDENT n = len ( string ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if string [ i ] < string [ j ] : NEW_LINE INDENT string = swap ( string , i , j ) NEW_LINE if string > maxm [ 0 ] : NEW_LINE INDENT maxm [ 0 ] = string NEW_LINE DEDENT findMaximumNum ( string , k - 1 , maxm ) NEW_LINE string = swap ( string , i , j ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "129814999" NEW_LINE k = 4 NEW_LINE maxm = [ string ] NEW_LINE findMaximumNum ( string , k , maxm ) NEW_LINE print ( maxm [ 0 ] ) NEW_LINE DEDENT |
Print all possible paths from top left to bottom right of a mXn matrix | Python3 program to Print all possible paths from top left to bottom right of a mXn matrix ; if we reach the bottom of maze , we can only move right ; path . append ( maze [ i ] [ k ] ) ; if we hit this block , it means one path is completed . Add it to paths list and print ; if we reach to the right most corner , we can only move down ; path . append ( maze [ j ] [ k ] ) if we hit this block , it means one path is completed . Add it to paths list and print ; add current element to the path list path . append ( maze [ i ] [ j ] ) ; move down in y direction and call findPathsUtil recursively ; move down in y direction and call findPathsUtil recursively ; Driver code | allPaths = [ ] NEW_LINE def findPaths ( maze , m , n ) : NEW_LINE INDENT path = [ 0 for d in range ( m + n - 1 ) ] NEW_LINE findPathsUtil ( maze , m , n , 0 , 0 , path , 0 ) NEW_LINE DEDENT def findPathsUtil ( maze , m , n , i , j , path , indx ) : NEW_LINE INDENT global allPaths NEW_LINE if i == m - 1 : NEW_LINE INDENT for k in range ( j , n ) : NEW_LINE INDENT path [ indx + k - j ] = maze [ i ] [ k ] NEW_LINE DEDENT print ( path ) NEW_LINE allPaths . append ( path ) NEW_LINE return NEW_LINE DEDENT if j == n - 1 : NEW_LINE INDENT for k in range ( i , m ) : NEW_LINE INDENT path [ indx + k - i ] = maze [ k ] [ j ] NEW_LINE DEDENT print ( path ) NEW_LINE allPaths . append ( path ) NEW_LINE return NEW_LINE DEDENT path [ indx ] = maze [ i ] [ j ] NEW_LINE findPathsUtil ( maze , m , n , i + 1 , j , path , indx + 1 ) NEW_LINE findPathsUtil ( maze , m , n , i , j + 1 , path , indx + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT maze = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE findPaths ( maze , 3 , 3 ) NEW_LINE DEDENT |
Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Function to find and print pair ; Driver code | def chkPair ( A , size , x ) : NEW_LINE INDENT for i in range ( 0 , size - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , size ) : NEW_LINE INDENT if ( A [ i ] + A [ j ] == x ) : NEW_LINE INDENT print ( " Pair β with β a β given β sum β " , x , " β is β ( " , A [ i ] , " , β " , A [ j ] , " ) " ) NEW_LINE return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT A = [ 0 , - 1 , 2 , - 3 , 1 ] NEW_LINE x = - 2 NEW_LINE size = len ( A ) NEW_LINE if ( chkPair ( A , size , x ) ) : NEW_LINE INDENT print ( " Valid β pair β exists " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No β valid β pair β exists β for β " , x ) NEW_LINE DEDENT |
Significant Inversions in an Array | Function that sorts the input array and returns the number of inversions in the array ; Recursive function that sorts the input array and returns the number of inversions in the array ; Divide the array into two parts and call _mergeSortAndCountInv ( ) for each of the parts ; Inversion count will be sum of the inversions in the left - part , the right - part and the number of inversions in merging ; Merge the two parts ; Function that merges the two sorted arrays and returns the inversion count in the arrays ; i is the index for the left subarray ; j is the index for the right subarray ; k is the index for the resultant merged subarray ; First pass to count number of significant inversions ; i is the index for the left subarray ; j is the index for the right subarray ; k is the index for the resultant merged subarray ; Second pass to merge the two sorted arrays ; Copy the remaining elements of the left subarray ( if there are any ) to temp ; Copy the remaining elements of the right subarray ( if there are any ) to temp ; Copy back the merged elements to the original array ; Driver code | def mergeSort ( arr , array_size ) : NEW_LINE INDENT temp = [ 0 for i in range ( array_size ) ] NEW_LINE return _mergeSort ( arr , temp , 0 , array_size - 1 ) NEW_LINE DEDENT def _mergeSort ( arr , temp , left , right ) : NEW_LINE INDENT mid , inv_count = 0 , 0 NEW_LINE if ( right > left ) : NEW_LINE INDENT mid = ( right + left ) // 2 NEW_LINE inv_count = _mergeSort ( arr , temp , left , mid ) NEW_LINE inv_count += _mergeSort ( arr , temp , mid + 1 , right ) NEW_LINE inv_count += merge ( arr , temp , left , mid + 1 , right ) NEW_LINE DEDENT return inv_count NEW_LINE DEDENT def merge ( arr , temp , left , mid , right ) : NEW_LINE INDENT inv_count = 0 NEW_LINE i = left NEW_LINE j = mid NEW_LINE k = left NEW_LINE while ( ( i <= mid - 1 ) and ( j <= right ) ) : NEW_LINE INDENT if ( arr [ i ] > 2 * arr [ j ] ) : NEW_LINE INDENT inv_count += ( mid - i ) NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT i = left NEW_LINE j = mid NEW_LINE k = left NEW_LINE while ( ( i <= mid - 1 ) and ( j <= right ) ) : NEW_LINE INDENT if ( arr [ i ] <= arr [ j ] ) : NEW_LINE INDENT temp [ k ] = arr [ i ] NEW_LINE i , k = i + 1 , k + 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp [ k ] = arr [ j ] NEW_LINE k , j = k + 1 , j + 1 NEW_LINE DEDENT DEDENT while ( i <= mid - 1 ) : NEW_LINE INDENT temp [ k ] = arr [ i ] NEW_LINE i , k = i + 1 , k + 1 NEW_LINE DEDENT while ( j <= right ) : NEW_LINE INDENT temp [ k ] = arr [ j ] NEW_LINE j , k = j + 1 , k + 1 NEW_LINE DEDENT for i in range ( left , right + 1 ) : NEW_LINE INDENT arr [ i ] = temp [ i ] NEW_LINE DEDENT return inv_count NEW_LINE DEDENT arr = [ 1 , 20 , 6 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( mergeSort ( arr , n ) ) NEW_LINE |
Find the number of different numbers in the array after applying the given operation q times | Python3 implementation for above approach ; To store the tree in lazy propagation ; To store the different numbers ; Function to update in the range [ x , y ) with given value ; check out of bound ; check for complete overlap ; find the mid number ; check for pending updates ; make lazy [ id ] = 0 , so that it has no pending updates ; call for two child nodes ; Function to find non - zero integersin the range [ l , r ) ; if id contains positive number ; There is no need to see the children , because all the interval have same number ; check for out of bound ; find the middle number ; call for two child nodes ; Driver code ; size of the array and number of queries ; Update operation for l , r , x , id , 0 , n ; Query operation to get answer in the range [ 0 , n - 1 ] ; Print the count of non - zero elements | N = 100005 NEW_LINE lazy = [ 0 ] * ( 4 * N ) ; NEW_LINE se = set ( ) NEW_LINE def update ( x , y , value , id , l , r ) : NEW_LINE INDENT if ( x >= r or l >= y ) : NEW_LINE INDENT return ; NEW_LINE DEDENT if ( x <= l and r <= y ) : NEW_LINE INDENT lazy [ id ] = value ; NEW_LINE return ; NEW_LINE DEDENT mid = ( l + r ) // 2 ; NEW_LINE if ( lazy [ id ] ) : NEW_LINE INDENT lazy [ 2 * id ] = lazy [ 2 * id + 1 ] = lazy [ id ] ; NEW_LINE DEDENT lazy [ id ] = 0 ; NEW_LINE update ( x , y , value , 2 * id , l , mid ) ; NEW_LINE update ( x , y , value , 2 * id + 1 , mid , r ) ; NEW_LINE DEDENT def query ( id , l , r ) : NEW_LINE INDENT if ( lazy [ id ] ) : NEW_LINE INDENT se . add ( lazy [ id ] ) ; NEW_LINE return ; NEW_LINE DEDENT if ( r - l < 2 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT mid = ( l + r ) // 2 ; NEW_LINE query ( 2 * id , l , mid ) ; NEW_LINE query ( 2 * id + 1 , mid , r ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; q = 3 ; NEW_LINE update ( 1 , 4 , 1 , 1 , 0 , n ) ; NEW_LINE update ( 0 , 2 , 2 , 1 , 0 , n ) ; NEW_LINE update ( 3 , 4 , 3 , 1 , 0 , n ) ; NEW_LINE query ( 1 , 0 , n ) ; NEW_LINE print ( len ( se ) ) ; NEW_LINE DEDENT |
Find Nth term ( A matrix exponentiation example ) | Python3 program to find n - th term of a recursive function using matrix exponentiation . ; This power function returns first row of { Transformation Matrix } ^ n - 1 * Initial Vector ; This is an identity matrix . ; this is Transformation matrix . ; Matrix exponentiation to calculate power of { tMat } ^ n - 1 store res in " res " matrix . ; res store { Transformation matrix } ^ n - 1 hence will be first row of res * Initial Vector . ; Driver code | MOD = 1000000009 ; NEW_LINE def power ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT n -= 1 ; NEW_LINE res = [ [ 1 , 0 ] , [ 0 , 1 ] ] ; NEW_LINE tMat = [ [ 2 , 3 ] , [ 1 , 0 ] ] ; NEW_LINE while ( n ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT tmp = [ [ 0 for x in range ( 2 ) ] for y in range ( 2 ) ] ; NEW_LINE tmp [ 0 ] [ 0 ] = ( res [ 0 ] [ 0 ] * tMat [ 0 ] [ 0 ] + res [ 0 ] [ 1 ] * tMat [ 1 ] [ 0 ] ) % MOD ; NEW_LINE tmp [ 0 ] [ 1 ] = ( res [ 0 ] [ 0 ] * tMat [ 0 ] [ 1 ] + res [ 0 ] [ 1 ] * tMat [ 1 ] [ 1 ] ) % MOD ; NEW_LINE tmp [ 1 ] [ 0 ] = ( res [ 1 ] [ 0 ] * tMat [ 0 ] [ 0 ] + res [ 1 ] [ 1 ] * tMat [ 1 ] [ 0 ] ) % MOD ; NEW_LINE tmp [ 1 ] [ 1 ] = ( res [ 1 ] [ 0 ] * tMat [ 0 ] [ 1 ] + res [ 1 ] [ 1 ] * tMat [ 1 ] [ 1 ] ) % MOD ; NEW_LINE res [ 0 ] [ 0 ] = tmp [ 0 ] [ 0 ] ; NEW_LINE res [ 0 ] [ 1 ] = tmp [ 0 ] [ 1 ] ; NEW_LINE res [ 1 ] [ 0 ] = tmp [ 1 ] [ 0 ] ; NEW_LINE res [ 1 ] [ 1 ] = tmp [ 1 ] [ 1 ] ; NEW_LINE DEDENT n = n // 2 ; NEW_LINE tmp = [ [ 0 for x in range ( 2 ) ] for y in range ( 2 ) ] ; NEW_LINE tmp [ 0 ] [ 0 ] = ( tMat [ 0 ] [ 0 ] * tMat [ 0 ] [ 0 ] + tMat [ 0 ] [ 1 ] * tMat [ 1 ] [ 0 ] ) % MOD ; NEW_LINE tmp [ 0 ] [ 1 ] = ( tMat [ 0 ] [ 0 ] * tMat [ 0 ] [ 1 ] + tMat [ 0 ] [ 1 ] * tMat [ 1 ] [ 1 ] ) % MOD ; NEW_LINE tmp [ 1 ] [ 0 ] = ( tMat [ 1 ] [ 0 ] * tMat [ 0 ] [ 0 ] + tMat [ 1 ] [ 1 ] * tMat [ 1 ] [ 0 ] ) % MOD ; NEW_LINE tmp [ 1 ] [ 1 ] = ( tMat [ 1 ] [ 0 ] * tMat [ 0 ] [ 1 ] + tMat [ 1 ] [ 1 ] * tMat [ 1 ] [ 1 ] ) % MOD ; NEW_LINE tMat [ 0 ] [ 0 ] = tmp [ 0 ] [ 0 ] ; NEW_LINE tMat [ 0 ] [ 1 ] = tmp [ 0 ] [ 1 ] ; NEW_LINE tMat [ 1 ] [ 0 ] = tmp [ 1 ] [ 0 ] ; NEW_LINE tMat [ 1 ] [ 1 ] = tmp [ 1 ] [ 1 ] ; NEW_LINE DEDENT return ( res [ 0 ] [ 0 ] * 1 + res [ 0 ] [ 1 ] * 1 ) % MOD ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( power ( n ) ) ; NEW_LINE |
Shuffle 2 n integers in format { a1 , b1 , a2 , b2 , a3 , b3 , ... ... , an , bn } without using extra space | Function to shuffle an array of size 2 n ; Rotate the element to the left ; swap a [ j - 1 ] , a [ j ] ; Driver Code | def shuffleArray ( a , n ) : NEW_LINE INDENT i , q , k = 0 , 1 , n NEW_LINE while ( i < n ) : NEW_LINE INDENT j = k NEW_LINE while ( j > i + q ) : NEW_LINE INDENT a [ j - 1 ] , a [ j ] = a [ j ] , a [ j - 1 ] NEW_LINE j -= 1 NEW_LINE DEDENT i += 1 NEW_LINE k += 1 NEW_LINE q += 1 NEW_LINE DEDENT DEDENT a = [ 1 , 3 , 5 , 7 , 2 , 4 , 6 , 8 ] NEW_LINE n = len ( a ) NEW_LINE shuffleArray ( a , int ( n / 2 ) ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE DEDENT |
Place k elements such that minimum distance is maximized | Returns true if it is possible to arrange k elements of arr [ 0. . n - 1 ] with minimum distance given as mid . ; Place first element at arr [ 0 ] position ; Initialize count of elements placed . ; Try placing k elements with minimum distance mid . ; Place next element if its distance from the previously placed element is greater than current mid ; Return if all elements are placed successfully ; Returns largest minimum distance for k elements in arr [ 0. . n - 1 ] . If elements can 't be placed, returns -1. ; Sort the positions ; Initialize result . ; Consider the maximum possible distance ; Do binary search for largest minimum distance ; If it is possible to place k elements with minimum distance mid , search for higher distance . ; Change value of variable max to mid iff all elements can be successfully placed ; If not possible to place k elements , search for lower distance ; Driver code | def isFeasible ( mid , arr , n , k ) : NEW_LINE INDENT pos = arr [ 0 ] NEW_LINE elements = 1 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( arr [ i ] - pos >= mid ) : NEW_LINE INDENT pos = arr [ i ] NEW_LINE elements += 1 NEW_LINE if ( elements == k ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return 0 NEW_LINE DEDENT def largestMinDist ( arr , n , k ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE res = - 1 NEW_LINE left = 1 NEW_LINE right = arr [ n - 1 ] NEW_LINE while ( left < right ) : NEW_LINE INDENT mid = ( left + right ) / 2 NEW_LINE if ( isFeasible ( mid , arr , n , k ) ) : NEW_LINE INDENT res = max ( res , mid ) NEW_LINE left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 8 , 4 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( largestMinDist ( arr , n , k ) ) NEW_LINE DEDENT |
Find frequency of each element in a limited range array in less than O ( n ) time | It prints number of occurrences of each element in the array . ; HashMap to store frequencies ; traverse the array ; update the frequency ; traverse the hashmap ; Driver function | def findFrequency ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] not in mp : NEW_LINE INDENT mp [ arr [ i ] ] = 0 NEW_LINE DEDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in mp : NEW_LINE INDENT print ( " Element " , i , " occurs " , mp [ i ] , " times " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 , 8 , 8 , 8 , 9 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE findFrequency ( arr , n ) NEW_LINE |
Square root of an integer | Returns floor of square root of x ; Base cases ; Do Binary Search for floor ( sqrt ( x ) ) ; If x is a perfect square ; Since we need floor , we update answer when mid * mid is smaller than x , and move closer to sqrt ( x ) ; If mid * mid is greater than x ; driver code | def floorSqrt ( x ) : NEW_LINE INDENT if ( x == 0 or x == 1 ) : NEW_LINE INDENT return x NEW_LINE DEDENT start = 1 NEW_LINE end = x NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE if ( mid * mid == x ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( mid * mid < x ) : NEW_LINE INDENT start = mid + 1 NEW_LINE ans = mid NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT x = 11 NEW_LINE print ( floorSqrt ( x ) ) NEW_LINE |
Sine Rule with Derivation , Example and Implementation | Python3 program for the above approach ; Function to calculate remaining two sides ; Calculate angle B ; Convert angles to their respective radians for using trigonometric functions ; Sine rule ; Print the answer ; Input ; Function Call | import math NEW_LINE def findSides ( A , C , c ) : NEW_LINE INDENT B = 180 - ( A + C ) NEW_LINE A = A * ( 3.14159 / 180 ) NEW_LINE C = C * ( 3.14159 / 180 ) NEW_LINE B = B * ( 3.14159 / 180 ) NEW_LINE a = ( c / math . sin ( C ) ) * math . sin ( A ) NEW_LINE b = ( c / math . sin ( C ) ) * math . sin ( B ) NEW_LINE print ( " { 0 : . 2f } " . format ( a ) ) NEW_LINE print ( " { 0 : . 2f } " . format ( b ) ) NEW_LINE DEDENT A = 45.0 NEW_LINE C = 35.0 NEW_LINE c = 23 NEW_LINE findSides ( A , C , c ) NEW_LINE |
Reverse alternate levels of a perfect binary tree | Python3 program to reverse alternate levels of a binary tree ; A Binary Tree node ; A utility function to create a new Binary Tree Node ; Function to store nodes of alternate levels in an array ; Base case ; Store elements of left subtree ; Store this node only if this is a odd level node ; Function to modify Binary Tree ( All odd level nodes areupdated by taking elements from array in inorder fashion ) ; Base case ; Update nodes in left subtree ; Update this node only if this is an odd level node ; Update nodes in right subtree ; A utility function to reverse an array from index 0 to n - 1 ; The main function to reverse alternate nodes of a binary tree ; Create an auxiliary array to store nodes of alternate levels ; First store nodes of alternate levels ; Reverse the array ; Update tree by taking elements from array ; A utility function to print indorder traversal of a binary tree ; Driver code | MAX = 100 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . data = data NEW_LINE DEDENT DEDENT def newNode ( item ) : NEW_LINE INDENT temp = Node ( item ) NEW_LINE return temp NEW_LINE DEDENT def storeAlternate ( root , arr , index , l ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return index ; NEW_LINE DEDENT index = storeAlternate ( root . left , arr , index , l + 1 ) ; NEW_LINE if ( l % 2 != 0 ) : NEW_LINE INDENT arr [ index ] = root . data ; NEW_LINE index += 1 ; NEW_LINE DEDENT index = storeAlternate ( root . right , arr , index , l + 1 ) ; NEW_LINE return index NEW_LINE DEDENT def modifyTree ( root , arr , index , l ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return index ; NEW_LINE DEDENT index = modifyTree ( root . left , arr , index , l + 1 ) ; NEW_LINE if ( l % 2 != 0 ) : NEW_LINE INDENT root . data = arr [ index ] ; NEW_LINE index += 1 ; NEW_LINE DEDENT index = modifyTree ( root . right , arr , index , l + 1 ) ; NEW_LINE return index NEW_LINE DEDENT def reverse ( arr , n ) : NEW_LINE INDENT l = 0 NEW_LINE r = n - 1 ; NEW_LINE while ( l < r ) : NEW_LINE INDENT arr [ l ] , arr [ r ] = ( arr [ r ] , arr [ l ] ) ; NEW_LINE l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT DEDENT def reverseAlternate ( root ) : NEW_LINE INDENT arr = [ 0 for i in range ( MAX ) ] NEW_LINE index = 0 ; NEW_LINE index = storeAlternate ( root , arr , index , 0 ) ; NEW_LINE reverse ( arr , index ) ; NEW_LINE index = 0 ; NEW_LINE index = modifyTree ( root , arr , index , 0 ) ; NEW_LINE DEDENT def printInorder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return ; NEW_LINE DEDENT printInorder ( root . left ) ; NEW_LINE print ( root . data , end = ' β ' ) NEW_LINE printInorder ( root . right ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = newNode ( ' a ' ) ; NEW_LINE root . left = newNode ( ' b ' ) ; NEW_LINE root . right = newNode ( ' c ' ) ; NEW_LINE root . left . left = newNode ( ' d ' ) ; NEW_LINE root . left . right = newNode ( ' e ' ) ; NEW_LINE root . right . left = newNode ( ' f ' ) ; NEW_LINE root . right . right = newNode ( ' g ' ) ; NEW_LINE root . left . left . left = newNode ( ' h ' ) ; NEW_LINE root . left . left . right = newNode ( ' i ' ) ; NEW_LINE root . left . right . left = newNode ( ' j ' ) ; NEW_LINE root . left . right . right = newNode ( ' k ' ) ; NEW_LINE root . right . left . left = newNode ( ' l ' ) ; NEW_LINE root . right . left . right = newNode ( ' m ' ) ; NEW_LINE root . right . right . left = newNode ( ' n ' ) ; NEW_LINE root . right . right . right = newNode ( ' o ' ) ; NEW_LINE print ( " Inorder β Traversal β of β given β tree " ) NEW_LINE printInorder ( root ) ; NEW_LINE reverseAlternate ( root ) ; NEW_LINE print ( " Inorder Traversal of modified tree " ) NEW_LINE printInorder ( root ) ; NEW_LINE DEDENT |
Equation of a straight line passing through a point and making a given angle with a given line | Python3 program for the above approach ; Function to find slope of given line ; Special case when slope of line is infinity or is perpendicular to x - axis ; Function to find equations of lines passing through the given point and making an angle with given line ; Store slope of given line ; Convert degrees to radians ; Special case when slope of given line is infinity : In this case slope of one line will be equal to alfa and the other line will be equal to ( 180 - alfa ) ; In this case slope of required lines can 't be infinity ; g and f are the variables of required equations ; Print first line equation ; Print second line equation ; Special case when slope of required line becomes infinity ; General case ; g and f are the variables of required equations ; Print first line equation ; Print second line equation ; Driver Code ; Given Input ; Function Call | import math NEW_LINE def line_slope ( a , b ) : NEW_LINE INDENT if ( a != 0 ) : NEW_LINE INDENT return - b / a NEW_LINE DEDENT else : NEW_LINE INDENT return ( - 2 ) NEW_LINE DEDENT DEDENT def line_equation ( a , b , c , x1 , y1 , alfa ) : NEW_LINE INDENT given_slope = line_slope ( a , b ) NEW_LINE x = alfa * 3.14159 / 180 NEW_LINE if ( given_slope == - 2 ) : NEW_LINE INDENT slope_1 = math . tan ( x ) NEW_LINE slope_2 = math . tan ( 3.14159 - x ) NEW_LINE g = x1 , f = x1 NEW_LINE g *= ( - slope_1 ) NEW_LINE g += y1 NEW_LINE if ( g > 0 ) : NEW_LINE INDENT print ( " y β = β " , round ( slope_1 , 2 ) , " x β + " , round ( g ) ) ; NEW_LINE DEDENT if ( g <= 0 ) : NEW_LINE INDENT print ( " y β = β " , round ( slope_1 , 2 ) , " x β " , round ( g ) ) NEW_LINE DEDENT f *= ( - slope_2 ) NEW_LINE f += y1 NEW_LINE if ( f > 0 ) : NEW_LINE INDENT print ( " y β = β " , round ( slope_2 , 2 ) , " x β + " , round ( f ) ) NEW_LINE DEDENT if ( f <= 0 ) : NEW_LINE INDENT print ( " y β = β " , round ( slope_2 , 2 ) , " x β " , round ( f ) ) NEW_LINE DEDENT return NEW_LINE DEDENT if ( 1 - math . tan ( x ) * given_slope == 0 ) : NEW_LINE INDENT print ( " x β = " , x1 ) NEW_LINE DEDENT if ( 1 + math . tan ( x ) * given_slope == 0 ) : NEW_LINE INDENT print ( " x β = " , x1 ) NEW_LINE DEDENT slope_1 = ( ( given_slope + math . tan ( x ) ) / ( 1 - math . tan ( x ) * given_slope ) ) NEW_LINE slope_2 = ( ( given_slope - math . tan ( x ) ) / ( 1 + math . tan ( x ) * given_slope ) ) NEW_LINE g = x1 NEW_LINE f = x1 NEW_LINE g *= ( - slope_1 ) NEW_LINE g += y1 NEW_LINE if ( g > 0 and 1 - math . tan ( x ) * given_slope != 0 ) : NEW_LINE INDENT print ( " y β = β " , round ( slope_1 , 2 ) , " x β + " , round ( g ) ) NEW_LINE DEDENT if ( g <= 0 and 1 - math . tan ( x ) * given_slope != 0 ) : NEW_LINE INDENT print ( " y β = β " , round ( slope_1 , 2 ) , " x β " , round ( g ) ) NEW_LINE DEDENT f *= ( - slope_2 ) NEW_LINE f += y1 NEW_LINE if ( f > 0 and 1 + math . tan ( x ) * given_slope != 0 ) : NEW_LINE INDENT print ( " y β = β " , round ( slope_2 , 2 ) , " x β + " , round ( f ) ) NEW_LINE DEDENT if ( f <= 0 and 1 + math . tan ( x ) * given_slope != 0 ) : NEW_LINE INDENT print ( " y β = β " , round ( slope_2 , 2 ) , " x β " , round ( f ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 2 NEW_LINE b = 3 NEW_LINE c = - 7 NEW_LINE x1 = 4 NEW_LINE y1 = 9 NEW_LINE alfa = 30 NEW_LINE line_equation ( a , b , c , x1 , y1 , alfa ) NEW_LINE DEDENT |
Equation of a normal to a Circle from a given point | Function to calculate the slope ; Store the coordinates the center of the circle ; If slope becomes infinity ; Stores the slope ; If slope is zero ; Return the result ; Function to find the equation of the normal to a circle from a given point ; Stores the slope of the normal ; If slope becomes infinity ; If slope is zero ; Otherwise , print the equation of the normal ; Given Input ; Function Call | def normal_slope ( a , b , x1 , y1 ) : NEW_LINE INDENT g = a / 2 NEW_LINE f = b / 2 NEW_LINE if ( g - x1 == 0 ) : NEW_LINE INDENT return ( - 1 ) NEW_LINE DEDENT slope = ( f - y1 ) / ( g - x1 ) NEW_LINE if ( slope == 0 ) : NEW_LINE INDENT return ( - 2 ) NEW_LINE DEDENT return slope NEW_LINE DEDENT def normal_equation ( a , b , x1 , y1 ) : NEW_LINE INDENT slope = normal_slope ( a , b , x1 , y1 ) NEW_LINE if ( slope == - 1 ) : NEW_LINE INDENT print ( " x β = β " , x1 ) NEW_LINE DEDENT if ( slope == - 2 ) : NEW_LINE INDENT print ( " y β = β " , y1 ) NEW_LINE DEDENT if ( slope != - 1 and slope != - 2 ) : NEW_LINE INDENT x1 *= - slope NEW_LINE x1 += y1 NEW_LINE if ( x1 > 0 ) : NEW_LINE INDENT print ( " y β = β " , slope , " x β + β " , x1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " y β = β " , slope , " x β " , x1 ) NEW_LINE DEDENT DEDENT DEDENT a = 4 NEW_LINE b = 6 NEW_LINE c = 5 NEW_LINE x1 = 12 NEW_LINE y1 = 14 NEW_LINE normal_equation ( a , b , x1 , y1 ) NEW_LINE |
Sum of squares of distances between all pairs from given points | Function to find the sum of squares of distance between all distinct pairs ; Stores final answer ; Traverse the array ; Adding the effect of this point for all the previous x - points ; Temporarily add the square of x - coordinate ; Add the effect of this point for all the previous y - points ; Print the desired answer ; Driver Code | def findSquareSum ( Coordinates , N ) : NEW_LINE INDENT xq , yq = 0 , 0 NEW_LINE xs , ys = 0 , 0 NEW_LINE res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT a = Coordinates [ i ] [ 0 ] NEW_LINE b = Coordinates [ i ] [ 1 ] NEW_LINE res += xq NEW_LINE res -= 2 * xs * a NEW_LINE res += i * ( a * a ) NEW_LINE xq += a * a NEW_LINE xs += a NEW_LINE res += yq NEW_LINE res -= 2 * ys * b NEW_LINE res += i * b * b NEW_LINE yq += b * b NEW_LINE ys += b NEW_LINE DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 1 ] , [ - 1 , - 1 ] , [ 1 , - 1 ] , [ - 1 , 1 ] ] NEW_LINE N = len ( arr ) NEW_LINE findSquareSum ( arr , N ) NEW_LINE DEDENT |
Count points from an array that lies inside a semi | Python implementation of above approach ; Traverse the array ; Stores if a point lies above the diameter or not ; Stores if the R is less than or equal to the distance between center and point ; Driver Code | def getPointsIns ( x1 , y1 , radius , x2 , y2 , points ) : NEW_LINE INDENT for point in points : NEW_LINE INDENT condOne = ( point [ 1 ] - y2 ) * ( x2 - x1 ) - ( y2 - y1 ) * ( point [ 0 ] - x2 ) >= 0 NEW_LINE condTwo = radius >= ( ( y1 - point [ 1 ] ) ** 2 + ( x1 - point [ 0 ] ) ** 2 ) ** ( 0.5 ) NEW_LINE if condOne and condTwo : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT X = 0 NEW_LINE Y = 0 NEW_LINE R = 5 NEW_LINE P = 5 NEW_LINE Q = 0 NEW_LINE arr = [ [ 2 , 3 ] , [ 5 , 6 ] , [ - 1 , 4 ] , [ 5 , 5 ] ] NEW_LINE print ( getPointsIns ( X , Y , R , P , Q , arr ) ) NEW_LINE |
Count pairs of points having distance between them equal to integral values in a K | Function to find pairs whose distance between the points of is an integer value . ; Stores count of pairs whose distance between points is an integer ; Traverse the array , points [ ] ; Stores distance between points ( i , j ) ; Traverse all the points of current pair ; Update temp ; Update dist ; If dist is a perfect square ; Update ans ; Given value of K ; Given points ; Given value of N ; Function Call | def cntPairs ( points , n , K ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT dist = 0 NEW_LINE for k in range ( K ) : NEW_LINE INDENT temp = ( points [ i ] [ k ] - points [ j ] [ k ] ) NEW_LINE dist += temp * temp NEW_LINE DEDENT if ( ( ( dist ) ** ( 1 / 2 ) ) * ( ( dist ) ** ( 1 / 2 ) ) == dist ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT K = 2 NEW_LINE points = [ [ 1 , 2 ] , [ 5 , 5 ] , [ - 2 , 8 ] ] NEW_LINE n = len ( points ) NEW_LINE cntPairs ( points , n , K ) NEW_LINE |
Circumradius of a Cyclic Quadrilateral using the length of Sides | Program to find Circumradius of a cyclic quadrilateral using sides ; Function to return the Circumradius of a cyclic quadrilateral using sides ; Find semiperimeter ; Calculate the radius ; Driver Code ; Function Call ; Print the radius | import math NEW_LINE def Circumradius ( a , b , c , d ) : NEW_LINE INDENT s = ( a + b + c + d ) / 2 NEW_LINE radius = ( 1 / 4 ) * math . sqrt ( ( ( a * b ) + ( c * d ) ) * ( ( a * c ) + ( b * d ) ) * ( ( a * d ) + ( b * c ) ) / ( ( s - a ) * ( s - b ) * ( s - c ) * ( s - d ) ) ) NEW_LINE return radius NEW_LINE DEDENT A = 3 NEW_LINE B = 4 NEW_LINE C = 5 NEW_LINE D = 6 NEW_LINE ans = Circumradius ( A , B , C , D ) NEW_LINE print ( round ( ans , 2 ) ) NEW_LINE |
Area of Triangle using Side | Python3 program to calculate the area of a triangle when the length of two adjacent sides and the angle between them is provided ; Function to return the area of triangle using Side - Angle - Side formula ; Driver Code ; Function Call ; Print the final answer | import math NEW_LINE def Area_of_Triangle ( a , b , k ) : NEW_LINE INDENT area = ( 1 / 2 ) * a * b * math . sin ( k ) NEW_LINE return area NEW_LINE DEDENT a = 9 NEW_LINE b = 12 NEW_LINE k = 2 NEW_LINE ans = Area_of_Triangle ( a , b , k ) NEW_LINE print ( round ( ans , 2 ) ) NEW_LINE |
Subsets and Splits