text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Populate Inorder Successor for all nodes | Python3 program to populate inorder traversal of all nodes ; A wrapper over populateNextRecur ; The first visited node will be the rightmost node next of the rightmost node will be NULL ; Set next of all descendants of p by traversing them in reverse Inorder ; First set the next pointer in right subtree ; Set the next as previously visited node in reverse Inorder ; Change the prev for subsequent node ; Finally , set the next pointer in right subtree | 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 self . next = None NEW_LINE DEDENT DEDENT next = None NEW_LINE def populateNext ( node ) : NEW_LINE INDENT populateNextRecur ( node , next ) NEW_LINE DEDENT def populateNextRecur ( p , next_ref ) : NEW_LINE INDENT if ( p != None ) : NEW_LINE INDENT populateNextRecur ( p . right , next_ref ) NEW_LINE p . next = next_ref NEW_LINE next_ref = p NEW_LINE populateNextRecur ( p . left , next_ref ) NEW_LINE DEDENT DEDENT |
Check if a binary string contains consecutive same or not | Function that returns true is str is valid ; Assuming the string is binary If any two consecutive characters are equal then the string is invalid ; If the string is alternating ; Driver code | def isValid ( string , length ) : NEW_LINE INDENT for i in range ( 1 , length ) : NEW_LINE INDENT if string [ i ] == string [ i - 1 ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "0110" NEW_LINE length = len ( string ) NEW_LINE if isValid ( string , length ) : NEW_LINE INDENT print ( " Valid " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Invalid " ) NEW_LINE DEDENT DEDENT |
Minimum K such that every substring of length atleast K contains a character c | This function checks if there exists some character which appears in all K length substrings ; Iterate over all possible characters ; stores the last occurrence ; set answer as true ; No occurrence found of current character in first substring of length K ; Check for every last substring of length K where last occurr - ence exists in substring ; If last occ is not present in substring ; current character is K amazing ; This function performs binary search over the answer to minimise it ; Check if answer is found try to minimise it ; Driver Code | def check ( s , K ) : NEW_LINE INDENT for ch in range ( 0 , 26 ) : NEW_LINE INDENT c = chr ( 97 + ch ) NEW_LINE last = - 1 NEW_LINE found = True NEW_LINE for i in range ( 0 , K ) : NEW_LINE INDENT if s [ i ] == c : NEW_LINE INDENT last = i NEW_LINE DEDENT DEDENT if last == - 1 : NEW_LINE INDENT continue NEW_LINE DEDENT for i in range ( K , len ( s ) ) : NEW_LINE INDENT if s [ i ] == c : NEW_LINE INDENT last = i NEW_LINE DEDENT if last <= ( i - K ) : NEW_LINE INDENT found = False NEW_LINE break NEW_LINE DEDENT DEDENT if found : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT def binarySearch ( s ) : NEW_LINE INDENT low , high , ans = 1 , len ( s ) , None NEW_LINE while low <= high : NEW_LINE INDENT mid = ( high + low ) >> 1 NEW_LINE if check ( s , mid ) : NEW_LINE INDENT ans , high = mid , mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abcde " NEW_LINE print ( binarySearch ( s ) ) NEW_LINE s = " aaaa " NEW_LINE print ( binarySearch ( s ) ) NEW_LINE DEDENT |
Check if number can be displayed using seven segment led | Pre - computed values of segment used by digit 0 to 9. ; Check if it is possible to display the number ; Finding sum of the segments used by each digit of the number ; Driver Code ; Function call to print required answer | seg = [ 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 ] NEW_LINE def LedRequired ( s , led ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT count += seg [ ord ( s [ i ] ) - 48 ] NEW_LINE DEDENT if ( count <= led ) : NEW_LINE INDENT return " YES " NEW_LINE DEDENT else : NEW_LINE INDENT return " NO " NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "123456789" NEW_LINE led = 20 NEW_LINE print ( LedRequired ( S , led ) ) NEW_LINE DEDENT |
Iterative Search for a key ' x ' in Binary Tree | A binary tree node has data , left child and right child ; Construct to create a newNode ; iterative process to search an element x in a given binary tree ; Base Case ; Create an empty stack and append root to it ; Do iterative preorder traversal to search x ; See the top item from stack and check if it is same as x ; append right and left children of the popped node to stack ; Driver Code | class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def iterativeSearch ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT nodeStack = [ ] NEW_LINE nodeStack . append ( root ) NEW_LINE while ( len ( nodeStack ) ) : NEW_LINE INDENT node = nodeStack [ 0 ] NEW_LINE if ( node . data == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT nodeStack . pop ( 0 ) NEW_LINE if ( node . right ) : NEW_LINE INDENT nodeStack . append ( node . right ) NEW_LINE DEDENT if ( node . left ) : NEW_LINE INDENT nodeStack . append ( node . left ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT 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 if iterativeSearch ( root , 6 ) : NEW_LINE INDENT print ( " Found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Found " ) NEW_LINE DEDENT if iterativeSearch ( root , 12 ) : NEW_LINE INDENT print ( " Found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Found " ) NEW_LINE DEDENT |
Check whether two strings can be made equal by increasing prefixes | check whether the first string can be converted to the second string by increasing the ASCII value of prefix string of first string ; length of two strings ; If lengths are not equal ; store the difference of ASCII values ; difference of first element ; traverse through the string ; the ASCII value of the second string should be greater than or equal to first string , if it is violated return false . ; store the difference of ASCII values ; the difference of ASCII values should be in descending order ; if the difference array is not in descending order ; if all the ASCII values of characters of first string is less than or equal to the second string and the difference array is in descending order , return true ; Driver code ; create two strings ; check whether the first string can be converted to the second string | def find ( s1 , s2 ) : NEW_LINE INDENT len__ = len ( s1 ) NEW_LINE len_1 = len ( s2 ) NEW_LINE if ( len__ != len_1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT d = [ 0 for i in range ( len__ ) ] NEW_LINE d [ 0 ] = ord ( s2 [ 0 ] ) - ord ( s1 [ 0 ] ) NEW_LINE for i in range ( 1 , len__ , 1 ) : NEW_LINE INDENT if ( s1 [ i ] > s2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT d [ i ] = ord ( s2 [ i ] ) - ord ( s1 [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len__ - 1 ) : NEW_LINE INDENT if ( d [ i ] < d [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " abcd " NEW_LINE s2 = " bcdd " NEW_LINE if ( find ( s1 , s2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
N | Function that returns the N - th character ; initially null string ; starting integer ; add integers in string ; one digit numbers added ; more than 1 digit number , generate equivalent number in a string s1 and concatenate s1 into s . ; add the number in string ; reverse the string ; attach the number ; if the length exceeds N ; Driver Code | def NthCharacter ( n ) : NEW_LINE INDENT s = " " NEW_LINE c = 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( c < 10 ) : NEW_LINE INDENT s += chr ( 48 + c ) NEW_LINE DEDENT else : NEW_LINE INDENT s1 = " " NEW_LINE dup = c NEW_LINE while ( dup > 0 ) : NEW_LINE INDENT s1 += chr ( ( dup % 10 ) + 48 ) NEW_LINE dup //= 10 NEW_LINE DEDENT s1 = " " . join ( reversed ( s1 ) ) NEW_LINE s += s1 NEW_LINE DEDENT c += 1 NEW_LINE if ( len ( s ) >= n ) : NEW_LINE INDENT return s [ n - 1 ] NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 11 NEW_LINE print ( NthCharacter ( n ) ) NEW_LINE DEDENT |
Sub | Function that counts all the sub - strings of length ' k ' which have all identical characters ; count of sub - strings , length , initial position of sliding window ; dictionary to store the frequency of the characters of sub - string ; increase the frequency of the character and length of the sub - string ; if the length of the sub - string is greater than K ; remove the character from the beginning of sub - string ; if the length of the sub string is equal to k and frequency of one of its characters is equal to the length of the sub - string i . e . all the characters are same increase the count ; display the number of valid sub - strings ; Driver code | def solve ( s , k ) : NEW_LINE INDENT count , length , pos = 0 , 0 , 0 NEW_LINE m = dict . fromkeys ( s , 0 ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT m [ s [ i ] ] += 1 NEW_LINE length += 1 NEW_LINE if length > k : NEW_LINE INDENT m [ s [ pos ] ] -= 1 NEW_LINE pos += 1 NEW_LINE length -= 1 NEW_LINE DEDENT if length == k and m [ s [ i ] ] == length : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aaaabbbccdddd " NEW_LINE k = 4 NEW_LINE solve ( s , k ) NEW_LINE DEDENT |
Program to replace every space in a string with hyphen | Python 3 program to replace space with - ; Get the String ; Traverse the string character by character . ; Changing the ith character to ' - ' if it 's a space. ; Print the modified string . | if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " A β computer β science β portal β for β geeks " NEW_LINE for i in range ( 0 , len ( str ) , 1 ) : NEW_LINE INDENT if ( str [ i ] == ' β ' ) : NEW_LINE INDENT str = str . replace ( str [ i ] , ' - ' ) NEW_LINE DEDENT DEDENT print ( str ) NEW_LINE DEDENT |
Minimum operation require to make first and last character same | Python program to find minimum operation require to make first and last character same ; Function to find minimum operation require to make first and last character same ; Base conditions ; If answer found ; If string is already visited ; Decrement ending index only ; Increment starting index only ; Increment starting index and decrement index ; Store the minimum value ; Driver code ; Function call | import sys NEW_LINE MAX = sys . maxsize NEW_LINE m = { } NEW_LINE Min = sys . maxsize NEW_LINE def minOperation ( s , i , j , count ) : NEW_LINE INDENT global Min , MAX NEW_LINE if ( ( i >= len ( s ) and j < 0 ) or ( i == j ) ) : NEW_LINE INDENT return MAX NEW_LINE DEDENT if ( s [ i ] == s [ j ] or count >= Min ) : NEW_LINE INDENT return count NEW_LINE DEDENT Str = str ( i ) + " | " + str ( j ) NEW_LINE if Str not in m : NEW_LINE INDENT if ( i >= len ( s ) ) : NEW_LINE INDENT m [ Str ] = minOperation ( s , i , j - 1 , count + 1 ) NEW_LINE DEDENT elif ( j < 0 ) : NEW_LINE INDENT m [ Str ] = minOperation ( s , i + 1 , j , count + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT m [ Str ] = min ( minOperation ( s , i , j - 1 , count + 1 ) , minOperation ( s , i + 1 , j , count + 1 ) ) NEW_LINE DEDENT DEDENT if ( m [ Str ] < Min ) : NEW_LINE INDENT Min = m [ Str ] NEW_LINE DEDENT return m [ Str ] NEW_LINE DEDENT s = " bacdefghipalop " NEW_LINE ans = minOperation ( s , 0 , len ( s ) - 1 , 0 ) NEW_LINE if ( ans == MAX ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT |
Check if any permutation of a large number is divisible by 8 | Function to check if any permutation of a large number is divisible by 8 ; Less than three digit number can be checked directly . ; check for the reverse of a number ; Stores the Frequency of characters in the n . ; Iterates for all three digit numbers divisible by 8 ; stores the frequency of all single digit in three - digit number ; check if the original number has the digit ; when all are checked its not possible ; Driver Code | def solve ( n , l ) : NEW_LINE INDENT if l < 3 : NEW_LINE INDENT if int ( n ) % 8 == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT n = n [ : : - 1 ] NEW_LINE if int ( n ) % 8 == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT hash = 10 * [ 0 ] NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT hash [ int ( n [ i ] ) - 0 ] += 1 ; NEW_LINE DEDENT for i in range ( 104 , 1000 , 8 ) : NEW_LINE INDENT dup = i NEW_LINE freq = 10 * [ 0 ] NEW_LINE freq [ int ( dup % 10 ) ] += 1 ; NEW_LINE dup = dup / 10 NEW_LINE freq [ int ( dup % 10 ) ] += 1 ; NEW_LINE dup = dup / 10 NEW_LINE freq [ int ( dup % 10 ) ] += 1 ; NEW_LINE dup = i NEW_LINE if ( freq [ int ( dup % 10 ) ] > hash [ int ( dup % 10 ) ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT dup = dup / 10 ; NEW_LINE if ( freq [ int ( dup % 10 ) ] > hash [ int ( dup % 10 ) ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT dup = dup / 10 NEW_LINE if ( freq [ int ( dup % 10 ) ] > hash [ int ( dup % 10 ) ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT number = "31462708" NEW_LINE l = len ( number ) NEW_LINE if solve ( number , l ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Lexicographically smallest string formed by appending a character from the first K characters of a given string | Function to find the new string thus formed by removing characters ; new string ; Remove characters until the string is empty ; Traverse to find the smallest character in the first k characters ; append the smallest character ; removing the lexicographically smallest character from the string ; Driver Code | def newString ( s , k ) : NEW_LINE INDENT X = " " NEW_LINE while ( len ( s ) > 0 ) : NEW_LINE INDENT temp = s [ 0 ] NEW_LINE i = 1 NEW_LINE while ( i < k and i < len ( s ) ) : NEW_LINE INDENT if ( s [ i ] < temp ) : NEW_LINE INDENT temp = s [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT X = X + temp NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( s [ i ] == temp ) : NEW_LINE INDENT s = s [ 0 : i ] + s [ i + 1 : ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT return X NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " gaurang " NEW_LINE k = 3 NEW_LINE print ( newString ( s , k ) ) NEW_LINE DEDENT |
Given a binary tree , how do you remove all the half nodes ? | A binary tree node ; For inorder traversal ; Removes all nodes with only one child and returns new root ( note that root may change ) ; If current nodes is a half node with left child None then it 's right child is returned and replaces it in the given tree ; if current nodes is a half node with right child NULL right , then it 's right child is returned and replaces it in the given tree ; Driver Program | 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 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 RemoveHalfNodes ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return None NEW_LINE DEDENT root . left = RemoveHalfNodes ( root . left ) NEW_LINE root . right = RemoveHalfNodes ( root . right ) NEW_LINE if root . left is None and root . right is None : NEW_LINE INDENT return root NEW_LINE DEDENT if root . left is None : NEW_LINE INDENT new_root = root . right NEW_LINE temp = root NEW_LINE root = None NEW_LINE del ( temp ) NEW_LINE return new_root NEW_LINE DEDENT if root . right is None : NEW_LINE INDENT new_root = root . left NEW_LINE temp = root NEW_LINE root = None NEW_LINE del ( temp ) NEW_LINE return new_root NEW_LINE DEDENT return root NEW_LINE DEDENT root = Node ( 2 ) NEW_LINE root . left = Node ( 7 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . left . right = Node ( 6 ) NEW_LINE root . left . right . left = Node ( 1 ) NEW_LINE root . left . right . right = Node ( 11 ) NEW_LINE root . right . right = Node ( 9 ) NEW_LINE root . right . right . left = Node ( 4 ) NEW_LINE print " Inorder β traversal β of β given β tree " NEW_LINE printInorder ( root ) NEW_LINE NewRoot = RemoveHalfNodes ( root ) NEW_LINE print " NEW_LINE Inorder traversal of the modified tree " NEW_LINE printInorder ( NewRoot ) NEW_LINE |
Palindrome by swapping only one character | Python3 program palindrome by swapping only one character ; counts the number of differences which prevents the string from being palindrome . ; keeps a record of the characters that prevents the string from being palindrome . ; loops from the start of a string till the midpoint of the string ; difference is encountered preventing the string from being palindrome ; 3 rd differences encountered and its no longer possible to make is palindrome by one swap ; record the different character ; store the different characters ; its already palindrome ; only one difference is found ; if the middleChar matches either of the difference producing characters , return true ; two differences are found ; if the characters contained in the two sets are same , return true ; Driver Code | def isPalindromePossible ( input : str ) -> bool : NEW_LINE INDENT length = len ( input ) NEW_LINE diffCount = 0 NEW_LINE i = 0 NEW_LINE diff = [ [ '0' ] * 2 ] * 2 NEW_LINE while i < length // 2 : NEW_LINE INDENT if input [ i ] != input [ length - i - 1 ] : NEW_LINE INDENT if diffCount == 2 : NEW_LINE INDENT return False NEW_LINE DEDENT diff [ diffCount ] [ 0 ] = input [ i ] NEW_LINE diff [ diffCount ] [ 1 ] = input [ length - i - 1 ] NEW_LINE diffCount += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if diffCount == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT elif diffCount == 1 : NEW_LINE INDENT midChar = input [ i ] NEW_LINE if length % 2 != 0 and ( diff [ 0 ] [ 0 ] == midChar or diff [ 0 ] [ 1 ] == midChar ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT elif diffCount == 2 : NEW_LINE INDENT if ( diff [ 0 ] [ 0 ] == diff [ 1 ] [ 0 ] and diff [ 0 ] [ 1 ] == diff [ 1 ] [ 1 ] ) or ( diff [ 0 ] [ 0 ] == diff [ 1 ] [ 1 ] and diff [ 0 ] [ 1 ] == diff [ 1 ] [ 0 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( isPalindromePossible ( " bbg " ) ) NEW_LINE print ( isPalindromePossible ( " bdababd " ) ) NEW_LINE print ( isPalindromePossible ( " gcagac " ) ) NEW_LINE DEDENT |
Convert String into Binary Sequence | utility function ; convert each char to ASCII value ; Convert ASCII value to binary ; Driver Code | def strToBinary ( s ) : NEW_LINE INDENT bin_conv = [ ] NEW_LINE for c in s : NEW_LINE INDENT ascii_val = ord ( c ) NEW_LINE binary_val = bin ( ascii_val ) NEW_LINE bin_conv . append ( binary_val [ 2 : ] ) NEW_LINE DEDENT return ( ' β ' . join ( bin_conv ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = ' geeks ' NEW_LINE DEDENT print ( strToBinary ( s ) ) NEW_LINE |
Print distinct sorted permutations with duplicates allowed in input | Python3 program to print all permutations of a string in sorted order . ; Calculating factorial of a number ; Method to find total number of permutations ; Building Map to store frequencies of all characters . ; Traversing map and finding duplicate elements . ; Start traversing from the end and find position ' i - 1' of the first character which is greater than its successor ; Finding smallest character after ' i - 1' and greater than temp [ i - 1 ] ; Swapping the above found characters . ; Sort all digits from position next to ' i - 1' to end of the string ; Print the String ; Sorting String ; Print first permutation ; Finding the total permutations ; Driver Code | from collections import defaultdict NEW_LINE def factorial ( n ) : NEW_LINE INDENT f = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT f = f * i NEW_LINE DEDENT return f NEW_LINE DEDENT def calculateTotal ( temp , n ) : NEW_LINE INDENT f = factorial ( n ) NEW_LINE hm = defaultdict ( int ) NEW_LINE for i in range ( len ( temp ) ) : NEW_LINE INDENT hm [ temp [ i ] ] += 1 NEW_LINE DEDENT for e in hm : NEW_LINE INDENT x = hm [ e ] NEW_LINE if ( x > 1 ) : NEW_LINE INDENT temp5 = factorial ( x ) NEW_LINE f //= temp5 NEW_LINE DEDENT return f NEW_LINE DEDENT DEDENT def nextPermutation ( temp ) : NEW_LINE INDENT for i in range ( len ( temp ) - 1 , 0 , - 1 ) : NEW_LINE INDENT if ( temp [ i ] > temp [ i - 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT min = i NEW_LINE x = temp [ i - 1 ] NEW_LINE for j in range ( i + 1 , len ( temp ) ) : NEW_LINE INDENT if ( ( temp [ j ] < temp [ min ] ) and ( temp [ j ] > x ) ) : NEW_LINE INDENT min = j NEW_LINE DEDENT DEDENT temp [ i - 1 ] , temp [ min ] = ( temp [ min ] , temp [ i - 1 ] ) NEW_LINE temp [ i : ] . sort ( ) NEW_LINE print ( ' ' . join ( temp ) ) NEW_LINE DEDENT def printAllPermutations ( s ) : NEW_LINE INDENT temp = list ( s ) NEW_LINE temp . sort ( ) NEW_LINE print ( ' ' . join ( temp ) ) NEW_LINE total = calculateTotal ( temp , len ( temp ) ) NEW_LINE for i in range ( 1 , total ) : NEW_LINE INDENT nextPermutation ( temp ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " AAB " NEW_LINE printAllPermutations ( s ) NEW_LINE DEDENT |
Swap Nodes in Binary tree of every k 'th level | constructor to create a new node ; A utility function swap left node and right node of tree of every k 'th level ; Base Case ; If current level + 1 is present in swap vector then we swap left and right node ; Recur for left and right subtree ; This function mainly calls recursive function swapEveryKLevelUtil ; Call swapEveryKLevelUtil function with initial level as 1 ; Method to find the inorder tree travesal ; 1 / \ 2 3 / / \ 4 7 8 | 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 swapEveryKLevelUtil ( root , level , k ) : NEW_LINE INDENT if ( root is None or ( root . left is None and root . right is None ) ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( level + 1 ) % k == 0 : NEW_LINE INDENT root . left , root . right = root . right , root . left NEW_LINE DEDENT swapEveryKLevelUtil ( root . left , level + 1 , k ) NEW_LINE swapEveryKLevelUtil ( root . right , level + 1 , k ) NEW_LINE DEDENT def swapEveryKLevel ( root , k ) : NEW_LINE INDENT swapEveryKLevelUtil ( root , 1 , k ) NEW_LINE DEDENT def inorder ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( root . left ) NEW_LINE print root . data , NEW_LINE inorder ( root . right ) NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . right . right = Node ( 8 ) NEW_LINE root . right . left = Node ( 7 ) NEW_LINE k = 2 NEW_LINE print " Before β swap β node β : " NEW_LINE inorder ( root ) NEW_LINE swapEveryKLevel ( root , k ) NEW_LINE print " NEW_LINE After swap Node : " NEW_LINE inorder ( root ) NEW_LINE |
Convert a sentence into its equivalent mobile numeric keypad sequence | Function which computes the sequence ; length of input string ; checking for space ; calculating index for each character ; output sequence ; storing the sequence in array | def printSequence ( arr , input ) : NEW_LINE INDENT n = len ( input ) NEW_LINE output = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( input [ i ] == ' β ' ) : NEW_LINE INDENT output = output + "0" NEW_LINE DEDENT else : NEW_LINE INDENT position = ord ( input [ i ] ) - ord ( ' A ' ) NEW_LINE output = output + arr [ position ] NEW_LINE DEDENT DEDENT return output NEW_LINE DEDENT str = [ "2" , "22" , "222" , "3" , "33" , "333" , "4" , "44" , "444" , "5" , "55" , "555" , "6" , "66" , "666" , "7" , "77" , "777" , "7777" , "8" , "88" , "888" , "9" , "99" , "999" , "9999" ] NEW_LINE input = " GEEKSFORGEEKS " ; NEW_LINE print ( printSequence ( str , input ) ) NEW_LINE |
Longest Uncommon Subsequence | function to calculate length of longest uncommon subsequence ; creating an unordered map to map strings to their frequency ; traversing all elements of vector strArr ; Creating all possible subsequences , i . e 2 ^ n ; ( ( i >> j ) & 1 ) determines which character goes into t ; If common subsequence is found , increment its frequency ; traversing the map ; if frequency equals 1 ; input strings | def findLUSlength ( a , b ) : NEW_LINE INDENT map = dict ( ) NEW_LINE strArr = [ ] NEW_LINE strArr . append ( a ) NEW_LINE strArr . append ( b ) NEW_LINE for s in strArr : NEW_LINE INDENT for i in range ( 1 << len ( s ) ) : NEW_LINE INDENT t = " " NEW_LINE for j in range ( len ( s ) ) : NEW_LINE INDENT if ( ( ( i >> j ) & 1 ) != 0 ) : NEW_LINE INDENT t += s [ j ] NEW_LINE DEDENT DEDENT if ( t in map . keys ( ) ) : NEW_LINE INDENT map [ t ] += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT map [ t ] = 1 NEW_LINE DEDENT DEDENT DEDENT res = 0 NEW_LINE for a in map : NEW_LINE INDENT if ( map [ a ] == 1 ) : NEW_LINE INDENT res = max ( res , len ( a ) ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT a = " abcdabcd " NEW_LINE b = " abcabc " NEW_LINE print ( findLUSlength ( a , b ) ) NEW_LINE |
Round the given number to nearest multiple of 10 | Function to round the number to the nearest number having one 's digit 0 ; Last character is 0 then return the original string ; If last character is 1 or 2 or 3 or 4 or 5 make it 0 ; Process carry ; Return final string ; Driver code ; Function call | def Round ( s , n ) : NEW_LINE INDENT s = list ( s ) NEW_LINE c = s . copy ( ) NEW_LINE if ( c [ n - 1 ] == '0' ) : NEW_LINE INDENT return ( " " . join ( s ) ) NEW_LINE DEDENT elif ( c [ n - 1 ] == '1' or c [ n - 1 ] == '2' or c [ n - 1 ] == '3' or c [ n - 1 ] == '4' or c [ n - 1 ] == '5' ) : NEW_LINE INDENT c [ n - 1 ] = '0' NEW_LINE return ( " " . join ( c ) ) NEW_LINE DEDENT else : NEW_LINE INDENT c [ n - 1 ] = '0' NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( c [ i ] == '9' ) : NEW_LINE INDENT c [ i ] = '0' NEW_LINE DEDENT else : NEW_LINE INDENT t = ord ( c [ i ] ) - ord ( '0' ) + 1 NEW_LINE c [ i ] = chr ( 48 + t ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT s1 = " " . join ( c ) NEW_LINE if ( s1 [ 0 ] == '0' ) : NEW_LINE INDENT s1 = "1" + s1 NEW_LINE DEDENT return s1 NEW_LINE DEDENT s = "5748965412485599999874589965999" NEW_LINE n = len ( s ) NEW_LINE print ( Round ( s , n ) ) NEW_LINE |
Check whether given floating point number is even or odd | Function to check even or odd . ; Loop to traverse number from LSB ; We ignore trailing 0 s after dot ; If it is ' . ' we will check next digit and it means decimal part is traversed . ; If digit is divisible by 2 means even number . ; Driver Function | def isEven ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE dotSeen = False NEW_LINE for i in range ( l - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == '0' and dotSeen == False ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( s [ i ] == ' . ' ) : NEW_LINE INDENT dotSeen = True NEW_LINE continue NEW_LINE DEDENT if ( ( int ) ( s [ i ] ) % 2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT DEDENT s = "100.70" NEW_LINE if ( isEven ( s ) ) : NEW_LINE INDENT print ( " Even " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Odd " ) NEW_LINE DEDENT |
Minimum cost to construct a string | Python 3 Program to find minimum cost to construct a string ; Initially all characters are un - seen ; Marking seen characters ; Count total seen character , and that is the cost ; Driver Code ; s is the string that needs to be constructed | def minCost ( s ) : NEW_LINE INDENT alphabets = [ False for i in range ( 26 ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT alphabets [ ord ( s [ i ] ) - 97 ] = True NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( alphabets [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE print ( " Total β cost β to β construct " , s , " is " , minCost ( s ) ) NEW_LINE DEDENT |
Root to leaf paths having equal lengths in a Binary Tree | utility that allocates a newNode with the given key ; Function to store counts of different root to leaf path lengths in hash map m . ; Base condition ; If leaf node reached , increment count of path length of this root to leaf path . ; Recursively call for left and right subtrees with path lengths more than 1. ; A wrapper over pathCountUtil ( ) ; create an empty hash table ; Recursively check in left and right subtrees . ; Print all path lenghts and their counts . ; Driver Code | class newnode : 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 pathCountUtil ( node , m , path_len ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( node . left == None and node . right == None ) : NEW_LINE INDENT if path_len [ 0 ] not in m : NEW_LINE INDENT m [ path_len [ 0 ] ] = 0 NEW_LINE DEDENT m [ path_len [ 0 ] ] += 1 NEW_LINE return NEW_LINE DEDENT pathCountUtil ( node . left , m , [ path_len [ 0 ] + 1 ] ) NEW_LINE pathCountUtil ( node . right , m , [ path_len [ 0 ] + 1 ] ) NEW_LINE DEDENT def pathCounts ( root ) : NEW_LINE INDENT m = { } NEW_LINE path_len = [ 1 ] NEW_LINE pathCountUtil ( root , m , path_len ) NEW_LINE for itr in sorted ( m , reverse = True ) : NEW_LINE INDENT print ( m [ itr ] , " β paths β have β length β " , itr ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newnode ( 8 ) NEW_LINE root . left = newnode ( 5 ) NEW_LINE root . right = newnode ( 4 ) NEW_LINE root . left . left = newnode ( 9 ) NEW_LINE root . left . right = newnode ( 7 ) NEW_LINE root . right . right = newnode ( 11 ) NEW_LINE root . right . right . left = newnode ( 3 ) NEW_LINE pathCounts ( root ) NEW_LINE DEDENT |
Possibility of moving out of maze | Function to check whether it will stay inside or come out ; marks all the positions that is visited ; Initial starting point ; initial assumption is it comes out ; runs till it is inside or comes out ; if the movement is towards left then we move left . The start variable and mark that position as visited if not visited previously . Else we break out ; It will be inside forever ; If the movement is towards right , then we move right . The start variable and mark that position as visited if not visited previously else we break out ; it will be inside forever ; Driver code | def checkingPossibility ( a , n , s ) : NEW_LINE INDENT mark = [ 0 ] * n NEW_LINE start = 0 NEW_LINE possible = 1 NEW_LINE while start >= 0 and start < n : NEW_LINE INDENT if s [ start ] == " < " : NEW_LINE INDENT if mark [ start ] == 0 : NEW_LINE INDENT mark [ start ] = 1 NEW_LINE start -= a [ start ] NEW_LINE DEDENT else : NEW_LINE INDENT possible = 0 NEW_LINE break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if mark [ start ] == 0 : NEW_LINE INDENT mark [ start ] = 1 NEW_LINE start += a [ start ] NEW_LINE DEDENT else : NEW_LINE INDENT possible = 0 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if possible == 0 : NEW_LINE INDENT print " it β stays β inside β forever " NEW_LINE DEDENT else : NEW_LINE INDENT print " comes β out " NEW_LINE DEDENT DEDENT n = 2 NEW_LINE s = " > < " NEW_LINE a = [ 1 , 2 ] NEW_LINE checkingPossibility ( a , n , s ) NEW_LINE |
a | A iterative function that removes consecutive duplicates from string S ; We don 't need to do anything for empty or single character string. ; j is used to store index is result string ( or index of current distinct character ) ; Traversing string ; If current character S [ i ] is different from S [ j ] ; Driver Code | def removeDuplicates ( S ) : NEW_LINE INDENT n = len ( S ) NEW_LINE if ( n < 2 ) : NEW_LINE INDENT return NEW_LINE DEDENT j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( S [ j ] != S [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE S [ j ] = S [ i ] NEW_LINE DEDENT DEDENT j += 1 NEW_LINE S = S [ : j ] NEW_LINE return S NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S1 = " geeksforgeeks " NEW_LINE S1 = list ( S1 . rstrip ( ) ) NEW_LINE S1 = removeDuplicates ( S1 ) NEW_LINE print ( * S1 , sep = " " ) NEW_LINE S2 = " aabcca " NEW_LINE S2 = list ( S2 . rstrip ( ) ) NEW_LINE S2 = removeDuplicates ( S2 ) NEW_LINE print ( * S2 , sep = " " ) NEW_LINE DEDENT |
Simplify the directory path ( Unix like ) | function to simplify a Unix - styled absolute path ; using vector in place of stack ; forming the current directory . ; if " . . " , we pop . ; do nothing ( added for better understanding . ) ; push the current directory into the vector . ; forming the ans ; vector is empty ; absolute path which we have to simplify . | def simplify ( path ) : NEW_LINE INDENT v = [ ] NEW_LINE n = len ( path ) NEW_LINE ans = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT Dir = " " NEW_LINE while ( i < n and path [ i ] != ' / ' ) : NEW_LINE INDENT Dir += path [ i ] NEW_LINE i += 1 NEW_LINE DEDENT if ( Dir == " . . " ) : NEW_LINE INDENT if ( len ( v ) > 0 ) : NEW_LINE INDENT v . pop ( ) NEW_LINE DEDENT DEDENT elif ( Dir == " . " or Dir == " " ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( Dir ) NEW_LINE DEDENT DEDENT for i in v : NEW_LINE INDENT ans += " / " + i NEW_LINE DEDENT if ( ans == " " ) : NEW_LINE INDENT return " / " NEW_LINE DEDENT return ans NEW_LINE DEDENT Str = " / a / . / b / . . / . . / c / " NEW_LINE res = simplify ( Str ) NEW_LINE print ( res ) NEW_LINE |
Evaluate a boolean expression represented as string | Python3 program to evaluate value of an expression . ; Evaluates boolean expression and returns the result ; Traverse all operands by jumping a character after every iteration . ; If operator next to current operand is AND . ; If operator next to current operand is OR . ; If operator next to current operand is XOR ( Assuming a valid input ) ; Driver code | import math as mt NEW_LINE def evaluateBoolExpr ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( 0 , n - 2 , 2 ) : NEW_LINE INDENT if ( s [ i + 1 ] == " A " ) : NEW_LINE INDENT if ( s [ i + 2 ] == "0" or s [ i ] == "0" ) : NEW_LINE INDENT s [ i + 2 ] = "0" NEW_LINE DEDENT else : NEW_LINE INDENT s [ i + 2 ] = "1" NEW_LINE DEDENT DEDENT elif ( s [ i + 1 ] == " B " ) : NEW_LINE INDENT if ( s [ i + 2 ] == "1" or s [ i ] == "1" ) : NEW_LINE INDENT s [ i + 2 ] = "1" NEW_LINE DEDENT else : NEW_LINE INDENT s [ i + 2 ] = "0" NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( s [ i + 2 ] == s [ i ] ) : NEW_LINE INDENT s [ i + 2 ] = "0" NEW_LINE DEDENT else : NEW_LINE INDENT s [ i + 2 ] = "1" NEW_LINE DEDENT DEDENT DEDENT return ord ( s [ n - 1 ] ) - ord ( "0" ) NEW_LINE DEDENT s = "1C1B1B0A0" NEW_LINE string = [ s [ i ] for i in range ( len ( s ) ) ] NEW_LINE print ( evaluateBoolExpr ( string ) ) NEW_LINE |
Efficiently find first repeated character in a string without using any additional data structure in one traversal | Returns - 1 if all characters of str are unique . Assumptions : ( 1 ) str contains only characters from ' a ' to ' z ' ( 2 ) integers are stored using 32 bits ; An integer to store presence / absence of 26 characters using its 32 bits . ; If bit corresponding to current character is already set ; set bit in checker ; Driver code | def FirstRepeated ( string ) : NEW_LINE INDENT checker = 0 NEW_LINE pos = 0 NEW_LINE for i in string : NEW_LINE INDENT val = ord ( i ) - ord ( ' a ' ) ; NEW_LINE if ( ( checker & ( 1 << val ) ) > 0 ) : NEW_LINE INDENT return pos NEW_LINE DEDENT checker |= ( 1 << val ) NEW_LINE pos += 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT string = " abcfdeacf " NEW_LINE i = FirstRepeated ( string ) NEW_LINE if i != - 1 : NEW_LINE INDENT print " Char β = β " , string [ i ] , " β and β Index β = β " , i ; NEW_LINE DEDENT else : NEW_LINE INDENT print " No β repeated β Char " NEW_LINE DEDENT |
Check if a string is Pangrammatic Lipogram | collection of letters ; function to check for a Pangrammatic Lipogram ; ; variable to keep count of all the letters not found in the string ; traverses the string for every letter of the alphabet ; character not found in string then increment count ; Driver program to test above function | alphabets = ' abcdefghijklmnopqrstuvwxyz ' NEW_LINE def panLipogramChecker ( s ) : NEW_LINE / * convert string to lower case * / NEW_LINE INDENT s . lower ( ) NEW_LINE counter = 0 NEW_LINE for ch in alphabets : NEW_LINE INDENT if ( s . find ( ch ) < 0 ) : NEW_LINE INDENT counter += 1 NEW_LINE DEDENT DEDENT if ( counter == 0 ) : NEW_LINE INDENT result = " Pangram " NEW_LINE DEDENT elif ( counter == 1 ) : NEW_LINE INDENT result = " Pangrammatic β Lipogram " NEW_LINE DEDENT else : NEW_LINE INDENT result = " Not β a β pangram β but β might β a β lipogram " NEW_LINE DEDENT return result NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT print ( panLipogramChecker ( " The β quick β brown β fox β \ β jumped β over β the β lazy β dog " ) ) NEW_LINE print ( panLipogramChecker ( " The β quick β brown β fox β \ β jumps β over β the β lazy β dog " ) ) NEW_LINE print ( panLipogramChecker ( " The β quick β brown β fox β jum\ β over β the β lazy β dog " ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Lexicographically n | Function to print nth permutation using next_permute ( ) ; Sort the string in lexicographically ascending order ; Keep iterating until we reach nth position ; check for nth iteration ; print string after nth iteration ; next_permutation method implementation ; Driver Code | def nPermute ( string , n ) : NEW_LINE INDENT string = list ( string ) NEW_LINE new_string = [ ] NEW_LINE string . sort ( ) NEW_LINE j = 2 NEW_LINE while next_permutation ( string ) : NEW_LINE INDENT new_string = string NEW_LINE if j == n : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT print ( ' ' . join ( new_string ) ) NEW_LINE DEDENT def next_permutation ( L ) : NEW_LINE INDENT n = len ( L ) NEW_LINE i = n - 2 NEW_LINE while i >= 0 and L [ i ] >= L [ i + 1 ] : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT if i == - 1 : NEW_LINE INDENT return False NEW_LINE DEDENT j = i + 1 NEW_LINE while j < n and L [ j ] > L [ i ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT j -= 1 NEW_LINE L [ i ] , L [ j ] = L [ j ] , L [ i ] NEW_LINE left = i + 1 NEW_LINE right = n - 1 NEW_LINE while left < right : NEW_LINE INDENT L [ left ] , L [ right ] = L [ right ] , L [ left ] NEW_LINE left += 1 NEW_LINE right -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GEEKSFORGEEKS " NEW_LINE n = 100 NEW_LINE nPermute ( string , n ) NEW_LINE DEDENT |
Split numeric , alphabetic and special symbols from a String | Python 3 program to split an alphanumeric string using STL ; Driver code | def splitString ( str ) : NEW_LINE INDENT alpha = " " NEW_LINE num = " " NEW_LINE special = " " NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] . isdigit ( ) ) : NEW_LINE INDENT num = num + str [ i ] NEW_LINE DEDENT elif ( ( str [ i ] >= ' A ' and str [ i ] <= ' Z ' ) or ( str [ i ] >= ' a ' and str [ i ] <= ' z ' ) ) : NEW_LINE INDENT alpha += str [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT special += str [ i ] NEW_LINE DEDENT DEDENT print ( alpha ) NEW_LINE print ( num ) NEW_LINE print ( special ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeks01 $ $ for02geeks03 ! @ ! ! " NEW_LINE splitString ( str ) NEW_LINE DEDENT |
Program to print all substrings of a given string | Function to print all sub strings ; Pick starting point in outer loop and lengths of different strings for a given starting point ; Driver program to test above function | def subString ( s , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for len in range ( i + 1 , n + 1 ) : NEW_LINE INDENT print ( s [ i : len ] ) ; NEW_LINE DEDENT DEDENT DEDENT s = " abcd " ; NEW_LINE subString ( s , len ( s ) ) ; NEW_LINE |
Program to print all substrings of a given string | Python program for the above approach ; outermost for loop this is for the selection of starting point ; 2 nd for loop is for selection of ending point ; 3 rd loop is for printing from starting point to ending point ; changing the line after printing from starting point to ending point ; Driver Code ; calling the method to print the substring | def printSubstrings ( string , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT for k in range ( i , ( j + 1 ) ) : NEW_LINE INDENT print ( string [ k ] , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT DEDENT string = " abcd " NEW_LINE printSubstrings ( string , len ( string ) ) NEW_LINE |
Maximum Tip Calculator | Recursive function to calculate sum of maximum tip order taken by X and Y ; When all orders have been taken ; When X cannot take more orders ; When Y cannot take more orders ; When both can take order calculate maximum out of two ; Driver code | def solve ( i , X , Y , a , b , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( X <= 0 ) : NEW_LINE INDENT return ( b [ i ] + solve ( i + 1 , X , Y - 1 , a , b , n ) ) NEW_LINE DEDENT if ( Y <= 0 ) : NEW_LINE INDENT return ( a [ i ] + solve ( i + 1 , X - 1 , Y , a , b , n ) ) NEW_LINE DEDENT else : NEW_LINE INDENT return max ( a [ i ] + solve ( i + 1 , X - 1 , Y , a , b , n ) , b [ i ] + solve ( i + 1 , X , Y - 1 , a , b , n ) ) NEW_LINE DEDENT DEDENT a = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE b = [ 5 , 4 , 3 , 2 , 1 ] NEW_LINE n = len ( a ) NEW_LINE x = 3 NEW_LINE y = 3 NEW_LINE print ( solve ( 0 , x , y , a , b , n ) ) NEW_LINE |
Print Kth character in sorted concatenated substrings of a string | Structure to store information of a suffix ; To store original index ; To store ranks and next rank pair ; This is the main function that takes a string ' txt ' of size n as an argument , builds and return the suffix array for the given string ; A structure to store suffixes and their indexes ; Store suffixes and their indexes in an array of structures . The structure is needed to sort the suffixes alphabatically and maintain their old indexes while sorting ; Sort the suffixes using the comparison function defined above . ; At his point , all suffixes are sorted according to first 2 characters . Let us sort suffixes according to first 4 characters , then first 8 and so on ; This array is needed to get the index in suffixes [ ] from original index . This mapping is needed to get next suffix . ; Assigning rank and index values to first suffix ; Assigning rank to suffixes ; If first rank and next ranks are same as that of previous suffix in array , assign the same new rank to this suffix ; Otherwise increment rank and assign ; Assign next rank to every suffix ; Sort the suffixes according to first k characters ; Store indexes of all sorted suffixes in the suffix array ; Return the suffix array ; To construct and return LCP ; To store LCP array ; An auxiliary array to store inverse of suffix array elements . For example if suffixArr [ 0 ] is 5 , the invSuff [ 5 ] would store 0. This is used to get next suffix string from suffix array . ; Fill values in invSuff [ ] ; Initialize length of previous LCP ; Process all suffixes one by one starting from first suffix in txt [ ] ; If the current suffix is at n - 1 , then we dont have next substring to consider . So lcp is not defined for this substring , we put zero . ; j contains index of the next substring to be considered to compare with the present substring , i . e . , next string in suffix array ; Directly start matching from k 'th index as at-least k-1 characters will match ; Deleting the starting character from the string . ; Return the constructed lcp array ; Utility method to get sum of first N numbers ; Returns Kth character in sorted concatenated substrings of str ; Calculating suffix array and lcp array ; Skipping characters common to substring ( n - suffixArr [ i ] ) is length of current maximum substring lcp [ i ] will length of common substring ; If characters are more than K , that means Kth character belongs to substring corresponding to current lcp [ i ] ; Loop from current lcp value to current string length ; Again reduce K by current substring 's length one by one and when it becomes less, print Kth character of current substring ; Driver code | class suffix : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . index = 0 NEW_LINE self . rank = [ 0 ] * 2 NEW_LINE DEDENT DEDENT def buildSuffixArray ( txt : str , n : int ) -> list : NEW_LINE INDENT suffixes = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT suffixes [ i ] = suffix ( ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT suffixes [ i ] . index = i NEW_LINE suffixes [ i ] . rank [ 0 ] = ord ( txt [ i ] ) - ord ( ' a ' ) NEW_LINE suffixes [ i ] . rank [ 1 ] = ( ord ( txt [ i + 1 ] ) - ord ( ' a ' ) ) if ( ( i + 1 ) < n ) else - 1 NEW_LINE DEDENT suffixes . sort ( key = lambda a : a . rank ) NEW_LINE ind = [ 0 ] * n NEW_LINE k = 4 NEW_LINE while k < 2 * n : NEW_LINE INDENT k *= 2 NEW_LINE rank = 0 NEW_LINE prev_rank = suffixes [ 0 ] . rank [ 0 ] NEW_LINE suffixes [ 0 ] . rank [ 0 ] = rank NEW_LINE ind [ suffixes [ 0 ] . index ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( suffixes [ i ] . rank [ 0 ] == prev_rank and suffixes [ i ] . rank [ 1 ] == suffixes [ i - 1 ] . rank [ 1 ] ) : NEW_LINE INDENT prev_rank = suffixes [ i ] . rank [ 0 ] NEW_LINE suffixes [ i ] . rank [ 0 ] = rank NEW_LINE DEDENT else : NEW_LINE INDENT prev_rank = suffixes [ i ] . rank [ 0 ] NEW_LINE rank += 1 NEW_LINE suffixes [ i ] . rank [ 0 ] = rank NEW_LINE DEDENT ind [ suffixes [ i ] . index ] = i NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT nextindex = suffixes [ i ] . index + k // 2 NEW_LINE suffixes [ i ] . rank [ 1 ] = suffixes [ ind [ nextindex ] ] . rank [ 0 ] if ( nextindex < n ) else - 1 NEW_LINE DEDENT suffixes . sort ( key = lambda a : a . rank ) NEW_LINE DEDENT suffixArr = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT suffixArr . append ( suffixes [ i ] . index ) NEW_LINE DEDENT return suffixArr NEW_LINE DEDENT def kasai ( txt : str , suffixArr : list ) -> list : NEW_LINE INDENT n = len ( suffixArr ) NEW_LINE lcp = [ 0 ] * n NEW_LINE invSuff = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT invSuff [ suffixArr [ i ] ] = i NEW_LINE DEDENT k = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( invSuff [ i ] == n - 1 ) : NEW_LINE INDENT k = 0 NEW_LINE continue NEW_LINE DEDENT j = suffixArr [ invSuff [ i ] + 1 ] NEW_LINE while ( i + k < n and j + k < n and txt [ i + k ] == txt [ j + k ] ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT lcp [ invSuff [ i ] ] = k NEW_LINE if ( k > 0 ) : NEW_LINE INDENT k -= 1 NEW_LINE DEDENT DEDENT return lcp NEW_LINE DEDENT def sumOfFirstN ( N : int ) -> int : NEW_LINE INDENT return ( N * ( N + 1 ) ) // 2 NEW_LINE DEDENT def printKthCharInConcatSubstring ( string : str , K : int ) -> str : NEW_LINE INDENT n = len ( string ) NEW_LINE suffixArr = buildSuffixArray ( string , n ) NEW_LINE lcp = kasai ( string , suffixArr ) NEW_LINE for i in range ( len ( lcp ) ) : NEW_LINE INDENT charToSkip = ( sumOfFirstN ( n - suffixArr [ i ] ) - sumOfFirstN ( lcp [ i ] ) ) NEW_LINE if ( K <= charToSkip ) : NEW_LINE INDENT for j in range ( lcp [ i ] + 1 , ( n - suffixArr [ i ] ) + 1 ) : NEW_LINE INDENT curSubstringLen = j NEW_LINE if ( K <= curSubstringLen ) : NEW_LINE INDENT return string [ ( suffixArr [ i ] + K - 1 ) ] NEW_LINE DEDENT else : NEW_LINE INDENT K -= curSubstringLen NEW_LINE DEDENT DEDENT break NEW_LINE DEDENT else : NEW_LINE INDENT K -= charToSkip NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " banana " NEW_LINE K = 10 NEW_LINE print ( printKthCharInConcatSubstring ( string , K ) ) NEW_LINE DEDENT |
Number of even substrings in a string of digits | Return the even number substrings . ; If current digit is even , add count of substrings ending with it . The count is ( i + 1 ) ; Driven Program | def evenNumSubstring ( str ) : NEW_LINE INDENT length = len ( str ) NEW_LINE count = 0 NEW_LINE for i in range ( 0 , length , 1 ) : NEW_LINE INDENT temp = ord ( str [ i ] ) - ord ( '0' ) NEW_LINE if ( temp % 2 == 0 ) : NEW_LINE INDENT count += ( i + 1 ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = [ '1' , '2' , '3' , '4' ] NEW_LINE print ( evenNumSubstring ( str ) ) NEW_LINE DEDENT |
Maximum Consecutive Increasing Path Length in Binary Tree | A binary tree node ; Returns the maximum consecutive path length ; Get the vlue of current node The value of the current node will be prev node for its left and right children ; If current node has to be a part of the consecutive path then it should be 1 greater thn the value of the previous node ; a ) Find the length of the left path b ) Find the length of the right path Return the maximum of left path and right path ; Find the length of the maximum path under subtree rooted with this node ; Take the maximum previous path and path under subtree rooted with this node ; A Wrapper over maxPathLenUtil ( ) ; Return 0 if root is None ; Else compute maximum consecutive increasing path length using maxPathLenUtil ; Driver program to test above function | class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def maxPathLenUtil ( root , prev_val , prev_len ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return prev_len NEW_LINE DEDENT curr_val = root . val NEW_LINE if curr_val == prev_val + 1 : NEW_LINE INDENT return max ( maxPathLenUtil ( root . left , curr_val , prev_len + 1 ) , maxPathLenUtil ( root . right , curr_val , prev_len + 1 ) ) NEW_LINE DEDENT newPathLen = max ( maxPathLenUtil ( root . left , curr_val , 1 ) , maxPathLenUtil ( root . right , curr_val , 1 ) ) NEW_LINE return max ( prev_len , newPathLen ) NEW_LINE DEDENT def maxConsecutivePathLength ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return maxPathLenUtil ( root , root . val - 1 , 0 ) NEW_LINE DEDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 11 ) NEW_LINE root . right = Node ( 9 ) NEW_LINE root . left . left = Node ( 13 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . right . left = Node ( 13 ) NEW_LINE root . right . right = Node ( 8 ) NEW_LINE print " Maximum β Consecutive β Increasing β Path β Length β is " , NEW_LINE print maxConsecutivePathLength ( root ) NEW_LINE |
Find largest word in dictionary by deleting some characters of given string | Returns true if str1 [ ] is a subsequence of str2 [ ] . m is length of str1 and n is length of str2 ; Traverse str2 and str1 , and compare current character of str2 with first unmatched char of str1 , if matched then move ahead in str1 ; If all characters of str1 were found in str2 ; Returns the longest string in dictionary which is a subsequence of str . ; Traverse through all words of dictionary ; If current word is subsequence of str and is largest such word so far . ; Return longest string ; Driver program to test above function | def isSubSequence ( str1 , str2 ) : NEW_LINE INDENT m = len ( str1 ) ; NEW_LINE n = len ( str2 ) ; NEW_LINE i = 0 ; NEW_LINE while ( i < n and j < m ) : NEW_LINE INDENT if ( str1 [ j ] == str2 [ i ] ) : NEW_LINE INDENT j += 1 ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT return ( j == m ) ; NEW_LINE DEDENT def findLongestString ( dict1 , str1 ) : NEW_LINE INDENT result = " " ; NEW_LINE length = 0 ; NEW_LINE for word in dict1 : NEW_LINE INDENT if ( length < len ( word ) and isSubSequence ( word , str1 ) ) : NEW_LINE INDENT result = word ; NEW_LINE length = len ( word ) ; NEW_LINE DEDENT DEDENT return result ; NEW_LINE DEDENT dict1 = [ " ale " , " apple " , " monkey " , " plea " ] ; NEW_LINE str1 = " abpcplea " ; NEW_LINE print ( findLongestString ( dict1 , str1 ) ) ; NEW_LINE |
XOR Cipher | The same function is used to encrypt and decrypt ; Define XOR key Any character value will work ; calculate length of input string ; perform XOR operation of key with every character in string ; Driver Code ; Encrypt the string ; Decrypt the string | def encryptDecrypt ( inpString ) : NEW_LINE INDENT xorKey = ' P ' ; NEW_LINE length = len ( inpString ) ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT inpString = ( inpString [ : i ] + chr ( ord ( inpString [ i ] ) ^ ord ( xorKey ) ) + inpString [ i + 1 : ] ) ; NEW_LINE print ( inpString [ i ] , end = " " ) ; NEW_LINE DEDENT return inpString ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT sampleString = " GeeksforGeeks " ; NEW_LINE print ( " Encrypted β String : β " , end = " " ) ; NEW_LINE sampleString = encryptDecrypt ( sampleString ) ; NEW_LINE print ( " " ) ; NEW_LINE print ( " Decrypted β String : β " , end = " " ) ; NEW_LINE encryptDecrypt ( sampleString ) ; NEW_LINE DEDENT |
Repeated subsequence of length 2 or more | Python3 program to check if any repeated subsequence exists in the String ; A function to check if a String Str is palindrome ; l and h are leftmost and rightmost corners of Str Keep comparing characters while they are same ; The main function that checks if repeated subsequence exists in the String ; Find length of input String ; Create an array to store all characters and their frequencies in Str [ ] ; Traverse the input String and store frequencies of all characters in freq [ ] array . ; If the character count is more than 2 we found a repetition ; In - place remove non - repeating characters from the String ; check if the resultant String is palindrome ; special case - if length is odd return true if the middle character is same as previous one ; return false if String is a palindrome ; return true if String is not a palindrome ; Driver code | MAX_CHAR = 256 NEW_LINE def isPalindrome ( Str , l , h ) : NEW_LINE INDENT while ( h > l ) : NEW_LINE INDENT if ( Str [ l ] != Str [ h ] ) : NEW_LINE INDENT l += 1 NEW_LINE h -= 1 NEW_LINE return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def check ( Str ) : NEW_LINE INDENT n = len ( Str ) NEW_LINE freq = [ 0 for i in range ( MAX_CHAR ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( Str [ i ] ) ] += 1 NEW_LINE if ( freq [ ord ( Str [ i ] ) ] > 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT k = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( freq [ ord ( Str [ i ] ) ] > 1 ) : NEW_LINE INDENT Str [ k ] = Str [ i ] NEW_LINE k += 1 NEW_LINE DEDENT DEDENT Str [ k ] = ' \0' NEW_LINE if ( isPalindrome ( Str , 0 , k - 1 ) ) : NEW_LINE INDENT if ( k & 1 ) : NEW_LINE INDENT return Str [ k // 2 ] == Str [ k // 2 - 1 ] NEW_LINE DEDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT S = " ABCABD " NEW_LINE Str = [ i for i in S ] NEW_LINE if ( check ( Str ) ) : NEW_LINE INDENT print ( " Repeated β Subsequence β Exists " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Repeated β Subsequence β Doesn ' t β Exists " ) NEW_LINE DEDENT |
How to find Lexicographically previous permutation ? | Function to compute the previous permutation ; Find index of the last element of the string ; Find largest index i such that str [ i - 1 ] > str [ i ] ; if string is sorted in ascending order we 're at the last permutation ; Note - str [ i . . n ] is sorted in ascending order . Find rightmost element 's index that is less than str[i - 1] ; Swap character at i - 1 with j ; Reverse the substring [ i . . n ] ; Driver code | def prevPermutation ( str ) : NEW_LINE INDENT n = len ( str ) - 1 NEW_LINE i = n NEW_LINE while ( i > 0 and str [ i - 1 ] <= str [ i ] ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT if ( i <= 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT j = i - 1 NEW_LINE while ( j + 1 <= n and str [ j + 1 ] <= str [ i - 1 ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT str = list ( str ) NEW_LINE temp = str [ i - 1 ] NEW_LINE str [ i - 1 ] = str [ j ] NEW_LINE str [ j ] = temp NEW_LINE str = ' ' . join ( str ) NEW_LINE str [ : : - 1 ] NEW_LINE return True , str NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "4321" NEW_LINE b , str = prevPermutation ( str ) NEW_LINE if ( b == True ) : NEW_LINE INDENT print ( " Previous β permutation β is " , str ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Previous β permutation β doesn ' t β exist " ) NEW_LINE DEDENT DEDENT |
Longest Path with Same Values in a Binary Tree | Function to print the longest path of same values ; Recursive calls to check for subtrees ; Variables to store maximum lengths in two directions ; If curr node and it 's left child has same value ; If curr node and it 's right child has same value ; Driver function to find length of longest same value path ; Helper function that allocates a new node with the given data and None left and right pointers . ; Driver code ; Let us construct a Binary Tree 4 / \ 4 4 / \ \ 4 9 5 | def length ( node , ans ) : NEW_LINE INDENT if ( not node ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT left = length ( node . left , ans ) NEW_LINE right = length ( node . right , ans ) NEW_LINE Leftmax = 0 NEW_LINE Rightmax = 0 NEW_LINE if ( node . left and node . left . val == node . val ) : NEW_LINE INDENT Leftmax += left + 1 NEW_LINE DEDENT if ( node . right and node . right . val == node . val ) : NEW_LINE INDENT Rightmax += right + 1 NEW_LINE DEDENT ans [ 0 ] = max ( ans [ 0 ] , Leftmax + Rightmax ) NEW_LINE return max ( Leftmax , Rightmax ) NEW_LINE DEDENT def longestSameValuePath ( root ) : NEW_LINE INDENT ans = [ 0 ] NEW_LINE length ( root , ans ) NEW_LINE return ans [ 0 ] NEW_LINE DEDENT class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . val = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = newNode ( 4 ) NEW_LINE root . left = newNode ( 4 ) NEW_LINE root . right = newNode ( 4 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 9 ) NEW_LINE root . right . right = newNode ( 5 ) NEW_LINE print ( longestSameValuePath ( root ) ) NEW_LINE DEDENT |
Check if edit distance between two strings is one | Returns true if edit distance between s1 and s2 is one , else false ; Find lengths of given strings ; If difference between lengths is more than 1 , then strings can 't be at one distance ; count = 0 Count of isEditDistanceOne ; If current characters dont match ; If length of one string is more , then only possible edit is to remove a character ; else : If lengths of both strings is same ; Increment count of edits ; else : if current characters match ; if last character is extra in any string ; Driver program | def isEditDistanceOne ( s1 , s2 ) : NEW_LINE INDENT m = len ( s1 ) NEW_LINE n = len ( s2 ) NEW_LINE if abs ( m - n ) > 1 : NEW_LINE INDENT return false NEW_LINE DEDENT i = 0 NEW_LINE j = 0 NEW_LINE while i < m and j < n : NEW_LINE INDENT if s1 [ i ] != s2 [ j ] : NEW_LINE INDENT if count == 1 : NEW_LINE INDENT return false NEW_LINE DEDENT if m > n : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif m < n : NEW_LINE INDENT j += 1 NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT count += 1 NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT if i < m or j < n : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count == 1 NEW_LINE DEDENT s1 = " gfg " NEW_LINE s2 = " gf " NEW_LINE if isEditDistanceOne ( s1 , s2 ) : NEW_LINE INDENT print " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT print " No " NEW_LINE DEDENT |
Count of numbers from range [ L , R ] whose sum of digits is Y | Set 2 | Python program for the above approach ; Function to find the sum of digits of numbers in the range [ 0 , X ] ; Check if count of digits in a number greater than count of digits in X ; Check if sum of digits of a number is equal to Y ; Check if current subproblem has already been comrputed ; Stores count of numbers whose sum of digits is Y ; Check if the number exceeds Y or not ; Iterate over all possible values of i - th digits ; Update res ; Return res ; Utility function to count the numbers in the range [ L , R ] whose sum of digits is Y ; Base Case ; Stores numbers in the form of its equivalent ; Stores overlapping subproblems ; Stores count of numbers in the range [ 0 , R ] ; Update str ; Stores count of numbers in the range [ 0 , L - 1 ] ; Driver Code | M = 1000 NEW_LINE def cntNum ( X , i , sum , tight , dp ) : NEW_LINE INDENT if ( i >= len ( X ) or sum < 0 ) : NEW_LINE INDENT if ( sum == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( dp [ sum ] [ i ] [ tight ] != - 1 ) : NEW_LINE INDENT return dp [ sum ] [ i ] [ tight ] NEW_LINE DEDENT res , end = 0 , 9 NEW_LINE if tight : NEW_LINE INDENT end = ord ( X [ i ] ) - ord ( '0' ) NEW_LINE DEDENT for j in range ( end + 1 ) : NEW_LINE INDENT res += cntNum ( X , i + 1 , sum - j , ( tight & ( j == end ) ) , dp ) NEW_LINE DEDENT dp [ sum ] [ i ] [ tight ] = res NEW_LINE return res NEW_LINE DEDENT def UtilCntNumRange ( L , R , Y ) : NEW_LINE INDENT if ( R == 0 and Y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT strr = str ( R ) NEW_LINE dp = [ [ [ - 1 for i in range ( 2 ) ] for i in range ( M ) ] for i in range ( M ) ] NEW_LINE cntR = cntNum ( strr , 0 , Y , True , dp ) NEW_LINE strr = str ( L - 1 ) NEW_LINE cntL = cntNum ( strr , 0 , Y , True , dp ) NEW_LINE return ( cntR - cntL ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R , Y = 20 , 10000 , 14 NEW_LINE print ( UtilCntNumRange ( L , R , Y ) ) NEW_LINE DEDENT |
Remove spaces from a given string | Function to remove all spaces from a given string ; Driver program | def removeSpaces ( string ) : NEW_LINE INDENT string = string . replace ( ' β ' , ' ' ) NEW_LINE return string NEW_LINE DEDENT string = " g β eeks β for β ge β eeks β " NEW_LINE print ( removeSpaces ( string ) ) NEW_LINE |
Given a binary string , count number of substrings that start and end with 1. | A simple Python 3 program to count number of substrings starting and ending with 1 ; Initialize result ; Pick a starting point ; Search for all possible ending point ; Driver program to test above function | def countSubStr ( st , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( st [ i ] == '1' ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( st [ j ] == '1' ) : NEW_LINE INDENT res = res + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return res NEW_LINE DEDENT st = "00100101" ; NEW_LINE list ( st ) NEW_LINE n = len ( st ) NEW_LINE print ( countSubStr ( st , n ) , end = " " ) NEW_LINE |
An in | A utility function to reverse string str [ low . . high ] ; Cycle leader algorithm to move all even positioned elements at the end . ; odd index ; even index ; keep the back - up of element at new position ; The main function to transform a string . This function mainly uses cycleLeader ( ) to transform ; Step 1 : Find the largest prefix subarray of the form 3 ^ k + 1 ; Step 2 : Apply cycle leader algorithm for the largest subarrau ; Step 4.1 : Reverse the second half of first subarray ; Step 4.2 : Reverse the first half of second sub - string ; Step 4.3 Reverse the second half of first sub - string and first half of second sub - string together ; Increase the length of first subarray ; Driver Code | def Reverse ( string : list , low : int , high : int ) : NEW_LINE INDENT while low < high : NEW_LINE INDENT string [ low ] , string [ high ] = string [ high ] , string [ low ] NEW_LINE low += 1 NEW_LINE high -= 1 NEW_LINE DEDENT DEDENT def cycleLeader ( string : list , shift : int , len : int ) : NEW_LINE INDENT i = 1 NEW_LINE while i < len : NEW_LINE INDENT j = i NEW_LINE item = string [ j + shift ] NEW_LINE while True : NEW_LINE INDENT if j & 1 : NEW_LINE INDENT j = len // 2 + j // 2 NEW_LINE DEDENT else : NEW_LINE INDENT j //= 2 NEW_LINE DEDENT string [ j + shift ] , item = item , string [ j + shift ] NEW_LINE if j == i : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT i *= 3 NEW_LINE DEDENT DEDENT def moveNumberToSecondHalf ( string : list ) : NEW_LINE INDENT k , lenFirst = 0 , 0 NEW_LINE lenRemaining = len ( string ) NEW_LINE shift = 0 NEW_LINE while lenRemaining : NEW_LINE INDENT k = 0 NEW_LINE while pow ( 3 , k ) + 1 <= lenRemaining : NEW_LINE INDENT k += 1 NEW_LINE DEDENT lenFirst = pow ( 3 , k - 1 ) + 1 NEW_LINE lenRemaining -= lenFirst NEW_LINE cycleLeader ( string , shift , lenFirst ) NEW_LINE Reverse ( string , shift // 2 , shift - 1 ) NEW_LINE Reverse ( string , shift , shift + lenFirst // 2 - 1 ) NEW_LINE Reverse ( string , shift // 2 , shift + lenFirst // 2 - 1 ) NEW_LINE shift += lenFirst NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " a1b2c3d4e5f6g7" NEW_LINE string = list ( string ) NEW_LINE moveNumberToSecondHalf ( string ) NEW_LINE print ( ' ' . join ( string ) ) NEW_LINE DEDENT |
Remove nodes on root to leaf paths of length < K | New node of a tree ; Utility method that actually removes the nodes which are not on the pathLen >= k . This method can change the root as well . ; Base condition ; Traverse the tree in postorder fashion so that if a leaf node path length is shorter than k , then that node and all of its descendants till the node which are not on some other path are removed . ; If root is a leaf node and it 's level is less than k then remove this node. This goes up and check for the ancestor nodes also for the same condition till it finds a node which is a part of other path(s) too. ; Return root ; Method which calls the utitlity method to remove the short path nodes . ; Method to print the tree in inorder fashion . ; Driver Code | 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 removeShortPathNodesUtil ( root , level , k ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT root . left = removeShortPathNodesUtil ( root . left , level + 1 , k ) NEW_LINE root . right = removeShortPathNodesUtil ( root . right , level + 1 , k ) NEW_LINE if ( root . left == None and root . right == None and level < k ) : NEW_LINE INDENT return None NEW_LINE DEDENT return root NEW_LINE DEDENT def removeShortPathNodes ( root , k ) : NEW_LINE INDENT pathLen = 0 NEW_LINE return removeShortPathNodesUtil ( root , 1 , k ) NEW_LINE DEDENT def prInorder ( root ) : NEW_LINE INDENT if ( root ) : NEW_LINE INDENT prInorder ( root . left ) NEW_LINE print ( root . data , end = " β " ) NEW_LINE prInorder ( root . right ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 4 NEW_LINE 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 . left . left . left = newNode ( 7 ) NEW_LINE root . right . right = newNode ( 6 ) NEW_LINE root . right . right . left = newNode ( 8 ) NEW_LINE print ( " Inorder β Traversal β of β Original β tree " ) NEW_LINE prInorder ( root ) NEW_LINE print ( ) NEW_LINE print ( " Inorder β Traversal β of β Modified β tree " ) NEW_LINE res = removeShortPathNodes ( root , k ) NEW_LINE prInorder ( res ) NEW_LINE DEDENT |
Remove duplicates from a given string | Python program to remove duplicate character from character array and print in sorted order ; Create a set using String characters ; Print content of the set ; Driver code | def removeDuplicate ( str , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in str : NEW_LINE INDENT s . add ( i ) NEW_LINE DEDENT st = " " NEW_LINE for i in s : NEW_LINE INDENT st = st + i NEW_LINE DEDENT return st NEW_LINE DEDENT str = " geeksforgeeks " NEW_LINE n = len ( str ) NEW_LINE print ( removeDuplicate ( list ( str ) , n ) ) NEW_LINE |
Shortest path from a source cell to a destination cell of a Binary Matrix through cells consisting only of 1 s | Python3 program for the above approach ; Stores the coordinates of the matrix cell ; Stores coordinates of a cell and its distance ; Check if the given cell is valid or not ; Stores the moves of the directions of adjacent cells ; Function to find the shortest path from the source to destination in the given matrix ; Stores the distance for each cell from the source cell ; Distance of source cell is 0 ; Initialize a visited array ; Mark source cell as visited ; Create a queue for BFS ; Distance of source cell is 0 ; Enqueue source cell ; Keeps track of whether destination is reached or not ; Iterate until queue is not empty ; Deque front of the queue ; If the destination cell is reached , then find the path ; Assign the distance of destination to the distance matrix ; Stores the smallest path ; Iterate until source is reached ; Append D ; Append U ; Append R ; Append L ; Reverse the backtracked path ; Explore all adjacent directions ; If the current cell is valid cell and can be traversed ; Mark the adjacent cells as visited ; Enque the adjacent cells ; Update the distance of the adjacent cells ; If the destination is not reachable ; Driver Code | from collections import deque NEW_LINE class Point : NEW_LINE INDENT def __init__ ( self , xx , yy ) : NEW_LINE INDENT self . x = xx NEW_LINE self . y = yy NEW_LINE DEDENT DEDENT class Node : NEW_LINE INDENT def __init__ ( self , P , d ) : NEW_LINE INDENT self . pt = P NEW_LINE self . dist = d NEW_LINE DEDENT DEDENT def isValid ( row , col ) : NEW_LINE INDENT return ( row >= 0 ) and ( col >= 0 ) and ( row < 4 ) and ( col < 4 ) NEW_LINE DEDENT dRow = [ - 1 , 0 , 0 , 1 ] NEW_LINE dCol = [ 0 , - 1 , 1 , 0 ] NEW_LINE def pathMoves ( mat , src , dest ) : NEW_LINE INDENT d = [ [ - 1 for i in range ( 4 ) ] for i in range ( 4 ) ] NEW_LINE d [ src . x ] [ src . y ] = 0 NEW_LINE visited = [ [ False for i in range ( 4 ) ] for i in range ( 4 ) ] NEW_LINE visited [ src . x ] [ src . y ] = True NEW_LINE q = deque ( ) NEW_LINE s = Node ( src , 0 ) NEW_LINE q . append ( s ) NEW_LINE ok = False NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT curr = q . popleft ( ) NEW_LINE pt = curr . pt NEW_LINE if ( pt . x == dest . x and pt . y == dest . y ) : NEW_LINE INDENT xx , yy = pt . x , pt . y NEW_LINE dist = curr . dist NEW_LINE d [ pt . x ] [ pt . y ] = dist NEW_LINE pathmoves = " " NEW_LINE while ( xx != src . x or yy != src . y ) : NEW_LINE INDENT if ( xx > 0 and d [ xx - 1 ] [ yy ] == dist - 1 ) : NEW_LINE INDENT pathmoves += ' D ' NEW_LINE xx -= 1 NEW_LINE DEDENT if ( xx < 4 - 1 and d [ xx + 1 ] [ yy ] == dist - 1 ) : NEW_LINE INDENT pathmoves += ' U ' NEW_LINE xx += 1 NEW_LINE DEDENT if ( yy > 0 and d [ xx ] [ yy - 1 ] == dist - 1 ) : NEW_LINE INDENT pathmoves += ' R ' NEW_LINE yy -= 1 NEW_LINE DEDENT if ( yy < 4 - 1 and d [ xx ] [ yy + 1 ] == dist - 1 ) : NEW_LINE INDENT pathmoves += ' L ' NEW_LINE yy += 1 NEW_LINE DEDENT dist -= 1 NEW_LINE DEDENT pathmoves = pathmoves [ : : - 1 ] NEW_LINE print ( pathmoves , end = " " ) NEW_LINE ok = True NEW_LINE break NEW_LINE DEDENT for i in range ( 4 ) : NEW_LINE INDENT row = pt . x + dRow [ i ] NEW_LINE col = pt . y + dCol [ i ] NEW_LINE if ( isValid ( row , col ) and ( mat [ row ] [ col ] == '1' or mat [ row ] [ col ] == ' s ' or mat [ row ] [ col ] == ' d ' ) and ( not visited [ row ] [ col ] ) ) : NEW_LINE INDENT visited [ row ] [ col ] = True NEW_LINE adjCell = Node ( Point ( row , col ) , curr . dist + 1 ) NEW_LINE q . append ( adjCell ) NEW_LINE d [ row ] [ col ] = curr . dist + 1 NEW_LINE DEDENT DEDENT DEDENT if ( not ok ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ '0' , '1' , '0' , '1' ] , [ '1' , '0' , '1' , '1' ] , [ '0' , '1' , '1' , '1' ] , [ '1' , '1' , '1' , '0' ] ] NEW_LINE src = Point ( 0 , 3 ) NEW_LINE dest = Point ( 3 , 0 ) NEW_LINE pathMoves ( mat , src , dest ) NEW_LINE DEDENT |
Check if any King is unsafe on the Chessboard or not | Function to check if any of the two kings is unsafe or not ; Find the position of both the kings ; Check for all pieces which can attack White King ; Check for Knight ; Check for Pawn ; Check for Rook ; Check for Bishop ; Check for Queen ; Check for King ; Check for all pieces which can attack Black King ; Check for Knight ; Check for Pawn ; Check for Rook ; Check for Bishop ; Check for Queen ; Check for King ; Store all possible moves of the king ; incrementing index values ; checking boundary conditions and character match ; Function to check if Queen can attack the King ; Queen 's moves are a combination of both the Bishop and the Rook ; Function to check if bishop can attack the king ; Check the lower right diagonal ; Check the lower left diagonal ; Check the upper right diagonal ; Check the upper left diagonal ; Check if ; Check downwards ; Check upwards ; Check right ; Check left ; Check if the knight can attack the king ; All possible moves of the knight ; Incrementing index values ; Checking boundary conditions and character match ; Function to check if pawn can attack the king ; Check for white pawn ; Check for black pawn ; Check if the indices are within the matrix or not ; Checking boundary conditions ; Chessboard instance | def checkBoard ( board ) : NEW_LINE INDENT for i in range ( 8 ) : NEW_LINE INDENT for j in range ( 8 ) : NEW_LINE INDENT if board [ i ] [ j ] == ' k ' : NEW_LINE INDENT if lookForn ( board , ' N ' , i , j ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if lookForp ( board , ' P ' , i , j ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if lookForr ( board , ' R ' , i , j ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if lookForb ( board , ' B ' , i , j ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if lookForq ( board , ' Q ' , i , j ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if lookFork ( board , ' K ' , i , j ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT if board [ i ] [ j ] == ' K ' : NEW_LINE INDENT if lookForn ( board , ' n ' , i , j ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT if lookForp ( board , ' p ' , i , j ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT if lookForr ( board , ' r ' , i , j ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT if lookForb ( board , ' b ' , i , j ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT if lookForq ( board , ' q ' , i , j ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT if lookFork ( board , ' k ' , i , j ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT DEDENT DEDENT DEDENT return 1 NEW_LINE DEDENT def lookFork ( board , c , i , j ) : NEW_LINE INDENT x = [ - 1 , - 1 , - 1 , 0 , 0 , 1 , 1 , 1 ] NEW_LINE y = [ - 1 , 0 , 1 , - 1 , 1 , - 1 , 0 , 1 ] NEW_LINE for k in range ( 8 ) : NEW_LINE INDENT m = i + x [ k ] NEW_LINE n = j + y [ k ] NEW_LINE if inBounds ( m , n ) and board [ m ] [ n ] == c : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def lookForq ( board , c , i , j ) : NEW_LINE INDENT if lookForb ( board , c , i , j ) or lookForr ( board , c , i , j ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def lookForb ( board , c , i , j ) : NEW_LINE INDENT k = 0 NEW_LINE while inBounds ( i + + + k , j + k ) : NEW_LINE INDENT if board [ i + k ] [ j + k ] == c : NEW_LINE INDENT return True NEW_LINE DEDENT if board [ i + k ] [ j + k ] != ' - ' : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT k = 0 NEW_LINE while inBounds ( i + + + k , j - k ) : NEW_LINE INDENT if board [ i + k ] [ j - k ] == c : NEW_LINE INDENT return True NEW_LINE DEDENT if board [ i + k ] [ j - k ] != ' - ' : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT k = 0 NEW_LINE while inBounds ( i - + + k , j + k ) : NEW_LINE INDENT if board [ i - k ] [ j + k ] == c : NEW_LINE INDENT return True NEW_LINE DEDENT if board [ i - k ] [ j + k ] != ' - ' : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT k = 0 NEW_LINE while inBounds ( i - + + k , j - k ) : NEW_LINE INDENT if board [ i - k ] [ j - k ] == c : NEW_LINE INDENT return True NEW_LINE DEDENT if board [ i - k ] [ j - k ] != ' - ' : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def lookForr ( board , c , i , j ) : NEW_LINE INDENT k = 0 NEW_LINE while inBounds ( i + + + k , j ) : NEW_LINE INDENT if board [ i + k ] [ j ] == c : NEW_LINE INDENT return True NEW_LINE DEDENT if board [ i + k ] [ j ] != ' - ' : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT k = 0 NEW_LINE while inBounds ( i + - - k , j ) : NEW_LINE INDENT if board [ i + k ] [ j ] == c : NEW_LINE INDENT return True NEW_LINE DEDENT if board [ i + k ] [ j ] != ' - ' : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT k = 0 NEW_LINE while inBounds ( i , j + + + k ) : NEW_LINE INDENT if board [ i ] [ j + k ] == c : NEW_LINE INDENT return True NEW_LINE DEDENT if board [ i ] [ j + k ] != ' - ' : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT k = 0 NEW_LINE while inBounds ( i , j + - - k ) : NEW_LINE INDENT if board [ i ] [ j + k ] == c : NEW_LINE INDENT return True NEW_LINE DEDENT if board [ i ] [ j + k ] != ' - ' : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def lookForn ( board , c , i , j ) : NEW_LINE INDENT x = [ 2 , 2 , - 2 , - 2 , 1 , 1 , - 1 , - 1 ] NEW_LINE y = [ 1 , - 1 , 1 , - 1 , 2 , - 2 , 2 , - 2 ] NEW_LINE for k in range ( 8 ) : NEW_LINE INDENT m = i + x [ k ] NEW_LINE n = j + y [ k ] NEW_LINE if inBounds ( m , n ) and board [ m ] [ n ] == c : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def lookForp ( board , c , i , j ) : NEW_LINE INDENT if ord ( c ) >= 65 and ord ( c ) <= 90 : NEW_LINE INDENT lookFor = ' P ' NEW_LINE if inBounds ( i + 1 , j - 1 ) and board [ i + 1 ] [ j - 1 ] == lookFor : NEW_LINE INDENT return True NEW_LINE DEDENT if inBounds ( i + 1 , j + 1 ) and board [ i + 1 ] [ j + 1 ] == lookFor : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT lookFor = ' p ' NEW_LINE if inBounds ( i - 1 , j - 1 ) and board [ i - 1 ] [ j - 1 ] == lookFor : NEW_LINE INDENT return True NEW_LINE DEDENT if inBounds ( i - 1 , j + 1 ) and board [ i - 1 ] [ j + 1 ] == lookFor : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def inBounds ( i , j ) : NEW_LINE INDENT return i >= 0 and i < 8 and j >= 0 and j < 8 NEW_LINE DEDENT board = [ [ ' - ' , ' - ' , ' - ' , ' k ' , ' - ' , ' - ' , ' - ' , ' - ' ] , [ ' p ' , ' p ' , ' p ' , ' - ' , ' p ' , ' p ' , ' p ' , ' p ' ] , [ ' - ' , ' - ' , ' - ' , ' - ' , ' - ' , ' b ' , ' - ' , ' - ' ] , [ ' - ' , ' - ' , ' - ' , ' R ' , ' - ' , ' - ' , ' - ' , ' - ' ] , [ ' - ' , ' - ' , ' - ' , ' - ' , ' - ' , ' - ' , ' - ' , ' - ' ] , [ ' - ' , ' - ' , ' - ' , ' - ' , ' - ' , ' - ' , ' - ' , ' - ' ] , [ ' P ' , ' - ' , ' P ' , ' P ' , ' P ' , ' P ' , ' P ' , ' P ' ] , [ ' K ' , ' - ' , ' - ' , ' - ' , ' - ' , ' - ' , ' - ' , ' - ' ] ] NEW_LINE if checkBoard ( board ) == 0 : NEW_LINE INDENT print ( " No β king β in β danger " ) NEW_LINE DEDENT elif checkBoard ( board ) == 1 : NEW_LINE INDENT print ( " White β king β in β danger " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Black β king β in β danger " ) NEW_LINE DEDENT |
Sudoku | Backtracking | N is the size of the 2D matrix N * N ; A utility function to print grid ; Checks whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return false ; Check if we find the same num in the similar column , we return false ; Check if we find the same num in the particular 3 * 3 matrix , we return false ; Takes a partially filled - in grid and attempts to assign values to all unassigned locations in such a way to meet the requirements for Sudoku solution ( non - duplication across rows , columns , and boxes ) ; Check if we have reached the 8 th row and 9 th column ( 0 indexed matrix ) , we are returning true to avoid further backtracking ; Check if column value becomes 9 , we move to next row and column start from 0 ; Check if the current position of the grid already contains value > 0 , we iterate for next column ; Check if it is safe to place the num ( 1 - 9 ) in the given row , col -> we move to next column ; Assigning the num in the current ( row , col ) position of the grid and assuming our assigned num in the position is correct ; Checking for next possibility with next column ; Removing the assigned num , since our assumption was wrong , and we go for next assumption with diff num value ; 0 means unassigned cells | N = 9 NEW_LINE def printing ( arr ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def isSafe ( grid , row , col , num ) : NEW_LINE INDENT for x in range ( 9 ) : NEW_LINE INDENT if grid [ row ] [ x ] == num : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for x in range ( 9 ) : NEW_LINE INDENT if grid [ x ] [ col ] == num : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT startRow = row - row % 3 NEW_LINE startCol = col - col % 3 NEW_LINE for i in range ( 3 ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT if grid [ i + startRow ] [ j + startCol ] == num : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def solveSuduko ( grid , row , col ) : NEW_LINE INDENT if ( row == N - 1 and col == N ) : NEW_LINE INDENT return True NEW_LINE DEDENT if col == N : NEW_LINE INDENT row += 1 NEW_LINE col = 0 NEW_LINE DEDENT if grid [ row ] [ col ] > 0 : NEW_LINE INDENT return solveSuduko ( grid , row , col + 1 ) NEW_LINE DEDENT for num in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT if isSafe ( grid , row , col , num ) : NEW_LINE INDENT grid [ row ] [ col ] = num NEW_LINE if solveSuduko ( grid , row , col + 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT grid [ row ] [ col ] = 0 NEW_LINE DEDENT return False NEW_LINE DEDENT grid = [ [ 3 , 0 , 6 , 5 , 0 , 8 , 4 , 0 , 0 ] , [ 5 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 8 , 7 , 0 , 0 , 0 , 0 , 3 , 1 ] , [ 0 , 0 , 3 , 0 , 1 , 0 , 0 , 8 , 0 ] , [ 9 , 0 , 0 , 8 , 6 , 3 , 0 , 0 , 5 ] , [ 0 , 5 , 0 , 0 , 9 , 0 , 6 , 0 , 0 ] , [ 1 , 3 , 0 , 0 , 0 , 0 , 2 , 5 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 4 ] , [ 0 , 0 , 5 , 2 , 0 , 6 , 3 , 0 , 0 ] ] NEW_LINE if ( solveSuduko ( grid , 0 , 0 ) ) : NEW_LINE INDENT printing ( grid ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " no β solution β exists β " ) NEW_LINE DEDENT |
Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | function to check for the given sum in the array ; checking for condition ; driver code | def printPairs ( arr , arr_size , sum ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 0 , arr_size ) : NEW_LINE INDENT temp = sum - arr [ i ] NEW_LINE if ( temp in s ) : NEW_LINE INDENT print " Pair β with β given β sum β " + str ( sum ) + NEW_LINE DEDENT DEDENT " β is β ( " + str ( arr [ i ] ) + " , β " + str ( temp ) + " ) " NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE DEDENT DEDENT A = [ 1 , 4 , 45 , 6 , 10 , 8 ] NEW_LINE n = 16 NEW_LINE printPairs ( A , len ( A ) , n ) NEW_LINE |
Longest consecutive sequence in Binary tree | A utility class to create a node ; Utility method to return length of longest consecutive sequence of tree ; if root data has one more than its parent then increase current length ; update the maximum by current length ; recursively call left and right subtree with expected value 1 more than root data ; method returns length of longest consecutive sequence rooted at node root ; call utility method with current length 0 ; Driver Code | 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 longestConsecutiveUtil ( root , curLength , expected , res ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . data == expected ) : NEW_LINE INDENT curLength += 1 NEW_LINE DEDENT else : NEW_LINE INDENT curLength = 1 NEW_LINE DEDENT res [ 0 ] = max ( res [ 0 ] , curLength ) NEW_LINE longestConsecutiveUtil ( root . left , curLength , root . data + 1 , res ) NEW_LINE longestConsecutiveUtil ( root . right , curLength , root . data + 1 , res ) NEW_LINE DEDENT def longestConsecutive ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = [ 0 ] NEW_LINE longestConsecutiveUtil ( root , 0 , root . data , res ) NEW_LINE return res [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 6 ) NEW_LINE root . right = newNode ( 9 ) NEW_LINE root . right . left = newNode ( 7 ) NEW_LINE root . right . right = newNode ( 10 ) NEW_LINE root . right . right . right = newNode ( 11 ) NEW_LINE print ( longestConsecutive ( root ) ) NEW_LINE DEDENT |
Find remainder when a number A raised to N factorial is divided by P | Function to calculate ( A ^ N ! ) % P in O ( log y ) ; Initialize result ; Update x if it is more than or Equal to p ; In case x is divisible by p ; If y is odd , multiply x with result ; y must be even now ; Returning modular power ; Function to calculate resultant remainder ; Initializing ans to store final remainder ; Calculating remainder ; Returning resultant remainder ; Given input ; Function Call | def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def remainder ( n , a , p ) : NEW_LINE INDENT ans = a % p NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = power ( ans , i , p ) NEW_LINE DEDENT return ans NEW_LINE DEDENT A = 2 NEW_LINE N = 1 NEW_LINE P = 2 NEW_LINE print ( remainder ( N , A , P ) ) NEW_LINE |
Find all array elements occurring more than Γ’ΕΕ N / 3 Γ’Ε βΉ times | ''Function to find Majority element in an array ; '' if this element is previously seen, increment count1. ; '' if this element is previously seen, increment count2. ; '' if current element is different from both the previously seen variables, decrement both the counts. ; ; | def findMajority ( arr , n ) : NEW_LINE INDENT count1 = 0 NEW_LINE DEDENT count2 = 0 NEW_LINE = first = 2147483647 NEW_LINE INDENT second = 2147483647 NEW_LINE flag = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if first == arr [ i ] : NEW_LINE count1 += 1 NEW_LINE elif second == arr [ i ] : NEW_LINE count2 += 1 NEW_LINE elif count1 == 0 : NEW_LINE count1 += 1 NEW_LINE DEDENT first = arr [ i ] NEW_LINE INDENT elif count2 == 0 : NEW_LINE count2 += 1 NEW_LINE second = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT count1 -= 1 NEW_LINE count2 -= 1 NEW_LINE count1 = 0 NEW_LINE count2 = 0 NEW_LINE DEDENT ' gain traverse the array and find the NEW_LINE INDENT actual counts . ''' STRNEWLINE β for β i β in β range ( n ) : STRNEWLINE β if β arr [ i ] β = = β first : STRNEWLINE β count1 β + = β 1 STRNEWLINE β elif β arr [ i ] β = = β second : STRNEWLINE count2 β + = β 1 STRNEWLINE β if β count1 β > β int ( n β / β 3 ) : STRNEWLINE β print ( first , β end β = β " β " ) STRNEWLINE β flag β = β 1 STRNEWLINE β if β count2 β > β int ( n β / β 3 ) : STRNEWLINE print ( second , β end β = β " β " ) STRNEWLINE β flag β = β 1 STRNEWLINE β if β flag β = = β 0 : STRNEWLINE β print ( " No β Majority β Element " ) STRNEWLINE ' Driver β code β ''' NEW_LINE DEDENT arr = [ 2 , 2 , 3 , 1 , 3 , 2 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE findMajority ( arr , n ) NEW_LINE |
Modular exponentiation ( Recursive ) | Recursive Python program to compute modular power ; Base Cases ; If B is Even ; If B is Odd ; Driver Code | def exponentMod ( A , B , C ) : NEW_LINE INDENT if ( A == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( B == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT y = 0 NEW_LINE if ( B % 2 == 0 ) : NEW_LINE INDENT y = exponentMod ( A , B / 2 , C ) NEW_LINE y = ( y * y ) % C NEW_LINE DEDENT else : NEW_LINE INDENT y = A % C NEW_LINE y = ( y * exponentMod ( A , B - 1 , C ) % C ) % C NEW_LINE DEDENT return ( ( y + C ) % C ) NEW_LINE DEDENT A = 2 NEW_LINE B = 5 NEW_LINE C = 13 NEW_LINE print ( " Power β is " , exponentMod ( A , B , C ) ) NEW_LINE |
Find frequency of each element in a limited range array in less than O ( n ) time | python program to count number of occurrences of each element in the array in O ( n ) time and O ( 1 ) space ; check if the current element is equal to previous element . ; reset the frequency ; print the last element and its frequency ; | def findFrequencies ( ele , n ) : NEW_LINE INDENT freq = 1 NEW_LINE idx = 1 NEW_LINE element = ele [ 0 ] NEW_LINE while ( idx < n ) : NEW_LINE INDENT if ( ele [ idx - 1 ] == ele [ idx ] ) : NEW_LINE INDENT freq += 1 NEW_LINE idx += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( element , " β " , freq ) ; NEW_LINE element = ele [ idx ] NEW_LINE idx += 1 NEW_LINE freq = 1 NEW_LINE DEDENT DEDENT print ( element , " β " , freq ) ; NEW_LINE DEDENT / * Driver code * / NEW_LINE print ( " - - - frequencies β in β a β sorted β array - - - - " ) ; NEW_LINE arr = [ 10 , 20 , 30 , 30 , 30 , 40 , 50 , 50 , 50 , 50 , 70 ] ; NEW_LINE n = len ( arr ) NEW_LINE findFrequencies ( arr , n ) NEW_LINE |
Modular Exponentiation ( Power in Modular Arithmetic ) | Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize result ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Change x to x ^ 2 | def power ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) != 0 ) : NEW_LINE INDENT res = res * x NEW_LINE DEDENT DEDENT DEDENT y = y >> 1 NEW_LINE x = x * x NEW_LINE INDENT return res NEW_LINE DEDENT |
Modular Exponentiation ( Power in Modular Arithmetic ) | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now ; Driver Code | def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) == 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y >> 1 y = y / 2 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT x = 2 ; y = 5 ; p = 13 NEW_LINE print ( " Power β is β " , power ( x , y , p ) ) NEW_LINE |
Path length having maximum number of bends | Utility function to create a new node ; Recursive function to calculate the path Length having maximum number of bends . The following are parameters for this function . node - . pointer to the current node Dir - . determines whether the current node is left or right child of it 's parent node bends -. number of bends so far in the current path. maxBends -. maximum number of bends in a path from root to leaf soFar -. Length of the current path so far traversed Len -. Length of the path having maximum number of bends ; Base Case ; Leaf node ; Having both left and right child ; Helper function to call findMaxBendsUtil ( ) ; Call for left subtree of the root ; Call for right subtree of the root ; Include the root node as well in the path Length ; Driver code ; Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2 \ 1 / 9 | class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . key = key NEW_LINE DEDENT DEDENT def findMaxBendsUtil ( node , Dir , bends , maxBends , soFar , Len ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( node . left == None and node . right == None ) : NEW_LINE INDENT if ( bends > maxBends [ 0 ] ) : NEW_LINE INDENT maxBends [ 0 ] = bends NEW_LINE Len [ 0 ] = soFar NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( Dir == ' l ' ) : NEW_LINE INDENT findMaxBendsUtil ( node . left , Dir , bends , maxBends , soFar + 1 , Len ) NEW_LINE findMaxBendsUtil ( node . right , ' r ' , bends + 1 , maxBends , soFar + 1 , Len ) NEW_LINE DEDENT else : NEW_LINE INDENT findMaxBendsUtil ( node . right , Dir , bends , maxBends , soFar + 1 , Len ) NEW_LINE findMaxBendsUtil ( node . left , ' l ' , bends + 1 , maxBends , soFar + 1 , Len ) NEW_LINE DEDENT DEDENT DEDENT def findMaxBends ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT Len = [ 0 ] NEW_LINE bends = 0 NEW_LINE maxBends = [ - 1 ] NEW_LINE if ( node . left ) : NEW_LINE INDENT findMaxBendsUtil ( node . left , ' l ' , bends , maxBends , 1 , Len ) NEW_LINE DEDENT if ( node . right ) : NEW_LINE INDENT findMaxBendsUtil ( node . right , ' r ' , bends , maxBends , 1 , Len ) NEW_LINE DEDENT Len [ 0 ] += 1 NEW_LINE return Len [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 8 ) NEW_LINE root . right = newNode ( 2 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 2 ) NEW_LINE root . right . left . right = newNode ( 1 ) NEW_LINE root . right . left . right . left = newNode ( 9 ) NEW_LINE print ( findMaxBends ( root ) - 1 ) NEW_LINE DEDENT |
Program to calculate angle between two N | Python3 program for the above approach ; Function to find the magnitude of the given vector ; Stores the final magnitude ; Traverse the array ; Return square root of magnitude ; Function to find the dot product of two vectors ; Stores dot product ; Traverse the array ; Return the product ; Stores dot product of two vectors ; Stores magnitude of vector A ; Stores magnitude of vector B ; Stores angle between given vectors ; Print the angle ; Driver Code ; Given magnitude arrays ; Size of the array ; Function call to find the angle between two vectors | import math NEW_LINE def magnitude ( arr , N ) : NEW_LINE INDENT magnitude = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT magnitude += arr [ i ] * arr [ i ] NEW_LINE DEDENT return math . sqrt ( magnitude ) NEW_LINE DEDENT def dotProduct ( arr , brr , N ) : NEW_LINE INDENT product = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT product = product + arr [ i ] * brr [ i ] NEW_LINE DEDENT return product NEW_LINE DEDENT def angleBetweenVectors ( arr , brr , N ) : NEW_LINE INDENT dotProductOfVectors = dotProduct ( arr , brr , N ) NEW_LINE magnitudeOfA = magnitude ( arr , N ) NEW_LINE magnitudeOfB = magnitude ( brr , N ) NEW_LINE angle = ( dotProductOfVectors / ( magnitudeOfA * magnitudeOfB ) ) NEW_LINE print ( ' % .5f ' % angle ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 0.5 , - 2 , 1 ] NEW_LINE brr = [ - 1 , - 1 , 0.3 ] NEW_LINE N = len ( arr ) NEW_LINE angleBetweenVectors ( arr , brr , N ) NEW_LINE DEDENT |
Sum of sides of largest and smallest child polygons possible from a given polygon | Function to find the sum of largest and smallest secondary polygons if possible ; Count edges of primary polygon ; Calculate edges present in the largest secondary polygon ; Driver Code ; Given Exterior Angle | def secondary_polygon ( Angle ) : NEW_LINE INDENT edges_primary = 360 // Angle NEW_LINE if edges_primary >= 6 : NEW_LINE INDENT edges_max_secondary = edges_primary // 2 NEW_LINE return edges_max_secondary + 3 NEW_LINE DEDENT else : NEW_LINE INDENT return " Not β Possible " NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Angle = 45 NEW_LINE print ( secondary_polygon ( Angle ) ) NEW_LINE DEDENT |
Area of Circumcircle of an Equilateral Triangle using Median | Python3 implementation to find the equation of circle which inscribes equilateral triangle of median M ; Function to find the equation of circle whose center is ( x1 , y1 ) and the radius of circle is r ; Function to find the equation of circle which inscribes equilateral triangle of median M ; Function to find the circle equation ; Driver code ; Function call | pi = 3.14159265358979323846 NEW_LINE def circleArea ( r ) : NEW_LINE INDENT print ( round ( pi * r * r , 4 ) ) NEW_LINE DEDENT def findCircleAreaByMedian ( m ) : NEW_LINE INDENT r = 2 * m / 3 NEW_LINE circleArea ( r ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 3 NEW_LINE findCircleAreaByMedian ( m ) NEW_LINE DEDENT |
Number of turns to reach from one node to other in binary tree | A Binary Tree Node ; Utility function to create a new tree Node ; Utility function to find the LCA of two given values n1 and n2 . ; Base case ; If either n1 or n2 matches with root 's key, report the presence by returning root (Note that if a key is ancestor of other, then the ancestor key becomes LCA ; Look for keys in left and right subtrees ; If both of the above calls return Non - NULL , then one key is present in once subtree and other is present in other , So this node is the LCA ; Otherwise check if left subtree or right subtree is LCA ; function count number of turn need to reach given node from it 's LCA we have two way to ; if found the key value in tree ; Case 1 : ; Case 2 : ; Function to find nodes common to given two nodes ; there is no path between these two node ; case 1 : ; count number of turns needs to reached the second node from LCA ; count number of turns needs to reached the first node from LCA ; case 2 : ; count number of turns needs to reached the second node from LCA ; count number of turns needs to reached the first node from LCA1 ; Driver Code ; Let us create binary tree given in the above example | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . key = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( key : int ) -> Node : NEW_LINE INDENT temp = Node ( ) NEW_LINE temp . key = key NEW_LINE temp . left = None NEW_LINE temp . right = None NEW_LINE return temp NEW_LINE DEDENT def findLCA ( root : Node , n1 : int , n2 : int ) -> Node : NEW_LINE INDENT if root is None : NEW_LINE INDENT return None NEW_LINE DEDENT if root . key == n1 or root . key == n2 : NEW_LINE INDENT return root NEW_LINE DEDENT left_lca = findLCA ( root . left , n1 , n2 ) NEW_LINE right_lca = findLCA ( root . right , n1 , n2 ) NEW_LINE if left_lca and right_lca : NEW_LINE INDENT return root NEW_LINE DEDENT return ( left_lca if left_lca is not None else right_lca ) NEW_LINE DEDENT def countTurn ( root : Node , key : int , turn : bool ) -> bool : NEW_LINE INDENT global count NEW_LINE if root is None : NEW_LINE INDENT return False NEW_LINE DEDENT if root . key == key : NEW_LINE INDENT return True NEW_LINE DEDENT if turn is True : NEW_LINE INDENT if countTurn ( root . left , key , turn ) : NEW_LINE INDENT return True NEW_LINE DEDENT if countTurn ( root . right , key , not turn ) : NEW_LINE INDENT count += 1 NEW_LINE return True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if countTurn ( root . right , key , turn ) : NEW_LINE INDENT return True NEW_LINE DEDENT if countTurn ( root . left , key , not turn ) : NEW_LINE INDENT count += 1 NEW_LINE return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def numberOfTurn ( root : Node , first : int , second : int ) -> int : NEW_LINE INDENT global count NEW_LINE LCA = findLCA ( root , first , second ) NEW_LINE if LCA is None : NEW_LINE INDENT return - 1 NEW_LINE DEDENT count = 0 NEW_LINE if LCA . key != first and LCA . key != second : NEW_LINE INDENT if countTurn ( LCA . right , second , False ) or countTurn ( LCA . left , second , True ) : NEW_LINE INDENT pass NEW_LINE DEDENT if countTurn ( LCA . left , first , True ) or countTurn ( LCA . right , first , False ) : NEW_LINE INDENT pass NEW_LINE DEDENT return count + 1 NEW_LINE DEDENT if LCA . key == first : NEW_LINE INDENT countTurn ( LCA . right , second , False ) NEW_LINE countTurn ( LCA . left , second , True ) NEW_LINE return count NEW_LINE DEDENT else : NEW_LINE INDENT countTurn ( LCA . right , first , False ) NEW_LINE countTurn ( LCA . left , first , True ) NEW_LINE return count NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT count = 0 NEW_LINE root = Node ( ) NEW_LINE 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 ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . left . left . left = newNode ( 8 ) NEW_LINE root . right . left . left = newNode ( 9 ) NEW_LINE root . right . left . right = newNode ( 10 ) NEW_LINE turn = numberOfTurn ( root , 5 , 10 ) NEW_LINE if turn : NEW_LINE INDENT print ( turn ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β possible " ) NEW_LINE DEDENT DEDENT |
Find the type of triangle from the given sides | Function to find the type of triangle with the help of sides ; Driver Code ; Function Call | def checkTypeOfTriangle ( a , b , c ) : NEW_LINE INDENT sqa = pow ( a , 2 ) NEW_LINE sqb = pow ( b , 2 ) NEW_LINE sqc = pow ( c , 2 ) NEW_LINE if ( sqa == sqa + sqb or sqb == sqa + sqc or sqc == sqa + sqb ) : NEW_LINE INDENT print ( " Right - angled β Triangle " ) NEW_LINE DEDENT elif ( sqa > sqc + sqb or sqb > sqa + sqc or sqc > sqa + sqb ) : NEW_LINE INDENT print ( " Obtuse - angled β Triangle " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Acute - angled β Triangle " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 2 NEW_LINE b = 2 NEW_LINE c = 2 NEW_LINE checkTypeOfTriangle ( a , b , c ) NEW_LINE DEDENT |
Check whether the triangle is valid or not if angles are given | Function to check if sum of the three angles is 180 or not ; Check condition ; Driver code ; function calling and print output | def Valid ( a , b , c ) : NEW_LINE INDENT if ( ( a + b + c == 180 ) and a != 0 and b != 0 and c != 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 60 NEW_LINE b = 40 NEW_LINE c = 80 NEW_LINE if ( Valid ( a , b , c ) ) : NEW_LINE INDENT print ( " Valid " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Invalid " ) NEW_LINE DEDENT DEDENT |
Area of the Largest Triangle inscribed in a Hexagon | Python3 Program to find the biggest triangle which can be inscribed within the hexagon ; Function to find the area of the triangle ; side cannot be negative ; area of the triangle ; Driver code | import math NEW_LINE def trianglearea ( a ) : NEW_LINE INDENT if ( a < 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT area = ( 3 * math . sqrt ( 3 ) * math . pow ( a , 2 ) ) / 4 ; NEW_LINE return area ; NEW_LINE DEDENT a = 6 ; NEW_LINE print ( trianglearea ( a ) ) NEW_LINE |
Equation of ellipse from its focus , directrix , and eccentricity | Function to find equation of ellipse . ; Driver Code | def equation_ellipse ( x1 , y1 , a , b , c , e ) : NEW_LINE INDENT t = a * a + b * b NEW_LINE a1 = t - e * ( a * a ) NEW_LINE b1 = t - e * ( b * b ) NEW_LINE c1 = ( - 2 * t * x1 ) - ( 2 * e * c * a ) NEW_LINE d1 = ( - 2 * t * y1 ) - ( 2 * e * c * b ) NEW_LINE e1 = - 2 * e * a * b NEW_LINE f1 = ( - e * c * c ) + ( t * x1 * x1 ) + ( t * y1 * y1 ) NEW_LINE print ( " Equation β of β ellipse β is " , a1 , " x ^ 2 β + " , b1 , " y ^ 2 β + " , c1 , " x β + " , d1 , " y β + " , e1 , " xy β + " , f1 , " = β 0" ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x1 , y1 , a , b , c , e = 1 , 1 , 1 , - 1 , 3 , 0.5 * 0.5 NEW_LINE equation_ellipse ( x1 , y1 , a , b , c , e ) NEW_LINE DEDENT |
Create loops of even and odd values in a binary tree | Utility function to create a new node ; preorder traversal to place the node pointer in the respective even_ptrs or odd_ptrs list ; place node ptr in even_ptrs list if node contains even number ; else place node ptr in odd_ptrs list ; function to create the even and odd loops ; forming even loop ; for the last element ; Similarly forming odd loop ; traversing the loop from any random node in the loop ; Driver program to test above ; Binary tree formation ; traversing odd loop from any random odd node ; traversing even loop from any random even node | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE self . abtr = None NEW_LINE DEDENT DEDENT even_ptrs = [ ] NEW_LINE odd_ptrs = [ ] NEW_LINE def preorderTraversal ( root ) : NEW_LINE INDENT global even_ptrs , odd_ptrs NEW_LINE if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . data % 2 == 0 ) : NEW_LINE INDENT even_ptrs . append ( root ) NEW_LINE DEDENT else : NEW_LINE INDENT odd_ptrs . append ( root ) NEW_LINE DEDENT preorderTraversal ( root . left ) NEW_LINE preorderTraversal ( root . right ) NEW_LINE DEDENT def createLoops ( root ) : NEW_LINE INDENT preorderTraversal ( root ) NEW_LINE i = 1 NEW_LINE while i < len ( even_ptrs ) : NEW_LINE INDENT even_ptrs [ i - 1 ] . abtr = even_ptrs [ i ] NEW_LINE i += 1 NEW_LINE DEDENT even_ptrs [ i - 1 ] . abtr = even_ptrs [ 0 ] NEW_LINE i = 1 NEW_LINE while i < len ( odd_ptrs ) : NEW_LINE INDENT odd_ptrs [ i - 1 ] . abtr = odd_ptrs [ i ] NEW_LINE i += 1 NEW_LINE DEDENT odd_ptrs [ i - 1 ] . abtr = odd_ptrs [ 0 ] NEW_LINE DEDENT def traverseLoop ( start ) : NEW_LINE INDENT curr = start NEW_LINE while True and curr : NEW_LINE INDENT print ( curr . data , end = " β " ) NEW_LINE curr = curr . abtr NEW_LINE if curr == start : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = 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 . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE createLoops ( root ) NEW_LINE print ( " Odd β nodes : " , end = " β " ) NEW_LINE traverseLoop ( root . right ) NEW_LINE print ( " Even β nodes : " , end = " β " ) NEW_LINE traverseLoop ( root . left ) NEW_LINE DEDENT |
Area of circle which is inscribed in equilateral triangle | Python3 program to find the area of circle which is inscribed in equilateral triangle ; Function return the area of circle inscribed in equilateral triangle ; Driver code | from math import pi NEW_LINE def circle_inscribed ( a ) : NEW_LINE INDENT return pi * ( a * a ) / 12 NEW_LINE DEDENT a = 4 NEW_LINE print ( circle_inscribed ( a ) ) NEW_LINE |
Program to find the Volume of an irregular tetrahedron | Python 3 implementation of above approach ; Function to find the volume ; Steps to calculate volume of a Tetrahedron using formula ; Driver code ; edge lengths | from math import * NEW_LINE def findVolume ( u , v , w , U , V , W , b ) : NEW_LINE INDENT uPow = pow ( u , 2 ) NEW_LINE vPow = pow ( v , 2 ) NEW_LINE wPow = pow ( w , 2 ) NEW_LINE UPow = pow ( U , 2 ) NEW_LINE VPow = pow ( V , 2 ) NEW_LINE WPow = pow ( W , 2 ) NEW_LINE a = ( 4 * ( uPow * vPow * wPow ) - uPow * pow ( ( vPow + wPow - UPow ) , 2 ) - vPow * pow ( ( wPow + uPow - VPow ) , 2 ) - wPow * pow ( ( uPow + vPow - WPow ) , 2 ) + ( vPow + wPow - UPow ) * ( wPow + uPow - VPow ) * ( uPow + vPow - WPow ) ) NEW_LINE vol = sqrt ( a ) NEW_LINE vol /= b NEW_LINE print ( round ( vol , 4 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT u , v , w = 1000 , 1000 , 1000 NEW_LINE U , V , W = 3 , 4 , 5 NEW_LINE b = 12 NEW_LINE findVolume ( u , v , w , U , V , W , b ) NEW_LINE DEDENT |
Check if it is possible to create a polygon with a given angle | Function to check whether it is possible to make a regular polygon with a given angle . ; N denotes the number of sides of polygons possible ; Driver Code ; function calling | def makePolygon ( a ) : NEW_LINE INDENT n = 360 / ( 180 - a ) NEW_LINE if n == int ( n ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 90 NEW_LINE makePolygon ( a ) NEW_LINE DEDENT |
Finding Quadrant of a Coordinate with respect to a Circle | Python3 Program to find the quadrant of a given coordinate w . rt . the centre of a circle ; Thus function returns the quadrant number ; Coincides with center ; Outside circle ; 1 st quadrant ; 2 nd quadrant ; 3 rd quadrant ; 4 th quadrant ; Coordinates of centre ; Radius of circle ; Coordinates of the given po | import math NEW_LINE def getQuadrant ( X , Y , R , PX , PY ) : NEW_LINE INDENT if ( PX == X and PY == Y ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT val = ( math . pow ( ( PX - X ) , 2 ) + math . pow ( ( PY - Y ) , 2 ) ) ; NEW_LINE if ( val > pow ( R , 2 ) ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( PX > X and PY >= Y ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( PX <= X and PY > Y ) : NEW_LINE INDENT return 2 ; NEW_LINE DEDENT if ( PX < X and PY <= Y ) : NEW_LINE INDENT return 3 ; NEW_LINE DEDENT if ( PX >= X and PY < Y ) : NEW_LINE INDENT return 4 ; NEW_LINE DEDENT DEDENT X = 0 ; NEW_LINE Y = 3 ; NEW_LINE R = 2 ; NEW_LINE PX = 1 ; NEW_LINE PY = 4 ; NEW_LINE ans = getQuadrant ( X , Y , R , PX , PY ) ; NEW_LINE if ( ans == - 1 ) : print ( " Lies β Outside β the β circle " ) ; NEW_LINE elif ( ans == 0 ) : print ( " Coincides β with β centre " ) ; NEW_LINE else : print ( ans , " Quadrant " ) ; NEW_LINE |
Hexadecagonal number | Function to calculate hexadecagonal number ; Driver Code | def hexadecagonalNum ( n ) : NEW_LINE INDENT return ( ( 14 * n * n ) - 12 * n ) // 2 NEW_LINE DEDENT n = 5 NEW_LINE print ( " % sth β Hexadecagonal β number β : β " % n , hexadecagonalNum ( n ) ) NEW_LINE n = 9 NEW_LINE print ( " % sth β Hexadecagonal β number β : β " % n , hexadecagonalNum ( n ) ) NEW_LINE |
Find first non matching leaves in two binary trees | Utility function to create a new tree Node ; Prints the first non - matching leaf node in two trees if it exists , else prints nothing . ; If any of the tree is empty ; Create two stacks for preorder traversals ; If traversal of one tree is over and other tree still has nodes . ; Do iterative traversal of first tree and find first lead node in it as " temp1" ; pushing right childfirst so that left child comes first while popping . ; Do iterative traversal of second tree and find first lead node in it as " temp2" ; If we found leaves in both trees ; Driver Code | 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 isLeaf ( t ) : NEW_LINE INDENT return ( ( t . left == None ) and ( t . right == None ) ) NEW_LINE DEDENT def findFirstUnmatch ( root1 , root2 ) : NEW_LINE INDENT if ( root1 == None or root2 == None ) : NEW_LINE INDENT return NEW_LINE DEDENT s1 = [ ] NEW_LINE s2 = [ ] NEW_LINE s1 . insert ( 0 , root1 ) NEW_LINE s2 . insert ( 0 , root2 ) NEW_LINE while ( len ( s1 ) or len ( s2 ) ) : NEW_LINE INDENT if ( len ( s1 ) == 0 or len ( s2 ) == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT temp1 = s1 [ 0 ] NEW_LINE s1 . pop ( 0 ) NEW_LINE while ( temp1 and not isLeaf ( temp1 ) ) : NEW_LINE INDENT s1 . insert ( 0 , temp1 . right ) NEW_LINE s1 . insert ( 0 , temp1 . left ) NEW_LINE temp1 = s1 [ 0 ] NEW_LINE s1 . pop ( 0 ) NEW_LINE DEDENT temp2 = s2 [ 0 ] NEW_LINE s2 . pop ( 0 ) NEW_LINE while ( temp2 and not isLeaf ( temp2 ) ) : NEW_LINE INDENT s2 . insert ( 0 , temp2 . right ) NEW_LINE s2 . insert ( 0 , temp2 . left ) NEW_LINE temp2 = s2 [ 0 ] NEW_LINE s2 . pop ( 0 ) NEW_LINE DEDENT if ( temp1 != None and temp2 != None ) : NEW_LINE INDENT if ( temp1 . data != temp2 . data ) : NEW_LINE INDENT print ( " First β non β matching β leaves β : " , temp1 . data , " " , temp2 . data ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = newNode ( 5 ) NEW_LINE root1 . left = newNode ( 2 ) NEW_LINE root1 . right = newNode ( 7 ) NEW_LINE root1 . left . left = newNode ( 10 ) NEW_LINE root1 . left . right = newNode ( 11 ) NEW_LINE root2 = newNode ( 6 ) NEW_LINE root2 . left = newNode ( 10 ) NEW_LINE root2 . right = newNode ( 15 ) NEW_LINE findFirstUnmatch ( root1 , root2 ) NEW_LINE DEDENT |
Maximum points of intersection n circles | Returns maximum number of intersections ; Driver code | def intersection ( n ) : NEW_LINE INDENT return n * ( n - 1 ) ; NEW_LINE DEDENT print ( intersection ( 3 ) ) NEW_LINE |
Find the perimeter of a cylinder | Function to calculate the perimeter of a cylinder ; Driver function | def perimeter ( diameter , height ) : NEW_LINE INDENT return 2 * ( diameter + height ) NEW_LINE DEDENT diameter = 5 ; NEW_LINE height = 10 ; NEW_LINE print ( " Perimeter β = β " , perimeter ( diameter , height ) ) NEW_LINE |
Find all possible coordinates of parallelogram | coordinates of A ; coordinates of B ; coordinates of C | ay = 0 NEW_LINE ax = 5 NEW_LINE by = 1 NEW_LINE bx = 1 NEW_LINE cy = 5 NEW_LINE cx = 2 NEW_LINE print ( ax + bx - cx , " , β " , ay + by - cy ) NEW_LINE print ( ax + cx - bx , " , β " , ay + cy - by ) NEW_LINE print ( cx + bx - ax , " , β " , cy + by - ax ) NEW_LINE |
Check whether a given point lies inside a rectangle or not | A utility function to calculate area of triangle formed by ( x1 , y1 ) , ( x2 , y2 ) and ( x3 , y3 ) ; A function to check whether point P ( x , y ) lies inside the rectangle formed by A ( x1 , y1 ) , B ( x2 , y2 ) , C ( x3 , y3 ) and D ( x4 , y4 ) ; Calculate area of rectangle ABCD ; Calculate area of triangle PAB ; Calculate area of triangle PBC ; Calculate area of triangle PCD ; Calculate area of triangle PAD ; Check if sum of A1 , A2 , A3 and A4 is same as A ; Driver Code ; Let us check whether the point P ( 10 , 15 ) lies inside the rectangle formed by A ( 0 , 10 ) , B ( 10 , 0 ) C ( 0 , - 10 ) D ( - 10 , 0 ) | def area ( x1 , y1 , x2 , y2 , x3 , y3 ) : NEW_LINE INDENT return abs ( ( x1 * ( y2 - y3 ) + x2 * ( y3 - y1 ) + x3 * ( y1 - y2 ) ) / 2.0 ) NEW_LINE DEDENT def check ( x1 , y1 , x2 , y2 , x3 , y3 , x4 , y4 , x , y ) : NEW_LINE INDENT A = ( area ( x1 , y1 , x2 , y2 , x3 , y3 ) + area ( x1 , y1 , x4 , y4 , x3 , y3 ) ) NEW_LINE A1 = area ( x , y , x1 , y1 , x2 , y2 ) NEW_LINE A2 = area ( x , y , x2 , y2 , x3 , y3 ) NEW_LINE A3 = area ( x , y , x3 , y3 , x4 , y4 ) NEW_LINE A4 = area ( x , y , x1 , y1 , x4 , y4 ) ; NEW_LINE return ( A == A1 + A2 + A3 + A4 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT if ( check ( 0 , 10 , 10 , 0 , 0 , - 10 , - 10 , 0 , 10 , 15 ) ) : NEW_LINE INDENT print ( " yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " no " ) NEW_LINE DEDENT DEDENT |
Get maximum left node in binary tree | Get max of left element using Inorder traversal ; Return maximum of three values 1 ) Recursive max in left subtree 2 ) Value in left node 3 ) Recursive max in right subtree ; Utility class to create a new tree node ; Driver Code ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1 | def maxOfLeftElement ( root ) : NEW_LINE INDENT res = - 999999999999 NEW_LINE if ( root == None ) : NEW_LINE INDENT return res NEW_LINE DEDENT if ( root . left != None ) : NEW_LINE INDENT res = root . left . data NEW_LINE DEDENT return max ( { maxOfLeftElement ( root . left ) , res , maxOfLeftElement ( root . right ) } ) NEW_LINE DEDENT 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 if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 7 ) NEW_LINE root . left = newNode ( 6 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 2 ) NEW_LINE root . right . right = newNode ( 1 ) NEW_LINE print ( maxOfLeftElement ( root ) ) NEW_LINE DEDENT |
Pizza cut problem ( Or Circle Division by Lines ) | Function for finding maximum pieces with n cuts . ; Driver code | def findMaximumPieces ( n ) : NEW_LINE INDENT return int ( 1 + n * ( n + 1 ) / 2 ) NEW_LINE DEDENT print ( findMaximumPieces ( 3 ) ) NEW_LINE |
Optimum location of point to minimize total distance | A Python3 program to find optimum location and total cost ; Class defining a point ; Class defining a line of ax + by + c = 0 form ; Method to get distance of point ( x , y ) from point p ; Utility method to compute total distance all points when choose point on given line has x - coordinate value as X ; Calculating Y of chosen point by line equation ; Utility method to find minimum total distance ; Loop until difference between low and high become less than EPS ; mid1 and mid2 are representative x co - ordiantes of search space ; If mid2 point gives more total distance , skip third part ; If mid1 point gives more total distance , skip first part ; Compute optimum distance cost by sending average of low and high as X ; Method to find optimum cost ; Converting 2D array input to point array ; Driver Code | import math NEW_LINE class Optimum_distance : NEW_LINE INDENT class Point : NEW_LINE INDENT def __init__ ( self , x , y ) : NEW_LINE INDENT self . x = x NEW_LINE self . y = y NEW_LINE DEDENT DEDENT class Line : NEW_LINE INDENT def __init__ ( self , a , b , c ) : NEW_LINE INDENT self . a = a NEW_LINE self . b = b NEW_LINE self . c = c NEW_LINE DEDENT DEDENT def dist ( self , x , y , p ) : NEW_LINE INDENT return math . sqrt ( ( x - p . x ) ** 2 + ( y - p . y ) ** 2 ) NEW_LINE DEDENT def compute ( self , p , n , l , x ) : NEW_LINE INDENT res = 0 NEW_LINE y = - 1 * ( l . a * x + l . c ) / l . b NEW_LINE for i in range ( n ) : NEW_LINE INDENT res += self . dist ( x , y , p [ i ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT def find_Optimum_cost_untill ( self , p , n , l ) : NEW_LINE INDENT low = - 1e6 NEW_LINE high = 1e6 NEW_LINE eps = 1e-6 + 1 NEW_LINE while ( ( high - low ) > eps ) : NEW_LINE INDENT mid1 = low + ( high - low ) / 3 NEW_LINE mid2 = high - ( high - low ) / 3 NEW_LINE dist1 = self . compute ( p , n , l , mid1 ) NEW_LINE dist2 = self . compute ( p , n , l , mid2 ) NEW_LINE if ( dist1 < dist2 ) : NEW_LINE INDENT high = mid2 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid1 NEW_LINE DEDENT DEDENT return self . compute ( p , n , l , ( low + high ) / 2 ) NEW_LINE DEDENT def find_Optimum_cost ( self , p , l ) : NEW_LINE INDENT n = len ( p ) NEW_LINE p_arr = [ None ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT p_obj = self . Point ( p [ i ] [ 0 ] , p [ i ] [ 1 ] ) NEW_LINE p_arr [ i ] = p_obj NEW_LINE DEDENT return self . find_Optimum_cost_untill ( p_arr , n , l ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT obj = Optimum_distance ( ) NEW_LINE l = obj . Line ( 1 , - 1 , - 3 ) NEW_LINE p = [ [ - 3 , - 2 ] , [ - 1 , 0 ] , [ - 1 , 2 ] , [ 1 , 2 ] , [ 3 , 4 ] ] NEW_LINE print ( obj . find_Optimum_cost ( p , l ) ) NEW_LINE DEDENT |
Klee 's Algorithm (Length Of Union Of Segments of a line) | Returns sum of lengths covered by union of given segments ; Initialize empty points container ; Create a vector to store starting and ending points ; Sorting all points by point value ; Initialize result as 0 ; To keep track of counts of current open segments ( Starting point is processed , but ending point is not ) ; Traverse through all points ; If there are open points , then we add the difference between previous and current point . ; If this is an ending point , reduce , count of open points . ; Driver code | def segmentUnionLength ( segments ) : NEW_LINE INDENT n = len ( segments ) NEW_LINE points = [ None ] * ( n * 2 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT points [ i * 2 ] = ( segments [ i ] [ 0 ] , False ) NEW_LINE points [ i * 2 + 1 ] = ( segments [ i ] [ 1 ] , True ) NEW_LINE DEDENT points = sorted ( points , key = lambda x : x [ 0 ] ) NEW_LINE result = 0 NEW_LINE Counter = 0 NEW_LINE for i in range ( 0 , n * 2 ) : NEW_LINE INDENT if ( i > 0 ) & ( points [ i ] [ 0 ] > points [ i - 1 ] [ 0 ] ) & ( Counter > 0 ) : NEW_LINE INDENT result += ( points [ i ] [ 0 ] - points [ i - 1 ] [ 0 ] ) NEW_LINE DEDENT if points [ i ] [ 1 ] : NEW_LINE INDENT Counter -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT Counter += 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT segments = [ ( 2 , 5 ) , ( 4 , 8 ) , ( 9 , 12 ) ] NEW_LINE print ( segmentUnionLength ( segments ) ) NEW_LINE DEDENT |
Find all duplicate and missing numbers in given permutation array of 1 to N | Function to find the duplicate and the missing elements over the range [ 1 , N ] ; Stores the missing and duplicate numbers in the array arr [ ] ; Traverse the given array arr [ ] ; Check if the current element is not same as the element at index arr [ i ] - 1 , then swap ; Otherwise , increment the index ; Traverse the array again ; If the element is not at its correct position ; Stores the missing and the duplicate elements ; Print the Missing Number ; Print the Duplicate Number ; Driver code | def findElements ( arr , N ) : NEW_LINE INDENT i = 0 ; NEW_LINE missing = [ ] ; NEW_LINE duplicate = set ( ) ; NEW_LINE while ( i != N ) : NEW_LINE INDENT if ( arr [ i ] != arr [ arr [ i ] - 1 ] ) : NEW_LINE INDENT t = arr [ i ] NEW_LINE arr [ i ] = arr [ arr [ i ] - 1 ] NEW_LINE arr [ t - 1 ] = t NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] != i + 1 ) : NEW_LINE INDENT missing . append ( i + 1 ) ; NEW_LINE duplicate . add ( arr [ i ] ) ; NEW_LINE DEDENT DEDENT print ( " Missing β Numbers : β " , end = " " ) ; NEW_LINE for it in missing : NEW_LINE INDENT print ( it , end = " β " ) ; NEW_LINE DEDENT print ( " Duplicate Numbers : " , end = " " ) ; NEW_LINE for it in list ( duplicate ) : NEW_LINE INDENT print ( it , end = ' β ' ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 2 , 4 , 5 , 7 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE findElements ( arr , N ) ; NEW_LINE DEDENT |
Check if elements of given array can be rearranged such that ( arr [ i ] + i * K ) % N = i for all values of i in range [ 0 , N | Function to check if it is possible to generate all numbers in range [ 0 , N - 1 ] using the sum of elements + in the multiset A and B mod N ; If no more pair of elements can be selected ; If the number of elements in C = N , then return true ; Otherwise return false ; Stores the value of final answer ; Iterate through all the pairs in the given multiset A and B ; Stores the set A without x ; Stores the set A without y ; Stores the set A without x + y % N ; Recursive call ; Return Answer ; Function to check if it is possible to rearrange array elements such that ( arr [ i ] + i * K ) % N = i ; Stores the values of arr [ ] modulo N ; Stores all the values of i * K modulo N ; Print Answer ; Driver code | def isPossible ( A , B , C , N ) : NEW_LINE INDENT if ( len ( A ) == 0 or len ( B ) == 0 ) : NEW_LINE INDENT if ( len ( C ) == N ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT ans = False NEW_LINE for x in A : NEW_LINE INDENT for y in B : NEW_LINE INDENT _A = A NEW_LINE _A . remove ( x ) NEW_LINE _B = B NEW_LINE _B . remove ( y ) NEW_LINE _C = C NEW_LINE _C . add ( ( x + y ) % N ) NEW_LINE ans = ( ans or isPossible ( _A , _B , _C , N ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def rearrangeArray ( arr , N , K ) : NEW_LINE INDENT A = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT A . append ( arr [ i ] % N ) NEW_LINE DEDENT A . sort ( ) NEW_LINE B = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT B . append ( ( i * K ) % N ) NEW_LINE DEDENT B . sort ( ) NEW_LINE C = set ( ) NEW_LINE if isPossible ( A , B , C , N ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 0 ] NEW_LINE K = 5 NEW_LINE N = len ( arr ) NEW_LINE rearrangeArray ( arr , N , K ) NEW_LINE |
Height of Factor Tree for a given number | Python 3 program for the above approach ; Function to find the height of the Factor Tree of the integer N ; Stores the height of Factor Tree ; Loop to iterate over values of N ; Stores if there exist a factor of N or not ; Loop to find the smallest factor of N ; If i is a factor of N ; Increment the height ; If there are no factors of N i . e , N is prime , break loop ; Return Answer ; Driver Code | from math import sqrt NEW_LINE def factorTree ( N ) : NEW_LINE INDENT height = 0 NEW_LINE while ( N > 1 ) : NEW_LINE INDENT flag = False NEW_LINE for i in range ( 2 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT N = N // i NEW_LINE flag = True NEW_LINE break NEW_LINE DEDENT DEDENT height += 1 NEW_LINE if ( flag == False ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return height NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 48 NEW_LINE print ( factorTree ( N ) ) NEW_LINE DEDENT |
Maximize the largest number K such that bitwise and of K till N is 0 | ; Function to find maximum value of k which makes bitwise AND zero . ; Finding the power less than N ; Driver Code | import math NEW_LINE def findMaxK ( N ) : NEW_LINE INDENT p = math . log ( N ) // math . log ( 2 ) ; NEW_LINE return int ( pow ( 2 , p ) ) ; NEW_LINE DEDENT N = 5 ; NEW_LINE print ( findMaxK ( N ) - 1 ) ; NEW_LINE |
Count of Ks in the Array for a given range of indices after array updates for Q queries | Python3 program for the above approach ; Function to build the segment tree ; Base case ; Since the count of zero is required set leaf node as 1 ; If the value in array is not zero , store 0 in the leaf node ; Find the mid ; Recursive call for left subtree ; Recursive call for right subtree ; Parent nodes contains the count of zero in range tl to tr ; Function to find the count of 0 s in range l to r ; Base Case ; Case when no two segment are combining ; Finding the mid ; When it is required to combine left subtree and right subtree to get the range l to r ; Function that updates the segment tree nodes ; Base Case ; If array element is 0 ; If array element is not 0 ; Otherwise ; Find the mid ; Update the tree or count which is stored in parent node ; Function to solve all the queries ; When query type is 1 ; When query type is 2 ; Driver code | a = [ ] NEW_LINE seg_tree = [ ] NEW_LINE query = [ ] NEW_LINE def build_tree ( v , tl , tr ) : NEW_LINE INDENT global a , seg_tree , query NEW_LINE if ( tl != tr ) : NEW_LINE INDENT if ( a [ tl ] == 0 ) : NEW_LINE INDENT seg_tree [ v ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT seg_tree [ v ] = 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT tm = int ( ( tl + tr ) / 2 ) NEW_LINE build_tree ( v * 2 , tl , tm ) NEW_LINE build_tree ( v * 2 + 1 , tm + 1 , tr ) NEW_LINE seg_tree [ v ] = seg_tree [ v * 2 ] + seg_tree [ v * 2 + 1 ] NEW_LINE DEDENT DEDENT def frequency_zero ( v , tl , tr , l , r ) : NEW_LINE INDENT global a , seg_tree , query NEW_LINE if ( l > r ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( l == tl and r == tr ) : NEW_LINE INDENT return seg_tree [ v ] NEW_LINE DEDENT tm = int ( ( tl + tr ) / 2 ) NEW_LINE return frequency_zero ( v * 2 , tl , tm , l , min ( r , tm ) ) + frequency_zero ( v * 2 + 1 , tm + 1 , tr , max ( l , tm + 1 ) , r ) NEW_LINE DEDENT def update ( v , tl , tr , pos , new_val ) : NEW_LINE INDENT global a , seg_tree , query NEW_LINE if ( tl == tr ) : NEW_LINE INDENT if ( new_val == 0 ) : NEW_LINE INDENT seg_tree [ v ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT seg_tree [ v ] = 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT tm = int ( ( tl + tr ) / 2 ) NEW_LINE if ( pos <= tm ) : NEW_LINE INDENT update ( v * 2 , tl , tm , pos , new_val ) NEW_LINE DEDENT else : NEW_LINE INDENT update ( v * 2 + 1 , tm + 1 , tr , pos , new_val ) NEW_LINE DEDENT seg_tree [ v ] = seg_tree [ v * 2 ] + seg_tree [ v * 2 + 1 ] NEW_LINE DEDENT DEDENT def solve ( n , q ) : NEW_LINE INDENT global a , seg_tree , query NEW_LINE qu = [ 5 , 3 , 6 ] NEW_LINE seg_tree = [ 0 ] * ( 4 * n + 1 ) NEW_LINE build_tree ( 1 , 0 , n - 1 ) NEW_LINE for i in range ( len ( qu ) ) : NEW_LINE INDENT print ( qu [ i ] ) NEW_LINE DEDENT for i in range ( q , q ) : NEW_LINE INDENT if query [ i - 1 ] [ 0 ] == 1 : NEW_LINE INDENT l = query [ i - 1 ] [ 1 ] NEW_LINE r = query [ i - 1 ] [ 2 ] NEW_LINE print ( frequency_zero ( 1 , 0 , n - 1 , l , r ) ) NEW_LINE DEDENT else : NEW_LINE INDENT a [ query [ i - 1 ] [ 1 ] ] = query [ i - 1 ] [ 2 ] NEW_LINE pos = query [ i - 1 ] [ 1 ] NEW_LINE new_val = query [ i - 1 ] [ 2 ] NEW_LINE update ( 1 , 0 , n - 1 , pos , new_val ) NEW_LINE DEDENT DEDENT DEDENT a = [ 9 , 5 , 7 , 6 , 9 , 0 , 0 , 0 , 0 , 5 , 6 , 7 , 3 , 9 , 0 , 7 , 0 , 9 , 0 ] NEW_LINE Q = 5 NEW_LINE query = [ [ 1 , 5 , 14 ] , [ 2 , 6 , 1 ] , [ 1 , 0 , 8 ] , [ 2 , 13 , 0 ] , [ 1 , 6 , 18 ] ] NEW_LINE N = len ( a ) NEW_LINE solve ( N , Q ) NEW_LINE |
Find a number in minimum steps | Python program to find a number in minimum steps ; To represent data of a node in tree ; Prints level of node n ; Create a queue and insert root ; Do level order traversal ; Remove a node from queue ; q . pop ( ) To avoid infinite loop ; Check if dequeued number is same as n ; Insert children of dequeued node to queue ; Driver code | from collections import deque NEW_LINE InF = 99999 NEW_LINE class number : NEW_LINE INDENT def __init__ ( self , n , l ) : NEW_LINE INDENT self . no = n NEW_LINE self . level = l NEW_LINE DEDENT DEDENT def findnthnumber ( n ) : NEW_LINE INDENT q = deque ( ) NEW_LINE r = number ( 0 , 1 ) NEW_LINE q . append ( r ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT temp = q . popleft ( ) NEW_LINE if ( temp . no >= InF or temp . no <= - InF ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( temp . no == n ) : NEW_LINE INDENT print ( " Found β number β n β at β level " , temp . level - 1 ) NEW_LINE break NEW_LINE DEDENT q . append ( number ( temp . no + temp . level , temp . level + 1 ) ) NEW_LINE q . append ( number ( temp . no - temp . level , temp . level + 1 ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT findnthnumber ( 13 ) NEW_LINE DEDENT |
Check if all 3 Candy bags can be emptied by removing 2 candies from any one bag and 1 from the other two repeatedly | Python code for the above approach ; If total candies are not multiple of 4 then its not possible to be left with 0 candies ; If minimum candies of three bags are less than number of operations required then the task is not possible ; Driver code | def can_empty ( a , b , c ) : NEW_LINE INDENT if ( ( a + b + c ) % 4 != 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT else : NEW_LINE INDENT m = min ( a , min ( b , c ) ) ; NEW_LINE if ( m < ( a + b + c ) // 4 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT a = 4 NEW_LINE b = 2 NEW_LINE c = 2 NEW_LINE print ( " true " if can_empty ( a , b , c ) else " false " ) ; NEW_LINE a = 3 NEW_LINE b = 4 NEW_LINE c = 2 NEW_LINE print ( " true " if can_empty ( a , b , c ) else " false " ) ; NEW_LINE |
Difference between maximum and minimum average of all K | Function to find the difference between averages of the maximum and the minimum subarrays of length k ; Stores min and max sum ; Iterate through starting points ; Sum up next K elements ; Update max and min moving sum ; Return the difference between max and min average ; Given Input ; Function Call | def Avgdifference ( arr , N , K ) : NEW_LINE INDENT min = 1000000 ; NEW_LINE max = - 1 ; NEW_LINE for i in range ( N - K + 1 ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for j in range ( K ) : NEW_LINE INDENT sum += arr [ i + j ] ; NEW_LINE DEDENT if ( min > sum ) : NEW_LINE INDENT min = sum ; NEW_LINE DEDENT if ( max < sum ) : NEW_LINE INDENT max = sum ; NEW_LINE DEDENT DEDENT return ( max - min ) / K ; NEW_LINE DEDENT arr = [ 3 , 8 , 9 , 15 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 2 ; NEW_LINE print ( Avgdifference ( arr , N , K ) ) ; NEW_LINE |
Find a number in minimum steps | Python3 program to Find a number in minimum steps ; Steps sequence ; Current sum ; Sign of the number ; Basic steps required to get sum >= required value . ; If we have reached ahead to destination . ; If the last step was an odd number , then it has following mechanism for negating a particular number and decreasing the sum to required number Also note that it may require 1 more step in order to reach the sum . ; If the current time instance is even and sum is odd than it takes 2 more steps and few negations in previous elements to reach there . ; Driver code | def find ( n ) : NEW_LINE INDENT ans = [ ] NEW_LINE Sum = 0 NEW_LINE i = 0 NEW_LINE sign = 0 NEW_LINE if ( n >= 0 ) : NEW_LINE INDENT sign = 1 NEW_LINE DEDENT else : NEW_LINE INDENT sign = - 1 NEW_LINE DEDENT n = abs ( n ) NEW_LINE i = 1 NEW_LINE while ( Sum < n ) : NEW_LINE INDENT ans . append ( sign * i ) NEW_LINE Sum += i NEW_LINE i += 1 NEW_LINE DEDENT if ( Sum > sign * n ) : NEW_LINE INDENT if ( i % 2 != 0 ) : NEW_LINE INDENT Sum -= n NEW_LINE if ( Sum % 2 != 0 ) : NEW_LINE INDENT ans . append ( sign * i ) NEW_LINE Sum += i NEW_LINE i += 1 NEW_LINE DEDENT ans [ int ( Sum / 2 ) - 1 ] *= - 1 NEW_LINE DEDENT else : NEW_LINE INDENT Sum -= n NEW_LINE if ( Sum % 2 != 0 ) : NEW_LINE INDENT Sum -= 1 NEW_LINE ans . append ( sign * i ) NEW_LINE ans . append ( sign * - 1 * ( i + 1 ) ) NEW_LINE DEDENT ans [ int ( ( sum / 2 ) ) - 1 ] *= - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n = 20 NEW_LINE if ( n == 0 ) : NEW_LINE INDENT print ( " Minimum number of Steps : 0 Step sequence : 0 " ) NEW_LINE DEDENT else : NEW_LINE INDENT a = find ( n ) NEW_LINE print ( " Minimum β number β of β Steps : " , len ( a ) ) NEW_LINE print ( " Step β sequence : " ) NEW_LINE print ( * a , sep = " β " ) NEW_LINE DEDENT |
Maximum range length such that A [ i ] is maximum in given range for all i from [ 1 , N ] | Python 3 program for the above approach ; Function to find maximum range for each i such that arr [ i ] is max in range ; Vector to store the left and right index for each i such that left [ i ] > arr [ i ] and right [ i ] > arr [ i ] ; Traverse the array ; While s . top ( ) . first < a [ i ] remove the top element from the stack ; Modify left [ i ] ; Clear the stack ; Traverse the array to find right [ i ] for each i ; While s . top ( ) . first < a [ i ] remove the top element from the stack ; Modify right [ i ] ; Print the value range for each i ; Driver Code ; Given Input ; Function Call | import sys NEW_LINE def MaxRange ( A , n ) : NEW_LINE INDENT left = [ 0 ] * n NEW_LINE right = [ 0 ] * n NEW_LINE s = [ ] NEW_LINE s . append ( ( sys . maxsize , - 1 ) ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( s [ - 1 ] [ 0 ] < A [ i ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT left [ i ] = s [ - 1 ] [ 1 ] NEW_LINE s . append ( ( A [ i ] , i ) ) NEW_LINE DEDENT while ( len ( s ) != 0 ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT s . append ( ( sys . maxsize , n ) ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT while ( s [ - 1 ] [ 0 ] < A [ i ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT right [ i ] = s [ - 1 ] [ 1 ] NEW_LINE s . append ( ( A [ i ] , i ) ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( left [ i ] + 1 , ' β ' , right [ i ] - 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE MaxRange ( arr , n ) NEW_LINE DEDENT |
Find Nth smallest number having exactly 4 divisors | Function to find the nth number which has exactly 4 divisors ; The divs [ ] array to store number of divisors of every element ; The vis [ ] array to check if given number is considered or not ; The cnt stores number of elements having exactly 4 divisors ; Iterate while cnt less than n ; If i is a prime ; Iterate in the range [ 2 * i , 1000000 ] with increment of i ; If the number j is already considered ; Dividing currNum by i until currNum % i is equal to 0 ; Case a single prime in its factorization ; Case of two distinct primes which divides j exactly once each ; Given Input ; Function Call | def nthNumber ( n ) : NEW_LINE INDENT divs = [ 0 for i in range ( 1000000 ) ] ; NEW_LINE vis = [ 0 for i in range ( 1000000 ) ] ; NEW_LINE cnt = 0 ; NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( divs [ i ] == 0 ) : NEW_LINE INDENT for j in range ( 2 * i , 1000000 ) : NEW_LINE INDENT if ( vis [ j ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT vis [ j ] = 1 ; NEW_LINE currNum = j ; NEW_LINE count = 0 ; NEW_LINE while ( currNum % i == 0 ) : NEW_LINE INDENT divs [ j ] += 1 ; NEW_LINE currNum = currNum // i ; NEW_LINE count += 1 ; NEW_LINE DEDENT if ( currNum == 1 and count == 3 and divs [ j ] == 3 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT elif ( currNum != 1 and divs [ currNum ] == 0 and count == 1 and divs [ j ] == 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if ( cnt == n ) : NEW_LINE INDENT return j ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return - 1 ; NEW_LINE DEDENT N = 24 ; NEW_LINE print ( nthNumber ( N ) ) ; NEW_LINE |
Maximum number formed from the digits of given three numbers | Function to find the maximum number formed by taking the maximum digit at the same position from each number ; Stores the result ; Stores the position value of a digit ; Stores the digit at the unit place ; Stores the digit at the unit place ; Stores the digit at the unit place ; Update A , B and C ; Stores the maximum digit ; Increment ans cur * a ; Update cur ; Return ans ; Driver Code ; Given Input ; Function call | def findkey ( A , B , C ) : NEW_LINE INDENT ans = 0 NEW_LINE cur = 1 NEW_LINE while ( A > 0 ) : NEW_LINE INDENT a = A % 10 NEW_LINE b = B % 10 NEW_LINE c = C % 10 NEW_LINE A = A // 10 NEW_LINE B = B // 10 NEW_LINE C = C // 10 NEW_LINE m = max ( a , max ( c , b ) ) NEW_LINE ans += cur * m NEW_LINE cur = cur * 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 3521 NEW_LINE B = 2452 NEW_LINE C = 1352 NEW_LINE print ( findkey ( A , B , C ) ) NEW_LINE DEDENT |
Count of distinct GCDs among all the non | Python 3 program for the above approach ; Function to calculate the number of distinct GCDs among all non - empty subsequences of an array ; variables to store the largest element in array and the required count ; Map to store whether a number is present in A ; calculate largest number in A and mapping A to Mp ; iterate over all possible values of GCD ; variable to check current GCD ; iterate over all multiples of i ; If j is present in A ; calculate gcd of all encountered multiples of i ; current GCD is possible ; return answer ; Driver code ; Input ; Function calling | from math import gcd NEW_LINE def distinctGCDs ( arr , N ) : NEW_LINE INDENT M = - 1 NEW_LINE ans = 0 NEW_LINE Mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT M = max ( M , arr [ i ] ) NEW_LINE Mp [ arr [ i ] ] = 1 NEW_LINE DEDENT for i in range ( 1 , M + 1 , 1 ) : NEW_LINE INDENT currGcd = 0 NEW_LINE for j in range ( i , M + 1 , i ) : NEW_LINE INDENT if ( j in Mp ) : NEW_LINE INDENT currGcd = gcd ( currGcd , j ) NEW_LINE if ( currGcd == i ) : NEW_LINE INDENT ans += 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 11 , 14 , 6 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE print ( distinctGCDs ( arr , N ) ) NEW_LINE DEDENT |
Compress a Binary Tree into an integer diagonally | Python program for the above approach ; Function to compress the elements in an array into an integer ; Check for each bit position ; Update the count of set and non - set bits ; If number of set bits exceeds the number of non - set bits , then add set bits value to ans ; Function to compress a given Binary Tree into an integer ; Declare a map ; Perform Inorder Traversal on the Binary Tree ; Store all nodes of the same line together as a vector ; Increase the vertical distance of left child ; Vertical distance remains same for right child ; Store all the compressed values of diagonal elements in an array ; Compress the array into an integer ; Driver Code Given Input ; Function Call | class TreeNode : NEW_LINE INDENT def __init__ ( self , val = ' ' , left = None , right = None ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def findCompressValue ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE getBit = 1 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT S = 0 NEW_LINE NS = 0 NEW_LINE for j in arr : NEW_LINE INDENT if getBit & j : NEW_LINE INDENT S += 1 NEW_LINE DEDENT else : NEW_LINE INDENT NS += 1 NEW_LINE DEDENT DEDENT if S > NS : NEW_LINE INDENT ans += 2 ** i NEW_LINE DEDENT getBit <<= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def findInteger ( root ) : NEW_LINE INDENT mp = { } NEW_LINE def diagonalOrder ( root , d , mp ) : NEW_LINE INDENT if not root : NEW_LINE INDENT return NEW_LINE DEDENT try : NEW_LINE INDENT mp [ d ] . append ( root . val ) NEW_LINE DEDENT except KeyError : NEW_LINE INDENT mp [ d ] = [ root . val ] NEW_LINE DEDENT diagonalOrder ( root . left , d + 1 , mp ) NEW_LINE diagonalOrder ( root . right , d , mp ) NEW_LINE DEDENT diagonalOrder ( root , 0 , mp ) NEW_LINE arr = [ ] NEW_LINE for i in mp : NEW_LINE INDENT arr . append ( findCompressValue ( mp [ i ] ) ) NEW_LINE DEDENT return findCompressValue ( arr ) NEW_LINE DEDENT root = TreeNode ( 6 ) NEW_LINE root . left = TreeNode ( 5 ) NEW_LINE root . right = TreeNode ( 3 ) NEW_LINE root . left . left = TreeNode ( 3 ) NEW_LINE root . left . right = TreeNode ( 5 ) NEW_LINE root . right . left = TreeNode ( 3 ) NEW_LINE root . right . right = TreeNode ( 4 ) NEW_LINE print ( findInteger ( root ) ) NEW_LINE |
Egg Dropping Puzzle | DP | ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; If there are no floors , then no trials needed . OR if there is one floor , one trial needed . ; We need k trials for one egg and k floors ; Consider all droppings from 1 st floor to kth floor and return the minimum of these values plus 1. ; Driver Code | import sys NEW_LINE def eggDrop ( n , k ) : NEW_LINE INDENT if ( k == 1 or k == 0 ) : NEW_LINE INDENT return k NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return k NEW_LINE DEDENT min = sys . maxsize NEW_LINE for x in range ( 1 , k + 1 ) : NEW_LINE INDENT res = max ( eggDrop ( n - 1 , x - 1 ) , eggDrop ( n , k - x ) ) NEW_LINE if ( res < min ) : NEW_LINE INDENT min = res NEW_LINE DEDENT DEDENT return min + 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 NEW_LINE k = 10 NEW_LINE print ( " Minimum β number β of β trials β in β worst β case β with " , n , " eggs β and " , k , " floors β is " , eggDrop ( n , k ) ) NEW_LINE DEDENT |
K | Function to find the kth digit from last in an eger n ; If k is less than equal to 0 ; Divide the number n by 10 upto k - 1 times ; If the number n is equal 0 ; Pr the right most digit ; Driver code ; Given Input ; Function call | def kthDigitFromLast ( n , k ) : NEW_LINE INDENT if ( k <= 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT while ( ( k - 1 ) > 0 and n > 0 ) : NEW_LINE INDENT n = n / 10 NEW_LINE k -= 1 NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( int ( n % 10 ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2354 NEW_LINE k = 2 NEW_LINE kthDigitFromLast ( n , k ) NEW_LINE DEDENT |
Subsets and Splits