codeparrot/xlcost-text-to-code huggingface dataset:
Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree | ''Python3 program of the above approach ; ''Stores the nodes to be deleted ; ''Structure of a Tree node ; ''Function to find the min value of node for each level ; '' Count is used to diffentiate  each level of the tree ; ''Function to check whether the nodes in the level below it are smaller by performing post order traversal ; '' Traverse the left subtree ; '' Traverse right subtree ; '' Check from minimum values  computed at each level ; ''Function to print count of nodes from all lower levels having values less than the the nodes in the current level ; '' Stores the number of levels ; '' Stores the required count  of nodes for each level ; ''Driver Code ; ''  4  / \  3 5  / \ / \  10 2 3 1
from collections import deque NEW_LINE from sys import maxsize as INT_MAX NEW_LINE mp = dict ( ) NEW_LINE 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 def calculateMin ( root : Node , levelMin : list ) -> None : NEW_LINE INDENT qt = deque ( ) NEW_LINE qt . append ( root ) NEW_LINE count = 1 NEW_LINE min_v = INT_MAX NEW_LINE while ( qt ) : NEW_LINE INDENT temp = qt . popleft ( ) NEW_LINE min_v = min ( min_v , temp . key ) NEW_LINE if ( temp . left ) : NEW_LINE INDENT qt . append ( temp . left ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT qt . append ( temp . right ) NEW_LINE DEDENT count -= 1 NEW_LINE if ( count == 0 ) : NEW_LINE INDENT levelMin . append ( min_v ) NEW_LINE min_v = INT_MAX NEW_LINE count = len ( qt ) NEW_LINE DEDENT DEDENT DEDENT def findNodes ( root : Node , levelMin : list , levelResult : list , level : int ) -> None : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT findNodes ( root . left , levelMin , levelResult , level + 1 ) NEW_LINE findNodes ( root . right , levelMin , levelResult , level + 1 ) NEW_LINE for i in range ( level ) : NEW_LINE INDENT if ( root . key <= levelMin [ i ] ) : NEW_LINE INDENT levelResult [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT def printNodes ( root : Node ) -> None : NEW_LINE INDENT levelMin = [ ] NEW_LINE calculateMin ( root , levelMin ) NEW_LINE numLevels = len ( levelMin ) NEW_LINE levelResult = [ 0 ] * numLevels NEW_LINE findNodes ( root , levelMin , levelResult , 0 ) NEW_LINE for i in range ( numLevels ) : NEW_LINE INDENT print ( levelResult [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 4 ) NEW_LINE root . left = Node ( 3 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 3 ) NEW_LINE root . right . right = Node ( 1 ) NEW_LINE root . left . left = Node ( 10 ) NEW_LINE root . left . right = Node ( 2 ) NEW_LINE printNodes ( root ) NEW_LINE DEDENT
Design a data structure that supports insert , delete , search and getRandom in constant time | Python program to design a DS that supports following operations in Theta ( n ) time : a ) Insertb ) Deletec ) Searchd ) getRandom ; Class to represent the required data structure ; Constructor ( creates a list and a hash ) ; A resizable array ; A hash where keys are lists elements and values are indexes of the list ; A Theta ( 1 ) function to add an element to MyDS data structure ; If element is already present , then nothing has to be done ; Else put element at the end of the list ; Also put it into hash ; A Theta ( 1 ) function to remove an element from MyDS data structure ; Check if element is present ; If present , then remove element from hash ; Swap element with last element so that removal from the list can be done in O ( 1 ) time ; Remove last element ( This is O ( 1 ) ) ; Update hash table for new index of last element ; Returns a random element from MyDS ; Find a random index from 0 to size - 1 ; Return element at randomly picked index ; Returns index of element if element is present , otherwise none ; Driver Code
import random NEW_LINE class MyDS : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . arr = [ ] NEW_LINE self . hashd = { } NEW_LINE DEDENT def add ( self , x ) : NEW_LINE INDENT if x in self . hashd : NEW_LINE INDENT return NEW_LINE DEDENT s = len ( self . arr ) NEW_LINE self . arr . append ( x ) NEW_LINE self . hashd [ x ] = s NEW_LINE DEDENT def remove ( self , x ) : NEW_LINE INDENT index = self . hashd . get ( x , None ) NEW_LINE if index == None : NEW_LINE INDENT return NEW_LINE DEDENT del self . hashd [ x ] NEW_LINE size = len ( self . arr ) NEW_LINE last = self . arr [ size - 1 ] NEW_LINE self . arr [ index ] , self . arr [ size - 1 ] = self . arr [ size - 1 ] , self . arr [ index ] NEW_LINE del self . arr [ - 1 ] NEW_LINE self . hashd [ last ] = index NEW_LINE DEDENT def getRandom ( self ) : NEW_LINE INDENT index = random . randrange ( 0 , len ( self . arr ) ) NEW_LINE return self . arr [ index ] NEW_LINE DEDENT def search ( self , x ) : NEW_LINE INDENT return self . hashd . get ( x , None ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT ds = MyDS ( ) NEW_LINE ds . add ( 10 ) NEW_LINE ds . add ( 20 ) NEW_LINE ds . add ( 30 ) NEW_LINE ds . add ( 40 ) NEW_LINE print ( ds . search ( 30 ) ) NEW_LINE ds . remove ( 20 ) NEW_LINE ds . add ( 50 ) NEW_LINE print ( ds . search ( 50 ) ) NEW_LINE print ( ds . getRandom ( ) ) NEW_LINE DEDENT
Count subarrays which contains both the maximum and minimum array element | ''Function to count subarray containing both maximum and minimum array elements ; '' If the length of the  array is less than 2 ; '' Find the index of  maximum element ; '' Find the index of  minimum element ; '' If i > j, then swap  the value of i and j ; '' Return the answer ; ''Function to return max_element index ; ''Function to return min_element index ; ''Driver Code ; '' Function call
def countSubArray ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT i = max_element ( arr ) ; NEW_LINE j = min_element ( arr ) ; NEW_LINE if ( i > j ) : NEW_LINE INDENT tmp = arr [ i ] ; NEW_LINE arr [ i ] = arr [ j ] ; NEW_LINE arr [ j ] = tmp ; NEW_LINE DEDENT return ( i + 1 ) * ( n - j ) ; NEW_LINE DEDENT def max_element ( arr ) : NEW_LINE INDENT idx = 0 ; NEW_LINE max = arr [ 0 ] ; NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT if ( max < arr [ i ] ) : NEW_LINE INDENT max = arr [ i ] ; NEW_LINE idx = i ; NEW_LINE DEDENT DEDENT return idx ; NEW_LINE DEDENT def min_element ( arr ) : NEW_LINE INDENT idx = 0 ; NEW_LINE min = arr [ 0 ] ; NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] < min ) : NEW_LINE INDENT min = arr [ i ] ; NEW_LINE idx = i ; NEW_LINE DEDENT DEDENT return idx ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 1 , 2 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countSubArray ( arr , n ) ) ; NEW_LINE DEDENT
Count pairs of leaf nodes in a Binary Tree which are at most K distance apart | ''Structure of a Node ; ''Stores the count of required pairs ; ''Function to perform dfs to find pair of leaf nodes at most K distance apart ; '' Return empty array if node is None ; '' If node is a leaf node and return res ; '' Traverse to the left ; '' Traverse to the right ; '' Update the distance between left  and right leaf node ; '' Count all pair of leaf nodes  which are at most K distance apart ; '' Return res to parent node ; ''Driver Code ; ''  1  / \  2 3  /  4   ; '' Given distance K ; '' Function call
class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT result = 0 NEW_LINE def dfs ( root , distance ) : NEW_LINE INDENT global result NEW_LINE if ( root == None ) : NEW_LINE INDENT res = [ 0 for i in range ( distance + 1 ) ] NEW_LINE return res NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT res = [ 0 for i in range ( distance + 1 ) ] NEW_LINE res [ 1 ] += 1 NEW_LINE return res NEW_LINE DEDENT left = dfs ( root . left , distance ) NEW_LINE right = dfs ( root . right , distance ) NEW_LINE res = [ 0 for i in range ( distance + 1 ) ] NEW_LINE i = len ( res ) - 2 NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT res [ i + 1 ] = left [ i ] + right [ i ] NEW_LINE i -= 1 NEW_LINE DEDENT for l in range ( 1 , len ( left ) ) : NEW_LINE INDENT for r in range ( len ( right ) ) : NEW_LINE INDENT if ( l + r <= distance ) : NEW_LINE INDENT result += left [ l ] * right [ r ] NEW_LINE DEDENT DEDENT DEDENT return res 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 K = 3 NEW_LINE dfs ( root , K ) NEW_LINE print ( result ) NEW_LINE DEDENT
Maximum absolute difference between any two level sum in a N | Python3 program for the above approach ; Function to find the maximum absolute difference of level sum ; Create the adjacency list ; Initialize value of maximum and minimum level sum ; Do Level order traversal keeping track of nodes at every level ; Get the size of queue when the level order traversal for one level finishes ; Iterate for all the nodes in the queue currently ; Dequeue an node from queue ; Enqueue the children of dequeued node ; Update the maximum level sum value ; Update the minimum level sum value ; Return the result ; Driver Code ; Number of nodes and edges ; Edges of the N - ary tree ; Given cost ; Function call
from collections import deque NEW_LINE def maxAbsDiffLevelSum ( N , M , cost , Edges ) : NEW_LINE INDENT adj = [ [ ] for i in range ( N ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT u = Edges [ i ] [ 0 ] NEW_LINE v = Edges [ i ] [ 1 ] NEW_LINE adj [ u ] . append ( v ) NEW_LINE DEDENT maxSum = cost [ 0 ] NEW_LINE minSum = cost [ 0 ] NEW_LINE q = deque ( ) NEW_LINE q . append ( 0 ) NEW_LINE while len ( q ) > 0 : NEW_LINE INDENT count = len ( q ) NEW_LINE sum = 0 NEW_LINE while ( count ) : NEW_LINE INDENT temp = q . popleft ( ) NEW_LINE q . pop ( ) NEW_LINE sum = sum + cost [ temp ] NEW_LINE for i in adj [ temp ] : NEW_LINE INDENT q . append ( i ) NEW_LINE DEDENT count -= 1 NEW_LINE DEDENT maxSum = max ( sum , maxSum ) NEW_LINE minSum = min ( sum , minSum ) NEW_LINE DEDENT print ( abs ( maxSum - minSum ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE M = 9 NEW_LINE Edges = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 0 , 3 ] , [ 1 , 4 ] , [ 1 , 5 ] , [ 3 , 6 ] , [ 6 , 7 ] , [ 6 , 8 ] , [ 6 , 9 ] ] NEW_LINE cost = [ 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 6 , 12 , 7 ] NEW_LINE maxAbsDiffLevelSum ( N , M , cost , Edges ) NEW_LINE DEDENT
Split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray | Python3 program for the above approach ; Function to find the minimum cost of splitting the array into subarrays ; Get the maximum element ; dp will store the minimum cost upto index i ; Initialize the result array ; Initialise the first element ; Create the frequency array ; Update the frequency ; Counting the cost of the duplicate element ; Minimum cost of operation from 0 to j ; Total cost of the array ; Driver Code ; Given cost K ; Function call
import sys NEW_LINE def findMinCost ( a , k , n ) : NEW_LINE INDENT max_ele = max ( a ) NEW_LINE dp = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] = sys . maxsize NEW_LINE DEDENT dp [ 0 ] = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT freq = [ 0 ] * ( max_ele + 1 ) NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT freq [ a [ j ] ] += 1 NEW_LINE cost = 0 NEW_LINE for x in range ( 0 , max_ele + 1 ) : NEW_LINE INDENT cost += ( 0 if ( freq [ x ] == 1 ) else freq [ x ] ) NEW_LINE DEDENT dp [ j + 1 ] = min ( dp [ i ] + cost + k , dp [ j + 1 ] ) NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 1 , 1 ] ; NEW_LINE K = 2 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findMinCost ( arr , K , n ) ) ; NEW_LINE DEDENT
Find subarray with given sum | Set 2 ( Handles Negative Numbers ) | Function to print subarray with sum as given sum ; create an empty map ; if curr_sum is equal to target sum we found a subarray starting from index 0 and ending at index i ; If curr_sum - sum already exists in map we have found a subarray with target sum ; if value is not present then add to hashmap ; If we reach here , then no subarray exists ; Driver program to test above function
def subArraySum ( arr , n , Sum ) : NEW_LINE INDENT Map = { } NEW_LINE curr_sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT curr_sum = curr_sum + arr [ i ] NEW_LINE if curr_sum == Sum : NEW_LINE INDENT print ( " Sum ▁ found ▁ between ▁ indexes ▁ 0 ▁ to " , i ) NEW_LINE return NEW_LINE DEDENT if ( curr_sum - Sum ) in Map : NEW_LINE INDENT print ( " Sum ▁ found ▁ between ▁ indexes " ,   \ Map [ curr_sum - Sum ] + 1 , " to " , i ) NEW_LINE return NEW_LINE DEDENT Map [ curr_sum ] = i NEW_LINE DEDENT print ( " No ▁ subarray ▁ with ▁ given ▁ sum ▁ exists " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 2 , - 2 , - 20 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE Sum = - 10 NEW_LINE subArraySum ( arr , n , Sum ) NEW_LINE DEDENT
Write Code to Determine if Two Trees are Identical | A binary tree node has data , pointer to left child and a pointer to right child ; Given two trees , return true if they are structurally identical ; 1. Both empty ; 2. Both non - empty -> Compare them ; 3. one empty , one not -- false ; Driver program to test identicalTress 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 identicalTrees ( a , b ) : NEW_LINE INDENT if a is None and b is None : NEW_LINE INDENT return True NEW_LINE DEDENT if a is not None and b is not None : NEW_LINE INDENT return ( ( a . data == b . data ) and identicalTrees ( a . left , b . left ) and identicalTrees ( a . right , b . right ) ) NEW_LINE DEDENT return False NEW_LINE DEDENT root1 = Node ( 1 ) NEW_LINE root2 = Node ( 1 ) NEW_LINE root1 . left = Node ( 2 ) NEW_LINE root1 . right = Node ( 3 ) NEW_LINE root1 . left . left = Node ( 4 ) NEW_LINE root1 . left . right = Node ( 5 ) NEW_LINE root2 . left = Node ( 2 ) NEW_LINE root2 . right = Node ( 3 ) NEW_LINE root2 . left . left = Node ( 4 ) NEW_LINE root2 . left . right = Node ( 5 ) NEW_LINE if identicalTrees ( root1 , root2 ) : NEW_LINE INDENT print " Both ▁ trees ▁ are ▁ identical " NEW_LINE DEDENT else : NEW_LINE INDENT print " Trees ▁ are ▁ not ▁ identical " NEW_LINE DEDENT
Queries to find Kth greatest character in a range [ L , R ] from a string with updates | Maximum Size of a String ; Fenwick Tree to store the frequencies of 26 alphabets ; Size of the String . ; Function to update Fenwick Tree for Character c at index val ; Add val to current node Fenwick Tree ; Move index to parent node in update View ; Function to get sum of frequencies of character c till index ; Stores the sum ; Add current element of Fenwick tree to sum ; Move index to parent node in getSum View ; Function to create the Fenwick tree ; Function to print the kth largest character in the range of l to r ; Stores the count of characters ; Stores the required character ; Calculate frequency of C in the given range ; Increase count ; If count exceeds K ; Required character found ; Function to update character at pos by character s ; 0 based index system ; Driver Code ; Number of queries ; Construct the Fenwick Tree
maxn = 100005 NEW_LINE BITree = [ [ 0 for x in range ( maxn ) ] for y in range ( 26 ) ] NEW_LINE N = 0 NEW_LINE def update_BITree ( index , C , val ) : NEW_LINE INDENT while ( index <= N ) : NEW_LINE INDENT BITree [ ord ( C ) - ord ( ' a ' ) ] [ index ] += val NEW_LINE index += ( index & - index ) NEW_LINE DEDENT DEDENT def sum_BITree ( index , C ) : NEW_LINE INDENT s = 0 NEW_LINE while ( index ) : NEW_LINE INDENT s += BITree [ ord ( C ) - ord ( ' a ' ) ] [ index ] NEW_LINE index -= ( index & - index ) NEW_LINE DEDENT return s NEW_LINE DEDENT def buildTree ( st ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT update_BITree ( i , st [ i ] , 1 ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def printCharacter ( st , l , r , k ) : NEW_LINE INDENT count = 0 NEW_LINE for C in range ( ord ( ' z ' ) , ord ( ' a ' ) - 1 , - 1 ) : NEW_LINE INDENT times = ( sum_BITree ( r , chr ( C ) ) - sum_BITree ( l - 1 , chr ( C ) ) ) NEW_LINE count += times NEW_LINE if ( count >= k ) : NEW_LINE INDENT ans = chr ( C ) NEW_LINE break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def updateTree ( st , pos , s ) : NEW_LINE INDENT index = pos ; NEW_LINE update_BITree ( index , st [ index ] , - 1 ) NEW_LINE st . replace ( st [ index ] , s , 1 ) NEW_LINE update_BITree ( index , s , 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " abcddef " NEW_LINE N = len ( st ) NEW_LINE Q = 3 NEW_LINE buildTree ( st ) NEW_LINE print ( printCharacter ( st , 1 , 2 , 2 ) ) NEW_LINE updateTree ( st , 4 , ' g ' ) NEW_LINE print ( printCharacter ( st , 1 , 5 , 4 ) ) NEW_LINE DEDENT
Generate a string from an array of alphanumeric strings based on given conditions | Function to generate required string ; To store the result ; Split name and number ; Stores the maximum number less than or equal to the length of name ; Check for number by parsing it to integer if it is greater than max number so far ; Check if no such number is found then we append X to the result . ; Otherwise ; Append max index of the name ; Return the final string ; Driver Code ; Function call
def generatePassword ( s , T ) : NEW_LINE INDENT result = [ ] NEW_LINE for currentString in s : NEW_LINE INDENT person = currentString . split ( " : " ) NEW_LINE name = person [ 0 ] NEW_LINE number = person [ 1 ] NEW_LINE n = len ( name ) NEW_LINE max = 0 NEW_LINE for i in range ( len ( number ) ) : NEW_LINE INDENT temp = int ( number [ i ] ) NEW_LINE if ( temp > max and temp <= n ) : NEW_LINE INDENT max = temp NEW_LINE DEDENT DEDENT if max == 0 : NEW_LINE INDENT result . append ( T ) NEW_LINE DEDENT else : NEW_LINE INDENT result . append ( name [ max - 1 ] ) NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ " Geeks : 89167" , " gfg : 68795" ] NEW_LINE T = ' X ' NEW_LINE print ( * generatePassword ( arr , T ) , sep = " " ) NEW_LINE
Minimum number of edges required to be removed from an Undirected Graph to make it acyclic | Stores the adjacency list ; Stores if a vertex is visited or not ; Function to perform DFS Traversal to count the number and size of all connected components ; Mark the current node as visited ; Traverse the adjacency list of the current node ; For every unvisited node ; Recursive DFS Call ; Function to add undirected edge in the graph ; Function to calculate minimum number of edges to be removed ; Create Adjacency list ; Iterate over all the nodes ; Print the final count ; Driver Code
vec = [ [ ] for i in range ( 100001 ) ] NEW_LINE vis = [ False ] * 100001 NEW_LINE cc = 1 NEW_LINE def dfs ( node ) : NEW_LINE INDENT global cc NEW_LINE vis [ node ] = True NEW_LINE for x in vec [ node ] : NEW_LINE INDENT if ( vis [ x ] == 0 ) : NEW_LINE INDENT cc += 1 NEW_LINE dfs ( x ) NEW_LINE DEDENT DEDENT DEDENT def addEdge ( u , v ) : NEW_LINE INDENT vec [ u ] . append ( v ) NEW_LINE vec [ v ] . append ( u ) NEW_LINE DEDENT def minEdgeRemoved ( N , M , Edges ) : NEW_LINE INDENT global cc NEW_LINE for i in range ( M ) : NEW_LINE INDENT addEdge ( Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) NEW_LINE DEDENT memset ( vis , false , sizeof ( vis ) ) NEW_LINE k = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( not vis [ i ] ) : NEW_LINE INDENT cc = 1 NEW_LINE dfs ( i ) NEW_LINE k += 1 NEW_LINE DEDENT DEDENT print ( M - N + k ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE M = 2 NEW_LINE Edges = [ [ 1 , 2 ] , [ 2 , 3 ] ] NEW_LINE minEdgeRemoved ( N , M , Edges ) NEW_LINE DEDENT
Group Shifted String | Total lowercase letter ; Method to a difference string for a given string . If string is " adf " then difference string will be " cb " ( first difference3 then difference 2 ) ; Representing the difference as char ; This string will be 1 less length than str ; Method for grouping shifted string ; map for storing indices of string which are in same group ; Iterating through map to print group ; Driver code
ALPHA = 26 NEW_LINE def getDiffString ( str ) : NEW_LINE INDENT shift = " " NEW_LINE for i in range ( 1 , len ( str ) ) : NEW_LINE INDENT dif = ( ord ( str [ i ] ) - ord ( str [ i - 1 ] ) ) NEW_LINE if ( dif < 0 ) : NEW_LINE INDENT dif += ALPHA NEW_LINE DEDENT shift += chr ( dif + ord ( ' a ' ) ) NEW_LINE DEDENT return shift NEW_LINE DEDENT def groupShiftedString ( str , n ) : NEW_LINE INDENT groupMap = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT diffStr = getDiffString ( str [ i ] ) NEW_LINE if diffStr not in groupMap : NEW_LINE INDENT groupMap [ diffStr ] = [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT groupMap [ diffStr ] . append ( i ) NEW_LINE DEDENT DEDENT for it in groupMap : NEW_LINE INDENT v = groupMap [ it ] NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT print ( str [ v [ i ] ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT str = [ " acd " , " dfg " , " wyz " , " yab " , " mop " , " bdfh " , " a " , " x " , " moqs " ] NEW_LINE n = len ( str ) NEW_LINE groupShiftedString ( str , n ) NEW_LINE
Check if a Binary Tree consists of a pair of leaf nodes with sum K | Stores if a pair exists or not ; Struct binary tree node ; Function to check if a pair of leaf nodes exists with sum K ; Checks if root is NULL ; Checks if the current node is a leaf node ; Checks for a valid pair of leaf nodes ; Insert value of current node into the set ; Traverse left and right subtree ; Driver Code ; Construct binary tree ; Stores the leaf nodes
pairFound = False NEW_LINE S = set ( ) 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 DEDENT DEDENT def pairSum ( root , target ) : NEW_LINE INDENT global pairFound NEW_LINE global S NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT temp = list ( S ) NEW_LINE if ( temp . count ( target - root . data ) ) : NEW_LINE INDENT print ( target - root . data , root . data ) NEW_LINE pairFound = True NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT S . add ( root . data ) NEW_LINE DEDENT DEDENT pairSum ( root . left , target ) NEW_LINE pairSum ( root . right , target ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . right . right . right = newNode ( 8 ) NEW_LINE K = 13 NEW_LINE pairSum ( root , K ) NEW_LINE if ( pairFound == False ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT