text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Edit Distance | DP | A Space efficient Dynamic Programming based Python3 program to find minimum number operations to convert str1 to str2 ; Create a DP array to memoize result of previous computations ; Base condition when second String is empty then we remove all characters ; Start filling the DP This loop run for every character in second String ; This loop compares the char from second String with first String characters ; If first String is empty then we have to perform add character operation to get second String ; If character from both String is same then we do not perform any operation . here i % 2 is for bound the row number . ; If character from both String is not same then we take the minimum from three specified operation ; After complete fill the DP array if the len2 is even then we end up in the 0 th row else we end up in the 1 th row so we take len2 % 2 to get row ; Driver code
def EditDistDP ( str1 , str2 ) : NEW_LINE INDENT len1 = len ( str1 ) NEW_LINE len2 = len ( str2 ) NEW_LINE DP = [ [ 0 for i in range ( len1 + 1 ) ] for j in range ( 2 ) ] ; NEW_LINE for i in range ( 0 , len1 + 1 ) : NEW_LINE INDENT DP [ 0 ] [ i ] = i NEW_LINE DEDENT for i in range ( 1 , len2 + 1 ) : NEW_LINE INDENT for j in range ( 0 , len1 + 1 ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT DP [ i % 2 ] [ j ] = i NEW_LINE DEDENT elif ( str1 [ j - 1 ] == str2 [ i - 1 ] ) : NEW_LINE INDENT DP [ i % 2 ] [ j ] = DP [ ( i - 1 ) % 2 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT DP [ i % 2 ] [ j ] = ( 1 + min ( DP [ ( i - 1 ) % 2 ] [ j ] , min ( DP [ i % 2 ] [ j - 1 ] , DP [ ( i - 1 ) % 2 ] [ j - 1 ] ) ) ) NEW_LINE DEDENT DEDENT DEDENT print ( DP [ len2 % 2 ] [ len1 ] , " " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " food " NEW_LINE str2 = " money " NEW_LINE EditDistDP ( str1 , str2 ) NEW_LINE DEDENT
Sum of Bitwise XOR of elements of an array with all elements of another array | Function to calculate sum of Bitwise XOR of elements of arr [ ] with k ; Initialize sum to be zero ; Iterate over each set bit ; Stores contribution of i - th bet to the sum ; If the i - th bit is set ; Stores count of elements whose i - th bit is not set ; Update value ; Update value ; Add value to sum ; Move to the next power of two ; Stores the count of elements whose i - th bit is set ; Traverse the array ; Iterate over each bit ; If the i - th bit is set ; Increase count ; Driver Code
def xorSumOfArray ( arr , n , k , count ) : NEW_LINE INDENT sum = 0 NEW_LINE p = 1 NEW_LINE for i in range ( 31 ) : NEW_LINE INDENT val = 0 NEW_LINE if ( ( k & ( 1 << i ) ) != 0 ) : NEW_LINE INDENT not_set = n - count [ i ] NEW_LINE val = ( ( not_set ) * p ) NEW_LINE DEDENT else : NEW_LINE INDENT val = ( count [ i ] * p ) NEW_LINE DEDENT sum += val NEW_LINE p = ( p * 2 ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def sumOfXors ( arr , n , queries , q ) : NEW_LINE INDENT count = [ 0 for i in range ( 32 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 31 ) : NEW_LINE INDENT if ( arr [ i ] & ( 1 << j ) ) : NEW_LINE INDENT count [ j ] += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( q ) : NEW_LINE INDENT k = queries [ i ] NEW_LINE print ( xorSumOfArray ( arr , n , k , count ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 2 , 3 ] NEW_LINE queries = [ 3 , 8 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE q = len ( queries ) NEW_LINE sumOfXors ( arr , n , queries , q ) NEW_LINE DEDENT
Minimum time required to schedule K processes | Function to execute k processes that can be gained in minimum amount of time ; Stores all the array elements ; Push all the elements to the priority queue ; Stores the required result ; Loop while the queue is not empty and K is positive ; Store the top element from the pq ; Add it to the answer ; Divide it by 2 and push it back to the pq ; Print the answer ; Driver Code
def executeProcesses ( A , N , K ) : NEW_LINE INDENT pq = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT pq . append ( A [ i ] ) NEW_LINE DEDENT ans = 0 NEW_LINE pq . sort ( ) NEW_LINE while ( len ( pq ) > 0 and K > 0 ) : NEW_LINE INDENT top = pq . pop ( ) NEW_LINE ans += 1 NEW_LINE K -= top NEW_LINE top //= 2 NEW_LINE pq . append ( top ) NEW_LINE pq . sort ( ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT A = [ 3 , 1 , 7 , 4 , 2 ] NEW_LINE K = 15 NEW_LINE N = len ( A ) NEW_LINE executeProcesses ( A , N , K ) NEW_LINE
Median of all nodes from a given range in a Binary Search Tree ( BST ) | Tree Node structure ; Function to create a new BST node ; Function to insert a new node with given key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; Return the node pointer ; Function to find all the nodes that lies over the range [ node1 , node2 ] ; If the tree is empty , return ; Traverse for the left subtree ; If a second node is found , then update the flag as false ; Traverse the right subtree ; Function to find the median of all the values in the given BST that lies over the range [ node1 , node2 ] ; Stores all the nodes in the range [ node1 , node2 ] ; Store the size of the array ; Print the median of array based on the size of array ; Given BST
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT interNodes = [ ] NEW_LINE def newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE return temp NEW_LINE DEDENT def insertNode ( node , key ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return newNode ( key ) NEW_LINE DEDENT if ( key < node . key ) : NEW_LINE INDENT node . left = insertNode ( node . left , key ) NEW_LINE DEDENT elif ( key > node . key ) : NEW_LINE INDENT node . right = insertNode ( node . right , key ) NEW_LINE DEDENT return node NEW_LINE DEDENT def getIntermediateNodes ( root , node1 , node2 ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT getIntermediateNodes ( root . left , node1 , node2 ) NEW_LINE if ( root . key <= node2 and root . key >= node1 ) : NEW_LINE INDENT interNodes . append ( root . key ) NEW_LINE DEDENT getIntermediateNodes ( root . right , node1 , node2 ) NEW_LINE DEDENT def findMedian ( root , node1 , node2 ) : NEW_LINE INDENT getIntermediateNodes ( root , node1 , node2 ) NEW_LINE nSize = len ( interNodes ) NEW_LINE if nSize % 2 == 1 : NEW_LINE INDENT return interNodes [ int ( nSize / 2 ) ] NEW_LINE DEDENT else : NEW_LINE INDENT return ( interNodes [ int ( ( nSize - 1 ) / 2 ) ] + interNodes [ nSize / 2 ] ) / 2 NEW_LINE DEDENT DEDENT root = None NEW_LINE root = insertNode ( root , 8 ) NEW_LINE insertNode ( root , 3 ) NEW_LINE insertNode ( root , 1 ) NEW_LINE insertNode ( root , 6 ) NEW_LINE insertNode ( root , 4 ) NEW_LINE insertNode ( root , 11 ) NEW_LINE insertNode ( root , 15 ) NEW_LINE print ( findMedian ( root , 3 , 11 ) ) NEW_LINE
Count number of pairs ( i , j ) up to N that can be made equal on multiplying with a pair from the range [ 1 , N / 2 ] | Function to compute totient of all numbers smaller than or equal to N ; Iterate over the range [ 2 , N ] ; If phi [ p ] is not computed already then p is prime ; Phi of a prime number p is ( p - 1 ) ; Update phi values of all multiples of p ; Add contribution of p to its multiple i by multiplying with ( 1 - 1 / p ) ; Function to count the pairs ( i , j ) from the range [ 1 , N ] , satisfying the given condition ; Stores the counts of first and second type of pairs respectively ; Count of first type of pairs ; Stores the phi or totient values ; Calculate the Phi values ; Iterate over the range [ N / 2 + 1 , N ] ; Update the value of cnt_type2 ; Print the total count ; Driver Code
def computeTotient ( N , phi ) : NEW_LINE INDENT for p in range ( 2 , N + 1 ) : NEW_LINE INDENT if phi [ p ] == p : NEW_LINE INDENT phi [ p ] = p - 1 NEW_LINE for i in range ( 2 * p , N + 1 , p ) : NEW_LINE INDENT phi [ i ] = ( phi [ i ] // p ) * ( p - 1 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def countPairs ( N ) : NEW_LINE INDENT cnt_type1 = 0 NEW_LINE cnt_type2 = 0 NEW_LINE half_N = N // 2 NEW_LINE cnt_type1 = ( half_N * ( half_N - 1 ) ) // 2 NEW_LINE phi = [ 0 for i in range ( N + 1 ) ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT phi [ i ] = i NEW_LINE DEDENT computeTotient ( N , phi ) NEW_LINE for i in range ( ( N // 2 ) + 1 , N + 1 ) : NEW_LINE INDENT cnt_type2 += ( i - phi [ i ] - 1 ) NEW_LINE DEDENT print ( cnt_type1 + cnt_type2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE countPairs ( N ) NEW_LINE DEDENT
Sum of subsets nearest to K possible from two given arrays | Stores the sum closest to K ; Stores the minimum absolute difference ; Function to choose the elements from the array B [ ] ; If absolute difference is less then minimum value ; Update the minimum value ; Update the value of ans ; If absolute difference between curr and K is equal to minimum ; Update the value of ans ; If i is greater than M - 1 ; Includes the element B [ i ] once ; Includes the element B [ i ] twice ; Excludes the element B [ i ] ; Function to find a subset sum whose sum is closest to K ; Traverse the array A [ ] ; Function Call ; Return the ans ; Driver Code ; Input ; Function Call
ans = 10 ** 8 NEW_LINE mini = 10 ** 8 NEW_LINE def findClosestTarget ( i , curr , B , M , K ) : NEW_LINE INDENT global ans , mini NEW_LINE if ( abs ( curr - K ) < mini ) : NEW_LINE INDENT mini = abs ( curr - K ) NEW_LINE ans = curr NEW_LINE DEDENT if ( abs ( curr - K ) == mini ) : NEW_LINE INDENT ans = min ( ans , curr ) NEW_LINE DEDENT if ( i >= M ) : NEW_LINE INDENT return NEW_LINE DEDENT findClosestTarget ( i + 1 , curr + B [ i ] , B , M , K ) NEW_LINE findClosestTarget ( i + 1 , curr + 2 * B [ i ] , B , M , K ) NEW_LINE findClosestTarget ( i + 1 , curr , B , M , K ) NEW_LINE DEDENT def findClosest ( A , B , N , M , K ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT findClosestTarget ( 0 , A [ i ] , B , M , K ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 2 , 3 ] NEW_LINE B = [ 4 , 5 , 30 ] NEW_LINE N = len ( A ) NEW_LINE M = len ( B ) NEW_LINE K = 18 NEW_LINE print ( findClosest ( A , B , N , M , K ) ) NEW_LINE DEDENT
Check if every node can me made accessible from a node of a Tree by at most N / 2 given operations | ; Store the indegree of every node ; Store the nodes having indegree equal to 0 ; Traverse the array ; If the indegree of i - th node is 0 ; Increment count0 by 1 ; If the number of operations needed is at most floor ( n / 2 ) ; Otherwise ; Driver Code ; Given number of nodes ; Given Directed Tree
/ * Function to check if there is a NEW_LINE INDENT node in tree from where all other NEW_LINE nodes are accessible or not * / NEW_LINE DEDENT def findNode ( mp , n ) : NEW_LINE INDENT a = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] = mp [ i + 1 ] NEW_LINE DEDENT count0 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT count0 += 1 NEW_LINE DEDENT DEDENT count0 -= 1 NEW_LINE if ( count0 <= ( n ) / ( 2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE mp = { } NEW_LINE mp [ 1 ] = 0 NEW_LINE mp [ 2 ] = 2 NEW_LINE mp [ 3 ] = 0 NEW_LINE findNode ( mp , N ) NEW_LINE DEDENT
Check if Bitwise AND of concatenation of diagonals exceeds that of middle row / column elements of a Binary Matrix | Functio to convert obtained binary representation to decimal value ; Stores the resultant number ; Traverse string arr ; Return the number formed ; Function to count the number of set bits in the number num ; Stores the count of set bits ; Iterate until num > 0 ; Function to check if the given matrix satisfies the given condition or not ; To get P , S , MR , and MC ; Stores decimal equivalents of binary representations ; Gett the number of set bits ; Print the answer ; Driver Code
def convert ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in arr : NEW_LINE INDENT ans = ( ans << 1 ) | i NEW_LINE DEDENT return ans NEW_LINE DEDENT def count ( num ) : NEW_LINE INDENT ans = 0 NEW_LINE while num : NEW_LINE INDENT ans += num & 1 NEW_LINE num >>= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def checkGoodMatrix ( mat ) : NEW_LINE INDENT P = [ ] NEW_LINE S = [ ] NEW_LINE MR = [ ] NEW_LINE MC = [ ] NEW_LINE for i in range ( len ( mat ) ) : NEW_LINE INDENT for j in range ( len ( mat [ 0 ] ) ) : NEW_LINE INDENT if i == j : NEW_LINE INDENT P . append ( mat [ i ] [ j ] ) NEW_LINE DEDENT if i + j == len ( mat ) - 1 : NEW_LINE INDENT S . append ( mat [ i ] [ j ] ) NEW_LINE DEDENT if i == ( len ( mat ) - 1 ) // 2 : NEW_LINE INDENT MR . append ( mat [ i ] [ j ] ) NEW_LINE DEDENT if j == ( len ( mat ) - 1 ) // 2 : NEW_LINE INDENT MC . append ( mat [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT S . reverse ( ) NEW_LINE P = convert ( P ) NEW_LINE S = convert ( S ) NEW_LINE MR = convert ( MR ) NEW_LINE MC = convert ( MC ) NEW_LINE setBitsPS = count ( P & S ) NEW_LINE setBitsMM = count ( MR & MC ) NEW_LINE if setBitsPS > setBitsMM : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT mat = [ [ 1 , 0 , 1 ] , [ 0 , 0 , 1 ] , [ 0 , 1 , 1 ] ] NEW_LINE checkGoodMatrix ( mat ) NEW_LINE
Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path | Python3 program for the above approach ; Function to assign values to nodes of the tree s . t . sum of values of nodes of path between any 2 nodes is not divisible by length of path ; Stores the adjacency list ; Create a adjacency list ; Stores whether any node is visited or not ; Stores the node values ; Variable used to assign values to the nodes alternatively to the parent child ; Declare a queue ; Push the 1 st node ; Assign K value to this node ; Dequeue the node ; Mark it as visited ; Upgrade the value of K ; Assign K to the child nodes ; If the child is unvisited ; Enqueue the child ; Assign K to the child ; Print the value assigned to the nodes ; Driver Code ; Function Call
from collections import deque NEW_LINE def assignValues ( Edges , n ) : NEW_LINE INDENT tree = [ [ ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT u = Edges [ i ] [ 0 ] NEW_LINE v = Edges [ i ] [ 1 ] NEW_LINE tree [ u ] . append ( v ) NEW_LINE tree [ v ] . append ( u ) NEW_LINE DEDENT visited = [ False ] * ( n + 1 ) NEW_LINE answer = [ 0 ] * ( n + 1 ) NEW_LINE K = 1 NEW_LINE q = deque ( ) NEW_LINE q . append ( 1 ) NEW_LINE answer [ 1 ] = K NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT node = q . popleft ( ) NEW_LINE visited [ node ] = True NEW_LINE K = 2 if ( answer [ node ] == 1 ) else 1 NEW_LINE for child in tree [ node ] : NEW_LINE INDENT if ( not visited [ child ] ) : NEW_LINE INDENT q . append ( child ) NEW_LINE answer [ child ] = K NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( answer [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE Edges = [ [ 1 , 2 ] , [ 4 , 6 ] , [ 3 , 5 ] , [ 1 , 4 ] , [ 7 , 5 ] , [ 5 , 1 ] ] NEW_LINE assignValues ( Edges , N ) NEW_LINE DEDENT
Number of full binary trees such that each node is product of its children | Return the number of all possible full binary tree with given product property . ; Finding the minimum and maximum values in given array . ; Marking the presence of each array element and initialising the number of possible full binary tree for each integer equal to 1 because single node will also contribute as a full binary tree . ; From minimum value to maximum value of array finding the number of all possible Full Binary Trees . ; Find if value present in the array ; For each multiple of i , less than equal to maximum value of array ; If multiple is not present in the array then continue . ; Finding the number of possible Full binary trees for multiple j by multiplying number of possible Full binary tree from the number i and number of possible Full binary tree from i / j . ; Condition for possiblity when left chid became right child and vice versa . ; Driver Code
def numoffbt ( arr , n ) : NEW_LINE INDENT maxvalue = - 2147483647 NEW_LINE minvalue = 2147483647 NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxvalue = max ( maxvalue , arr [ i ] ) NEW_LINE minvalue = min ( minvalue , arr [ i ] ) NEW_LINE DEDENT mark = [ 0 for i in range ( maxvalue + 2 ) ] NEW_LINE value = [ 0 for i in range ( maxvalue + 2 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT mark [ arr [ i ] ] = 1 NEW_LINE value [ arr [ i ] ] = 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( minvalue , maxvalue + 1 ) : NEW_LINE INDENT if ( mark [ i ] != 0 ) : NEW_LINE INDENT j = i + i NEW_LINE while ( j <= maxvalue and j // i <= i ) : NEW_LINE INDENT if ( mark [ j ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT value [ j ] = value [ j ] + ( value [ i ] * value [ j // i ] ) NEW_LINE if ( i != j // i ) : NEW_LINE INDENT value [ j ] = value [ j ] + ( value [ i ] * value [ j // i ] ) NEW_LINE DEDENT j += i NEW_LINE DEDENT DEDENT ans += value [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( numoffbt ( arr , n ) ) NEW_LINE
Minimum prime numbers required to be subtracted to make all array elements equal | Python3 program for the above approach ; Stores the sieve of prime numbers ; Function that performs the Sieve of Eratosthenes ; Iterate over the range [ 2 , 1000 ] ; If the current element is a prime number ; Mark all its multiples as false ; Function to find the minimum number of subtraction of primes numbers required to make all array elements the same ; Perform sieve of eratosthenes ; Find the minimum value ; Stores the value to each array element should be reduced ; If an element exists with value ( M + 1 ) ; Stores the minimum count of subtraction of prime numbers ; Traverse the array ; If D is equal to 0 ; If D is a prime number ; Increase count by 1 ; If D is an even number ; Increase count by 2 ; If D - 2 is prime ; Increase count by 2 ; Otherwise , increase count by 3 ; Driver Code
import sys NEW_LINE limit = 100000 NEW_LINE prime = [ True ] * ( limit + 1 ) NEW_LINE def sieve ( ) : NEW_LINE INDENT p = 2 NEW_LINE while ( p * p <= limit ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , limit , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def findOperations ( arr , n ) : NEW_LINE INDENT sieve ( ) NEW_LINE minm = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT minm = min ( minm , arr [ i ] ) NEW_LINE DEDENT val = minm NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == minm + 1 ) : NEW_LINE INDENT val = minm - 2 NEW_LINE break NEW_LINE DEDENT DEDENT cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT D = arr [ i ] - val NEW_LINE if ( D == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( prime [ D ] == True ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT elif ( D % 2 == 0 ) : NEW_LINE INDENT cnt += 2 NEW_LINE DEDENT else : NEW_LINE INDENT if ( prime [ D - 2 ] == True ) : NEW_LINE INDENT cnt += 2 NEW_LINE DEDENT else : NEW_LINE INDENT cnt += 3 NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT arr = [ 7 , 10 , 4 , 5 ] NEW_LINE N = 4 NEW_LINE print ( findOperations ( arr , N ) ) NEW_LINE
Print all unique digits present in concatenation of all array elements in the order of their occurrence | Function to print unique elements ; Reverse the list ; Traverse the list ; Function which check for all unique digits ; Stores the final number ; Stores the count of unique digits ; Converting string to integer to remove leading zeros ; Stores count of digits ; Iterate over the digits of N ; Retrieve the last digit of N ; Increase the count of the last digit ; Remove the last digit of N ; Converting string to integer again ; Iterate over the digits of N ; Retrieve the last digit of N ; If the value of this digit is not visited ; If its frequency is 1 ( unique ) ; Mark the digit visited ; Remove the last digit of N ; Passing this list to print the reversed list ; Function to concatenate array elements ; Stores the concatenated number ; Traverse the array ; Convert to equivalent string ; Concatenate the string ; Passing string to checkUnique function ; Driver Code ; Function call to print unique digits present in the concatenation of array elements
def printUnique ( lis ) : NEW_LINE INDENT lis . reverse ( ) NEW_LINE for i in lis : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT def checkUnique ( string ) : NEW_LINE INDENT lis = [ ] NEW_LINE res = 0 NEW_LINE N = int ( string ) NEW_LINE cnt = [ 0 ] * 10 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT rem = N % 10 NEW_LINE cnt [ rem ] += 1 NEW_LINE N = N // 10 NEW_LINE DEDENT N = int ( string ) NEW_LINE while ( N > 0 ) : NEW_LINE INDENT rem = N % 10 NEW_LINE if ( cnt [ rem ] != ' visited ' ) : NEW_LINE INDENT if ( cnt [ rem ] == 1 ) : NEW_LINE INDENT lis . append ( rem ) NEW_LINE DEDENT DEDENT cnt [ rem ] = ' visited ' NEW_LINE N = N // 10 NEW_LINE DEDENT printUnique ( lis ) NEW_LINE DEDENT def combineArray ( lis ) : NEW_LINE INDENT string = " " NEW_LINE for el in lis : NEW_LINE INDENT el = str ( el ) NEW_LINE string = string + el NEW_LINE DEDENT checkUnique ( string ) NEW_LINE DEDENT arr = [ 122 , 474 , 612 , 932 ] NEW_LINE combineArray ( arr ) NEW_LINE
Maximize sum of Bitwise AND of same | Function to calculate sum of Bitwise AND of same indexed elements of the arrays p [ ] and arr [ ] ; Stores the resultant sum ; Traverse the array ; Update sum of Bitwise AND ; Return the value obtained ; Function to generate all permutations and calculate the maximum sum of Bitwise AND of same indexed elements present in any permutation and an array arr [ ] ; If the size of the array is N ; Calculate cost of permutation ; Generate all permutations ; Update chosen [ i ] ; Update the permutation p [ ] ; Generate remaining permutations ; Return the resultant sum ; Function to find the maximum sum of Bitwise AND of same indexed elements in a permutation of first N natural numbers and arr [ ] ; Stores the resultant maximum sum ; Stores the generated permutation P ; Function call to store result ; Print the result ; Driver Code ; Function Call
def calcScore ( p , arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT ans += ( p [ i ] & arr [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getMaxUtil ( p , arr , ans , chosen , N ) : NEW_LINE INDENT if len ( p ) == N : NEW_LINE INDENT ans = max ( ans , calcScore ( p , arr ) ) NEW_LINE return ans NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if chosen [ i ] : NEW_LINE INDENT continue NEW_LINE DEDENT chosen [ i ] = True NEW_LINE p . append ( i ) NEW_LINE ans = getMaxUtil ( p , arr , ans , chosen , N ) NEW_LINE chosen [ i ] = False NEW_LINE p . pop ( ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getMax ( arr , N ) : NEW_LINE INDENT ans = 0 NEW_LINE chosen = [ False for i in range ( N ) ] NEW_LINE p = [ ] NEW_LINE res = getMaxUtil ( p , arr , ans , chosen , N ) NEW_LINE print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 3 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE getMax ( arr , N ) NEW_LINE DEDENT
Sum of array elements whose count of set bits are unique | Function to count the number of set bits in an integer N ; Stores the count of set bits ; Iterate until N is non - zero ; Stores the resultant count ; Function to calculate sum of all array elements whose count of set bits are unique ; Stores frequency of all possible count of set bits ; Stores the sum of array elements ; Traverse the array ; Count the number of set bits ; Traverse the array and Update the value of ans ; If frequency is 1 ; Driver Code
def setBitCount ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while n : NEW_LINE INDENT ans += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def getSum ( arr ) : NEW_LINE INDENT mp = { } NEW_LINE ans = 0 NEW_LINE for i in arr : NEW_LINE INDENT key = setBitCount ( i ) NEW_LINE mp [ key ] = [ 0 , i ] NEW_LINE DEDENT for i in arr : NEW_LINE INDENT key = setBitCount ( i ) NEW_LINE mp [ key ] [ 0 ] += 1 NEW_LINE DEDENT for i in mp : NEW_LINE INDENT if mp [ i ] [ 0 ] == 1 : NEW_LINE INDENT ans += mp [ i ] [ 1 ] NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 8 , 3 , 7 , 5 , 3 ] NEW_LINE getSum ( arr ) NEW_LINE
Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | Function to check if array can be split into three equal sum subarrays by removing a pair ; Stores prefix sum array ; Traverse the array ; Stores sums of all three subarrays ; Sum of left subarray ; Sum of middle subarray ; Sum of right subarray ; Check if sum of subarrays are equal ; Prthe possible pair ; If no such pair exists , pr - 1 ; Driver Code ; Given array ; Size of the array
def findSplit ( arr , N ) : NEW_LINE INDENT sum = [ i for i in arr ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT sum [ i ] += sum [ i - 1 ] NEW_LINE DEDENT for l in range ( 1 , N - 3 ) : NEW_LINE INDENT for r in range ( l + 2 , N - 1 ) : NEW_LINE INDENT lsum , rsum , msum = 0 , 0 , 0 NEW_LINE lsum = sum [ l - 1 ] NEW_LINE msum = sum [ r - 1 ] - sum [ l ] NEW_LINE rsum = sum [ N - 1 ] - sum [ r ] NEW_LINE if ( lsum == rsum and rsum == msum ) : NEW_LINE INDENT print ( l , r ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 5 , 12 , 7 , 19 , 4 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE findSplit ( arr , N ) NEW_LINE DEDENT
Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | Function to check if array can be split into three equal sum subarrays by removing a pair ; Two pointers l and r ; Stores prefix sum array ; Traverse the array ; Two pointer approach ; Sum of left subarray ; Sum of middle subarray ; Sum of right subarray ; Print split indices if sum is equal ; Move left pointer if lsum < rsum ; Move right pointer if rsum > lsum ; Move both pointers if lsum = rsum but they are not equal to msum ; If no possible pair exists , print - 1 ; Driver Code ; Given array ; Size of the array
def findSplit ( arr , N ) : NEW_LINE INDENT l = 1 ; r = N - 2 ; NEW_LINE sum = [ 0 ] * N ; NEW_LINE sum [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT sum [ i ] = sum [ i - 1 ] + arr [ i ] ; NEW_LINE DEDENT while ( l < r ) : NEW_LINE INDENT lsum = sum [ l - 1 ] ; NEW_LINE msum = sum [ r - 1 ] - sum [ l ] ; NEW_LINE rsum = sum [ N - 1 ] - sum [ r ] ; NEW_LINE if ( lsum == msum and msum == rsum ) : NEW_LINE INDENT print ( l , r ) ; NEW_LINE return ; NEW_LINE DEDENT if ( lsum < rsum ) : NEW_LINE INDENT l += 1 ; NEW_LINE DEDENT elif ( lsum > rsum ) : NEW_LINE INDENT r -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT l += 1 ; NEW_LINE r -= 1 ; NEW_LINE DEDENT DEDENT print ( - 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 5 , 12 , 7 , 19 , 4 , 3 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE findSplit ( arr , N ) ; NEW_LINE DEDENT
Number of subtrees having odd count of even numbers | Helper class that allocates a new Node with the given data and None left and right pointers . ; Returns count of subtrees having odd count of even numbers ; base condition ; count even nodes in left subtree ; Add even nodes in right subtree ; Check if root data is an even number ; if total count of even numbers for the subtree is odd ; Total count of even nodes of the subtree ; A wrapper over countRec ( ) ; Driver Code ; binary tree formation 2 ; / \ ; 1 3 ; / \ / \ ; 4 10 8 5 ; / ; 6 ;
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def countRec ( root , pcount ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT c = countRec ( root . left , pcount ) NEW_LINE c += countRec ( root . right , pcount ) NEW_LINE if ( root . data % 2 == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if c % 2 != 0 : NEW_LINE INDENT pcount [ 0 ] += 1 NEW_LINE DEDENT return c NEW_LINE DEDENT def countSubtrees ( root ) : NEW_LINE INDENT count = [ 0 ] NEW_LINE pcount = count NEW_LINE countRec ( root , pcount ) NEW_LINE return count [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 2 ) NEW_LINE root . left = newNode ( 1 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 10 ) NEW_LINE root . right . left = newNode ( 8 ) NEW_LINE root . right . right = newNode ( 5 ) NEW_LINE root . left . right . left = newNode ( 6 ) NEW_LINE print ( " Count ▁ = ▁ " , countSubtrees ( root ) ) NEW_LINE DEDENT
Inorder Successor of a node in Binary Tree | A Binary Tree Node Utility function to create a new tree node ; function to find left most node in a tree ; function to find right most node in a tree ; recursive function to find the Inorder Scuccessor when the right child of node x is None ; function to find inorder successor of a node ; Case1 : If right child is not None ; Case2 : If right child is None ; case3 : If x is the right most node ; Driver Code ; Case 1 ; case 2 ; case 3
class newNode : 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 leftMostNode ( node ) : NEW_LINE INDENT while ( node != None and node . left != None ) : NEW_LINE INDENT node = node . left NEW_LINE DEDENT return node NEW_LINE DEDENT def rightMostNode ( node ) : NEW_LINE INDENT while ( node != None and node . right != None ) : NEW_LINE INDENT node = node . right NEW_LINE DEDENT return node NEW_LINE DEDENT def findInorderRecursive ( root , x ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( root == x or ( findInorderRecursive ( root . left , x ) ) or ( findInorderRecursive ( root . right , x ) ) ) : NEW_LINE INDENT if findInorderRecursive ( root . right , x ) : NEW_LINE INDENT temp = findInorderRecursive ( root . right , x ) NEW_LINE DEDENT else : NEW_LINE INDENT temp = findInorderRecursive ( root . left , x ) NEW_LINE DEDENT if ( temp ) : NEW_LINE INDENT if ( root . left == temp ) : NEW_LINE INDENT print ( " Inorder ▁ Successor ▁ of " , x . data , end = " " ) NEW_LINE print ( " ▁ is " , root . data ) NEW_LINE return None NEW_LINE DEDENT DEDENT return root NEW_LINE DEDENT return None NEW_LINE DEDENT def inorderSuccesor ( root , x ) : NEW_LINE INDENT if ( x . right != None ) : NEW_LINE INDENT inorderSucc = leftMostNode ( x . right ) NEW_LINE print ( " Inorder ▁ Successor ▁ of " , x . data , " is " , end = " ▁ " ) NEW_LINE print ( inorderSucc . data ) NEW_LINE DEDENT if ( x . right == None ) : NEW_LINE INDENT f = 0 NEW_LINE rightMost = rightMostNode ( root ) NEW_LINE if ( rightMost == x ) : NEW_LINE INDENT print ( " No ▁ inorder ▁ successor ! " , " Right ▁ most ▁ node . " ) NEW_LINE DEDENT else : NEW_LINE INDENT findInorderRecursive ( root , x ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . right = newNode ( 6 ) NEW_LINE inorderSuccesor ( root , root . right ) NEW_LINE inorderSuccesor ( root , root . left . left ) NEW_LINE inorderSuccesor ( root , root . right . right ) NEW_LINE DEDENT
Binary Tree | Set 1 ( Introduction ) | Class containing left and right child of current node and key value ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . val = key NEW_LINE 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
Find distance from root to given node in a binary tree | A class to create a new Binary Tree Node ; Returns - 1 if x doesn 't exist in tree. Else returns distance of x from root ; Base case ; Initialize distance ; Check if x is present at root or in left subtree or right subtree . ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def findDistance ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT dist = - 1 NEW_LINE if ( root . data == x ) : NEW_LINE INDENT return dist + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dist = findDistance ( root . left , x ) NEW_LINE if dist >= 0 : NEW_LINE INDENT return dist + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dist = findDistance ( root . right , x ) NEW_LINE if dist >= 0 : NEW_LINE INDENT return dist + 1 NEW_LINE DEDENT DEDENT DEDENT return dist NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 5 ) NEW_LINE root . left = newNode ( 10 ) NEW_LINE root . right = newNode ( 15 ) NEW_LINE root . left . left = newNode ( 20 ) NEW_LINE root . left . right = newNode ( 25 ) NEW_LINE root . left . right . right = newNode ( 45 ) NEW_LINE root . right . left = newNode ( 30 ) NEW_LINE root . right . right = newNode ( 35 ) NEW_LINE print ( findDistance ( root , 45 ) ) NEW_LINE DEDENT
Find right sibling of a binary tree with parent pointers | A class to create a new Binary Tree Node ; Method to find right sibling ; GET Parent pointer whose right child is not a parent or itself of this node . There might be case when parent has no right child , but , current node is left child of the parent ( second condition is for that ) . ; Move to the required child , where right sibling can be present ; find right sibling in the given subtree ( from current node ) , when level will be 0 ; Iterate through subtree ; if no child are there , we cannot have right sibling in this path ; This is the case when we reach 9 node in the tree , where we need to again recursively find the right sibling ; Driver Code ; passing 10
class newNode : NEW_LINE INDENT def __init__ ( self , item , parent ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = self . right = None NEW_LINE self . parent = parent NEW_LINE DEDENT DEDENT def findRightSibling ( node , level ) : NEW_LINE INDENT if ( node == None or node . parent == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT while ( node . parent . right == node or ( node . parent . right == None and node . parent . left == node ) ) : NEW_LINE INDENT if ( node . parent == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT node = node . parent NEW_LINE level -= 1 NEW_LINE DEDENT node = node . parent . right NEW_LINE while ( level < 0 ) : NEW_LINE INDENT if ( node . left != None ) : NEW_LINE INDENT node = node . left NEW_LINE DEDENT elif ( node . right != None ) : NEW_LINE INDENT node = node . right NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT level += 1 NEW_LINE DEDENT if ( level == 0 ) : NEW_LINE INDENT return node NEW_LINE DEDENT return findRightSibling ( node , level ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 , None ) NEW_LINE root . left = newNode ( 2 , root ) NEW_LINE root . right = newNode ( 3 , root ) NEW_LINE root . left . left = newNode ( 4 , root . left ) NEW_LINE root . left . right = newNode ( 6 , root . left ) NEW_LINE root . left . left . left = newNode ( 7 , root . left . left ) NEW_LINE root . left . left . left . left = newNode ( 10 , root . left . left . left ) NEW_LINE root . left . right . right = newNode ( 9 , root . left . right ) NEW_LINE root . right . right = newNode ( 5 , root . right ) NEW_LINE root . right . right . right = newNode ( 8 , root . right . right ) NEW_LINE root . right . right . right . right = newNode ( 12 , root . right . right . right ) NEW_LINE res = findRightSibling ( root . left . left . left . left , 0 ) NEW_LINE if ( res == None ) : NEW_LINE INDENT print ( " No ▁ right ▁ sibling " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( res . data ) NEW_LINE DEDENT DEDENT
Find next right node of a given key | Set 2 | class to create a new tree node ; Function to find next node for given node in same level in a binary tree by using pre - order traversal ; return None if tree is empty ; if desired node is found , set value_level to current level ; if value_level is already set , then current node is the next right node ; recurse for left subtree by increasing level by 1 ; if node is found in left subtree , return it ; recurse for right subtree by increasing level by 1 ; Function to find next node of given node in the same level in given binary tree ; A utility function to test above functions ; Driver Code ; Let us create binary tree given in the above example
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def nextRightNode ( root , k , level , value_level ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( root . key == k ) : NEW_LINE INDENT value_level [ 0 ] = level NEW_LINE return None NEW_LINE DEDENT elif ( value_level [ 0 ] ) : NEW_LINE INDENT if ( level == value_level [ 0 ] ) : NEW_LINE INDENT return root NEW_LINE DEDENT DEDENT leftNode = nextRightNode ( root . left , k , level + 1 , value_level ) NEW_LINE if ( leftNode ) : NEW_LINE INDENT return leftNode NEW_LINE DEDENT return nextRightNode ( root . right , k , level + 1 , value_level ) NEW_LINE DEDENT def nextRightNodeUtil ( root , k ) : NEW_LINE INDENT value_level = [ 0 ] NEW_LINE return nextRightNode ( root , k , 1 , value_level ) NEW_LINE DEDENT def test ( root , k ) : NEW_LINE INDENT nr = nextRightNodeUtil ( root , k ) NEW_LINE if ( nr != None ) : NEW_LINE INDENT print ( " Next ▁ Right ▁ of " , k , " is " , nr . key ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ next ▁ right ▁ node ▁ found ▁ for " , k ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 5 ) NEW_LINE root . left . left = newNode ( 8 ) NEW_LINE root . left . right = newNode ( 4 ) NEW_LINE test ( root , 10 ) NEW_LINE test ( root , 2 ) NEW_LINE test ( root , 6 ) NEW_LINE test ( root , 5 ) NEW_LINE test ( root , 8 ) NEW_LINE test ( root , 4 ) NEW_LINE DEDENT
Top three elements in binary tree | Helper function that allocates a new Node with the given data and None left and right pointers . ; function to find three largest element ; if data is greater than first large number update the top three list ; if data is greater than second large number and not equal to first update the bottom two list ; if data is greater than third large number and not equal to first & second update the third highest list ; Driver Code
class newNode : 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 threelargest ( root , first , second , third ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . data > first [ 0 ] ) : NEW_LINE INDENT third [ 0 ] = second [ 0 ] NEW_LINE second [ 0 ] = first [ 0 ] NEW_LINE first [ 0 ] = root . data NEW_LINE DEDENT elif ( root . data > second [ 0 ] and root . data != first [ 0 ] ) : NEW_LINE INDENT third [ 0 ] = second [ 0 ] NEW_LINE second [ 0 ] = root . data NEW_LINE DEDENT elif ( root . data > third [ 0 ] and root . data != first [ 0 ] and root . data != second [ 0 ] ) : NEW_LINE INDENT third [ 0 ] = root . data NEW_LINE DEDENT threelargest ( root . left , first , second , third ) NEW_LINE threelargest ( root . right , first , second , third ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 4 ) NEW_LINE root . right . right = newNode ( 5 ) NEW_LINE first = [ 0 ] NEW_LINE second = [ 0 ] NEW_LINE third = [ 0 ] NEW_LINE threelargest ( root , first , second , third ) NEW_LINE print ( " three ▁ largest ▁ elements ▁ are " , first [ 0 ] , second [ 0 ] , third [ 0 ] ) NEW_LINE DEDENT
Find maximum ( or minimum ) in Binary Tree | A class to create a new node ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; Returns maximum value in a given Binary Tree ; Base case ; Return maximum of 3 values : 1 ) Root 's data 2) Max in Left Subtree 3) Max in right subtree ; Driver Code ; Function call
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def findMax ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return float ( ' - inf ' ) NEW_LINE DEDENT res = root . data NEW_LINE lres = findMax ( root . left ) NEW_LINE rres = findMax ( root . right ) NEW_LINE if ( lres > res ) : NEW_LINE INDENT res = lres NEW_LINE DEDENT if ( rres > res ) : NEW_LINE INDENT res = rres NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 2 ) NEW_LINE root . left = newNode ( 7 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . left . right . left = newNode ( 1 ) NEW_LINE root . left . right . right = newNode ( 11 ) NEW_LINE root . right . right = newNode ( 9 ) NEW_LINE root . right . right . left = newNode ( 4 ) NEW_LINE print ( " Maximum ▁ element ▁ is " , findMax ( root ) ) NEW_LINE DEDENT
Find maximum ( or minimum ) in Binary Tree | Returns the min value in a binary tree
def find_min_in_BT ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return float ( ' inf ' ) NEW_LINE DEDENT res = root . data NEW_LINE lres = find_min_in_BT ( root . leftChild ) NEW_LINE rres = find_min_in_BT ( root . rightChild ) NEW_LINE if lres < res : NEW_LINE INDENT res = lres NEW_LINE DEDENT if rres < res : NEW_LINE INDENT res = rres NEW_LINE DEDENT return res NEW_LINE DEDENT
Extract Leaves of a Binary Tree in a Doubly Linked List | A binary tree node ; Main function which extracts all leaves from given Binary Tree . The function returns new root of Binary Tree ( Note thatroot may change if Binary Tree has only one node ) . The function also sets * head_ref as head of doubly linked list . left pointer of tree is used as prev in DLL and right pointer is used as next ; Utility function for printing tree in InOrder ; Utility function for printing double linked list . ; Driver program to test above function
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 extractLeafList ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return None NEW_LINE DEDENT if root . left is None and root . right is None : NEW_LINE INDENT root . right = extractLeafList . head NEW_LINE if extractLeafList . head is not None : NEW_LINE INDENT extractLeafList . head . left = root NEW_LINE DEDENT extractLeafList . head = root NEW_LINE return None NEW_LINE DEDENT root . right = extractLeafList ( root . right ) NEW_LINE root . left = extractLeafList ( root . left ) NEW_LINE return root NEW_LINE DEDENT def printInorder ( root ) : NEW_LINE INDENT if root is not None : NEW_LINE INDENT printInorder ( root . left ) NEW_LINE print root . data , NEW_LINE printInorder ( root . right ) NEW_LINE DEDENT DEDENT def printList ( head ) : NEW_LINE INDENT while ( head ) : NEW_LINE INDENT if head . data is not None : NEW_LINE INDENT print head . data , NEW_LINE DEDENT head = head . right NEW_LINE DEDENT DEDENT extractLeafList . head = Node ( None ) NEW_LINE 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 . right = Node ( 6 ) NEW_LINE root . left . left . left = Node ( 7 ) NEW_LINE root . left . left . right = Node ( 8 ) NEW_LINE root . right . right . left = Node ( 9 ) NEW_LINE root . right . right . right = Node ( 10 ) NEW_LINE print " Inorder ▁ traversal ▁ of ▁ given ▁ tree ▁ is : " NEW_LINE printInorder ( root ) NEW_LINE root = extractLeafList ( root ) NEW_LINE print " NEW_LINE Extract Double Linked List is : " NEW_LINE printList ( extractLeafList . head ) NEW_LINE print " NEW_LINE Inorder traversal of modified tree is : " NEW_LINE printInorder ( root ) NEW_LINE
Inorder Successor of a node in Binary Tree | A Binary Tree Node ; Function to create a new Node . ; function that prints the inorder successor of a target node . next will point the last tracked node , which will be the answer . ; if root is None then return ; if target node found , then enter this condition ; Driver Code ; Let 's construct the binary tree as shown in above diagram. ; Case 1 ; case 2 ; case 3
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 newNode ( val ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . data = val NEW_LINE temp . left = None NEW_LINE temp . right = None NEW_LINE return temp NEW_LINE DEDENT def inorderSuccessor ( root , target_node ) : NEW_LINE INDENT global next NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT inorderSuccessor ( root . right , target_node ) NEW_LINE if ( root . data == target_node . data ) : NEW_LINE INDENT if ( next == None ) : NEW_LINE INDENT print ( " inorder ▁ successor ▁ of " , root . data , " ▁ is : ▁ None " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " inorder ▁ successor ▁ of " , root . data , " is : " , next . data ) NEW_LINE DEDENT DEDENT next = root NEW_LINE inorderSuccessor ( root . left , target_node ) NEW_LINE DEDENT next = None NEW_LINE if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . right = newNode ( 6 ) NEW_LINE next = None NEW_LINE inorderSuccessor ( root , root . right ) NEW_LINE next = None NEW_LINE inorderSuccessor ( root , root . left . left ) NEW_LINE next = None NEW_LINE inorderSuccessor ( root , root . right . right ) NEW_LINE DEDENT
Graph representations using set and hash | ; Adds an edge to undirected graph ; Add an edge from source to destination . A new element is inserted to adjacent list of source . ; Add an dge from destination to source . A new element is inserted to adjacent list of destination . ; A utility function to print the adjacency list representation of graph ; Search for a given edge in graph ; Driver code ; Create the graph given in the above figure ; Print adjacenecy list representation of graph ; Search the given edge in a graph
class graph ( object ) : NEW_LINE INDENT def __init__ ( self , v ) : NEW_LINE INDENT self . v = v NEW_LINE self . graph = dict ( ) NEW_LINE DEDENT def addEdge ( self , source , destination ) : NEW_LINE INDENT if source not in self . graph : NEW_LINE INDENT self . graph = { destination } NEW_LINE DEDENT else : NEW_LINE INDENT self . graph . add ( destination ) NEW_LINE DEDENT if destination not in self . graph : NEW_LINE INDENT self . graph [ destination ] = { source } NEW_LINE DEDENT else : NEW_LINE INDENT self . graph [ destination ] . add ( source ) NEW_LINE DEDENT DEDENT def print ( self ) : NEW_LINE INDENT for i , adjlist in sorted ( self . graph . items ( ) ) : NEW_LINE INDENT print ( " Adjacency ▁ list ▁ of ▁ vertex ▁ " , i ) NEW_LINE for j in sorted ( adjlist , reverse = True ) : NEW_LINE INDENT print ( j , end = " ▁ " ) NEW_LINE DEDENT print ( ' ' ) NEW_LINE DEDENT DEDENT def searchEdge ( self , source , destination ) : NEW_LINE INDENT if source in self . graph : NEW_LINE INDENT if destination in self . graph : NEW_LINE INDENT print ( " Edge from { 0 } to { 1 } found . " . format ( source , destination ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Edge from { 0 } to { 1 } not found . " . format ( source , destination ) ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " Source vertex { } is not present in graph . " . format ( source ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT g = graph ( 5 ) NEW_LINE g . addEdge ( 0 , 1 ) NEW_LINE g . addEdge ( 0 , 4 ) NEW_LINE g . addEdge ( 1 , 2 ) NEW_LINE g . addEdge ( 1 , 3 ) NEW_LINE g . addEdge ( 1 , 4 ) NEW_LINE g . addEdge ( 2 , 3 ) NEW_LINE g . addEdge ( 3 , 4 ) NEW_LINE g . print ( ) NEW_LINE g . searchEdge ( 2 , 1 ) NEW_LINE g . searchEdge ( 0 , 3 ) NEW_LINE DEDENT
Find n | Python3 program for nth node of inorder traversal ; A Binary Tree Node ; Given a binary tree , print the nth node of inorder traversal ; first recur on left child ; when count = n then prelement ; now recur on right child ; Driver Code
count = [ 0 ] NEW_LINE class newNode : 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 self . visited = False NEW_LINE DEDENT DEDENT def NthInorder ( node , n ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( count [ 0 ] <= n ) : NEW_LINE INDENT NthInorder ( node . left , n ) NEW_LINE count [ 0 ] += 1 NEW_LINE if ( count [ 0 ] == n ) : NEW_LINE INDENT print ( node . data , end = " ▁ " ) NEW_LINE DEDENT NthInorder ( node . right , n ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 20 ) NEW_LINE root . right = newNode ( 30 ) NEW_LINE root . left . left = newNode ( 40 ) NEW_LINE root . left . right = newNode ( 50 ) NEW_LINE n = 4 NEW_LINE NthInorder ( root , n ) NEW_LINE DEDENT
Minimum initial vertices to traverse whole matrix with given conditions | Python3 program to find minimum initial vertices to reach whole matrix ; ( n , m ) is current source cell from which we need to do DFS . N and M are total no . of rows and columns . ; Marking the vertex as visited ; If below neighbor is valid and has value less than or equal to current cell 's value ; If right neighbor is valid and has value less than or equal to current cell 's value ; If above neighbor is valid and has value less than or equal to current cell 's value ; If left neighbor is valid and has value less than or equal to current cell 's value ; Storing the cell value and cell indices in a vector . ; Sorting the newly created array according to cell values ; Create a visited array for DFS and initialize it as false . ; Applying dfs for each vertex with highest value ; If the given vertex is not visited then include it in the set ; Driver code
MAX = 100 NEW_LINE def dfs ( n , m , visit , adj , N , M ) : NEW_LINE INDENT visit [ n ] [ m ] = 1 NEW_LINE if ( n + 1 < N and adj [ n ] [ m ] >= adj [ n + 1 ] [ m ] and not visit [ n + 1 ] [ m ] ) : NEW_LINE INDENT dfs ( n + 1 , m , visit , adj , N , M ) NEW_LINE DEDENT if ( m + 1 < M and adj [ n ] [ m ] >= adj [ n ] [ m + 1 ] and not visit [ n ] [ m + 1 ] ) : NEW_LINE INDENT dfs ( n , m + 1 , visit , adj , N , M ) NEW_LINE DEDENT if ( n - 1 >= 0 and adj [ n ] [ m ] >= adj [ n - 1 ] [ m ] and not visit [ n - 1 ] [ m ] ) : NEW_LINE INDENT dfs ( n - 1 , m , visit , adj , N , M ) NEW_LINE DEDENT if ( m - 1 >= 0 and adj [ n ] [ m ] >= adj [ n ] [ m - 1 ] and not visit [ n ] [ m - 1 ] ) : NEW_LINE INDENT dfs ( n , m - 1 , visit , adj , N , M ) NEW_LINE DEDENT DEDENT def printMinSources ( adj , N , M ) : NEW_LINE INDENT x = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT x . append ( [ adj [ i ] [ j ] , [ i , j ] ] ) NEW_LINE DEDENT DEDENT x . sort ( ) NEW_LINE visit = [ [ False for i in range ( MAX ) ] for i in range ( N ) ] NEW_LINE for i in range ( len ( x ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( not visit [ x [ i ] [ 1 ] [ 0 ] ] [ x [ i ] [ 1 ] [ 1 ] ] ) : NEW_LINE INDENT print ( ' { } ▁ { } ' . format ( x [ i ] [ 1 ] [ 0 ] , x [ i ] [ 1 ] [ 1 ] ) ) NEW_LINE dfs ( x [ i ] [ 1 ] [ 0 ] , x [ i ] [ 1 ] [ 1 ] , visit , adj , N , M ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE M = 2 NEW_LINE adj = [ [ 3 , 3 ] , [ 1 , 1 ] ] NEW_LINE printMinSources ( adj , N , M ) NEW_LINE DEDENT
Shortest path to reach one prime to other by changing single digit at a time | Python3 program to reach a prime number from another by changing single digits and using only prime numbers . ; Finding all 4 digit prime numbers ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Forming a vector of prime numbers ; in1 and in2 are two vertices of graph which are actually indexes in pset [ ] ; Returns true if num1 and num2 differ by single digit . ; To compare the digits ; If the numbers differ only by a single digit return true else false ; Generate all 4 digit ; Create a graph where node numbers are indexes in pset [ ] and there is an edge between two nodes only if they differ by single digit . ; Since graph nodes represent indexes of numbers in pset [ ] , we find indexes of num1 and num2 . ; Driver code
import queue NEW_LINE class Graph : NEW_LINE INDENT def __init__ ( self , V ) : NEW_LINE INDENT self . V = V ; NEW_LINE self . l = [ [ ] for i in range ( V ) ] NEW_LINE DEDENT def addedge ( self , V1 , V2 ) : NEW_LINE INDENT self . l [ V1 ] . append ( V2 ) ; NEW_LINE self . l [ V2 ] . append ( V1 ) ; NEW_LINE DEDENT DEDENT def SieveOfEratosthenes ( v ) : NEW_LINE INDENT n = 9999 NEW_LINE prime = [ True ] * ( n + 1 ) NEW_LINE p = 2 NEW_LINE while p * p <= n : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 1000 , n + 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT v . append ( p ) NEW_LINE DEDENT DEDENT def bfs ( self , in1 , in2 ) : NEW_LINE INDENT visited = [ 0 ] * self . V NEW_LINE que = queue . Queue ( ) NEW_LINE visited [ in1 ] = 1 NEW_LINE que . put ( in1 ) NEW_LINE while ( not que . empty ( ) ) : NEW_LINE INDENT p = que . queue [ 0 ] NEW_LINE que . get ( ) NEW_LINE i = 0 NEW_LINE while i < len ( self . l [ p ] ) : NEW_LINE INDENT if ( not visited [ self . l [ p ] [ i ] ] ) : NEW_LINE INDENT visited [ self . l [ p ] [ i ] ] = visited [ p ] + 1 NEW_LINE que . put ( self . l [ p ] [ i ] ) NEW_LINE DEDENT if ( self . l [ p ] [ i ] == in2 ) : NEW_LINE INDENT return visited [ self . l [ p ] [ i ] ] - 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def compare ( num1 , num2 ) : NEW_LINE INDENT s1 = str ( num1 ) NEW_LINE s2 = str ( num2 ) NEW_LINE c = 0 NEW_LINE if ( s1 [ 0 ] != s2 [ 0 ] ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( s1 [ 1 ] != s2 [ 1 ] ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( s1 [ 2 ] != s2 [ 2 ] ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( s1 [ 3 ] != s2 [ 3 ] ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT return ( c == 1 ) NEW_LINE DEDENT def shortestPath ( num1 , num2 ) : NEW_LINE INDENT pset = [ ] NEW_LINE SieveOfEratosthenes ( pset ) NEW_LINE g = Graph ( len ( pset ) ) NEW_LINE for i in range ( len ( pset ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( pset ) ) : NEW_LINE INDENT if ( compare ( pset [ i ] , pset [ j ] ) ) : NEW_LINE INDENT g . addedge ( i , j ) NEW_LINE DEDENT DEDENT DEDENT in1 , in2 = None , None NEW_LINE for j in range ( len ( pset ) ) : NEW_LINE INDENT if ( pset [ j ] == num1 ) : NEW_LINE INDENT in1 = j NEW_LINE DEDENT DEDENT for j in range ( len ( pset ) ) : NEW_LINE INDENT if ( pset [ j ] == num2 ) : NEW_LINE INDENT in2 = j NEW_LINE DEDENT DEDENT return g . bfs ( in1 , in2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num1 = 1033 NEW_LINE num2 = 8179 NEW_LINE print ( shortestPath ( num1 , num2 ) ) NEW_LINE DEDENT
Level of Each node in a Tree from source node ( using BFS ) | Python3 Program to determine level of each node and print level ; function to determine level of each node starting from x using BFS ; array to store level of each node ; create a queue ; enqueue element x ; initialize level of source node to 0 ; marked it as visited ; do until queue is empty ; get the first element of queue ; traverse neighbors of node x ; b is neighbor of node x ; if b is not marked already ; enqueue b in queue ; level of b is level of x + 1 ; mark b ; display all nodes and their levels ; Driver Code ; adjacency graph for tree ; call levels function with source as 0
import queue NEW_LINE def printLevels ( graph , V , x ) : NEW_LINE INDENT level = [ None ] * V NEW_LINE marked = [ False ] * V NEW_LINE que = queue . Queue ( ) NEW_LINE que . put ( x ) NEW_LINE level [ x ] = 0 NEW_LINE marked [ x ] = True NEW_LINE while ( not que . empty ( ) ) : NEW_LINE INDENT x = que . get ( ) NEW_LINE for i in range ( len ( graph [ x ] ) ) : NEW_LINE INDENT b = graph [ x ] [ i ] NEW_LINE if ( not marked [ b ] ) : NEW_LINE INDENT que . put ( b ) NEW_LINE level [ b ] = level [ x ] + 1 NEW_LINE marked [ b ] = True NEW_LINE DEDENT DEDENT DEDENT print ( " Nodes " , " ▁ " , " Level " ) NEW_LINE for i in range ( V ) : NEW_LINE INDENT print ( " ▁ " , i , " ▁ - - > ▁ " , level [ i ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = 8 NEW_LINE graph = [ [ ] for i in range ( V ) ] NEW_LINE graph [ 0 ] . append ( 1 ) NEW_LINE graph [ 0 ] . append ( 2 ) NEW_LINE graph [ 1 ] . append ( 3 ) NEW_LINE graph [ 1 ] . append ( 4 ) NEW_LINE graph [ 1 ] . append ( 5 ) NEW_LINE graph [ 2 ] . append ( 5 ) NEW_LINE graph [ 2 ] . append ( 6 ) NEW_LINE graph [ 6 ] . append ( 7 ) NEW_LINE printLevels ( graph , V , 0 ) NEW_LINE DEDENT
Construct binary palindrome by repeated appending and trimming | function to apply DFS ; set the parent marked ; if the node has not been visited set it and its children marked ; link which digits must be equal ; connect the two indices ; set everything connected to first character as 1 ; Driver Code
def dfs ( parent , ans , connectchars ) : NEW_LINE INDENT ans [ parent ] = 1 NEW_LINE for i in range ( len ( connectchars [ parent ] ) ) : NEW_LINE INDENT if ( not ans [ connectchars [ parent ] [ i ] ] ) : NEW_LINE INDENT dfs ( connectchars [ parent ] [ i ] , ans , connectchars ) NEW_LINE DEDENT DEDENT DEDENT def printBinaryPalindrome ( n , k ) : NEW_LINE INDENT arr = [ 0 ] * n NEW_LINE ans = [ 0 ] * n NEW_LINE connectchars = [ [ ] for i in range ( k ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = i % k NEW_LINE DEDENT for i in range ( int ( n / 2 ) ) : NEW_LINE INDENT connectchars [ arr [ i ] ] . append ( arr [ n - i - 1 ] ) NEW_LINE connectchars [ arr [ n - i - 1 ] ] . append ( arr [ i ] ) NEW_LINE DEDENT dfs ( 0 , ans , connectchars ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( ans [ arr [ i ] ] , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE k = 4 NEW_LINE printBinaryPalindrome ( n , k ) NEW_LINE DEDENT
Find n | A Binary Tree Node Utility function to create a new tree node ; function to find the N - th node in the postorder traversal of a given binary tree ; left recursion ; right recursion ; prints the n - th node of preorder traversal ; Driver Code ; prints n - th node found
class createNode : 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 flag = [ 0 ] NEW_LINE def NthPostordernode ( root , N ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( flag [ 0 ] <= N [ 0 ] ) : NEW_LINE INDENT NthPostordernode ( root . left , N ) NEW_LINE NthPostordernode ( root . right , N ) NEW_LINE flag [ 0 ] += 1 NEW_LINE if ( flag [ 0 ] == N [ 0 ] ) : NEW_LINE INDENT print ( root . data ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = createNode ( 25 ) NEW_LINE root . left = createNode ( 20 ) NEW_LINE root . right = createNode ( 30 ) NEW_LINE root . left . left = createNode ( 18 ) NEW_LINE root . left . right = createNode ( 22 ) NEW_LINE root . right . left = createNode ( 24 ) NEW_LINE root . right . right = createNode ( 32 ) NEW_LINE N = [ 6 ] NEW_LINE NthPostordernode ( root , N ) NEW_LINE DEDENT
Path in a Rectangle with Circles | Python3 program to find out path in a rectangle containing circles . ; Function to find out if there is any possible path or not . ; Take an array of m * n size and initialize each element to 0. ; Now using Pythagorean theorem find if a cell touches or within any circle or not . ; If the starting cell comes within any circle return false . ; Now use BFS to find if there is any possible path or not . Initialize the queue which holds the discovered cells whose neighbors are not discovered yet . ; Discover cells until queue is not empty ; Discover the eight adjacent nodes . check top - left cell ; check top cell ; check top - right cell ; check left cell ; check right cell ; check bottom - left cell ; check bottom cell ; check bottom - right cell ; Now if the end cell ( i . e . bottom right cell ) is 1 ( reachable ) then we will send true . ; Driver Code ; Test case 1 ; Function call ; Test case 2 ; Function call
import math NEW_LINE import queue NEW_LINE def isPossible ( m , n , k , r , X , Y ) : NEW_LINE INDENT rect = [ [ 0 ] * n for i in range ( m ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT for p in range ( k ) : NEW_LINE INDENT if ( math . sqrt ( ( pow ( ( X [ p ] - 1 - i ) , 2 ) + pow ( ( Y [ p ] - 1 - j ) , 2 ) ) ) <= r ) : NEW_LINE INDENT rect [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( rect [ 0 ] [ 0 ] == - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT qu = queue . Queue ( ) NEW_LINE rect [ 0 ] [ 0 ] = 1 NEW_LINE qu . put ( [ 0 , 0 ] ) NEW_LINE while ( not qu . empty ( ) ) : NEW_LINE INDENT arr = qu . get ( ) NEW_LINE elex = arr [ 0 ] NEW_LINE eley = arr [ 1 ] NEW_LINE if ( ( elex > 0 ) and ( eley > 0 ) and ( rect [ elex - 1 ] [ eley - 1 ] == 0 ) ) : NEW_LINE INDENT rect [ elex - 1 ] [ eley - 1 ] = 1 NEW_LINE v = [ elex - 1 , eley - 1 ] NEW_LINE qu . put ( v ) NEW_LINE DEDENT if ( ( elex > 0 ) and ( rect [ elex - 1 ] [ eley ] == 0 ) ) : NEW_LINE INDENT rect [ elex - 1 ] [ eley ] = 1 NEW_LINE v = [ elex - 1 , eley ] NEW_LINE qu . put ( v ) NEW_LINE DEDENT if ( ( elex > 0 ) and ( eley < n - 1 ) and ( rect [ elex - 1 ] [ eley + 1 ] == 0 ) ) : NEW_LINE INDENT rect [ elex - 1 ] [ eley + 1 ] = 1 NEW_LINE v = [ elex - 1 , eley + 1 ] NEW_LINE qu . put ( v ) NEW_LINE DEDENT if ( ( eley > 0 ) and ( rect [ elex ] [ eley - 1 ] == 0 ) ) : NEW_LINE INDENT rect [ elex ] [ eley - 1 ] = 1 NEW_LINE v = [ elex , eley - 1 ] NEW_LINE qu . put ( v ) NEW_LINE DEDENT if ( ( eley < n - 1 ) and ( rect [ elex ] [ eley + 1 ] == 0 ) ) : NEW_LINE INDENT rect [ elex ] [ eley + 1 ] = 1 NEW_LINE v = [ elex , eley + 1 ] NEW_LINE qu . put ( v ) NEW_LINE DEDENT if ( ( elex < m - 1 ) and ( eley > 0 ) and ( rect [ elex + 1 ] [ eley - 1 ] == 0 ) ) : NEW_LINE INDENT rect [ elex + 1 ] [ eley - 1 ] = 1 NEW_LINE v = [ elex + 1 , eley - 1 ] NEW_LINE qu . put ( v ) NEW_LINE DEDENT if ( ( elex < m - 1 ) and ( rect [ elex + 1 ] [ eley ] == 0 ) ) : NEW_LINE INDENT rect [ elex + 1 ] [ eley ] = 1 NEW_LINE v = [ elex + 1 , eley ] NEW_LINE qu . put ( v ) NEW_LINE DEDENT if ( ( elex < m - 1 ) and ( eley < n - 1 ) and ( rect [ elex + 1 ] [ eley + 1 ] == 0 ) ) : NEW_LINE INDENT rect [ elex + 1 ] [ eley + 1 ] = 1 NEW_LINE v = [ elex + 1 , eley + 1 ] NEW_LINE qu . put ( v ) NEW_LINE DEDENT DEDENT return ( rect [ m - 1 ] [ n - 1 ] == 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m1 = 5 NEW_LINE n1 = 5 NEW_LINE k1 = 2 NEW_LINE r1 = 1 NEW_LINE X1 = [ 1 , 3 ] NEW_LINE Y1 = [ 3 , 3 ] NEW_LINE if ( isPossible ( m1 , n1 , k1 , r1 , X1 , Y1 ) ) : NEW_LINE INDENT print ( " Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE DEDENT m2 = 5 NEW_LINE n2 = 5 NEW_LINE k2 = 2 NEW_LINE r2 = 1 NEW_LINE X2 = [ 1 , 1 ] NEW_LINE Y2 = [ 2 , 3 ] NEW_LINE if ( isPossible ( m2 , n2 , k2 , r2 , X2 , Y2 ) ) : NEW_LINE INDENT print ( " Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE DEDENT DEDENT
DFS for a n | DFS on tree ; Printing traversed node ; Traversing adjacent edges ; Not traversing the parent node ; Driver Code ; Number of nodes ; Adjacency List ; Designing the tree ; Function call
def dfs ( List , node , arrival ) : NEW_LINE INDENT print ( node ) NEW_LINE for i in range ( len ( List [ node ] ) ) : NEW_LINE INDENT if ( List [ node ] [ i ] != arrival ) : NEW_LINE INDENT dfs ( List , List [ node ] [ i ] , node ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT nodes = 5 NEW_LINE List = [ [ ] for i in range ( 10000 ) ] NEW_LINE List [ 1 ] . append ( 2 ) NEW_LINE List [ 2 ] . append ( 1 ) NEW_LINE List [ 1 ] . append ( 3 ) NEW_LINE List [ 3 ] . append ( 1 ) NEW_LINE List [ 2 ] . append ( 4 ) NEW_LINE List [ 4 ] . append ( 2 ) NEW_LINE List [ 3 ] . append ( 5 ) NEW_LINE List [ 5 ] . append ( 3 ) NEW_LINE dfs ( List , 1 , 0 ) NEW_LINE DEDENT
Maximum number of edges to be added to a tree so that it stays a Bipartite graph | To store counts of nodes with two colors ; Increment count of nodes with current color ; Traversing adjacent nodes ; Not recurring for the parent node ; Finds maximum number of edges that can be added without violating Bipartite property . ; Do a DFS to count number of nodes of each color ; Driver code To store counts of nodes with two colors
def dfs ( adj , node , parent , color ) : NEW_LINE INDENT count_color [ color ] += 1 NEW_LINE for i in range ( len ( adj [ node ] ) ) : NEW_LINE INDENT if ( adj [ node ] [ i ] != parent ) : NEW_LINE INDENT dfs ( adj , adj [ node ] [ i ] , node , not color ) NEW_LINE DEDENT DEDENT DEDENT def findMaxEdges ( adj , n ) : NEW_LINE INDENT dfs ( adj , 1 , 0 , 0 ) NEW_LINE return ( count_color [ 0 ] * count_color [ 1 ] - ( n - 1 ) ) NEW_LINE DEDENT count_color = [ 0 , 0 ] NEW_LINE n = 5 NEW_LINE adj = [ [ ] for i in range ( n + 1 ) ] NEW_LINE adj [ 1 ] . append ( 2 ) NEW_LINE adj [ 1 ] . append ( 3 ) NEW_LINE adj [ 2 ] . append ( 4 ) NEW_LINE adj [ 3 ] . append ( 5 ) NEW_LINE print ( findMaxEdges ( adj , n ) ) NEW_LINE
Min steps to empty an Array by removing a pair each time with sum at most K | Function to count minimum steps ; Function to sort the array ; Run while loop ; Condition to check whether sum exceed the target or not ; Increment the step by 1 ; Return minimum steps ; Given array arr [ ] ; Given target value ; Function call
def countMinSteps ( arr , target , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE minimumSteps = 0 NEW_LINE i , j = 0 , n - 1 NEW_LINE while i <= j : NEW_LINE INDENT if arr [ i ] + arr [ j ] <= target : NEW_LINE INDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT minimumSteps += 1 NEW_LINE DEDENT return minimumSteps NEW_LINE DEDENT arr = [ 4 , 6 , 2 , 9 , 6 , 5 , 8 , 10 ] NEW_LINE target = 11 NEW_LINE size = len ( arr ) NEW_LINE print ( countMinSteps ( arr , target , size ) ) NEW_LINE
Sort the strings based on the numbers of matchsticks required to represent them | Stick [ ] stores the count of sticks required to represent the alphabets ; Number [ ] stores the count of sticks required to represent the numerals ; Function that return the count of sticks required to represent the given string str ; Loop to iterate over every character of the string ; Add the count of sticks required to represent the current character ; Function to sort the array according to the number of sticks required to represent it ; Vector to store the number of sticks required with respective strings ; Inserting number of sticks with respective strings ; Sort the vector ; Print the sorted vector ; Driver Code
sticks = [ 6 , 7 , 4 , 6 , 5 , 4 , 6 , 5 , 2 , 4 , 4 , 3 , 6 , 6 , 6 , 5 , 7 , 6 , 5 , 3 , 5 , 4 , 6 , 4 , 3 , 4 ] NEW_LINE number = [ 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 ] NEW_LINE def countSticks ( st ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( len ( st ) ) : NEW_LINE INDENT ch = st [ i ] NEW_LINE if ( ch >= ' A ' and ch <= ' Z ' ) : NEW_LINE INDENT cnt += sticks [ ord ( ch ) - ord ( ' A ' ) ] NEW_LINE DEDENT else : NEW_LINE INDENT cnt += number [ ord ( ch ) - ord ( '0' ) ] NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT vp = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT vp . append ( [ countSticks ( 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 = [ " GEEKS " , " FOR " , " GEEKSFORGEEKS " ] NEW_LINE n = len ( arr ) NEW_LINE sortArr ( arr , n ) NEW_LINE DEDENT
Count number of pairs with positive sum in an array | Returns number of pairs in arr [ 0. . n - 1 ] with positive sum ; Initialize result ; Consider all possible pairs and check their sums ; If arr [ i ] & arr [ j ] form valid pair ; Driver 's Code ; Function call to find the count of pairs
def CountPairs ( arr , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] > 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 7 , - 1 , 3 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( CountPairs ( arr , n ) ) ; NEW_LINE DEDENT
Find if there exists a direction for ranges such that no two range intersect | Python implementation of the approach ; Function that returns true if the assignment of directions is possible ; Structure to hold details of each interval ; Sort the intervals based on velocity ; Test the condition for all intervals with same velocity ; If for any velocity , 3 or more intervals share a common poreturn false ; Driver code
MAX = 100001 NEW_LINE def isPossible ( rangee , N ) : NEW_LINE INDENT test = [ [ 0 for x in range ( 3 ) ] for x in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT test [ i ] [ 0 ] = rangee [ i ] [ 0 ] NEW_LINE test [ i ] [ 1 ] = rangee [ i ] [ 1 ] NEW_LINE test [ i ] [ 2 ] = rangee [ i ] [ 2 ] NEW_LINE DEDENT test . sort ( key = lambda x : x [ 2 ] ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT count = [ 0 ] * MAX NEW_LINE current_velocity = test [ i ] [ 2 ] NEW_LINE j = i NEW_LINE while ( j < N and test [ j ] [ 2 ] == current_velocity ) : NEW_LINE INDENT for k in range ( test [ j ] [ 0 ] , test [ j ] [ 1 ] + 1 ) : NEW_LINE INDENT count [ k ] += 1 NEW_LINE if ( count [ k ] >= 3 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT j += 1 NEW_LINE DEDENT i = j - 1 NEW_LINE DEDENT return True NEW_LINE DEDENT rangee = [ [ 1 , 2 , 3 ] , [ 2 , 5 , 1 ] , [ 3 , 10 , 1 ] , [ 4 , 4 , 1 ] , [ 5 , 7 , 10 ] ] NEW_LINE n = len ( rangee ) NEW_LINE if ( isPossible ( rangee , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
a | Function to return the modified string ; To store the previous character ; To store the starting indices of all the groups ; Starting index of the first group ; If the current character and the previous character differ ; Push the starting index of the new group ; The current character now becomes previous ; Sort the first group ; Sort all the remaining groups ; print ( ''.join(st)) ; Return the modified string ; Driver code
def get_string ( st , n ) : NEW_LINE INDENT prev = st [ 0 ] NEW_LINE result = [ ] NEW_LINE result . append ( 0 ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( st [ i ] . isdigit ( ) != prev . isdigit ( ) ) : NEW_LINE INDENT result . append ( i ) NEW_LINE DEDENT prev = st [ i ] NEW_LINE DEDENT st = list ( st ) NEW_LINE st [ : result [ 0 ] ] . sort ( ) NEW_LINE p = st . copy ( ) NEW_LINE for i in range ( len ( result ) - 1 ) : NEW_LINE INDENT p [ result [ i ] : result [ i + 1 ] ] = sorted ( st [ result [ i ] : result [ i + 1 ] ] ) NEW_LINE DEDENT p [ len ( p ) - 2 : ] = sorted ( st [ result [ - 1 ] : ] ) NEW_LINE return ' ' . join ( p ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "121geeks21" NEW_LINE n = len ( st ) NEW_LINE print ( get_string ( st , n ) ) NEW_LINE DEDENT
Find the kth smallest number with sum of digits as m | Python3 implementation of the approach ; Recursively moving to add all the numbers upto a limit with sum of digits as m ; Max nber of digits allowed in a nber for this implementation ; Function to return the kth number with sum of digits as m ; The kth smallest number is found ; Driver code
N = 2005 NEW_LINE ans = dict ( ) NEW_LINE def dfs ( n , left , ct ) : NEW_LINE INDENT if ( ct >= 15 ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( left == 0 ) : NEW_LINE INDENT ans [ n ] = 1 NEW_LINE DEDENT for i in range ( min ( left , 9 ) + 1 ) : NEW_LINE INDENT dfs ( n * 10 + i , left - i , ct + 1 ) NEW_LINE DEDENT DEDENT def getKthNum ( m , k ) : NEW_LINE INDENT dfs ( 0 , m , 0 ) NEW_LINE c = 0 NEW_LINE for it in sorted ( ans . keys ( ) ) : NEW_LINE INDENT c += 1 NEW_LINE if ( c == k ) : NEW_LINE INDENT return it NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT m = 5 NEW_LINE k = 3 NEW_LINE print ( getKthNum ( m , k ) ) NEW_LINE
Remove minimum elements from the array such that 2 * min becomes more than max | Python3 program to remove minimum elements from the array such that 2 * min becomes more than max ; Function to remove minimum elements from the array such that 2 * min becomes more than max ; Sort the array ; To store the required answer ; Traverse from left to right ; Update the answer ; Return the required answer ; Driver code ; Function call
from bisect import bisect_left as upper_bound NEW_LINE def Removal ( v , n ) : NEW_LINE INDENT v = sorted ( v ) NEW_LINE ans = 10 ** 9 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT j = upper_bound ( v , ( 2 * ( a [ i ] ) ) ) NEW_LINE ans = min ( ans , n - ( j - i - 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ 4 , 5 , 100 , 9 , 10 , 11 , 12 , 15 , 200 ] NEW_LINE n = len ( a ) NEW_LINE print ( Removal ( a , n ) ) NEW_LINE
Sort the Queue using Recursion | defining a class Queue ; Function to push element in last by popping from front until size becomes 0 ; Base condition ; pop front element and push this last in a queue ; Recursive call for pushing element ; Function to push an element in the queue while maintaining the sorted order ; Base condition ; If current element is less than the element at the front ; Call stack with front of queue ; Recursive call for inserting a front element of the queue to the last ; Push front element into last in a queue ; Recursive call for pushing element in a queue ; Function to sort the given queue using recursion ; Return if queue is empty ; Get the front element which will be stored in this variable throughout the recursion stack ; Recursive call ; Push the current element into the queue according to the sorting order ; Driver code ; Data is inserted into Queue using put ( ) Data is inserted at the end ; Sort the queue ; Print the elements of the queue after sorting
class Queue : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . queue = [ ] NEW_LINE DEDENT def put ( self , item ) : NEW_LINE INDENT self . queue . append ( item ) NEW_LINE DEDENT def get ( self ) : NEW_LINE INDENT if len ( self . queue ) < 1 : NEW_LINE INDENT return None NEW_LINE DEDENT return self . queue . pop ( 0 ) NEW_LINE DEDENT def front ( self ) : NEW_LINE INDENT return self . queue [ 0 ] NEW_LINE DEDENT def size ( self ) : NEW_LINE INDENT return len ( self . queue ) NEW_LINE DEDENT def empty ( self ) : NEW_LINE INDENT return not ( len ( self . queue ) ) NEW_LINE DEDENT DEDENT def FrontToLast ( q , qsize ) : NEW_LINE INDENT if qsize <= 0 : NEW_LINE INDENT return NEW_LINE DEDENT q . put ( q . get ( ) ) NEW_LINE FrontToLast ( q , qsize - 1 ) NEW_LINE DEDENT def pushInQueue ( q , temp , qsize ) : NEW_LINE INDENT if q . empty ( ) or qsize == 0 : NEW_LINE INDENT q . put ( temp ) NEW_LINE return NEW_LINE DEDENT elif temp <= q . front ( ) : NEW_LINE INDENT q . put ( temp ) NEW_LINE FrontToLast ( q , qsize ) NEW_LINE DEDENT else : NEW_LINE INDENT q . put ( q . get ( ) ) NEW_LINE pushInQueue ( q , temp , qsize - 1 ) NEW_LINE DEDENT DEDENT def sortQueue ( q ) : NEW_LINE INDENT if q . empty ( ) : NEW_LINE INDENT return NEW_LINE DEDENT temp = q . get ( ) NEW_LINE sortQueue ( q ) NEW_LINE pushInQueue ( q , temp , q . size ( ) ) NEW_LINE DEDENT qu = Queue ( ) NEW_LINE qu . put ( 10 ) NEW_LINE qu . put ( 7 ) NEW_LINE qu . put ( 16 ) NEW_LINE qu . put ( 9 ) NEW_LINE qu . put ( 20 ) NEW_LINE qu . put ( 5 ) NEW_LINE sortQueue ( qu ) NEW_LINE while not qu . empty ( ) : NEW_LINE INDENT print ( qu . get ( ) , end = ' ▁ ' ) NEW_LINE DEDENT
Sort the character array based on ASCII % N | This function takes last element as pivot , places the pivot element at its correct position in sorted array , and places all smaller ( smaller than pivot ) to left of pivot and all greater elements to right of pivot ; pivot ; Index of smaller element ; If current element is smaller than or equal to pivot Instead of values , ASCII % m values are compared ; Increment index of smaller element ; swap ; The main function that implements QuickSort arr [ ] -- > Array to be sorted , low -- > Starting index , high -- > Ending index ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition ; Function to print the given array ; Driver code ; Sort the given array ; Print the sorted array
def partition ( arr , low , high , mod ) : NEW_LINE INDENT pivot = ord ( arr [ high ] ) ; NEW_LINE i = ( low - 1 ) ; NEW_LINE piv = pivot % mod ; NEW_LINE for j in range ( low , high ) : NEW_LINE INDENT a = ord ( arr [ j ] ) % mod ; NEW_LINE if ( a <= piv ) : NEW_LINE INDENT i += 1 ; NEW_LINE arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE DEDENT DEDENT arr [ i + 1 ] , arr [ high ] = arr [ high ] , arr [ i + 1 ] NEW_LINE return ( i + 1 ) ; NEW_LINE DEDENT def quickSort ( arr , low , high , mod ) : NEW_LINE INDENT if ( low < high ) : NEW_LINE INDENT pi = partition ( arr , low , high , mod ) ; NEW_LINE quickSort ( arr , low , pi - 1 , mod ) ; NEW_LINE quickSort ( arr , pi + 1 , high , mod ) ; NEW_LINE return arr NEW_LINE DEDENT DEDENT def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( 0 , size ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ ' g ' , ' e ' , ' e ' , ' k ' , ' s ' ] ; NEW_LINE n = len ( arr ) ; NEW_LINE mod = 8 ; NEW_LINE arr = quickSort ( arr , 0 , n - 1 , mod ) ; NEW_LINE printArray ( arr , n ) ; NEW_LINE DEDENT
Iterative selection sort for linked list | Linked List Node ; Function to sort a linked list using selection sort algorithm by swapping the next pointers ; While b is not the last node ; While d is pointing to a valid node ; If d appears immediately after b ; Case 1 : b is the head of the linked list ; Move d before b ; Swap b and d pointers ; Update the head ; Skip to the next element as it is already in order ; Case 2 : b is not the head of the linked list ; Move d before b ; Swap b and d pointers ; Skip to the next element as it is already in order ; If b and d have some non - zero number of nodes in between them ; Case 3 : b is the head of the linked list ; Swap b . next and d . next ; Swap b and d pointers ; Skip to the next element as it is already in order ; Update the head ; Case 4 : b is not the head of the linked list ; Swap b . next and d . next ; Swap b and d pointers ; Skip to the next element as it is already in order ; Update c and skip to the next element as it is already in order ; Function to print the list ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . data = val NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def selectionSort ( head ) : NEW_LINE INDENT a = b = head NEW_LINE while b . next : NEW_LINE INDENT c = d = b . next NEW_LINE while d : NEW_LINE INDENT if b . data > d . data : NEW_LINE INDENT if b . next == d : NEW_LINE INDENT if b == head : NEW_LINE INDENT b . next = d . next NEW_LINE d . next = b NEW_LINE b , d = d , b NEW_LINE c = d NEW_LINE head = b NEW_LINE d = d . next NEW_LINE DEDENT else : NEW_LINE INDENT b . next = d . next NEW_LINE d . next = b NEW_LINE a . next = d NEW_LINE b , d = d , b NEW_LINE c = d NEW_LINE d = d . next NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if b == head : NEW_LINE INDENT r = b . next NEW_LINE b . next = d . next NEW_LINE d . next = r NEW_LINE c . next = b NEW_LINE b , d = d , b NEW_LINE c = d NEW_LINE d = d . next NEW_LINE head = b NEW_LINE DEDENT else : NEW_LINE INDENT r = b . next NEW_LINE b . next = d . next NEW_LINE d . next = r NEW_LINE c . next = b NEW_LINE a . next = d NEW_LINE b , d = d , b NEW_LINE c = d NEW_LINE d = d . next NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT c = d NEW_LINE d = d . next NEW_LINE DEDENT DEDENT a = b NEW_LINE b = b . next NEW_LINE DEDENT return head NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT while head : NEW_LINE INDENT print ( head . data , end = " ▁ " ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT head = Node ( 5 ) NEW_LINE head . next = Node ( 4 ) NEW_LINE head . next . next = Node ( 3 ) NEW_LINE head = selectionSort ( head ) NEW_LINE printList ( head ) NEW_LINE DEDENT
Find original numbers from gcd ( ) every pair | Python 3 implementation of the approach ; Utility function to print the contents of an array ; Function to find the required numbers ; Sort array in decreasing order ; Count frequency of each element ; Size of the resultant array ; Store the highest element in the resultant array ; Decrement the frequency of that element ; Compute GCD ; Decrement GCD value by 2 ; ; Driver code
from math import sqrt , gcd NEW_LINE def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def findNumbers ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE freq = [ 0 for i in range ( arr [ 0 ] + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT size = int ( sqrt ( n ) ) NEW_LINE brr = [ 0 for i in range ( len ( arr ) ) ] NEW_LINE l = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( freq [ arr [ i ] ] > 0 ) : NEW_LINE INDENT brr [ l ] = arr [ i ] NEW_LINE freq [ brr [ l ] ] -= 1 NEW_LINE l += 1 NEW_LINE for j in range ( l ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT x = gcd ( arr [ i ] , brr [ j ] ) NEW_LINE freq [ x ] -= 2 NEW_LINE DEDENT DEDENT DEDENT DEDENT printArr ( brr , size ) NEW_LINE DEDENT / * reverse array * / NEW_LINE if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 5 , 5 , 5 , 7 , 10 , 12 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE findNumbers ( arr , n ) NEW_LINE DEDENT
Bitwise AND of N binary strings | Python3 implementation of the above approach ; Function to find the bitwise AND of all the binary strings ; To store the largest and the smallest string ' s ▁ size , ▁ We ▁ need ▁ this ▁ to ▁ add ▁ ' 0 's in the resultant string ; Reverse each string Since we need to perform AND operation on bits from Right to Left ; Update the respective length values ; Traverse bits from 0 to smallest string 's size ; If at this bit position , there is a 0 in any of the given strings then AND operation on current bit position will be 0 ; Add resultant bit to result ; Add 0 's to the string. ; Reverse the string Since we started from LEFT to RIGHT ; Return the resultant string ; Driver code
import sys ; NEW_LINE def strBitwiseAND ( arr , n ) : NEW_LINE INDENT res = " " NEW_LINE smallest_size = sys . maxsize ; NEW_LINE largest_size = - ( sys . maxsize - 1 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = arr [ i ] [ : : - 1 ] ; NEW_LINE smallest_size = min ( smallest_size , len ( arr [ i ] ) ) ; NEW_LINE largest_size = max ( largest_size , len ( arr [ i ] ) ) ; NEW_LINE DEDENT for i in range ( smallest_size ) : NEW_LINE INDENT all_ones = True ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ j ] [ i ] == '0' ) : NEW_LINE INDENT all_ones = False ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if all_ones : NEW_LINE INDENT res += '1' ; NEW_LINE DEDENT else : NEW_LINE INDENT res += '0' ; NEW_LINE DEDENT DEDENT for i in range ( largest_size - smallest_size ) : NEW_LINE INDENT res += '0' ; NEW_LINE DEDENT res = res [ : : - 1 ] ; NEW_LINE return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ "101" , "110110" , "111" ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( strBitwiseAND ( arr , n ) ) ; NEW_LINE DEDENT
Print all paths from a given source to a destination using BFS | Python3 program to print all paths of source to destination in given graph ; Utility function for printing the found path in graph ; Utility function to check if current vertex is already present in path ; Utility function for finding paths in graph from source to destination ; Create a queue which stores the paths ; Path vector to store the current path ; If last vertex is the desired destination then print the path ; Traverse to all the nodes connected to current vertex and push new path to queue ; Driver code ; Number of vertices ; Construct a graph ; Function for finding the paths
from typing import List NEW_LINE from collections import deque NEW_LINE def printpath ( path : List [ int ] ) -> None : NEW_LINE INDENT size = len ( path ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT print ( path [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def isNotVisited ( x : int , path : List [ int ] ) -> int : NEW_LINE INDENT size = len ( path ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( path [ i ] == x ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def findpaths ( g : List [ List [ int ] ] , src : int , dst : int , v : int ) -> None : NEW_LINE INDENT q = deque ( ) NEW_LINE path = [ ] NEW_LINE path . append ( src ) NEW_LINE q . append ( path . copy ( ) ) NEW_LINE while q : NEW_LINE INDENT path = q . popleft ( ) NEW_LINE last = path [ len ( path ) - 1 ] NEW_LINE if ( last == dst ) : NEW_LINE INDENT printpath ( path ) NEW_LINE DEDENT for i in range ( len ( g [ last ] ) ) : NEW_LINE INDENT if ( isNotVisited ( g [ last ] [ i ] , path ) ) : NEW_LINE INDENT newpath = path . copy ( ) NEW_LINE newpath . append ( g [ last ] [ i ] ) NEW_LINE q . append ( newpath ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT v = 4 NEW_LINE g = [ [ ] for _ in range ( 4 ) ] NEW_LINE g [ 0 ] . append ( 3 ) NEW_LINE g [ 0 ] . append ( 1 ) NEW_LINE g [ 0 ] . append ( 2 ) NEW_LINE g [ 1 ] . append ( 3 ) NEW_LINE g [ 2 ] . append ( 0 ) NEW_LINE g [ 2 ] . append ( 1 ) NEW_LINE src = 2 NEW_LINE dst = 3 NEW_LINE print ( " path ▁ from ▁ src ▁ { } ▁ to ▁ dst ▁ { } ▁ are " . format ( src , dst ) ) NEW_LINE findpaths ( g , src , dst , v ) NEW_LINE DEDENT
Rearrange Odd and Even values in Alternate Fashion in Ascending Order | Python3 implementation of the above approach ; Sort the array ; v1 = list ( ) to insert even values v2 = list ( ) to insert odd values ; Set flag to true if first element is even ; Start rearranging array ; If first element is even ; Else , first element is Odd ; Print the rearranged array ; Driver code
def AlternateRearrange ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT v1 . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT v2 . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT index = 0 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE flag = False NEW_LINE if ( arr [ 0 ] % 2 == 0 ) : NEW_LINE INDENT flag = True NEW_LINE DEDENT while ( index < n ) : NEW_LINE INDENT if ( flag == True and i < len ( v1 ) ) : NEW_LINE INDENT arr [ index ] = v1 [ i ] NEW_LINE index += 1 NEW_LINE i += 1 NEW_LINE flag = ~ flag NEW_LINE DEDENT elif j < len ( v2 ) : NEW_LINE INDENT arr [ index ] = v2 [ j ] NEW_LINE index += 1 NEW_LINE j += 1 NEW_LINE flag = ~ flag NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 9 , 8 , 13 , 2 , 19 , 14 , 21 , 23 , 25 ] NEW_LINE n = len ( arr ) NEW_LINE AlternateRearrange ( arr , n ) NEW_LINE
Convert given array to Arithmetic Progression by adding an element | Function to return the number to be added ; If difference of the current consecutive elements is different from the common difference ; If number has already been chosen then it 's not possible to add another number ; If the current different is twice the common difference then a number can be added midway from current and previous element ; Number has been chosen ; It 's not possible to maintain the common difference ; Return last element + common difference if no element is chosen and the array is already in AP ; Else return the chosen number ; Driver code
def getNumToAdd ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE d = arr [ 1 ] - arr [ 0 ] NEW_LINE numToAdd = - 1 NEW_LINE numAdded = False NEW_LINE for i in range ( 2 , n , 1 ) : NEW_LINE INDENT diff = arr [ i ] - arr [ i - 1 ] NEW_LINE if ( diff != d ) : NEW_LINE INDENT if ( numAdded ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( diff == 2 * d ) : NEW_LINE INDENT numToAdd = arr [ i ] - d NEW_LINE numAdded = True NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT DEDENT if ( numToAdd == - 1 ) : NEW_LINE INDENT return ( arr [ n - 1 ] + d ) NEW_LINE DEDENT return numToAdd NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 5 , 7 , 11 , 13 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE print ( getNumToAdd ( arr , n ) ) NEW_LINE DEDENT
Minimum Numbers of cells that are connected with the smallest path between 3 given cells | Function to return the minimum cells that are connected via the minimum length path ; Array to store column number of the given cells ; Sort cells in ascending order of row number ; Middle row number ; Set pair to store required cells ; Range of column number ; Store all cells of middle row within column number range ; Final step to store all the column number of 1 st and 3 rd cell upto MidRow ; Driver Code ; vector pair to store X , Y , Z
def Minimum_Cells ( v ) : NEW_LINE INDENT col = [ 0 ] * 3 NEW_LINE for i in range ( 3 ) : NEW_LINE INDENT column_number = v [ i ] [ 1 ] NEW_LINE col [ i ] = column_number NEW_LINE DEDENT col . sort ( ) NEW_LINE v . sort ( ) NEW_LINE MidRow = v [ 1 ] [ 0 ] NEW_LINE s = set ( ) NEW_LINE Maxcol = col [ 2 ] NEW_LINE MinCol = col [ 0 ] NEW_LINE for i in range ( MinCol , int ( Maxcol ) + 1 ) : NEW_LINE INDENT s . add ( ( MidRow , i ) ) NEW_LINE DEDENT for i in range ( 3 ) : NEW_LINE INDENT if ( v [ i ] [ 0 ] == MidRow ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT for j in range ( min ( v [ i ] [ 0 ] , MidRow ) , max ( v [ i ] [ 0 ] , MidRow ) + 1 ) : NEW_LINE INDENT s . add ( ( j , v [ i ] [ 1 ] ) ) ; NEW_LINE DEDENT DEDENT return len ( s ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT v = [ ( 0 , 0 ) , ( 1 , 1 ) , ( 2 , 2 ) ] NEW_LINE print ( Minimum_Cells ( v ) ) NEW_LINE DEDENT
Get maximum items when other items of total cost of an item are free | Function to count the total number of items ; Sort the prices ; Choose the last element ; Initial count of item ; Sum to keep track of the total price of free items ; If total is less than or equal to z then we will add 1 to the answer ;
def items ( n , a ) : NEW_LINE INDENT a . sort ( ) NEW_LINE z = a [ n - 1 ] NEW_LINE x = 1 NEW_LINE s = 0 NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT s += a [ i ] NEW_LINE if ( s <= z ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT / * Driver code * / NEW_LINE n = 5 NEW_LINE a = [ 5 , 3 , 1 , 5 , 6 ] NEW_LINE print ( items ( n , a ) ) NEW_LINE
Sorting array elements with set bits equal to K | Function to sort elements with set bits equal to k ; initialise two vectors ; first vector contains indices of required element ; second vector contains required elements ; sorting the elements in second vector ; replacing the elements with k set bits with the sorted elements ; printing the new sorted array elements ; Driver code
def sortWithSetbits ( arr , n , k ) : NEW_LINE INDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( bin ( arr [ i ] ) . count ( '1' ) == k ) : NEW_LINE INDENT v1 . append ( i ) NEW_LINE v2 . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT v2 . sort ( reverse = False ) NEW_LINE for i in range ( 0 , len ( v1 ) , 1 ) : NEW_LINE INDENT arr [ v1 [ i ] ] = v2 [ i ] NEW_LINE DEDENT for i in range ( 0 , n , 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 14 , 255 , 1 , 7 , 13 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE sortWithSetbits ( arr , n , k ) NEW_LINE DEDENT
Minimum boxes required to carry all gifts | Function to return number of boxes ; Sort the boxes in ascending order ; Try to fit smallest box with current heaviest box ( from right side ) ; Driver code
def numBoxex ( A , n , K ) : NEW_LINE INDENT A . sort ( ) NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE ans = 0 NEW_LINE while i <= j : NEW_LINE INDENT ans += 1 NEW_LINE if A [ i ] + A [ j ] <= K : NEW_LINE INDENT i += 1 NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 2 , 2 , 1 ] NEW_LINE K = 3 NEW_LINE n = len ( A ) NEW_LINE print ( numBoxex ( A , n , K ) ) NEW_LINE DEDENT
Count triplets in a sorted doubly linked list whose product is equal to a given value x | Python3 implementation to count triplets in a sorted doubly linked list whose product is equal to a given value 'x ; structure of node of doubly linked list ; function to count triplets in a sorted doubly linked list whose product is equal to a given value 'x ; unordered_map ' um ' implemented as hash table ; insert the tuple in 'um ; generate all possible pairs ; p_product = product of elements in the current pair ; if ' x / p _ product ' is present in ' um ' and either of the two nodes are not equal to the ' um [ x / p _ product ] ' node ; increment count ; required count of triplets division by 3 as each triplet is counted 3 times ; A utility function to insert a new node at the beginning of doubly linked list ; allocate node ; put in the data ; Driver code ; start with an empty doubly linked list ; insert values in sorted order
' NEW_LINE from math import ceil NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE self . prev = None NEW_LINE DEDENT DEDENT ' NEW_LINE def countTriplets ( head , x ) : NEW_LINE INDENT ptr , ptr1 , ptr2 = None , None , None NEW_LINE count = 0 NEW_LINE um = { } NEW_LINE DEDENT ' NEW_LINE INDENT ptr = head NEW_LINE while ptr != None : NEW_LINE INDENT um [ ptr . data ] = ptr NEW_LINE ptr = ptr . next NEW_LINE DEDENT ptr1 = head NEW_LINE while ptr1 != None : NEW_LINE INDENT ptr2 = ptr1 . next NEW_LINE while ptr2 != None : NEW_LINE INDENT p_product = ( ptr1 . data * ptr2 . data ) NEW_LINE if ( ( x / p_product ) in um and ( x / p_product ) != ptr1 and um [ x / p_product ] != ptr2 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT ptr2 = ptr2 . next NEW_LINE DEDENT ptr1 = ptr1 . next NEW_LINE DEDENT return ( count // 3 ) NEW_LINE DEDENT def insert ( head , data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE temp . data = data NEW_LINE temp . next = temp . prev = None NEW_LINE if ( head == None ) : NEW_LINE INDENT head = temp NEW_LINE DEDENT else : NEW_LINE INDENT temp . next = head NEW_LINE head . prev = temp NEW_LINE head = temp NEW_LINE DEDENT return head NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = insert ( head , 9 ) NEW_LINE head = insert ( head , 8 ) NEW_LINE head = insert ( head , 6 ) NEW_LINE head = insert ( head , 5 ) NEW_LINE head = insert ( head , 4 ) NEW_LINE head = insert ( head , 2 ) NEW_LINE head = insert ( head , 1 ) NEW_LINE x = 8 NEW_LINE print ( " Count ▁ = " , countTriplets ( head , x ) ) NEW_LINE DEDENT
Maximize the profit by selling at | Function to find profit ; Calculating profit for each gadget ; sort the profit array in descending order ; variable to calculate total profit ; check for best M profits ; Driver Code
def solve ( N , M , cp , sp ) : NEW_LINE INDENT profit = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT profit . append ( sp [ i ] - cp [ i ] ) NEW_LINE DEDENT profit . sort ( reverse = True ) NEW_LINE sum = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT if profit [ i ] > 0 : NEW_LINE INDENT sum += profit [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N , M = 5 , 3 NEW_LINE CP = [ 5 , 10 , 35 , 7 , 23 ] NEW_LINE SP = [ 11 , 10 , 0 , 9 , 19 ] NEW_LINE print ( solve ( N , M , CP , SP ) ) NEW_LINE DEDENT
Find the largest number that can be formed with the given digits | Function to generate largest possible number with given digits ; sort the given array in descending order ; generate the number ; Driver code
def findMaxNum ( arr , n ) : NEW_LINE INDENT arr . sort ( rever num = arr [ 0 ] se = True ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT num = num * 10 + arr [ i ] NEW_LINE DEDENT return num NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMaxNum ( arr , n ) ) NEW_LINE DEDENT
Minimum partitions of maximum size 2 and sum limited by given value | Python 3 program to count minimum number of partitions of size 2 and sum smaller than or equal to given key . ; sort the array ; if sum of ith smaller and jth larger element is less than key , then pack both numbers in a set otherwise pack the jth larger number alone in the set ; After ending of loop i will contain minimum number of sets ; Driver Code
def minimumSets ( arr , n , key ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE j = n - 1 NEW_LINE for i in range ( 0 , j + 1 , 1 ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] <= key ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT return i + 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 5 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE key = 5 NEW_LINE print ( minimumSets ( arr , n , key ) ) NEW_LINE DEDENT
Bubble Sort On Doubly Linked List | structure of a node ; Function to insert a node at the beginning of a linked list ; Function to print nodes in a given linked list ; Bubble sort the given linked list ; Checking for empty list ; Driver code ; start with empty linked list ; Create linked list from the array arr [ ] . Created linked list will be 1.11 . 2.56 . 12 ; print list before sorting ; sort the linked list ; print list after sorting
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . prev = None NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def insertAtTheBegin ( start_ref , data ) : NEW_LINE INDENT ptr1 = Node ( data ) NEW_LINE ptr1 . data = data ; NEW_LINE ptr1 . next = start_ref ; NEW_LINE if ( start_ref != None ) : NEW_LINE ( start_ref ) . prev = ptr1 ; NEW_LINE start_ref = ptr1 ; NEW_LINE return start_ref NEW_LINE DEDENT def printList ( start ) : NEW_LINE INDENT temp = start ; NEW_LINE print ( ) NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = ' ▁ ' ) NEW_LINE temp = temp . next ; NEW_LINE DEDENT DEDENT def bubbleSort ( start ) : NEW_LINE INDENT swapped = 0 NEW_LINE lptr = None ; NEW_LINE if ( start == None ) : NEW_LINE INDENT return ; NEW_LINE DEDENT while True : NEW_LINE INDENT swapped = 0 ; NEW_LINE ptr1 = start ; NEW_LINE while ( ptr1 . next != lptr ) : NEW_LINE INDENT if ( ptr1 . data > ptr1 . next . data ) : NEW_LINE INDENT ptr1 . data , ptr1 . next . data = ptr1 . next . data , ptr1 . data NEW_LINE swapped = 1 ; NEW_LINE DEDENT ptr1 = ptr1 . next ; NEW_LINE DEDENT lptr = ptr1 ; NEW_LINE if swapped == 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 56 , 2 , 11 , 1 , 90 ] NEW_LINE start = None ; NEW_LINE for i in range ( 6 ) : NEW_LINE INDENT start = insertAtTheBegin ( start , arr [ i ] ) ; NEW_LINE DEDENT print ( " Linked ▁ list ▁ before ▁ sorting ▁ " , end = ' ' ) ; NEW_LINE printList ( start ) ; NEW_LINE bubbleSort ( start ) ; NEW_LINE print ( " Linked list after sorting " , end = ' ' ) ; NEW_LINE printList ( start ) ; NEW_LINE DEDENT
Substring Sort | Alternative code to sort substrings ; sort the input array ; repeated length should be the same string ; two different strings with the same length input array cannot be sorted ; validate that each string is a substring of the following one ; get first element ; The array is valid and sorted print the strings in order ; Test 1 ; Test 2
def substringSort ( arr , n , maxLen ) : NEW_LINE INDENT count = [ 0 ] * ( maxLen ) NEW_LINE sortedArr = [ " " ] * ( maxLen ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = arr [ i ] NEW_LINE Len = len ( s ) NEW_LINE if ( count [ Len - 1 ] == 0 ) : NEW_LINE INDENT sortedArr [ Len - 1 ] = s NEW_LINE count [ Len - 1 ] = 1 NEW_LINE DEDENT elif ( sortedArr [ Len - 1 ] == s ) : NEW_LINE INDENT count [ Len - 1 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Cannot ▁ be ▁ sorted " ) NEW_LINE return NEW_LINE DEDENT DEDENT index = 0 NEW_LINE while ( count [ index ] == 0 ) : NEW_LINE INDENT index += 1 NEW_LINE DEDENT prev = index NEW_LINE prevString = sortedArr [ prev ] NEW_LINE index += 1 NEW_LINE while index < maxLen : NEW_LINE INDENT if ( count [ index ] != 0 ) : NEW_LINE INDENT current = sortedArr [ index ] NEW_LINE if ( prevString in current ) : NEW_LINE INDENT prev = index NEW_LINE prevString = current NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Cannot ▁ be ▁ sorted " ) NEW_LINE return NEW_LINE DEDENT DEDENT index += 1 NEW_LINE DEDENT for i in range ( maxLen ) : NEW_LINE INDENT s = sortedArr [ i ] NEW_LINE for j in range ( count [ i ] ) : NEW_LINE INDENT print ( s ) NEW_LINE DEDENT DEDENT DEDENT maxLen = 100 NEW_LINE arr1 = [ " d " , " zddsaaz " , " ds " , " ddsaa " , " dds " , " dds " ] NEW_LINE substringSort ( arr1 , len ( arr1 ) , maxLen ) NEW_LINE arr2 = [ " for " , " rof " ] NEW_LINE substringSort ( arr2 , len ( arr2 ) , maxLen ) NEW_LINE
Number of paths from source to destination in a directed acyclic graph | Python3 program for Number of paths from one vertex to another vertex in a Directed Acyclic Graph ; to make graph ; function to add edge in graph ; there is path from a to b . ; function to make topological sorting ; insert all vertices which don 't have any parent. ; using kahn 's algorithm for topological sorting ; insert front element of queue to vector ; go through all it 's childs ; whenever the frequency is zero then add this vertex to queue . ; Function that returns the number of paths ; make topological sorting ; to store required answer . ; answer from destination to destination is 1. ; traverse in reverse order ; Driver code ; here vertices are numbered from 0 to n - 1. ; to count number of vertex which don 't have any parents. ; to add all edges of graph ; Function that returns the number of paths
from collections import deque NEW_LINE MAXN = 1000005 NEW_LINE v = [ [ ] for i in range ( MAXN ) ] NEW_LINE def add_edge ( a , b , fre ) : NEW_LINE INDENT v [ a ] . append ( b ) NEW_LINE fre [ b ] += 1 NEW_LINE DEDENT def topological_sorting ( fre , n ) : NEW_LINE INDENT q = deque ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( not fre [ i ] ) : NEW_LINE INDENT q . append ( i ) NEW_LINE DEDENT DEDENT l = [ ] NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT u = q . popleft ( ) NEW_LINE l . append ( u ) NEW_LINE for i in range ( len ( v [ u ] ) ) : NEW_LINE INDENT fre [ v [ u ] [ i ] ] -= 1 NEW_LINE if ( not fre [ v [ u ] [ i ] ] ) : NEW_LINE INDENT q . append ( v [ u ] [ i ] ) NEW_LINE DEDENT DEDENT DEDENT return l NEW_LINE DEDENT def numberofPaths ( source , destination , n , fre ) : NEW_LINE INDENT s = topological_sorting ( fre , n ) NEW_LINE dp = [ 0 ] * n NEW_LINE dp [ destination ] = 1 NEW_LINE for i in range ( len ( s ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( len ( v [ s [ i ] ] ) ) : NEW_LINE INDENT dp [ s [ i ] ] += dp [ v [ s [ i ] ] [ j ] ] NEW_LINE DEDENT DEDENT return dp NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE source , destination = 0 , 4 NEW_LINE fre = [ 0 ] * n NEW_LINE add_edge ( 0 , 1 , fre ) NEW_LINE add_edge ( 0 , 2 , fre ) NEW_LINE add_edge ( 0 , 3 , fre ) NEW_LINE add_edge ( 0 , 4 , fre ) NEW_LINE add_edge ( 2 , 3 , fre ) NEW_LINE add_edge ( 3 , 4 , fre ) NEW_LINE print ( numberofPaths ( source , destination , n , fre ) ) NEW_LINE DEDENT
Print all the pairs that contains the positive and negative values of an element | Utility binary search ; Function ; Sort the array ; Traverse the array ; For every arr [ i ] < 0 element , do a binary search for arr [ i ] > 0. ; If found , print the pair . ; Driver code
def binary_search ( a , x , lo = 0 , hi = None ) : NEW_LINE INDENT if hi is None : NEW_LINE INDENT hi = len ( a ) NEW_LINE DEDENT while lo < hi : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE midval = a [ mid ] NEW_LINE if midval < x : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT elif midval > x : NEW_LINE INDENT hi = mid NEW_LINE DEDENT else : NEW_LINE INDENT return mid NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def printPairs ( arr , n ) : NEW_LINE INDENT pair_exists = Fals NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT if ( binary_search ( arr , - arr [ i ] ) ) : NEW_LINE INDENT print ( arr [ i ] , " , ▁ " , - arr [ i ] ) NEW_LINE pair_exists = True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( pair_exists == False ) : NEW_LINE INDENT print ( " No ▁ such ▁ pair ▁ exists " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 ] NEW_LINE n = len ( arr ) NEW_LINE printPairs ( arr , n ) NEW_LINE DEDENT
Multiset Equivalence Problem | Python3 program to check if two given multisets are equivalent ; sort the elements of both multisets ; Return true if both multisets are same . ; Driver code
def areSame ( a , b ) : NEW_LINE INDENT a . sort ( ) ; NEW_LINE b . sort ( ) ; NEW_LINE return ( a == b ) a = [ 7 , 7 , 5 ] ; NEW_LINE DEDENT b = [ 7 , 5 , 5 ] ; NEW_LINE if ( areSame ( a , b ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; ; NEW_LINE DEDENT
Minimum number of edges between two vertices of a Graph | Python3 program to find minimum edge between given two vertex of Graph ; function for finding minimum no . of edge using BFS ; visited [ n ] for keeping track of visited node in BFS ; Initialize distances as 0 ; queue to do BFS . ; update distance for i ; function for addition of edge ; Driver Code ; To store adjacency list of graph
import queue NEW_LINE def minEdgeBFS ( edges , u , v , n ) : NEW_LINE INDENT visited = [ 0 ] * n NEW_LINE distance = [ 0 ] * n NEW_LINE Q = queue . Queue ( ) NEW_LINE distance [ u ] = 0 NEW_LINE Q . put ( u ) NEW_LINE visited [ u ] = True NEW_LINE while ( not Q . empty ( ) ) : NEW_LINE INDENT x = Q . get ( ) NEW_LINE for i in range ( len ( edges [ x ] ) ) : NEW_LINE INDENT if ( visited [ edges [ x ] [ i ] ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT distance [ edges [ x ] [ i ] ] = distance [ x ] + 1 NEW_LINE Q . put ( edges [ x ] [ i ] ) NEW_LINE visited [ edges [ x ] [ i ] ] = 1 NEW_LINE DEDENT DEDENT return distance [ v ] NEW_LINE DEDENT def addEdge ( edges , u , v ) : NEW_LINE INDENT edges [ u ] . append ( v ) NEW_LINE edges [ v ] . append ( u ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 9 NEW_LINE edges = [ [ ] for i in range ( n ) ] NEW_LINE addEdge ( edges , 0 , 1 ) NEW_LINE addEdge ( edges , 0 , 7 ) NEW_LINE addEdge ( edges , 1 , 7 ) NEW_LINE addEdge ( edges , 1 , 2 ) NEW_LINE addEdge ( edges , 2 , 3 ) NEW_LINE addEdge ( edges , 2 , 5 ) NEW_LINE addEdge ( edges , 2 , 8 ) NEW_LINE addEdge ( edges , 3 , 4 ) NEW_LINE addEdge ( edges , 3 , 5 ) NEW_LINE addEdge ( edges , 4 , 5 ) NEW_LINE addEdge ( edges , 5 , 6 ) NEW_LINE addEdge ( edges , 6 , 7 ) NEW_LINE addEdge ( edges , 7 , 8 ) NEW_LINE u = 0 NEW_LINE v = 5 NEW_LINE print ( minEdgeBFS ( edges , u , v , n ) ) NEW_LINE DEDENT
Minimum swaps so that binary search can be applied | Function to find minimum swaps . ; Here we are getting number of smaller and greater elements of k . ; Here we are calculating the actual position of k in the array . ; Implementing binary search as per the above - discussed cases . ; If we find the k . ; If we need minimum element swap . ; Else the element is at the right position . ; If we need maximum element swap . ; Else element is at the right position ; Calculating the required swaps . ; If it is impossible . ; Driver function
def findMinimumSwaps ( arr , n , k ) : NEW_LINE INDENT num_min = num_max = need_minimum = 0 NEW_LINE need_maximum = swaps = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < k ) : NEW_LINE INDENT num_min += 1 NEW_LINE DEDENT elif ( arr [ i ] > k ) : NEW_LINE INDENT num_max += 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == k ) : NEW_LINE INDENT pos = i NEW_LINE break NEW_LINE DEDENT DEDENT left = 0 NEW_LINE right = n - 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = ( left + right ) // 2 NEW_LINE if ( arr [ mid ] == k ) : NEW_LINE INDENT break NEW_LINE DEDENT elif ( arr [ mid ] > k ) : NEW_LINE INDENT if ( pos > mid ) : NEW_LINE INDENT need_minimum += 1 NEW_LINE DEDENT else : NEW_LINE INDENT num_min -= 1 NEW_LINE DEDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( pos < mid ) : NEW_LINE INDENT need_maximum += 1 NEW_LINE DEDENT else : NEW_LINE INDENT num_max -= 1 NEW_LINE DEDENT right = mid - 1 NEW_LINE DEDENT DEDENT if ( need_minimum > need_maximum ) : NEW_LINE INDENT swaps = swaps + need_maximum NEW_LINE num_min = num_min - need_maximum NEW_LINE need_minimum = ( need_minimum - need_maximum ) NEW_LINE need_maximum = 0 NEW_LINE DEDENT else : NEW_LINE INDENT swaps = swaps + need_minimum NEW_LINE num_max = num_max - need_minimum NEW_LINE need_maximum = ( need_maximum - need_minimum ) NEW_LINE need_minimum = 0 NEW_LINE DEDENT if ( need_maximum > num_max or need_minimum > num_min ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( swaps + need_maximum + need_minimum ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 10 , 6 , 7 , 2 , 5 , 4 ] NEW_LINE k = 4 NEW_LINE n = len ( arr ) NEW_LINE print ( findMinimumSwaps ( arr , n , k ) ) NEW_LINE DEDENT
Stable sort for descending order |
/ * Driver code * / NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE arr . sort ( reverse = True ) NEW_LINE print ( " Array ▁ after ▁ sorting ▁ : ▁ " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT
Check if both halves of the string have at least one different character | Function which break string into two halves Sorts the two halves separately Compares the two halves return true if any index has non - zero value ; Declaration and initialization of counter array ; Driver function
def function ( st ) : NEW_LINE INDENT st = list ( st ) NEW_LINE l = len ( st ) NEW_LINE st [ : l // 2 ] = sorted ( st [ : l // 2 ] ) NEW_LINE st [ l // 2 : ] = sorted ( st [ l // 2 : ] ) NEW_LINE for i in range ( l // 2 ) : NEW_LINE INDENT if ( st [ i ] != st [ l // 2 + i ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT st = " abcasdsabcae " NEW_LINE if function ( st ) : print ( " Yes , ▁ both ▁ halves ▁ differ ▁ " , " by ▁ at ▁ least ▁ one ▁ character " ) NEW_LINE else : print ( " No , ▁ both ▁ halves ▁ do ▁ not ▁ differ ▁ at ▁ all " ) NEW_LINE
Sort an array of 0 s , 1 s and 2 s ( Simple Counting ) | Example input = [ 0 , 1 , 2 , 2 , 0 , 0 ] output = [ 0 , 0 , 0 , 1 , 2 , 2 ]
inputArray = [ 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 ] NEW_LINE outputArray = [ ] NEW_LINE indexOfOne = 0 NEW_LINE for item in inputArray : NEW_LINE INDENT if item == 2 : NEW_LINE INDENT outputArray . append ( item ) NEW_LINE DEDENT elif item == 1 : NEW_LINE INDENT outputArray . insert ( indexOfOne , item ) NEW_LINE indexOfOne += 1 NEW_LINE DEDENT elif item == 0 : NEW_LINE INDENT outputArray . insert ( 0 , item ) NEW_LINE indexOfOne += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( " ▁ wrong ▁ value ▁ - ▁ Aborting ▁ " ) NEW_LINE continue NEW_LINE DEDENT DEDENT print ( outputArray ) NEW_LINE
Number of visible boxes after putting one inside another | Python3 program to count number of visible boxes . ; return the minimum number of visible boxes ; New Queue of integers . ; sorting the array ; traversing the array ; checking if current element is greater than or equal to twice of front element ; Pushing each element of array ; driver Program
import collections NEW_LINE def minimumBox ( arr , n ) : NEW_LINE INDENT q = collections . deque ( [ ] ) NEW_LINE arr . sort ( ) NEW_LINE q . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT now = q [ 0 ] NEW_LINE if ( arr [ i ] >= 2 * now ) : NEW_LINE INDENT q . popleft ( ) NEW_LINE DEDENT q . append ( arr [ i ] ) NEW_LINE DEDENT return len ( q ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 1 , 2 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minimumBox ( arr , n ) ) NEW_LINE DEDENT
Sort a binary array using one traversal | A Python program to sort a binary array ; if number is smaller than 1 then swap it with j - th number ; Driver program
def sortBinaryArray ( a , n ) : NEW_LINE INDENT j = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] < 1 : NEW_LINE INDENT j = j + 1 NEW_LINE a [ i ] , a [ j ] = a [ j ] , a [ i ] NEW_LINE DEDENT DEDENT DEDENT a = [ 1 , 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 0 ] NEW_LINE n = len ( a ) NEW_LINE sortBinaryArray ( a , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT
Smallest element in an array that is repeated exactly ' k ' times . | finds the smallest number in arr [ ] that is repeated k times ; Sort the array ; Find the first element with exactly k occurrences . ; Driver code
def findDuplicate ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT j , count = i + 1 , 1 NEW_LINE while ( j < n and arr [ j ] == arr [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE j += 1 NEW_LINE DEDENT if ( count == k ) : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT i = j NEW_LINE DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 2 , 1 , 3 , 1 ] ; NEW_LINE k = 2 NEW_LINE n = len ( arr ) NEW_LINE print findDuplicate ( arr , n , k ) NEW_LINE
Longest Common Prefix using Sorting | Python 3 program to find longest common prefix of given array of words . ; if size is 0 , return empty string ; sort the array of strings ; find the minimum length from first and last string ; find the common prefix between the first and last string ; Driver Code
def longestCommonPrefix ( a ) : NEW_LINE INDENT size = len ( a ) NEW_LINE if ( size == 0 ) : NEW_LINE INDENT return " " NEW_LINE DEDENT if ( size == 1 ) : NEW_LINE INDENT return a [ 0 ] NEW_LINE DEDENT a . sort ( ) NEW_LINE end = min ( len ( a [ 0 ] ) , len ( a [ size - 1 ] ) ) NEW_LINE i = 0 NEW_LINE while ( i < end and a [ 0 ] [ i ] == a [ size - 1 ] [ i ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT pre = a [ 0 ] [ 0 : i ] NEW_LINE return pre NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input = [ " geeksforgeeks " , " geeks " , " geek " , " geezer " ] NEW_LINE print ( " The ▁ longest ▁ Common ▁ Prefix ▁ is ▁ : " , longestCommonPrefix ( input ) ) NEW_LINE DEDENT
Find the minimum and maximum amount to buy all N candies | Python implementation to find the minimum and maximum amount ; function to find the maximum and the minimum cost required ; Sort the array ; print the minimum cost ; print the maximum cost ; Driver Code ; Function call
from math import ceil NEW_LINE def find ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE b = int ( ceil ( n / k ) ) NEW_LINE print ( " minimum ▁ " , sum ( arr [ : b ] ) ) NEW_LINE print ( " maximum ▁ " , sum ( arr [ - b : ] ) ) NEW_LINE DEDENT arr = [ 3 , 2 , 1 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE find ( arr , n , k ) NEW_LINE
Check if it is possible to sort an array with conditional swapping of adjacent allowed | Returns true if it is possible to sort else false / ; We need to do something only if previousl element is greater ; If difference is more than one , then not possible ; Driver code
def checkForSorting ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i + 1 ] == 1 ) : NEW_LINE INDENT arr [ i ] , arr [ i + 1 ] = arr [ i + 1 ] , arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 1 , 0 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE if ( checkForSorting ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Sort an array of strings according to string lengths | Function to print the sorted array of string ; Function to Sort the array of string according to lengths . This function implements Insertion Sort . ; Insert s [ j ] at its correct position ; Driver code ; Function to perform sorting ; Calling the function to print result
def printArraystring ( string , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( string [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def sort ( s , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT temp = s [ i ] NEW_LINE j = i - 1 NEW_LINE while j >= 0 and len ( temp ) < len ( s [ j ] ) : NEW_LINE INDENT s [ j + 1 ] = s [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT s [ j + 1 ] = temp NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " GeeksforGeeks " , " I " , " from " , " am " ] NEW_LINE n = len ( arr ) NEW_LINE sort ( arr , n ) NEW_LINE printArraystring ( arr , n ) NEW_LINE DEDENT
Hoare 's vs Lomuto partition scheme in QuickSort | This function takes first element as pivot , and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side . It returns the index of the last element on the smaller side ; Find leftmost element greater than or equal to pivot ; Find rightmost element smaller than or equal to pivot ; If two pointers met . ; The main function that implements QuickSort arr -- > Array to be sorted , low -- > Starting index , high -- > Ending index ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition ; Function to pran array ; Driver code
def partition ( arr , low , high ) : NEW_LINE INDENT pivot = arr [ low ] NEW_LINE i = low - 1 NEW_LINE j = high + 1 NEW_LINE while ( True ) : NEW_LINE INDENT i += 1 NEW_LINE while ( arr [ i ] < pivot ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT j -= 1 NEW_LINE while ( arr [ j ] > pivot ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if ( i >= j ) : NEW_LINE INDENT return j NEW_LINE DEDENT arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE DEDENT DEDENT def quickSort ( arr , low , high ) : NEW_LINE INDENT if ( low < high ) : NEW_LINE INDENT pi = partition ( arr , low , high ) NEW_LINE quickSort ( arr , low , pi ) NEW_LINE quickSort ( arr , pi + 1 , high ) NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT arr = [ 10 , 7 , 8 , 9 , 1 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE quickSort ( arr , 0 , n - 1 ) NEW_LINE print ( " Sorted ▁ array : " ) NEW_LINE printArray ( arr , n ) NEW_LINE
K | Return the K - th smallest element . ; sort ( arr , arr + n ) ; Checking if k lies before 1 st element ; If k is the first element of array arr [ ] . ; If k is more than last element ; If first element of array is 1. ; Reducing k by numbers before arr [ 0 ] . ; Finding k 'th smallest element after removing array elements. ; Finding count of element between i - th and ( i - 1 ) - th element . ; Driver Code
def ksmallest ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE if ( k < arr [ 0 ] ) : NEW_LINE INDENT return k ; NEW_LINE DEDENT if ( k == arr [ 0 ] ) : NEW_LINE INDENT return arr [ 0 ] + 1 ; NEW_LINE DEDENT if ( k > arr [ n - 1 ] ) : NEW_LINE INDENT return k + n ; NEW_LINE DEDENT if ( arr [ 0 ] == 1 ) : NEW_LINE INDENT k -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT k -= ( arr [ 0 ] - 1 ) ; NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT c = arr [ i ] - arr [ i - 1 ] - 1 ; NEW_LINE if ( k <= c ) : NEW_LINE INDENT return arr [ i - 1 ] + k ; NEW_LINE DEDENT else : NEW_LINE INDENT k -= c ; NEW_LINE DEDENT DEDENT return arr [ n - 1 ] + k ; NEW_LINE DEDENT k = 1 ; NEW_LINE arr = [ 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( ksmallest ( arr , n , k ) ) ; NEW_LINE
Count nodes within K | Python3 program to count nodes inside K distance range from marked nodes ; Utility bfs method to fill distance vector and returns most distant marked node from node u ; push node u in queue and initialize its distance as 0 ; loop untill all nodes are processed ; if node is marked , update lastMarked variable ; loop over all neighbors of u and update their distance before pushing in queue ; if not given value already ; return last updated marked value ; method returns count of nodes which are in K - distance range from marked nodes ; vertices in a tree are one more than number of edges ; fill vector for graph ; fill boolean array mark from marked array ; vectors to store distances ; first bfs ( from any random node ) to get one distant marked node ; second bfs to get other distant marked node and also dl is filled with distances from first chosen marked node ; third bfs to fill dr by distances from second chosen marked node ; loop over all nodes ; increase res by 1 , if current node has distance less than K from both extreme nodes ; Driver Code
import queue NEW_LINE def bfsWithDistance ( g , mark , u , dis ) : NEW_LINE INDENT lastMarked = 0 NEW_LINE q = queue . Queue ( ) NEW_LINE q . put ( u ) NEW_LINE dis [ u ] = 0 NEW_LINE while ( not q . empty ( ) ) : NEW_LINE INDENT u = q . get ( ) NEW_LINE if ( mark [ u ] ) : NEW_LINE INDENT lastMarked = u NEW_LINE DEDENT for i in range ( len ( g [ u ] ) ) : NEW_LINE INDENT v = g [ u ] [ i ] NEW_LINE if ( dis [ v ] == - 1 ) : NEW_LINE INDENT dis [ v ] = dis [ u ] + 1 NEW_LINE q . put ( v ) NEW_LINE DEDENT DEDENT DEDENT return lastMarked NEW_LINE DEDENT def nodesKDistanceFromMarked ( edges , V , marked , N , K ) : NEW_LINE INDENT V = V + 1 NEW_LINE g = [ [ ] for i in range ( V ) ] NEW_LINE u , v = 0 , 0 NEW_LINE for i in range ( V - 1 ) : NEW_LINE INDENT u = edges [ i ] [ 0 ] NEW_LINE v = edges [ i ] [ 1 ] NEW_LINE g [ u ] . append ( v ) NEW_LINE g [ v ] . append ( u ) NEW_LINE DEDENT mark = [ False ] * V NEW_LINE for i in range ( N ) : NEW_LINE INDENT mark [ marked [ i ] ] = True NEW_LINE DEDENT tmp = [ - 1 ] * V NEW_LINE dl = [ - 1 ] * V NEW_LINE dr = [ - 1 ] * V NEW_LINE u = bfsWithDistance ( g , mark , 0 , tmp ) NEW_LINE u = bfsWithDistance ( g , mark , u , dl ) NEW_LINE bfsWithDistance ( g , mark , u , dr ) NEW_LINE res = 0 NEW_LINE for i in range ( V ) : NEW_LINE INDENT if ( dl [ i ] <= K and dr [ i ] <= K ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT edges = [ [ 1 , 0 ] , [ 0 , 3 ] , [ 0 , 8 ] , [ 2 , 3 ] , [ 3 , 5 ] , [ 3 , 6 ] , [ 3 , 7 ] , [ 4 , 5 ] , [ 5 , 9 ] ] NEW_LINE V = len ( edges ) NEW_LINE marked = [ 1 , 2 , 4 ] NEW_LINE N = len ( marked ) NEW_LINE K = 3 NEW_LINE print ( nodesKDistanceFromMarked ( edges , V , marked , N , K ) ) NEW_LINE DEDENT
Check whether a given number is even or odd | Returns true if n is even , else odd ; n & 1 is 1 , then odd , else even ; Driver code
def isEven ( n ) : NEW_LINE INDENT return ( not ( n & 1 ) ) NEW_LINE DEDENT n = 101 ; NEW_LINE print ( " Even " if isEven ( n ) else " Odd " ) NEW_LINE
Count distinct occurrences as a subsequence | Python3 program to count number of times S appears as a subsequence in T ; T can 't appear as a subsequence in S ; mat [ i ] [ j ] stores the count of occurrences of T ( 1. . i ) in S ( 1. . j ) . ; Initializing first column with all 0 s . x An empty string can 't have another string as suhsequence ; Initializing first row with all 1 s . An empty string is subsequence of all . ; Fill mat [ ] [ ] in bottom up manner ; If last characters don 't match, then value is same as the value without last character in S. ; Else value is obtained considering two cases . a ) All substrings without last character in S b ) All substrings without last characters in both . ; Driver Code
def findSubsequenceCount ( S , T ) : NEW_LINE INDENT m = len ( T ) NEW_LINE n = len ( S ) NEW_LINE if m > n : NEW_LINE INDENT return 0 NEW_LINE DEDENT mat = [ [ 0 for _ in range ( n + 1 ) ] for __ in range ( m + 1 ) ] NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT mat [ i ] [ 0 ] = 0 NEW_LINE DEDENT for j in range ( n + 1 ) : NEW_LINE INDENT mat [ 0 ] [ j ] = 1 NEW_LINE DEDENT for i in range ( 1 , m + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if T [ i - 1 ] != S [ j - 1 ] : NEW_LINE INDENT mat [ i ] [ j ] = mat [ i ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT mat [ i ] [ j ] = ( mat [ i ] [ j - 1 ] + mat [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return mat [ m ] [ n ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT T = " ge " NEW_LINE S = " geeksforgeeks " NEW_LINE print ( findSubsequenceCount ( S , T ) ) NEW_LINE DEDENT
QuickSort Tail Call Optimization ( Reducing worst case space to Log n ) | Python3 program for the above approach ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition
def quickSort ( arr , low , high ) : NEW_LINE INDENT if ( low < high ) : NEW_LINE INDENT pi = partition ( arr , low , high ) NEW_LINE quickSort ( arr , low , pi - 1 ) NEW_LINE quickSort ( arr , pi + 1 , high ) NEW_LINE DEDENT DEDENT
Check if a Regular Bracket Sequence can be formed with concatenation of given strings | Function to check possible RBS from the given strings ; Stores the values { sum , min_prefix } ; Iterate over the range ; Stores the total sum ; Stores the minimum prefix ; Check for minimum prefix ; Store these values in vector ; Store values according to the mentioned approach ; Sort the positive vector ; Stores the extra count of open brackets ; No valid bracket sequence can be formed ; Sort the negative vector ; Stores the count of the negative elements ; No valid bracket sequence can be formed ; Check if open is equal to negative ; Driver Code
def checkRBS ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE v = [ 0 ] * ( N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT s = S [ i ] NEW_LINE sum = 0 NEW_LINE pre = 0 NEW_LINE for c in s : NEW_LINE INDENT if ( c == ' ( ' ) : NEW_LINE INDENT sum += 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum -= 1 NEW_LINE DEDENT pre = min ( sum , pre ) NEW_LINE DEDENT v [ i ] = [ sum , pre ] NEW_LINE DEDENT pos = [ ] NEW_LINE neg = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( v [ i ] [ 0 ] >= 0 ) : NEW_LINE INDENT pos . append ( [ - v [ i ] [ 1 ] , v [ i ] [ 0 ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT neg . append ( [ v [ i ] [ 0 ] - v [ i ] [ 1 ] , - v [ i ] [ 0 ] ] ) NEW_LINE DEDENT DEDENT pos . sort ( ) NEW_LINE open = 0 NEW_LINE for p in pos : NEW_LINE INDENT if ( open - p [ 0 ] >= 0 ) : NEW_LINE INDENT open += p [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE return 0 NEW_LINE DEDENT DEDENT neg . sort ( ) NEW_LINE negative = 0 NEW_LINE for p in neg : NEW_LINE INDENT if ( negative - p [ 0 ] >= 0 ) : NEW_LINE INDENT negative += p [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE return 0 NEW_LINE DEDENT DEDENT if ( open != negative ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return 0 NEW_LINE DEDENT print ( " Yes " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : arr = [ " ) " , " ( ) ( " ] NEW_LINE INDENT checkRBS ( arr ) NEW_LINE DEDENT
Maximize count of unique Squares that can be formed with N arbitrary points in coordinate plane | Python program for the above approach ; Function to find the maximum number of unique squares that can be formed from the given N points ; Stores the resultant count of squares formed ; Base Case ; Subtract the maximum possible grid size as sqrt ( N ) ; Find the total squares till now for the maximum grid ; A i * i grid contains ( i - 1 ) * ( i - 1 ) + ( i - 2 ) * ( i - 2 ) + ... + 1 * 1 squares ; When N >= len then more squares will be counted ; Return total count of squares ; Driver Code
import math NEW_LINE def maximumUniqueSquares ( N ) : NEW_LINE INDENT ans = 0 NEW_LINE if N < 4 : NEW_LINE INDENT return 0 NEW_LINE DEDENT len = int ( math . sqrt ( N ) ) NEW_LINE N -= len * len NEW_LINE for i in range ( 1 , len ) : NEW_LINE INDENT ans += i * i NEW_LINE DEDENT if ( N >= len ) : NEW_LINE INDENT N -= len NEW_LINE for i in range ( 1 , len ) : NEW_LINE INDENT ans += i NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT ans += i NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 9 NEW_LINE print ( maximumUniqueSquares ( N ) ) NEW_LINE DEDENT
Lexicographically smallest permutation number up to K having given array as a subsequence | Function to find the lexicographically smallest permutation such that the given array is a subsequence of it ; Stores the missing elements in arr in the range [ 1 , K ] ; Stores if the ith element is present in arr or not ; Loop to mark all integers present in the array as visited ; Loop to insert all the integers not visited into missing ; Append INT_MAX at end in order to prevent going out of bounds ; Pointer to the current element ; Pointer to the missing element ; Stores the required permutation ; Loop to construct the permutation using greedy approach ; If missing element is smaller that the current element insert missing element ; Insert current element ; Print the required Permutation ; Driver Code ; Function Call
def findPermutation ( K , arr ) : NEW_LINE INDENT missing = [ ] NEW_LINE visited = [ 0 ] * ( K + 1 ) NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT visited [ arr [ i ] ] = 1 NEW_LINE DEDENT for i in range ( 1 , K + 1 ) : NEW_LINE INDENT if ( not visited [ i ] ) : NEW_LINE INDENT missing . append ( i ) NEW_LINE DEDENT DEDENT INT_MAX = 2147483647 NEW_LINE arr . append ( INT_MAX ) NEW_LINE missing . append ( INT_MAX ) NEW_LINE p1 = 0 NEW_LINE p2 = 0 NEW_LINE ans = [ ] NEW_LINE while ( len ( ans ) < K ) : NEW_LINE INDENT if ( arr [ p1 ] < missing [ p2 ] ) : NEW_LINE INDENT ans . append ( arr [ p1 ] ) NEW_LINE p1 = p1 + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans . append ( missing [ p2 ] ) NEW_LINE p2 = p2 + 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , K ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT K = 7 NEW_LINE arr = [ 6 , 4 , 2 , 1 ] NEW_LINE findPermutation ( K , arr ) NEW_LINE DEDENT
Last element remaining after repeated removal of Array elements at perfect square indices | Python 3 program for the above approach ; Function to find last remaining index after repeated removal of perfect square indices ; Initialize the ans variable as N ; Iterate a while loop and discard the possible values ; Total discarded values ; Check if this forms a perfect square ; Decrease answer by 1 ; Subtract the value from the current value of N ; Return the value remained ; Function to find last remaining element after repeated removal of array element at perfect square indices ; Find the remaining index ; Print the element at that index as the result ; Driver Code ; Given input
from math import sqrt NEW_LINE def findRemainingIndex ( N ) : NEW_LINE INDENT ans = N NEW_LINE while ( N > 1 ) : NEW_LINE INDENT discard = int ( sqrt ( N ) ) NEW_LINE if ( discard * discard == N ) : NEW_LINE INDENT ans -= 1 NEW_LINE DEDENT N -= discard NEW_LINE DEDENT return ans NEW_LINE DEDENT def findRemainingElement ( arr , N ) : NEW_LINE INDENT remainingIndex = findRemainingIndex ( N ) NEW_LINE print ( arr [ remainingIndex - 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 4 , 2 , 4 , - 3 , 1 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE findRemainingElement ( arr , N ) NEW_LINE DEDENT
Minimum time to reach from Node 1 to N if travel is allowed only when node is Green | Import library for Queue ; Function to find min edge ; Initialize queue and push [ 1 , 0 ] ; Create visited array to keep the track if node is visited or not ; Run infinite loop ; If node is N , terminate loop ; Travel adjacent nodes of crnt ; Check whether we visited previously or not ; Push into queue and make as true ; Function to Find time required to reach 1 to N ; Check color of node is red or green ; Add C sec from next green color time ; Add C ; Return the answer ; Driver Code ; Given Input ; Function Call ; Print total time
from queue import Queue NEW_LINE def minEdge ( ) : NEW_LINE INDENT Q = Queue ( ) NEW_LINE Q . put ( [ 1 , 0 ] ) NEW_LINE V = [ False for _ in range ( N + 1 ) ] NEW_LINE while 1 : NEW_LINE INDENT crnt , c = Q . get ( ) NEW_LINE if crnt == N : NEW_LINE INDENT break NEW_LINE DEDENT for _ in X [ crnt ] : NEW_LINE INDENT if not V [ _ ] : NEW_LINE INDENT Q . put ( [ _ , c + 1 ] ) NEW_LINE V [ _ ] = True NEW_LINE DEDENT DEDENT DEDENT return c NEW_LINE DEDENT def findTime ( c ) : NEW_LINE INDENT ans = 0 NEW_LINE for _ in range ( c ) : NEW_LINE INDENT if ( ans // T ) % 2 : NEW_LINE INDENT ans = ( ans // T + 1 ) * T + C NEW_LINE DEDENT else : NEW_LINE INDENT ans += C NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE M = 5 NEW_LINE T = 3 NEW_LINE C = 5 NEW_LINE X = [ [ ] , [ 2 , 3 , 4 ] , [ 4 , 5 ] , [ 1 ] , [ 1 , 2 ] , [ 2 ] ] NEW_LINE c = minEdge ( ) NEW_LINE ans = findTime ( c ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Count of subsets whose product is multiple of unique primes | Python program for the above approach ; Function to check number has distinct prime ; While N has factors of two ; Traversing till sqrt ( N ) ; If N has a factor of i ; While N has a factor of i ; Covering case , N is Prime ; Function to check wheather num can be added to the subset ; Recursive Function to count subset ; Base Case ; If currSubset is empty ; If Unique [ pos ] can be added to the Subset ; Function to count the subsets ; Initialize unique ; Check it is a product of distinct primes ; Count frequency of unique element ; Function Call ; Driver Code ; Given Input ; Function Call
from math import gcd , sqrt NEW_LINE def checkDistinctPrime ( n ) : NEW_LINE INDENT original = n NEW_LINE product = 1 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT product *= 2 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = n // 2 NEW_LINE DEDENT DEDENT for i in range ( 3 , int ( sqrt ( n ) ) , 2 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT product = product * i NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n = n // i NEW_LINE DEDENT DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT product = product * n NEW_LINE DEDENT return product == original NEW_LINE DEDENT def check ( pos , subset , unique ) : NEW_LINE INDENT for num in subset : NEW_LINE INDENT if gcd ( num , unique [ pos ] ) != 1 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def countPrime ( pos , currSubset , unique , frequency ) : NEW_LINE INDENT if pos == len ( unique ) : NEW_LINE INDENT if not currSubset : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 1 NEW_LINE for element in currSubset : NEW_LINE INDENT count *= frequency [ element ] NEW_LINE DEDENT return count NEW_LINE DEDENT if check ( pos , currSubset , unique ) : NEW_LINE INDENT return countPrime ( pos + 1 , currSubset , \ unique , frequency ) + countPrime ( pos + 1 , currSubset + [ unique [ pos ] ] , \ unique , frequency ) NEW_LINE DEDENT else : NEW_LINE INDENT return countPrime ( pos + 1 , currSubset , \ unique , frequency ) NEW_LINE DEDENT DEDENT def countSubsets ( arr , N ) : NEW_LINE INDENT unique = set ( ) NEW_LINE for element in arr : NEW_LINE INDENT if checkDistinctPrime ( element ) : NEW_LINE INDENT unique . add ( element ) NEW_LINE DEDENT DEDENT unique = list ( unique ) NEW_LINE frequency = dict ( ) NEW_LINE for element in unique : NEW_LINE INDENT frequency [ element ] = arr . count ( element ) NEW_LINE DEDENT ans = countPrime ( 0 , [ ] , unique , frequency ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 7 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE ans = countSubsets ( arr , N ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Lexicographically largest possible by merging two strings by adding one character at a time | Recursive function for finding the lexicographically largest string ; If either of the string length is 0 , return the other string ; If s1 is lexicographically larger than s2 ; Take first character of s1 and call the function ; Take first character of s2 and recursively call function for remaining string ; Driver code ; Given Input ; Function call
def largestMerge ( s1 , s2 ) : NEW_LINE INDENT if len ( s1 ) == 0 or len ( s2 ) == 0 : NEW_LINE INDENT return s1 + s2 NEW_LINE DEDENT if ( s1 > s2 ) : NEW_LINE INDENT return s1 [ 0 ] + largestMerge ( s1 [ 1 : ] , s2 ) NEW_LINE DEDENT return s2 [ 0 ] + largestMerge ( s1 , s2 [ 1 : ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " geeks " NEW_LINE s2 = " forgeeks " NEW_LINE print ( largestMerge ( s1 , s2 ) ) NEW_LINE DEDENT
Minimum distance between duplicates in a String | This function is used to find the required the minimum distances of repeating characters ; Define dictionary and list ; Traverse through string ; If character present in dictionary ; Difference between current position and last stored value ; Updating current position ; Storing difference in list ; If character not in dictionary assign it with initial of its position ; If no element inserted in list i . e . no repeating characters ; Return minimum distance ; Given Input ; Function Call
def shortestDistance ( S , N ) : NEW_LINE INDENT dic = { } NEW_LINE dis = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if S [ i ] in dic : NEW_LINE INDENT var = i - dic [ S [ i ] ] NEW_LINE dic [ S [ i ] ] = i NEW_LINE dis . append ( var ) NEW_LINE DEDENT else : NEW_LINE INDENT dic [ S [ i ] ] = i NEW_LINE DEDENT DEDENT if ( len ( dis ) == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return min ( dis ) - 1 NEW_LINE DEDENT DEDENT S = " geeksforgeeks " NEW_LINE N = 13 NEW_LINE print ( shortestDistance ( S , N ) ) NEW_LINE
Number of open doors | TCS Coding Question | Python3 code for the above approach ; Function that counts the number of doors opens after the Nth turn ; Find the number of open doors ; Return the resultant count of open doors ; Driver Code
import math NEW_LINE def countOpenDoors ( N ) : NEW_LINE INDENT doorsOpen = int ( math . sqrt ( N ) ) NEW_LINE return doorsOpen NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 100 NEW_LINE print ( countOpenDoors ( N ) ) NEW_LINE DEDENT
Minimum number of candies required to distribute among children based on given conditions | Function to count the minimum number of candies that is to be distributed ; Stores total count of candies ; Stores the amount of candies allocated to a student ; If the value of N is 1 ; Traverse the array arr [ ] ; If arr [ i + 1 ] is greater than arr [ i ] and ans [ i + 1 ] is at most ans [ i ] ; Assign ans [ i ] + 1 to ans [ i + 1 ] ; Iterate until i is atleast 0 ; If arr [ i ] is greater than arr [ i + 1 ] and ans [ i ] is at most ans [ i + 1 ] ; Assign ans [ i + 1 ] + 1 to ans [ i ] ; If arr [ i ] is equals arr [ i + 1 ] and ans [ i ] is less than ans [ i + 1 ] ; Assign ans [ i + 1 ] + 1 to ans [ i ] ; Increment the sum by ans [ i ] ; Return the resultant sum ; Driver Code
def countCandies ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE ans = [ 1 ] * n NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i + 1 ] > arr [ i ] and ans [ i + 1 ] <= ans [ i ] ) : NEW_LINE INDENT ans [ i + 1 ] = ans [ i ] + 1 NEW_LINE DEDENT DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] and ans [ i ] <= ans [ i + 1 ] ) : NEW_LINE INDENT ans [ i ] = ans [ i + 1 ] + 1 NEW_LINE DEDENT elif ( arr [ i ] == arr [ i + 1 ] and ans [ i ] < ans [ i + 1 ] ) : NEW_LINE INDENT ans [ i ] = ans [ i + 1 ] + 1 NEW_LINE DEDENT sum += ans [ i ] NEW_LINE DEDENT sum += ans [ n - 1 ] NEW_LINE return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countCandies ( arr , N ) ) NEW_LINE DEDENT
Maximize profit possible by selling M products such that profit of a product is the number of products left of that supplier | Function to find the maximum profit by selling M number of products ; Initialize a Max - Heap to keep track of the maximum value ; Stores the maximum profit ; Traverse the array and push all the elements in max_heap ; Iterate a loop until M > 0 ; Decrement the value of M by 1 ; Pop the maximum element from the heap ; Update the maxProfit ; Push ( X - 1 ) to max heap ; Print the result ; Driver code
def findMaximumProfit ( arr , M , N ) : NEW_LINE INDENT max_heap = [ ] NEW_LINE maxProfit = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT max_heap . append ( arr [ i ] ) NEW_LINE DEDENT max_heap . sort ( ) NEW_LINE max_heap . reverse ( ) NEW_LINE while ( M > 0 ) : NEW_LINE INDENT M -= 1 NEW_LINE X = max_heap [ 0 ] NEW_LINE max_heap . pop ( 0 ) NEW_LINE maxProfit += X NEW_LINE max_heap . append ( X - 1 ) NEW_LINE max_heap . sort ( ) NEW_LINE max_heap . reverse ( ) NEW_LINE DEDENT print ( maxProfit ) NEW_LINE DEDENT arr = [ 4 , 6 ] NEW_LINE M = 4 NEW_LINE N = len ( arr ) NEW_LINE findMaximumProfit ( arr , M , N ) NEW_LINE
Generate an array with K positive numbers such that arr [ i ] is either | Python program for the above approach Function to generate the resultant sequence of first N natural numbers ; Initialize an array of size N ; Stores the sum of positive and negative elements ; Mark the first N - K elements as negative ; Update the value of arr [ i ] ; Update the value of sumNeg ; Mark the remaining K elements as positive ; Update the value of arr [ i ] ; Update the value of sumPos ; If the sum of the sequence is negative , then pr - 1 ; Pr the required sequence ; Driver Code
def findSequence ( n , k ) : NEW_LINE INDENT arr = [ 0 ] * n NEW_LINE sumPos = 0 NEW_LINE sumNeg = 0 NEW_LINE for i in range ( 0 , n - k ) : NEW_LINE INDENT arr [ i ] = - ( i + 1 ) NEW_LINE sumNeg += arr [ i ] NEW_LINE DEDENT for i in range ( n - k , n ) : NEW_LINE INDENT arr [ i ] = i + 1 NEW_LINE sumPos += arr [ i ] NEW_LINE DEDENT if ( abs ( sumNeg ) >= sumPos ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT N = 10 NEW_LINE K = 6 NEW_LINE findSequence ( N , K ) NEW_LINE
Print the indices for every row of a grid from which escaping from the grid is possible | Function to find the row index for every row of a matrix from which one can exit the grid after entering from left ; Iterate over the range [ 0 , M - 1 ] ; Stores the direction from which a person enters a cell ; Row index from which one enters the grid ; Column index from which one enters the grid ; Iterate until j is atleast N - 1 ; If Mat [ i ] [ j ] is equal to 1 ; If entry is from left cell ; Decrement i by 1 ; Assign ' D ' to dir ; If entry is from upper cell ; Decrement j by 1 ; Assign ' R ' to dir ; If entry is from right cell ; Increment i by 1 ; Assign ' U ' to dir ; If entry is from bottom cell ; Increment j by 1 ; Assign ' L ' to dir ; Otherwise , ; If entry is from left cell ; Increment i by 1 ; Assign ' U ' to dir ; If entry is from upper cell ; Increment j by 1 ; Assign ' L ' to dir ; If entry is from right cell ; Decrement i by 1 ; Assign ' D ' to dir ; If entry is from lower cell ; Decrement j by 1 ; Assign ' R ' to dir ; If i or j is less than 0 or i is equal to M or j is equal to N ; If j is equal to N ; Otherwise ; Input ; Function call
def findPath ( arr , M , N ) : NEW_LINE INDENT for row in range ( M ) : NEW_LINE INDENT dir = ' L ' NEW_LINE i = row NEW_LINE j = 0 NEW_LINE while ( j < N ) : NEW_LINE INDENT if ( arr [ i ] [ j ] == 1 ) : NEW_LINE INDENT if ( dir == ' L ' ) : NEW_LINE INDENT i -= 1 NEW_LINE dir = ' D ' NEW_LINE DEDENT elif ( dir == ' U ' ) : NEW_LINE INDENT j -= 1 NEW_LINE dir = ' R ' NEW_LINE DEDENT elif ( dir == ' R ' ) : NEW_LINE INDENT i += 1 NEW_LINE dir = ' U ' NEW_LINE DEDENT elif ( dir == ' D ' ) : NEW_LINE INDENT j += 1 NEW_LINE dir = ' L ' NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( dir == ' L ' ) : NEW_LINE INDENT i += 1 NEW_LINE dir = ' U ' NEW_LINE DEDENT elif ( dir == ' U ' ) : NEW_LINE INDENT j += 1 NEW_LINE dir = ' L ' NEW_LINE DEDENT elif ( dir == ' R ' ) : NEW_LINE INDENT i -= 1 NEW_LINE dir = ' D ' NEW_LINE DEDENT elif ( dir == ' D ' ) : NEW_LINE INDENT j -= 1 NEW_LINE dir = ' R ' NEW_LINE DEDENT DEDENT if ( i < 0 or i == M or j < 0 or j == N ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( j == N ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ [ 1 , 1 , 0 , 1 ] , [ 1 , 1 , 0 , 0 ] , [ 1 , 0 , 0 , 0 ] , [ 1 , 1 , 0 , 1 ] , [ 0 , 1 , 0 , 1 ] ] NEW_LINE M = len ( arr ) NEW_LINE N = len ( arr [ 0 ] ) NEW_LINE findPath ( arr , M , N ) NEW_LINE
Maximize sum of array by repeatedly removing an element from pairs whose concatenation is a multiple of 3 | Function to calculate sum of digits of an integer ; Function to calculate maximum sum of array after removing pairs whose concatenation is divisible by 3 ; Stores the sum of digits of array element ; Find the sum of digits ; If i is divisible by 3 ; Otherwise , if i modulo 3 is 1 ; Otherwise , if i modulo 3 is 2 ; Return the resultant sum of array elements ; Driver Code
def getSum ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in str ( n ) : NEW_LINE INDENT ans += int ( i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getMax ( arr ) : NEW_LINE INDENT maxRem0 = 0 NEW_LINE rem1 = 0 NEW_LINE rem2 = 0 NEW_LINE for i in arr : NEW_LINE INDENT digitSum = getSum ( i ) NEW_LINE if digitSum % 3 == 0 : NEW_LINE INDENT maxRem0 = max ( maxRem0 , i ) NEW_LINE DEDENT elif digitSum % 3 == 1 : NEW_LINE INDENT rem1 += i NEW_LINE DEDENT else : NEW_LINE INDENT rem2 += i NEW_LINE DEDENT DEDENT print ( maxRem0 + max ( rem1 , rem2 ) ) NEW_LINE DEDENT arr = [ 23 , 12 , 43 , 3 , 56 ] NEW_LINE getMax ( arr ) NEW_LINE
Minimum edge reversals to make a root | Python3 program to find min edge reversal to make every node reachable from root ; Method to dfs in tree and populates disRev values ; Visit current node ; Looping over all neighbors ; Distance of v will be one more than distance of u ; Initialize back edge count same as parent node 's count ; If there is a reverse edge from u to i , then only update ; Return total reversal in subtree rooted at u ; Method prints root and minimum number of edge reversal ; Number of nodes are one more than number of edges ; Data structure to store directed tree ; disRev stores two values - distance and back edge count from root node ; Add 0 weight in direction of u to v ; Add 1 weight in reverse direction ; Initialize all variables ; dfs populates disRev data structure and store total reverse edge counts ; for ( i = 0 i < V i ++ ) { cout < < i < < " ▁ : ▁ " << disRev [ i ] [ 0 ] << " ▁ " << disRev [ i ] [ 1 ] << endl } ; Loop over all nodes to choose minimum edge reversal ; ( reversal in path to i ) + ( reversal in all other tree parts ) ; Choose minimum among all values ; Print the designated root and total edge reversal made ; Driver code
import sys NEW_LINE def dfs ( g , disRev , visit , u ) : NEW_LINE INDENT visit [ u ] = True NEW_LINE totalRev = 0 NEW_LINE for i in range ( len ( g [ u ] ) ) : NEW_LINE INDENT v = g [ u ] [ i ] [ 0 ] NEW_LINE if ( not visit [ v ] ) : NEW_LINE INDENT disRev [ v ] [ 0 ] = disRev [ u ] [ 0 ] + 1 NEW_LINE disRev [ v ] [ 1 ] = disRev [ u ] [ 1 ] NEW_LINE if ( g [ u ] [ i ] [ 1 ] ) : NEW_LINE INDENT disRev [ v ] [ 1 ] = disRev [ u ] [ 1 ] + 1 NEW_LINE totalRev += 1 NEW_LINE DEDENT totalRev += dfs ( g , disRev , visit , v ) NEW_LINE DEDENT DEDENT return totalRev NEW_LINE DEDENT def printMinEdgeReverseForRootNode ( edges , e ) : NEW_LINE INDENT V = e + 1 NEW_LINE g = [ [ ] for i in range ( V ) ] NEW_LINE disRev = [ [ 0 , 0 ] for i in range ( V ) ] NEW_LINE visit = [ False for i in range ( V ) ] NEW_LINE for i in range ( e ) : NEW_LINE INDENT u = edges [ i ] [ 0 ] NEW_LINE v = edges [ i ] [ 1 ] NEW_LINE g [ u ] . append ( [ v , 0 ] ) NEW_LINE g [ v ] . append ( [ u , 1 ] ) NEW_LINE DEDENT for i in range ( V ) : NEW_LINE INDENT visit [ i ] = False NEW_LINE disRev [ i ] [ 0 ] = disRev [ i ] [ 1 ] = 0 NEW_LINE DEDENT root = 0 NEW_LINE totalRev = dfs ( g , disRev , visit , root ) NEW_LINE res = sys . maxsize NEW_LINE for i in range ( V ) : NEW_LINE INDENT edgesToRev = ( ( totalRev - disRev [ i ] [ 1 ] ) + ( disRev [ i ] [ 0 ] - disRev [ i ] [ 1 ] ) ) NEW_LINE if ( edgesToRev < res ) : NEW_LINE INDENT res = edgesToRev NEW_LINE root = i NEW_LINE DEDENT DEDENT print ( root , res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT edges = [ [ 0 , 1 ] , [ 2 , 1 ] , [ 3 , 2 ] , [ 3 , 4 ] , [ 5 , 4 ] , [ 5 , 6 ] , [ 7 , 6 ] ] NEW_LINE e = len ( edges ) NEW_LINE printMinEdgeReverseForRootNode ( edges , e ) NEW_LINE DEDENT
Check if 2 * K + 1 non | Function to check if the S can be obtained by ( K + 1 ) non - empty substrings whose concatenation and concatenation of the reverse of these K strings ; Stores the size of the string ; If n is less than 2 * k + 1 ; Stores the first K characters ; Stores the last K characters ; Reverse the string ; If both the strings are equal ; Driver Code
def checkString ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE if ( 2 * k + 1 > n ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT a = s [ 0 : k ] NEW_LINE b = s [ n - k : n ] NEW_LINE b = b [ : : - 1 ] NEW_LINE if ( a == 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 S = " qwqwq " NEW_LINE K = 1 NEW_LINE checkString ( S , K ) NEW_LINE DEDENT
Minimum number of socks required to picked to have at least K pairs of the same color | Function to count the minimum number of socks to be picked ; Stores the total count of pairs of socks ; Find the total count of pairs ; If K is greater than pairs ; Otherwise ; Driver Code
def findMin ( arr , N , k ) : NEW_LINE INDENT pairs = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT pairs += arr [ i ] / 2 NEW_LINE DEDENT if ( k > pairs ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 2 * k + N - 1 NEW_LINE DEDENT DEDENT arr = [ 4 , 5 , 6 ] NEW_LINE k = 3 NEW_LINE print ( findMin ( arr , 3 , k ) ) ; NEW_LINE