text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Partition a number into two divisible parts | Finds if it is possible to partition str into two parts such that first part is divisible by a and second part is divisible by b . ; Create an array of size lenn + 1 and initialize it with 0. Store remainders from left to right when divided by 'a ; Compute remainders from right to left when divided by 'b ; Find a pothat can partition a number ; If split is not possible at this point ; We can split at i if one of the following two is true . a ) All characters after str [ i ] are 0 b ) after str [ i ] is divisible by b , i . e . , str [ i + 1. . n - 1 ] is divisible by b . ; Driver code | def findDivision ( str , a , b ) : NEW_LINE INDENT lenn = len ( str ) NEW_LINE DEDENT ' NEW_LINE INDENT lr = [ 0 ] * ( lenn + 1 ) NEW_LINE lr [ 0 ] = ( int ( str [ 0 ] ) ) % a NEW_LINE for i in range ( 1 , lenn ) : NEW_LINE INDENT lr [ i ] = ( ( lr [ i - 1 ] * 10 ) % a + int ( str [ i ] ) ) % a NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT rl = [ 0 ] * ( lenn + 1 ) NEW_LINE rl [ lenn - 1 ] = int ( str [ lenn - 1 ] ) % b NEW_LINE power10 = 10 NEW_LINE for i in range ( lenn - 2 , - 1 , - 1 ) : NEW_LINE INDENT rl [ i ] = ( rl [ i + 1 ] + int ( str [ i ] ) * power10 ) % b NEW_LINE power10 = ( power10 * 10 ) % b NEW_LINE DEDENT for i in range ( 0 , lenn - 1 ) : NEW_LINE INDENT if ( lr [ i ] != 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( rl [ i + 1 ] == 0 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE for k in range ( 0 , i + 1 ) : NEW_LINE INDENT print ( str [ k ] , end = " " ) NEW_LINE DEDENT print ( " , " , end = " β " ) NEW_LINE for i in range ( i + 1 , lenn ) : NEW_LINE INDENT print ( str [ k ] , end = " " ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( " NO " ) NEW_LINE DEDENT str = "123" NEW_LINE a , b = 12 , 3 NEW_LINE findDivision ( str , a , b ) NEW_LINE |
Efficient method for 2 's complement of a binary string | Function to find two 's complement ; Traverse the string to get first '1' from the last of string ; If there exists no '1' concatenate 1 at the starting of string ; Continue traversal after the position of first '1 ; Just flip the values ; return the modified string ; Driver code | def findTwoscomplement ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT if ( i == - 1 ) : NEW_LINE INDENT return '1' + str NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT k = i - 1 NEW_LINE while ( k >= 0 ) : NEW_LINE INDENT if ( str [ k ] == '1' ) : NEW_LINE INDENT str = list ( str ) NEW_LINE str [ k ] = '0' NEW_LINE str = ' ' . join ( str ) NEW_LINE DEDENT else : NEW_LINE INDENT str = list ( str ) NEW_LINE str [ k ] = '1' NEW_LINE str = ' ' . join ( str ) NEW_LINE DEDENT k -= 1 NEW_LINE DEDENT return str NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "00000101" NEW_LINE print ( findTwoscomplement ( str ) ) NEW_LINE DEDENT |
Check length of a string is equal to the number appended at its last | Function to find if given number is equal to length or not ; Traverse string from end and find the number stored at the end . x is used to store power of 10. ; Check if number is equal to string length except that number 's digits ; Driver Code | def isequal ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE num = 0 NEW_LINE x = 1 NEW_LINE i = n - 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( '0' <= str [ i ] and str [ i ] <= '9' ) : NEW_LINE INDENT num = ( ord ( str [ i ] ) - ord ( '0' ) ) * x + num NEW_LINE x = x * 10 NEW_LINE if ( num >= n ) : NEW_LINE INDENT return false NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return num == i + 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeksforgeeks13" NEW_LINE print ( " Yes " ) if isequal ( str ) else print ( " No " ) NEW_LINE DEDENT |
Check if two strings are k | Python 3 program for the above approach ; Function to check k anagram of two strings ; First Condition : If both the strings have different length , then they cannot form anagram ; Converting str1 to Character Array arr1 ; Converting str2 to Character Array arr2 ; Sort arr1 in increasing order ; Sort arr2 in increasing order ; Iterate till str1 . length ( ) ; Condition if arr1 [ i ] is not equal to arr2 [ i ] then add it to list ; Condition to check if strings for K - anagram or not ; Driver Code ; Function Call | import sys NEW_LINE def kAnagrams ( str1 , str2 , k ) : NEW_LINE INDENT flag = 0 NEW_LINE list1 = [ ] NEW_LINE if ( len ( str1 ) != len ( str2 ) ) : NEW_LINE INDENT sys . exit ( ) NEW_LINE DEDENT arr1 = list ( str1 ) NEW_LINE arr2 = list ( str2 ) NEW_LINE arr1 . sort ( ) NEW_LINE arr2 . sort ( ) NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT if ( arr1 [ i ] != arr2 [ i ] ) : NEW_LINE INDENT list1 . append ( arr2 [ i ] ) NEW_LINE DEDENT DEDENT if ( len ( list1 ) <= k ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT if ( flag == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " fodr " NEW_LINE str2 = " gork " NEW_LINE k = 2 NEW_LINE kAnagrams ( str1 , str2 , k ) NEW_LINE if ( kAnagrams ( str1 , str2 , k ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Minimum number of characters to be removed to make a binary string alternate | Returns count of minimum characters to be removed to make s alternate . ; if two alternating characters of string are same ; result += 1 then need to delete a character ; Driver code | def countToMake0lternate ( s ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( len ( s ) - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( countToMake0lternate ( "000111" ) ) NEW_LINE print ( countToMake0lternate ( "11111" ) ) NEW_LINE print ( countToMake0lternate ( "01010101" ) ) NEW_LINE DEDENT |
Convert to a string that is repetition of a substring of k length | Returns True if S can be converted to a with k repeated subs after replacing k characters . ; Length of must be a multiple of k ; Map to store s of length k and their counts ; If is already a repetition of k subs , return True . ; If number of distinct subs is not 2 , then not possible to replace a . ; One of the two distinct must appear exactly once . Either the first entry appears once , or it appears n / k - 1 times to make other sub appear once . ; Driver code | def check ( S , k ) : NEW_LINE INDENT n = len ( S ) NEW_LINE if ( n % k != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT mp = { } NEW_LINE for i in range ( 0 , n , k ) : NEW_LINE INDENT mp [ S [ i : k ] ] = mp . get ( S [ i : k ] , 0 ) + 1 NEW_LINE DEDENT if ( len ( mp ) == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( len ( mp ) != 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in mp : NEW_LINE INDENT if i == ( n // k - 1 ) or mp [ i ] == 1 : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if check ( " abababcd " , 2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Group all occurrences of characters according to first appearance | Since only lower case characters are there ; Function to print the string ; Initialize counts of all characters as 0 ; Count occurrences of all characters in string ; Starts traversing the string ; Print the character till its count in hash array ; Make this character 's count value as 0. ; Driver code | MAX_CHAR = 26 NEW_LINE def printGrouped ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE count = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ ord ( string [ i ] ) - ord ( " a " ) ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT while count [ ord ( string [ i ] ) - ord ( " a " ) ] : NEW_LINE INDENT print ( string [ i ] , end = " " ) NEW_LINE count [ ord ( string [ i ] ) - ord ( " a " ) ] -= 1 NEW_LINE DEDENT count [ ord ( string [ i ] ) - ord ( " a " ) ] = 0 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " NEW_LINE printGrouped ( string ) NEW_LINE DEDENT |
Sort a string according to the order defined by another string | Python3 program to sort a string according to the order defined by a pattern string ; Sort str according to the order defined by pattern . ; Create a count array store count of characters in str . ; Count number of occurrences of each character in str . ; Traverse the pattern and print every characters same number of times as it appears in str . This loop takes O ( m + n ) time where m is length of pattern and n is length of str . ; Driver code | MAX_CHAR = 26 NEW_LINE def sortByPattern ( str , pat ) : NEW_LINE INDENT global MAX_CHAR NEW_LINE count = [ 0 ] * MAX_CHAR NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT count [ ord ( str [ i ] ) - 97 ] += 1 NEW_LINE DEDENT index = 0 ; NEW_LINE str = " " NEW_LINE for i in range ( 0 , len ( pat ) ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < count [ ord ( pat [ i ] ) - ord ( ' a ' ) ] ) : NEW_LINE INDENT str += pat [ i ] NEW_LINE j = j + 1 NEW_LINE index += 1 NEW_LINE DEDENT DEDENT return str NEW_LINE DEDENT pat = " bca " NEW_LINE str = " abc " NEW_LINE print ( sortByPattern ( str , pat ) ) NEW_LINE |
Number of flips to make binary string alternate | Set 1 | Utility method to flip a character ; Utility method to get minimum flips when alternate string starts with expected char ; if current character is not expected , increase flip count ; flip expected character each time ; method return minimum flip to make binary string alternate ; return minimum of following two 1 ) flips when alternate string starts with 0 2 ) flips when alternate string starts with 1 ; Driver code to test above method | def flip ( ch ) : NEW_LINE INDENT return '1' if ( ch == '0' ) else '0' NEW_LINE DEDENT def getFlipWithStartingCharcter ( str , expected ) : NEW_LINE INDENT flipCount = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] != expected ) : NEW_LINE INDENT flipCount += 1 NEW_LINE DEDENT expected = flip ( expected ) NEW_LINE DEDENT return flipCount NEW_LINE DEDENT def minFlipToMakeStringAlternate ( str ) : NEW_LINE INDENT return min ( getFlipWithStartingCharcter ( str , '0' ) , getFlipWithStartingCharcter ( str , '1' ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = "0001010111" NEW_LINE print ( minFlipToMakeStringAlternate ( str ) ) NEW_LINE DEDENT |
Remainder with 7 for large numbers | Function which return Remainder after dividing the number by 7 ; This series is used to find remainder with 7 ; Index of next element in series ; Initialize result ; Traverse num from end ; Find current digit of num ; Add next term to result ; Move to next term in series ; Make sure that result never goes beyond 7. ; Make sure that remainder is positive ; Driver Code | def remainderWith7 ( num ) : NEW_LINE INDENT series = [ 1 , 3 , 2 , - 1 , - 3 , - 2 ] ; NEW_LINE series_index = 0 ; NEW_LINE result = 0 ; NEW_LINE for i in range ( ( len ( num ) - 1 ) , - 1 , - 1 ) : NEW_LINE INDENT digit = ord ( num [ i ] ) - 48 ; NEW_LINE result += digit * series [ series_index ] ; NEW_LINE series_index = ( series_index + 1 ) % 6 ; NEW_LINE result %= 7 ; NEW_LINE DEDENT if ( result < 0 ) : NEW_LINE INDENT result = ( result + 7 ) % 7 ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT str = "12345" ; NEW_LINE print ( " Remainder β with β 7 β is " , remainderWith7 ( str ) ) ; NEW_LINE |
Check if a string can become empty by recursively deleting a given sub | Returns true if str can be made empty by recursively removing sub_str . ; idx : to store starting index of sub - string found in the original string ; Erasing the found sub - string from the original string ; Driver code | def canBecomeEmpty ( string , sub_str ) : NEW_LINE INDENT while len ( string ) > 0 : NEW_LINE INDENT idx = string . find ( sub_str ) NEW_LINE if idx == - 1 : NEW_LINE INDENT break NEW_LINE DEDENT string = string . replace ( sub_str , " " , 1 ) NEW_LINE DEDENT return ( len ( string ) == 0 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GEEGEEKSKS " NEW_LINE sub_str = " GEEKS " NEW_LINE if canBecomeEmpty ( string , sub_str ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Perfect reversible string | This function basically checks if string is palindrome or not ; iterate from left and right ; Driver Code | def isReversible ( str ) : NEW_LINE INDENT i = 0 ; j = len ( str ) - 1 ; NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( str [ i ] != str [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT str = " aba " ; NEW_LINE if ( isReversible ( str ) ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE DEDENT |
Check if string follows order of characters defined by a pattern or not | Set 3 | Python3 program to find if a string follows order defined by a given pattern ; Returns true if characters of str follow order defined by a given ptr . ; Initialize all orders as - 1 ; Assign an order to pattern characters according to their appearance in pattern ; Give the pattern characters order ; Increment the order ; Now one by one check if string characters follow above order ; If order of this character is less than order of previous , return false ; Update last_order for next iteration ; return that str followed pat ; Driver Code | CHAR_SIZE = 256 NEW_LINE def checkPattern ( Str , pat ) : NEW_LINE INDENT label = [ - 1 ] * CHAR_SIZE NEW_LINE order = 1 NEW_LINE for i in range ( len ( pat ) ) : NEW_LINE INDENT label [ ord ( pat [ i ] ) ] = order NEW_LINE order += 1 NEW_LINE DEDENT last_order = - 1 NEW_LINE for i in range ( len ( Str ) ) : NEW_LINE INDENT if ( label [ ord ( Str [ i ] ) ] != - 1 ) : NEW_LINE INDENT if ( label [ ord ( Str [ i ] ) ] < last_order ) : NEW_LINE INDENT return False NEW_LINE DEDENT last_order = label [ ord ( Str [ i ] ) ] NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Str = " engineers β rock " NEW_LINE pattern = " gsr " NEW_LINE print ( checkPattern ( Str , pattern ) ) NEW_LINE DEDENT |
Check if string follows order of characters defined by a pattern or not | Set 2 | Python3 program to check if characters of a string follow pattern defined by given pattern . ; Insert all characters of pattern in a hash set , ; Build modified string ( string with characters only from pattern are taken ) ; Remove more than one consecutive occurrences of pattern characters from modified string . ; After above modifications , the length of modified string must be same as pattern length ; And pattern characters must also be same as modified string characters ; Driver Code | def followsPattern ( string , pattern ) : NEW_LINE INDENT patternSet = set ( ) NEW_LINE for i in range ( len ( pattern ) ) : NEW_LINE INDENT patternSet . add ( pattern [ i ] ) NEW_LINE DEDENT modifiedString = string NEW_LINE for i in range ( len ( string ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if not modifiedString [ i ] in patternSet : NEW_LINE INDENT modifiedString = modifiedString [ : i ] + modifiedString [ i + 1 : ] NEW_LINE DEDENT DEDENT for i in range ( len ( modifiedString ) - 1 , 0 , - 1 ) : NEW_LINE INDENT if modifiedString [ i ] == modifiedString [ i - 1 ] : NEW_LINE INDENT modifiedString = modifiedString [ : i ] + modifiedString [ i + 1 : ] NEW_LINE DEDENT DEDENT if len ( pattern ) != len ( modifiedString ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( len ( pattern ) ) : NEW_LINE INDENT if pattern [ i ] != modifiedString [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " engineers β rock " NEW_LINE pattern = " er " NEW_LINE print ( " Expected : β true , β Actual : " , followsPattern ( string , pattern ) ) NEW_LINE string = " engineers β rock " NEW_LINE pattern = " egr " NEW_LINE print ( " Expected : β false , β Actual : " , followsPattern ( string , pattern ) ) NEW_LINE string = " engineers β rock " NEW_LINE pattern = " gsr " NEW_LINE print ( " Expected : β false , β Actual : " , followsPattern ( string , pattern ) ) NEW_LINE string = " engineers β rock " NEW_LINE pattern = " eger " NEW_LINE print ( " Expected : β true , β Actual : " , followsPattern ( string , pattern ) ) NEW_LINE DEDENT |
Find k 'th character of decrypted string | Set 1 | Function to find K 'th character in Encoded String ; expand string variable is used to store final string after decompressing string str ; Current substring freq = 0 Count of current substring ; read characters until you find a number or end of string ; push character in temp ; read number for how many times string temp will be repeated in decompressed string ; generating frequency of temp ; now append string temp into expand equal to its frequency ; this condition is to handle the case when string str is ended with alphabets not with numeric value ; Driver Code | def encodedChar ( str , k ) : NEW_LINE INDENT expand = " " NEW_LINE i = 0 NEW_LINE while ( i < len ( str ) ) : NEW_LINE INDENT while ( i < len ( str ) and ord ( str [ i ] ) >= ord ( ' a ' ) and ord ( str [ i ] ) <= ord ( ' z ' ) ) : NEW_LINE INDENT temp += str [ i ] NEW_LINE i += 1 NEW_LINE DEDENT while ( i < len ( str ) and ord ( str [ i ] ) >= ord ( '1' ) and ord ( str [ i ] ) <= ord ( '9' ) ) : NEW_LINE INDENT freq = freq * 10 + ord ( str [ i ] ) - ord ( '0' ) NEW_LINE i += 1 NEW_LINE DEDENT for j in range ( 1 , freq + 1 , 1 ) : NEW_LINE INDENT expand += temp NEW_LINE DEDENT DEDENT if ( freq == 0 ) : NEW_LINE INDENT expand += temp NEW_LINE DEDENT return expand [ k - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " ab4c12ed3" NEW_LINE k = 21 NEW_LINE print ( encodedChar ( str , k ) ) NEW_LINE DEDENT |
Converting Decimal Number lying between 1 to 3999 to Roman Numerals | Function to calculate roman equivalent ; Storing roman values of digits from 0 - 9 when placed at different places ; Converting to roman ; Driver code | def intToRoman ( num ) : NEW_LINE INDENT m = [ " " , " M " , " MM " , " MMM " ] NEW_LINE c = [ " " , " C " , " CC " , " CCC " , " CD " , " D " , " DC " , " DCC " , " DCCC " , " CM β " ] NEW_LINE x = [ " " , " X " , " XX " , " XXX " , " XL " , " L " , " LX " , " LXX " , " LXXX " , " XC " ] NEW_LINE i = [ " " , " I " , " II " , " III " , " IV " , " V " , " VI " , " VII " , " VIII " , " IX " ] NEW_LINE thousands = m [ num // 1000 ] NEW_LINE hundereds = c [ ( num % 1000 ) // 100 ] NEW_LINE tens = x [ ( num % 100 ) // 10 ] NEW_LINE ones = i [ num % 10 ] NEW_LINE ans = ( thousands + hundereds + tens + ones ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT number = 3549 NEW_LINE print ( intToRoman ( number ) ) NEW_LINE DEDENT |
Longest Common Prefix using Binary Search | A Function to find the string having the minimum length and returns that length ; A Function that returns the longest common prefix from the array of strings ; We will do an in - place binary search on the first string of the array in the range 0 to index ; Same as ( low + high ) / 2 , but avoids overflow for large low and high ; If all the strings in the input array contains this prefix then append this substring to our answer ; And then go for the right part ; Go for the left part ; Driver Code | def findMinLength ( strList ) : NEW_LINE INDENT return len ( min ( arr , key = len ) ) NEW_LINE DEDENT def allContainsPrefix ( strList , str , start , end ) : NEW_LINE INDENT for i in range ( 0 , len ( strList ) ) : NEW_LINE INDENT word = strList [ i ] NEW_LINE for j in range ( start , end + 1 ) : NEW_LINE INDENT if word [ j ] != str [ j ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def CommonPrefix ( strList ) : NEW_LINE INDENT index = findMinLength ( strList ) NEW_LINE low , high = 0 , index - 1 NEW_LINE while low <= high : NEW_LINE INDENT mid = int ( low + ( high - low ) / 2 ) NEW_LINE if allContainsPrefix ( strList , strList [ 0 ] , low , mid ) : NEW_LINE INDENT prefix = prefix + strList [ 0 ] [ low : mid + 1 ] NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return prefix NEW_LINE DEDENT arr = [ " geeksforgeeks " , " geeks " , " geek " , " geezer " ] NEW_LINE lcp = CommonPrefix ( arr ) NEW_LINE if len ( lcp ) > 0 : NEW_LINE INDENT print ( " The β longest β common β prefix β is β " + str ( lcp ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " There β is β no β common β prefix " ) NEW_LINE DEDENT |
Lower case to upper case | Converts a string to uppercase ; Driver code | def to_upper ( s ) : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( ' a ' <= s [ i ] <= ' z ' ) : NEW_LINE INDENT s = s [ 0 : i ] + chr ( ord ( s [ i ] ) & ( ~ ( 1 << 5 ) ) ) + s [ i + 1 : ] ; NEW_LINE DEDENT DEDENT return s ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE print ( to_upper ( string ) ) ; NEW_LINE DEDENT |
Longest Common Prefix using Divide and Conquer Algorithm | A Utility Function to find the common prefix between strings - str1 and str2 ; A Divide and Conquer based function to find the longest common prefix . This is similar to the merge sort technique ; Same as ( low + high ) / 2 , but avoids overflow for large low and high ; Driver Code | def commonPrefixUtil ( str1 , str2 ) : NEW_LINE INDENT result = " " NEW_LINE n1 , n2 = len ( str1 ) , len ( str2 ) NEW_LINE i , j = 0 , 0 NEW_LINE while i <= n1 - 1 and j <= n2 - 1 : NEW_LINE INDENT if str1 [ i ] != str2 [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT result += str1 [ i ] NEW_LINE i , j = i + 1 , j + 1 NEW_LINE DEDENT return result NEW_LINE DEDENT def commonPrefix ( arr , low , high ) : NEW_LINE INDENT if low == high : NEW_LINE INDENT return arr [ low ] NEW_LINE DEDENT if high > low : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE str1 = commonPrefix ( arr , low , mid ) NEW_LINE str2 = commonPrefix ( arr , mid + 1 , high ) NEW_LINE return commonPrefixUtil ( str1 , str2 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " geeksforgeeks " , " geeks " , " geek " , " geezer " ] NEW_LINE n = len ( arr ) NEW_LINE ans = commonPrefix ( arr , 0 , n - 1 ) NEW_LINE if len ( ans ) : NEW_LINE INDENT print ( " The β longest β common β prefix β is " , ans ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " There β is β no β common β prefix " ) NEW_LINE DEDENT DEDENT |
Longest Common Prefix using Word by Word Matching | A Utility Function to find the common prefix between strings - str1 and str2 ; Compare str1 and str2 ; A Function that returns the longest common prefix from the array of strings ; Driver Code | def commonPrefixUtil ( str1 , str2 ) : NEW_LINE INDENT result = " " ; NEW_LINE n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while i <= n1 - 1 and j <= n2 - 1 : NEW_LINE INDENT if ( str1 [ i ] != str2 [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT result += str1 [ i ] NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return ( result ) NEW_LINE DEDENT def commonPrefix ( arr , n ) : NEW_LINE INDENT prefix = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix = commonPrefixUtil ( prefix , arr [ i ] ) NEW_LINE DEDENT return ( prefix ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " geeksforgeeks " , " geeks " , " geek " , " geezer " ] NEW_LINE n = len ( arr ) NEW_LINE ans = commonPrefix ( arr , n ) NEW_LINE if ( len ( ans ) ) : NEW_LINE INDENT print ( " The β longest β common β prefix β is β - " , ans ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " There β is β no β common β prefix " ) NEW_LINE DEDENT DEDENT |
Find all strings formed from characters mapped to digits of a number | Function to find all strings formed from a given number where each digit maps to given characters . ; vector of strings to store output ; stores index of first occurrence of the digits in input ; maintains index of current digit considered ; for each digit ; store index of first occurrence of the digit in the map ; clear vector contents for future use ; do for each character thats maps to the digit ; for first digit , simply push all its mapped characters in the output list ; from second digit onwards ; for each string in output list append current character to it . ; convert current character to string ; Imp - If this is not the first occurrence of the digit , use same character as used in its first occurrence ; store strings formed by current digit ; nothing more needed to be done if this is not the first occurrence of the digit ; replace contents of output list with temp list ; Driver Code ; vector to store the mappings ; vector to store input number ; print all possible strings | def findCombinations ( input : list , table : list ) -> list : NEW_LINE INDENT out , temp = [ ] , [ ] NEW_LINE mp = dict ( ) NEW_LINE index = 0 NEW_LINE for d in input : NEW_LINE INDENT if d not in mp : NEW_LINE INDENT mp [ d ] = index NEW_LINE DEDENT temp . clear ( ) NEW_LINE for i in range ( len ( table [ d - 1 ] ) ) : NEW_LINE INDENT if index == 0 : NEW_LINE INDENT s = table [ d - 1 ] [ i ] NEW_LINE out . append ( s ) NEW_LINE DEDENT if index > 0 : NEW_LINE INDENT for string in out : NEW_LINE INDENT s = table [ d - 1 ] [ i ] NEW_LINE if mp [ d ] != index : NEW_LINE INDENT s = string [ mp [ d ] ] NEW_LINE DEDENT string = string + s NEW_LINE temp . append ( string ) NEW_LINE DEDENT if mp [ d ] != index : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if index > 0 : NEW_LINE INDENT out = temp . copy ( ) NEW_LINE DEDENT index += 1 NEW_LINE DEDENT return out NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT table = [ [ ' A ' , ' B ' , ' C ' ] , [ ' D ' , ' E ' , ' F ' ] , [ ' G ' , ' H ' , ' I ' ] , [ ' J ' , ' K ' , ' L ' ] , [ ' M ' , ' N ' , ' O ' ] , [ ' P ' , ' Q ' , ' R ' ] , [ ' S ' , ' T ' , ' U ' ] , [ ' V ' , ' W ' , ' X ' ] , [ ' Y ' , ' Z ' ] ] NEW_LINE input = [ 1 , 2 , 1 ] NEW_LINE out = findCombinations ( input , table ) NEW_LINE for it in out : NEW_LINE INDENT print ( it , end = " β " ) NEW_LINE DEDENT DEDENT |
1 ' s β and β 2' s complement of a Binary Number | Returns '0' for '1' and '1' for '0 ; Print 1 ' s β and β 2' s complement of binary number represented by " bin " ; for ones complement flip every bit ; for two 's complement go from right to left in ones complement and if we get 1 make, we make them 0 and keep going left when we get first 0, make that 1 and go out of loop ; If No break : all are 1 as in 111 or 11111 in such case , add extra 1 at beginning ; Driver Code | ' NEW_LINE def flip ( c ) : NEW_LINE INDENT return '1' if ( c == '0' ) else '0' NEW_LINE DEDENT def printOneAndTwosComplement ( bin ) : NEW_LINE INDENT n = len ( bin ) NEW_LINE ones = " " NEW_LINE twos = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT ones += flip ( bin [ i ] ) NEW_LINE DEDENT ones = list ( ones . strip ( " " ) ) NEW_LINE twos = list ( ones ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( ones [ i ] == '1' ) : NEW_LINE INDENT twos [ i ] = '0' NEW_LINE DEDENT else : NEW_LINE INDENT twos [ i ] = '1' NEW_LINE break NEW_LINE DEDENT DEDENT i -= 1 NEW_LINE if ( i == - 1 ) : NEW_LINE INDENT twos . insert ( 0 , '1' ) NEW_LINE DEDENT print ( "1 ' s β complement : β " , * ones , sep = " " ) NEW_LINE print ( "2 ' s β complement : β " , * twos , sep = " " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT bin = "1100" NEW_LINE printOneAndTwosComplement ( bin . strip ( " " ) ) NEW_LINE DEDENT |
Print Concatenation of Zig | Function for zig - zag Concatenation ; Check is n is less or equal to 1 ; Iterate rowNum from 0 to n - 1 ; Iterate i till s . length ( ) - 1 ; Check is rowNum is 0 or n - 1 ; Driver Code | def zigZagConcat ( s , n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return s NEW_LINE DEDENT result = " " NEW_LINE for rowNum in range ( n ) : NEW_LINE INDENT i = rowNum NEW_LINE up = True NEW_LINE while ( i < len ( s ) ) : NEW_LINE INDENT result += s [ i ] NEW_LINE if ( rowNum == 0 or rowNum == n - 1 ) : NEW_LINE INDENT i += ( 2 * n - 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( up ) : NEW_LINE INDENT i += ( 2 * ( n - rowNum ) - 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT i += rowNum * 2 NEW_LINE DEDENT up ^= True NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT str = " GEEKSFORGEEKS " NEW_LINE n = 3 NEW_LINE print ( zigZagConcat ( str , n ) ) NEW_LINE |
Print string of odd length in ' X ' format | Function to print given string in cross pattern ; i and j are the indexes of characters to be displayed in the ith iteration i = 0 initially and go upto length of string j = length of string initially in each iteration of i , we increment i and decrement j , we print character only of k == i or k == j ; driver code | def pattern ( st , length ) : NEW_LINE INDENT for i in range ( length ) : NEW_LINE INDENT j = length - 1 - i NEW_LINE for k in range ( length ) : NEW_LINE INDENT if ( k == i or k == j ) : NEW_LINE INDENT print ( st [ k ] , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " β " , end = " " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " geeksforgeeks " NEW_LINE length = len ( st ) NEW_LINE pattern ( st , length ) NEW_LINE DEDENT |
Check if characters of a given string can be rearranged to form a palindrome | Python3 implementation to check if characters of a given string can be rearranged to form a palindrome ; function to check whether characters of a string can form a palindrome ; Create a count array and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; Count odd occurring characters ; Return true if odd count is 0 or 1 , ; Driver code | NO_OF_CHARS = 256 NEW_LINE def canFormPalindrome ( st ) : NEW_LINE INDENT count = [ 0 ] * ( NO_OF_CHARS ) NEW_LINE for i in range ( 0 , len ( st ) ) : NEW_LINE INDENT count [ ord ( st [ i ] ) ] = count [ ord ( st [ i ] ) ] + 1 NEW_LINE DEDENT odd = 0 NEW_LINE for i in range ( 0 , NO_OF_CHARS ) : NEW_LINE INDENT if ( count [ i ] & 1 ) : NEW_LINE INDENT odd = odd + 1 NEW_LINE DEDENT if ( odd > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if ( canFormPalindrome ( " geeksforgeeks " ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT if ( canFormPalindrome ( " geeksogeeks " ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Generate n | This function generates all n bit Gray codes and prints the generated codes ; Base case ; Recursive case ; Append 0 to the first half ; Append 1 to the second half ; Function to generate the Gray code of N bits ; Print contents of arr ; Driver Code | def generateGray ( n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return [ "0" ] NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return [ "0" , "1" ] NEW_LINE DEDENT recAns = generateGray ( n - 1 ) NEW_LINE mainAns = [ ] NEW_LINE for i in range ( len ( recAns ) ) : NEW_LINE INDENT s = recAns [ i ] NEW_LINE mainAns . append ( "0" + s ) NEW_LINE DEDENT for i in range ( len ( recAns ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT s = recAns [ i ] NEW_LINE mainAns . append ( "1" + s ) NEW_LINE DEDENT return mainAns NEW_LINE DEDENT def generateGrayarr ( n ) : NEW_LINE INDENT arr = generateGray ( n ) NEW_LINE print ( * arr , sep = " " ) NEW_LINE DEDENT generateGrayarr ( 3 ) NEW_LINE |
Check whether two strings are anagram of each other | Python program to check if two strings are anagrams of each other ; Function to check whether two strings are anagram of each other ; Create two count arrays and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; Compare count arrays ; Driver code ; Function call | NO_OF_CHARS = 256 NEW_LINE def areAnagram ( str1 , str2 ) : NEW_LINE INDENT count1 = [ 0 ] * NO_OF_CHARS NEW_LINE count2 = [ 0 ] * NO_OF_CHARS NEW_LINE for i in str1 : NEW_LINE INDENT count1 [ ord ( i ) ] += 1 NEW_LINE DEDENT for i in str2 : NEW_LINE INDENT count2 [ ord ( i ) ] += 1 NEW_LINE DEDENT if len ( str1 ) != len ( str2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in xrange ( NO_OF_CHARS ) : NEW_LINE INDENT if count1 [ i ] != count2 [ i ] : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT str1 = " geeksforgeeks " NEW_LINE str2 = " forgeeksgeeks " NEW_LINE if areAnagram ( str1 , str2 ) : NEW_LINE INDENT print " The β two β strings β are β anagram β of β each β other " NEW_LINE DEDENT else : NEW_LINE INDENT print " The β two β strings β are β not β anagram β of β each β other " NEW_LINE DEDENT |
Find the smallest window in a string containing all characters of another string | Python3 program to find the smallest window containing all characters of a pattern . ; Function to find smallest window containing all characters of 'pat ; Check if string ' s β length β is β β less β than β pattern ' s length . If yes then no such window can exist ; Store occurrence ofs characters of pattern ; Start traversing the string count = 0 count of characters ; count occurrence of characters of string ; If string ' s β char β matches β with β β pattern ' s char then increment count ; if all the characters are matched ; Try to minimize the window ; update window size ; If no window found ; Return substring starting from start_index and length min_len ; Driver code | no_of_chars = 256 NEW_LINE ' NEW_LINE def findSubString ( string , pat ) : NEW_LINE INDENT len1 = len ( string ) NEW_LINE len2 = len ( pat ) NEW_LINE if len1 < len2 : NEW_LINE INDENT print ( " No β such β window β exists " ) NEW_LINE return " " NEW_LINE DEDENT hash_pat = [ 0 ] * no_of_chars NEW_LINE hash_str = [ 0 ] * no_of_chars NEW_LINE for i in range ( 0 , len2 ) : NEW_LINE INDENT hash_pat [ ord ( pat [ i ] ) ] += 1 NEW_LINE DEDENT start , start_index , min_len = 0 , - 1 , float ( ' inf ' ) NEW_LINE for j in range ( 0 , len1 ) : NEW_LINE INDENT hash_str [ ord ( string [ j ] ) ] += 1 NEW_LINE if ( hash_str [ ord ( string [ j ] ) ] <= hash_pat [ ord ( string [ j ] ) ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if count == len2 : NEW_LINE INDENT while ( hash_str [ ord ( string [ start ] ) ] > hash_pat [ ord ( string [ start ] ) ] or hash_pat [ ord ( string [ start ] ) ] == 0 ) : NEW_LINE INDENT if ( hash_str [ ord ( string [ start ] ) ] > hash_pat [ ord ( string [ start ] ) ] ) : NEW_LINE INDENT hash_str [ ord ( string [ start ] ) ] -= 1 NEW_LINE DEDENT start += 1 NEW_LINE DEDENT len_window = j - start + 1 NEW_LINE if min_len > len_window : NEW_LINE INDENT min_len = len_window NEW_LINE start_index = start NEW_LINE DEDENT DEDENT DEDENT if start_index == - 1 : NEW_LINE INDENT print ( " No β such β window β exists " ) NEW_LINE return " " NEW_LINE DEDENT return string [ start_index : start_index + min_len ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " this β is β a β test β string " NEW_LINE pat = " tist " NEW_LINE print ( " Smallest β window β is β : β " ) NEW_LINE print ( findSubString ( string , pat ) ) NEW_LINE DEDENT |
Remove characters from the first string which are present in the second string | Python 3 program to remove duplicates ; we extract every character of string string 2 ; we find char exit or not ; if char exit we simply remove that char ; Driver Code | def removeChars ( string1 , string2 ) : NEW_LINE INDENT for i in string2 : NEW_LINE INDENT while i in string1 : NEW_LINE INDENT itr = string1 . find ( i ) NEW_LINE string1 = string1 . replace ( i , ' ' ) NEW_LINE DEDENT DEDENT return string1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string1 = " geeksforgeeks " NEW_LINE string2 = " mask " NEW_LINE print ( removeChars ( string1 , string2 ) ) NEW_LINE DEDENT |
Remove duplicates from a given string | Python3 program to remove duplicate character from character array and prin sorted order ; Used as index in the modified string ; Traverse through all characters ; Check if str [ i ] is present before it ; If not present , then add it to result . ; Driver code | def removeDuplicate ( str , n ) : NEW_LINE INDENT index = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , i + 1 ) : NEW_LINE INDENT if ( str [ i ] == str [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( j == i ) : NEW_LINE INDENT str [ index ] = str [ i ] NEW_LINE index += 1 NEW_LINE DEDENT DEDENT return " " . join ( str [ : index ] ) NEW_LINE DEDENT str = " geeksforgeeks " NEW_LINE n = len ( str ) NEW_LINE print ( removeDuplicate ( list ( str ) , n ) ) NEW_LINE |
Check if it β s possible to completely fill every container with same ball | A boolean function that returns true if it 's possible to completely fill the container else return false ; Base Case ; Backtracking ; Function to check the conditions ; Storing frequencies ; Function Call for backtracking ; Driver Code ; Given Input ; Function Call | def getans ( i , v , q ) : NEW_LINE INDENT if ( i == len ( q ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT for j in range ( len ( v ) ) : NEW_LINE INDENT if ( v [ j ] >= q [ i ] ) : NEW_LINE INDENT v [ j ] -= q [ i ] NEW_LINE if ( getans ( i + 1 , v , q ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT v [ j ] += q [ i ] NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def Check ( c , b ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( len ( b ) ) : NEW_LINE INDENT if b [ i ] in m : NEW_LINE INDENT m [ b [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ b [ i ] ] = 1 NEW_LINE DEDENT DEDENT v = [ ] NEW_LINE for key , value in m . items ( ) : NEW_LINE INDENT v . append ( value ) NEW_LINE DEDENT check = getans ( 0 , v , c ) NEW_LINE if ( check ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT c = [ 1 , 3 , 3 ] NEW_LINE b = [ 2 , 2 , 2 , 2 , 4 , 4 , 4 ] NEW_LINE Check ( c , b ) NEW_LINE DEDENT |
Maximum Bitwise XOR of node values of an Acyclic Graph made up of N given vertices using M edges | Function to find the maximum Bitwise XOR of any subset of the array of size K ; Number of node must K + 1 for K edges ; Stores the maximum Bitwise XOR ; Generate all subsets of the array ; __builtin_popcount ( ) returns the number of sets bits in an integer ; Initialize current xor as 0 ; If jth bit is set in i then include jth element in the current xor ; Update the maximum Bitwise XOR obtained so far ; Return the maximum XOR ; Driver Code | def maximumXOR ( arr , n , K ) : NEW_LINE INDENT K += 1 NEW_LINE maxXor = - 10 ** 9 NEW_LINE for i in range ( 1 << n ) : NEW_LINE INDENT if ( bin ( i ) . count ( '1' ) == K ) : NEW_LINE INDENT cur_xor = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( i & ( 1 << j ) ) : NEW_LINE INDENT cur_xor = cur_xor ^ arr [ j ] NEW_LINE DEDENT DEDENT maxXor = max ( maxXor , cur_xor ) NEW_LINE DEDENT DEDENT return maxXor NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE M = 2 NEW_LINE print ( maximumXOR ( arr , N , M ) ) NEW_LINE DEDENT |
Tower of Hanoi | Set 2 | Python program for the above approach ; Function to print order of movement of N disks across three rods to place all disks on the third rod from the first - rod using binary representation ; Iterate over the range [ 0 , 2 ^ N - 1 ] ; Print the movement of the current rod ; Driver Code | import math NEW_LINE def TowerOfHanoi ( N ) : NEW_LINE INDENT for x in range ( 1 , int ( math . pow ( 2 , N ) ) ) : NEW_LINE INDENT print ( " Move β from β Rod β " , ( ( x & x - 1 ) % 3 + 1 ) , " β to β Rod β " , ( ( ( x x - 1 ) + 1 ) % 3 + 1 ) ) NEW_LINE DEDENT DEDENT N = 3 NEW_LINE TowerOfHanoi ( N ) NEW_LINE |
Check if a path exists from a given cell to any boundary element of the Matrix with sum of elements not exceeding K | Python3 program for the above approach ; Function to check if it is valid to move to the given index or not ; Otherwise return false ; Function to check if there exists a path from the cell ( X , Y ) of the matrix to any boundary cell with sum of elements at most K or not ; Base Case ; If K >= board [ X ] [ Y ] ; Stores the current element ; Mark the current cell as visited ; Visit all the adjacent cells ; Mark the cell unvisited ; Return false ; Driver Code | import sys NEW_LINE INT_MAX = sys . maxsize NEW_LINE def isValid ( board , i , j , K ) : NEW_LINE INDENT if ( board [ i ] [ j ] <= K ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def findPath ( board , X , Y , M , N , K ) : NEW_LINE INDENT if ( X < 0 or X == M or Y < 0 or Y == N ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( isValid ( board , X , Y , K ) ) : NEW_LINE INDENT board_XY = board [ X ] [ Y ] NEW_LINE board [ X ] [ Y ] = INT_MAX NEW_LINE if ( findPath ( board , X + 1 , Y , M , N , K - board_XY ) or findPath ( board , X - 1 , Y , M , N , K - board_XY ) or findPath ( board , X , Y + 1 , M , N , K - board_XY ) or findPath ( board , X , Y - 1 , M , N , K - board_XY ) ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT board [ X ] [ Y ] = board_XY NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT grid = [ [ 25 , 5 , 25 , 25 , 25 , 25 ] , [ 25 , 1 , 1 , 5 , 12 , 25 ] , [ 25 , 1 , 12 , 0 , 15 , 25 ] , [ 22 , 1 , 11 , 2 , 19 , 15 ] , [ 25 , 2 , 2 , 1 , 12 , 15 ] , [ 25 , 9 , 10 , 1 , 11 , 25 ] , [ 25 , 25 , 25 , 25 , 25 , 25 ] ] NEW_LINE K = 17 NEW_LINE M = len ( grid ) NEW_LINE N = len ( grid [ 0 ] ) NEW_LINE X = 2 NEW_LINE Y = 3 NEW_LINE if ( findPath ( grid , X , Y , M , N , K ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Sum of all subsets whose sum is a Perfect Number from a given array | Function to check is a given number is a perfect number or not ; Stores sum of divisors ; Add all divisors of x to sum_div ; If the sum of divisors is equal to the given number , return true ; Otherwise , return false ; Function to find the sum of all the subsets from an array whose sum is a perfect number ; Stores the total number of subsets , i . e . 2 ^ n ; Consider all numbers from 0 to 2 ^ n - 1 ; Consider array elements from positions of set bits in the binary representation of n ; If sum of chosen elements is a perfect number ; Driver Code | def isPerfect ( x ) : NEW_LINE INDENT sum_div = 1 NEW_LINE for i in range ( 2 , int ( x / 2 + 1 ) ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT sum_div = sum_div + i NEW_LINE DEDENT DEDENT if ( sum_div == x ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def subsetSum ( arr , n ) : NEW_LINE INDENT total = 1 << n NEW_LINE for i in range ( total ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( i & ( 1 << j ) != 0 ) : NEW_LINE INDENT sum = sum + arr [ j ] NEW_LINE DEDENT DEDENT if ( isPerfect ( sum ) ) : NEW_LINE INDENT print ( sum , " β " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 5 , 4 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE subsetSum ( arr , N ) NEW_LINE |
Pen Distribution Problem | Recursive function to play Game ; Box is empty , Game Over ! or Both have quit , Game Over ! ; P1 moves ; P2 moves ; Increment X ; Switch moves between P1 and P2 ; Function to find the number of pens remaining in the box and calculate score for each player ; Score of P1 ; Score of P2 ; Initialized to zero ; Move = 0 , P1 ' s β turn β β Move β = β 1 , β P2' s turn ; Has P1 quit ; Has P2 quit ; Recursively continue the game ; Driver Code | def solve ( N , P1 , P2 , X , Move , QuitP1 , QuitP2 ) : NEW_LINE INDENT if ( N == 0 or ( QuitP1 and QuitP2 ) ) : NEW_LINE INDENT print ( " Number β of β pens β remaining β in β the β box : β " , N ) NEW_LINE print ( " Number β of β pens β collected β by β P1 : β " , P1 ) NEW_LINE print ( " Number β of β pens β collected β by β P2 : β " , P2 ) NEW_LINE return NEW_LINE DEDENT if ( Move == 0 and QuitP1 == False ) : NEW_LINE INDENT req_P1 = int ( pow ( 2 , X ) ) NEW_LINE if ( req_P1 <= N ) : NEW_LINE INDENT P1 += req_P1 NEW_LINE N -= req_P1 NEW_LINE DEDENT else : NEW_LINE INDENT QuitP1 = True NEW_LINE DEDENT DEDENT elif ( Move == 1 and QuitP2 == False ) : NEW_LINE INDENT req_P2 = int ( pow ( 3 , X ) ) NEW_LINE if ( req_P2 <= N ) : NEW_LINE INDENT P2 += req_P2 NEW_LINE N -= req_P2 NEW_LINE DEDENT else : NEW_LINE INDENT QuitP2 = True NEW_LINE DEDENT DEDENT X += 1 NEW_LINE if ( Move == 1 ) : NEW_LINE INDENT Move = 0 NEW_LINE DEDENT else : NEW_LINE INDENT Move = 1 NEW_LINE DEDENT solve ( N , P1 , P2 , X , Move , QuitP1 , QuitP2 ) NEW_LINE DEDENT def PenGame ( N ) : NEW_LINE INDENT P1 = 0 NEW_LINE P2 = 0 NEW_LINE X = 0 NEW_LINE Move = False NEW_LINE QuitP1 = False NEW_LINE QuitP2 = False NEW_LINE solve ( N , P1 , P2 , X , Move , QuitP1 , QuitP2 ) NEW_LINE DEDENT N = 22 NEW_LINE PenGame ( N ) NEW_LINE |
Generate all N digit numbers having absolute difference as K between adjacent digits | Function that recursively finds the possible numbers and append into ans ; Base Case ; Check the sum of last digit and k less than or equal to 9 or not ; If k == 0 , then subtraction and addition does not make any difference Hence , subtraction is skipped ; Function to call checkUntil function for every integer from 1 to 9 ; check_util function recursively store all numbers starting from i ; Function to print the all numbers which satisfy the conditions ; Driver Code ; Given N and K ; To store the result ; Function call ; Print resultant numbers | def checkUntil ( num , K , N , ans ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT ans . append ( num ) NEW_LINE return NEW_LINE DEDENT if ( ( num % 10 + K ) <= 9 ) : NEW_LINE INDENT checkUntil ( 10 * num + ( num % 10 + K ) , K , N - 1 , ans ) NEW_LINE DEDENT if ( K ) : NEW_LINE INDENT if ( ( num % 10 - K ) >= 0 ) : NEW_LINE INDENT checkUntil ( 10 * num + num % 10 - K , K , N - 1 , ans ) NEW_LINE DEDENT DEDENT DEDENT def check ( K , N , ans ) : NEW_LINE INDENT for i in range ( 1 , 10 ) : NEW_LINE INDENT checkUntil ( i , K , N , ans ) NEW_LINE DEDENT DEDENT def print_list ( ans ) : NEW_LINE INDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] , end = " , β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE K = 8 ; NEW_LINE ans = [ ] NEW_LINE check ( K , N , ans ) NEW_LINE print_list ( ans ) NEW_LINE DEDENT |
Minimum Cost Path in a directed graph via given set of intermediate nodes | Stores minimum - cost of path from source ; Function to Perform BFS on graph g starting from vertex v ; If destination is reached ; Set flag to true ; Visit all the intermediate nodes ; If any intermediate node is not visited ; If all intermediate nodes are visited ; Update the minSum ; Mark the current node visited ; Traverse adjacent nodes ; Mark the neighbour visited ; Find minimum cost path considering the neighbour as the source ; Mark the neighbour unvisited ; Mark the source unvisited ; Driver Code ; Stores the graph ; Number of nodes ; Source ; Destination ; Keeps a check on visited and unvisited nodes ; Stores intemediate nodes ; If no path is found | minSum = 1000000000 NEW_LINE def getMinPathSum ( graph , visited , necessary , source , dest , currSum ) : NEW_LINE INDENT global minSum NEW_LINE if ( src == dest ) : NEW_LINE INDENT flag = True ; NEW_LINE for i in necessary : NEW_LINE INDENT if ( not visited [ i ] ) : NEW_LINE INDENT flag = False ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT minSum = min ( minSum , currSum ) ; NEW_LINE DEDENT return ; NEW_LINE DEDENT else : NEW_LINE INDENT visited [ src ] = True ; NEW_LINE for node in graph [ src ] : NEW_LINE INDENT if not visited [ node [ 0 ] ] : NEW_LINE INDENT visited [ node [ 0 ] ] = True ; NEW_LINE getMinPathSum ( graph , visited , necessary , node [ 0 ] , dest , currSum + node [ 1 ] ) ; NEW_LINE visited [ node [ 0 ] ] = False ; NEW_LINE DEDENT DEDENT visited [ src ] = False ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT graph = dict ( ) NEW_LINE graph [ 0 ] = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 2 ] ] ; NEW_LINE graph [ 1 ] = [ [ 4 , 4 ] , [ 0 , 1 ] ] ; NEW_LINE graph [ 2 ] = [ [ 4 , 5 ] , [ 5 , 6 ] ] ; NEW_LINE graph [ 3 ] = [ [ 5 , 7 ] , [ 0 , 1 ] ] ; NEW_LINE graph [ 4 ] = [ [ 6 , 4 ] ] ; NEW_LINE graph [ 5 ] = [ [ 6 , 2 ] ] ; NEW_LINE graph [ 6 ] = [ [ 7 , 11 ] ] ; NEW_LINE n = 7 ; NEW_LINE source = 0 ; NEW_LINE dest = 6 ; NEW_LINE visited = [ False for i in range ( n + 1 ) ] NEW_LINE necessary = [ 2 , 4 ] ; NEW_LINE getMinPathSum ( graph , visited , necessary , source , dest , 0 ) ; NEW_LINE if ( minSum == 1000000000 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( minSum ) NEW_LINE DEDENT DEDENT |
Unique subsequences of length K with given sum | Function to find all the subsequences of a given length and having sum S ; Termination condition ; Add value to sum ; Check if the resultant sum equals to target sum ; If true ; Print resultant array ; End this recursion stack ; Check all the combinations using backtracking ; Check all the combinations using backtracking ; Driver code ; Given array ; To store the subsequence ; Function call | def comb ( arr , Len , r , ipos , op , opos , Sum ) : NEW_LINE INDENT if ( opos == r ) : NEW_LINE INDENT sum2 = 0 NEW_LINE for i in range ( opos ) : NEW_LINE INDENT sum2 = sum2 + op [ i ] NEW_LINE DEDENT if ( Sum == sum2 ) : NEW_LINE INDENT for i in range ( opos ) : NEW_LINE INDENT print ( op [ i ] , end = " , β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT return NEW_LINE DEDENT if ( ipos < Len ) : NEW_LINE INDENT comb ( arr , Len , r , ipos + 1 , op , opos , Sum ) NEW_LINE op [ opos ] = arr [ ipos ] NEW_LINE comb ( arr , Len , r , ipos + 1 , op , opos + 1 , Sum ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 6 , 8 , 2 , 12 ] NEW_LINE K = 3 NEW_LINE S = 20 NEW_LINE N = len ( arr ) NEW_LINE op = [ 0 ] * N NEW_LINE comb ( arr , N , K , 0 , op , 0 , S ) NEW_LINE DEDENT |
Traverse the matrix in Diagonally Bottum | Static variable for changing Row and column ; Flag variable for handling Bottum up diagonal traversing ; Recursive function to traverse the matrix Diagonally Bottom - up ; Base Condition ; Condition when to traverse Bottom Diagonal of the matrix ; Print matrix cell value ; Recursive function to traverse The matrix diagonally ; Recursive function to change diagonal ; Initialize the 5 x 5 matrix ; Function call for traversing matrix | k1 = 0 NEW_LINE k2 = 0 NEW_LINE flag = True NEW_LINE def traverseMatrixDiagonally ( m , i , j , row , col ) : NEW_LINE INDENT global k1 NEW_LINE global k2 NEW_LINE global flag NEW_LINE if ( i >= row or j >= col ) : NEW_LINE INDENT if ( flag ) : NEW_LINE INDENT a = k1 NEW_LINE k1 = k2 NEW_LINE k2 = a NEW_LINE if ( flag ) : NEW_LINE INDENT flag = False NEW_LINE DEDENT else : NEW_LINE INDENT flag = True NEW_LINE DEDENT k1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT a = k1 NEW_LINE k1 = k2 NEW_LINE k2 = a NEW_LINE if ( flag ) : NEW_LINE INDENT flag = False NEW_LINE DEDENT else : NEW_LINE INDENT flag = True NEW_LINE DEDENT DEDENT print ( ) NEW_LINE return False NEW_LINE DEDENT print ( m [ i ] [ j ] , end = " β " ) NEW_LINE if ( traverseMatrixDiagonally ( m , i + 1 , j + 1 , row , col ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( traverseMatrixDiagonally ( m , k1 , k2 , row , col ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return True NEW_LINE DEDENT mtrx = [ [ 10 , 11 , 12 , 13 , 14 ] , [ 15 , 16 , 17 , 18 , 19 ] , [ 20 , 21 , 22 , 23 , 24 ] , [ 25 , 26 , 27 , 28 , 29 ] , [ 30 , 31 , 32 , 33 , 34 ] ] NEW_LINE traverseMatrixDiagonally ( mtrx , 0 , 0 , 5 , 5 ) NEW_LINE |
Minimum colors required such that edges forming cycle do not have same color | Python3 implementation to find the minimum colors required to such that edges forming cycle don 't have same color ; Variable to store the graph ; To store that the vertex is visited or not ; Boolean Value to store that graph contains cycle or not ; Variable to store the color of the edges of the graph ; Function to traverse graph using DFS Traversal ; Loop to iterate for all edges from the source vertex ; If the vertex is not visited ; Condition to check cross and forward edges of the graph ; Presence of Back Edge ; Driver Code ; Loop to run DFS Traversal on vertex which is not visited ; Loop to print the colors of the edges | n = 5 NEW_LINE m = 7 ; NEW_LINE g = [ [ ] for i in range ( m ) ] NEW_LINE col = [ 0 for i in range ( n ) ] ; NEW_LINE cyc = True NEW_LINE res = [ 0 for i in range ( m ) ] ; NEW_LINE def dfs ( v ) : NEW_LINE INDENT col [ v ] = 1 ; NEW_LINE for p in g [ v ] : NEW_LINE INDENT to = p [ 0 ] NEW_LINE id = p [ 1 ] ; NEW_LINE if ( col [ to ] == 0 ) : NEW_LINE INDENT dfs ( to ) ; NEW_LINE res [ id ] = 1 ; NEW_LINE DEDENT elif ( col [ to ] == 2 ) : NEW_LINE INDENT res [ id ] = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT res [ id ] = 2 ; NEW_LINE cyc = True ; NEW_LINE DEDENT DEDENT col [ v ] = 2 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT g [ 0 ] . append ( [ 1 , 0 ] ) ; NEW_LINE g [ 0 ] . append ( [ 2 , 1 ] ) ; NEW_LINE g [ 1 ] . append ( [ 2 , 2 ] ) ; NEW_LINE g [ 1 ] . append ( [ 3 , 3 ] ) ; NEW_LINE g [ 2 ] . append ( [ 3 , 4 ] ) ; NEW_LINE g [ 3 ] . append ( [ 4 , 5 ] ) ; NEW_LINE g [ 4 ] . append ( [ 2 , 6 ] ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( col [ i ] == 0 ) : NEW_LINE INDENT dfs ( i ) ; NEW_LINE DEDENT DEDENT print ( 2 if cyc else 1 ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT print ( res [ i ] , end = ' β ' ) NEW_LINE DEDENT DEDENT |
Perfect Sum Problem | Function to print the subsets whose sum is equal to the given target K ; Create the new array with size equal to array set [ ] to create binary array as per n ( decimal number ) ; Convert the array into binary array ; Calculate the sum of this subset ; Check whether sum is equal to target if it is equal , then print the subset ; Function to find the subsets with sum K ; Calculate the total no . of subsets ; Run loop till total no . of subsets and call the function for each subset ; Driver code | def sumSubsets ( sets , n , target ) : NEW_LINE INDENT x = [ 0 ] * len ( sets ) ; NEW_LINE j = len ( sets ) - 1 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT x [ j ] = n % 2 ; NEW_LINE n = n // 2 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT sum = 0 ; NEW_LINE for i in range ( len ( sets ) ) : NEW_LINE INDENT if ( x [ i ] == 1 ) : NEW_LINE INDENT sum += sets [ i ] ; NEW_LINE DEDENT DEDENT if ( sum == target ) : NEW_LINE INDENT print ( " { " , end = " " ) ; NEW_LINE for i in range ( len ( sets ) ) : NEW_LINE INDENT if ( x [ i ] == 1 ) : NEW_LINE INDENT print ( sets [ i ] , end = " , β " ) ; NEW_LINE DEDENT DEDENT print ( " } , β " , end = " " ) ; NEW_LINE DEDENT DEDENT def findSubsets ( arr , K ) : NEW_LINE INDENT x = pow ( 2 , len ( arr ) ) ; NEW_LINE for i in range ( 1 , x ) : NEW_LINE INDENT sumSubsets ( arr , i , K ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 10 , 12 , 13 , 15 , 18 ] ; NEW_LINE K = 30 ; NEW_LINE findSubsets ( arr , K ) ; NEW_LINE DEDENT |
Sum of subsets of all the subsets of an array | O ( N ) | Python3 implementation of the approach ; To store factorial values ; Function to return ncr ; Function to return the required sum ; Initialising factorial ; Multiplier ; Finding the value of multipler according to the formula ; To store the final answer ; Calculate the final answer ; Driver code | maxN = 10 NEW_LINE fact = [ 0 ] * maxN ; NEW_LINE def ncr ( n , r ) : NEW_LINE INDENT return ( fact [ n ] // fact [ r ] ) // fact [ n - r ] ; NEW_LINE DEDENT def findSum ( arr , n ) : NEW_LINE INDENT fact [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT fact [ i ] = i * fact [ i - 1 ] ; NEW_LINE DEDENT mul = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT mul += ( 2 ** i ) * ncr ( n - 1 , i ) ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += mul * arr [ i ] ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findSum ( arr , n ) ) ; NEW_LINE DEDENT |
Count number of ways to reach destination in a maze | Python3 implementation of the approach ; Function to return the count of possible paths in a maze [ R ] [ C ] from ( 0 , 0 ) to ( R - 1 , C - 1 ) that do not pass through any of the marked cells ; If the initial cell is blocked , there is no way of moving anywhere ; Initializing the leftmost column ; If we encounter a blocked cell in leftmost row , there is no way of visiting any cell directly below it . ; Similarly initialize the topmost row ; If we encounter a blocked cell in bottommost row , there is no way of visiting any cell directly below it . ; The only difference is that if a cell is - 1 , simply ignore it else recursively compute count value maze [ i ] [ j ] ; If blockage is found , ignore this cell ; If we can reach maze [ i ] [ j ] from maze [ i - 1 ] [ j ] then increment count . ; If we can reach maze [ i ] [ j ] from maze [ i ] [ j - 1 ] then increment count . ; If the final cell is blocked , output 0 , otherwise the answer ; Function to return the count of all possible paths from ( 0 , 0 ) to ( n - 1 , m - 1 ) ; We have to calculate m + n - 2 C n - 1 here which will be ( m + n - 2 ) ! / ( n - 1 ) ! ( m - 1 ) ! ; Function to return the total count of paths from ( 0 , 0 ) to ( n - 1 , m - 1 ) that pass through at least one of the marked cells ; Total count of paths - Total paths that do not pass through any of the marked cell ; return answer ; Driver code | R = 4 NEW_LINE C = 4 NEW_LINE def countPaths ( maze ) : NEW_LINE INDENT if ( maze [ 0 ] [ 0 ] == - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( R ) : NEW_LINE INDENT if ( maze [ i ] [ 0 ] == 0 ) : NEW_LINE INDENT maze [ i ] [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( 1 , C ) : NEW_LINE INDENT if ( maze [ 0 ] [ i ] == 0 ) : NEW_LINE INDENT maze [ 0 ] [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( 1 , R ) : NEW_LINE INDENT for j in range ( 1 , C ) : NEW_LINE INDENT if ( maze [ i ] [ j ] == - 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( maze [ i - 1 ] [ j ] > 0 ) : NEW_LINE INDENT maze [ i ] [ j ] = ( maze [ i ] [ j ] + maze [ i - 1 ] [ j ] ) NEW_LINE DEDENT if ( maze [ i ] [ j - 1 ] > 0 ) : NEW_LINE INDENT maze [ i ] [ j ] = ( maze [ i ] [ j ] + maze [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT if ( maze [ R - 1 ] [ C - 1 ] > 0 ) : NEW_LINE INDENT return maze [ R - 1 ] [ C - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def numberOfPaths ( m , n ) : NEW_LINE INDENT path = 1 NEW_LINE for i in range ( n , m + n - 1 ) : NEW_LINE INDENT path *= i NEW_LINE path //= ( i - n + 1 ) NEW_LINE DEDENT return path NEW_LINE DEDENT def solve ( maze ) : NEW_LINE INDENT ans = ( numberOfPaths ( R , C ) - countPaths ( maze ) ) NEW_LINE return ans NEW_LINE DEDENT maze = [ [ 0 , 0 , 0 , 0 ] , [ 0 , - 1 , 0 , 0 ] , [ - 1 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] ] NEW_LINE print ( solve ( maze ) ) NEW_LINE |
Rat in a Maze with multiple steps or jump allowed | Maze size ; A utility function to prsolution matrix sol ; A utility function to check if x , y is valid index for N * N maze ; if ( x , y outside maze ) return false ; This function solves the Maze problem using Backtracking . It mainly uses solveMazeUtil ( ) to solve the problem . It returns false if no path is possible , otherwise return True and prints the path in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; A recursive utility function to solve Maze problem ; if ( x , y is goal ) return True ; Check if maze [ x ] [ y ] is valid ; mark x , y as part of solution path ; Move forward in x direction ; Move forward in x direction ; If moving in x direction doesn 't give solution then Move down in y direction ; If none of the above movements work then BACKTRACK : unmark x , y as part of solution path ; Driver Code | N = 4 NEW_LINE def printSolution ( sol ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( sol [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def isSafe ( maze , x , y ) : NEW_LINE INDENT if ( x >= 0 and x < N and y >= 0 and y < N and maze [ x ] [ y ] != 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def solveMaze ( maze ) : NEW_LINE INDENT sol = [ [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] ] NEW_LINE if ( solveMazeUtil ( maze , 0 , 0 , sol ) == False ) : NEW_LINE INDENT print ( " Solution β doesn ' t β exist " ) NEW_LINE return False NEW_LINE DEDENT printSolution ( sol ) NEW_LINE return True NEW_LINE DEDENT def solveMazeUtil ( maze , x , y , sol ) : NEW_LINE INDENT if ( x == N - 1 and y == N - 1 ) : NEW_LINE INDENT sol [ x ] [ y ] = 1 NEW_LINE return True NEW_LINE DEDENT if ( isSafe ( maze , x , y ) == True ) : NEW_LINE INDENT sol [ x ] [ y ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( i <= maze [ x ] [ y ] ) : NEW_LINE INDENT if ( solveMazeUtil ( maze , x + i , y , sol ) == True ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( solveMazeUtil ( maze , x , y + i , sol ) == True ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT sol [ x ] [ y ] = 0 NEW_LINE return False NEW_LINE DEDENT return False NEW_LINE DEDENT maze = [ [ 2 , 1 , 0 , 0 ] , [ 3 , 0 , 0 , 1 ] , [ 0 , 1 , 0 , 1 ] , [ 0 , 0 , 0 , 1 ] ] NEW_LINE solveMaze ( maze ) NEW_LINE |
Prime numbers after prime P with sum S | Python Program to print all N primes after prime P whose sum equals S ; vector to store prime and N primes whose sum equals given S ; function to check prime number ; square root of x ; since 1 is not prime number ; if any factor is found return false ; no factor found ; function to display N primes whose sum equals S ; function to evaluate all possible N primes whose sum equals S ; if total equals S And total is reached using N primes ; display the N primes ; if total is greater than S or if index has reached last element ; add prime [ index ] to set vector ; include the ( index ) th prime to total ; remove element from set vector ; exclude ( index ) th prime ; function to generate all primes ; all primes less than S itself ; if i is prime add it to prime vector ; if primes are less than N ; Driver Code | import math NEW_LINE set = [ ] NEW_LINE prime = [ ] NEW_LINE def isPrime ( x ) : NEW_LINE INDENT sqroot = int ( math . sqrt ( x ) ) NEW_LINE flag = True NEW_LINE if ( x == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , sqroot + 1 ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def display ( ) : NEW_LINE INDENT global set , prime NEW_LINE length = len ( set ) NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT print ( set [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def primeSum ( total , N , S , index ) : NEW_LINE INDENT global set , prime NEW_LINE if ( total == S and len ( set ) == N ) : NEW_LINE INDENT display ( ) NEW_LINE return NEW_LINE DEDENT if ( total > S or index == len ( prime ) ) : NEW_LINE INDENT return NEW_LINE DEDENT set . append ( prime [ index ] ) NEW_LINE primeSum ( total + prime [ index ] , N , S , index + 1 ) NEW_LINE set . pop ( ) NEW_LINE primeSum ( total , N , S , index + 1 ) NEW_LINE DEDENT def allPrime ( N , S , P ) : NEW_LINE INDENT global set , prime NEW_LINE for i in range ( P + 1 , S + 1 ) : NEW_LINE INDENT if ( isPrime ( i ) ) : NEW_LINE INDENT prime . append ( i ) NEW_LINE DEDENT DEDENT if ( len ( prime ) < N ) : NEW_LINE INDENT return NEW_LINE DEDENT primeSum ( 0 , N , S , 0 ) NEW_LINE DEDENT S = 54 NEW_LINE N = 2 NEW_LINE P = 3 NEW_LINE allPrime ( N , S , P ) NEW_LINE |
A backtracking approach to generate n bit Gray Codes | we have 2 choices for each of the n bits either we can include i . e invert the bit or we can exclude the bit i . e we can leave the number as it is . ; base case when we run out bits to process we simply include it in gray code sequence . ; ignore the bit . ; invert the bit . ; returns the vector containing the gray code sequence of n bits . ; num is passed by reference to keep track of current code . ; Driver Code | def grayCodeUtil ( res , n , num ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT res . append ( num [ 0 ] ) NEW_LINE return NEW_LINE DEDENT grayCodeUtil ( res , n - 1 , num ) NEW_LINE num [ 0 ] = num [ 0 ] ^ ( 1 << ( n - 1 ) ) NEW_LINE grayCodeUtil ( res , n - 1 , num ) NEW_LINE DEDENT def grayCodes ( n ) : NEW_LINE INDENT res = [ ] NEW_LINE num = [ 0 ] NEW_LINE grayCodeUtil ( res , n , num ) NEW_LINE return res NEW_LINE DEDENT n = 3 NEW_LINE code = grayCodes ( n ) NEW_LINE for i in range ( len ( code ) ) : NEW_LINE INDENT print ( code [ i ] ) NEW_LINE DEDENT |
Remove Invalid Parentheses | Method checks if character is parenthesis ( openor closed ) ; method returns true if contains valid parenthesis ; method to remove invalid parenthesis ; visit set to ignore already visited ; queue to maintain BFS ; pushing given as starting node into queu ; If answer is found , make level true so that valid of only that level are processed . ; Removing parenthesis from str and pushing into queue , if not visited already ; Driver Code | def isParenthesis ( c ) : NEW_LINE INDENT return ( ( c == ' ( ' ) or ( c == ' ) ' ) ) NEW_LINE DEDENT def isValidString ( str ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == ' ( ' ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT elif ( str [ i ] == ' ) ' ) : NEW_LINE INDENT cnt -= 1 NEW_LINE DEDENT if ( cnt < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return ( cnt == 0 ) NEW_LINE DEDENT def removeInvalidParenthesis ( str ) : NEW_LINE INDENT if ( len ( str ) == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT visit = set ( ) NEW_LINE q = [ ] NEW_LINE temp = 0 NEW_LINE level = 0 NEW_LINE q . append ( str ) NEW_LINE visit . add ( str ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT str = q [ 0 ] NEW_LINE q . pop ( ) NEW_LINE if ( isValidString ( str ) ) : NEW_LINE INDENT print ( str ) NEW_LINE level = True NEW_LINE DEDENT if ( level ) : NEW_LINE INDENT continue NEW_LINE DEDENT for i in range ( len ( str ) ) : NEW_LINE INDENT if ( not isParenthesis ( str [ i ] ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT temp = str [ 0 : i ] + str [ i + 1 : ] NEW_LINE if temp not in visit : NEW_LINE INDENT q . append ( temp ) NEW_LINE visit . add ( temp ) NEW_LINE DEDENT DEDENT DEDENT DEDENT expression = " ( ) ( ) ) ( ) " NEW_LINE removeInvalidParenthesis ( expression ) NEW_LINE expression = " ( ) v ) " NEW_LINE removeInvalidParenthesis ( expression ) NEW_LINE |
N Queen Problem | Backtracking | Python3 program to solve N Queen Problem using backtracking ; ld is an array where its indices indicate row - col + N - 1 ( N - 1 ) is for shifting the difference to store negative indices ; rd is an array where its indices indicate row + col and used to check whether a queen can be placed on right diagonal or not ; column array where its indices indicates column and used to check whether a queen can be placed in that row or not ; A utility function to print solution ; A recursive utility function to solve N Queen problem ; base case : If all queens are placed then return True ; Consider this column and try placing this queen in all rows one by one ; A check if a queen can be placed on board [ row ] [ col ] . We just need to check ld [ row - col + n - 1 ] and rd [ row + coln ] where ld and rd are for left and right diagonal respectively ; Place this queen in board [ i ] [ col ] ; recur to place rest of the queens ; board [ i ] [ col ] = 0 BACKTRACK ; If the queen cannot be placed in any row in this colum col then return False ; This function solves the N Queen problem using Backtracking . It mainly uses solveNQUtil ( ) to solve the problem . It returns False if queens cannot be placed , otherwise , return True and prints placement of queens in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; Driver Code | N = 4 NEW_LINE ld = [ 0 ] * 30 NEW_LINE rd = [ 0 ] * 30 NEW_LINE cl = [ 0 ] * 30 NEW_LINE def printSolution ( board ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( board [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def solveNQUtil ( board , col ) : NEW_LINE INDENT if ( col >= N ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( ( ld [ i - col + N - 1 ] != 1 and rd [ i + col ] != 1 ) and cl [ i ] != 1 ) : NEW_LINE INDENT board [ i ] [ col ] = 1 NEW_LINE ld [ i - col + N - 1 ] = rd [ i + col ] = cl [ i ] = 1 NEW_LINE if ( solveNQUtil ( board , col + 1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT ld [ i - col + N - 1 ] = rd [ i + col ] = cl [ i ] = 0 NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def solveNQ ( ) : NEW_LINE INDENT board = [ [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] ] NEW_LINE if ( solveNQUtil ( board , 0 ) == False ) : NEW_LINE INDENT printf ( " Solution β does β not β exist " ) NEW_LINE return False NEW_LINE DEDENT printSolution ( board ) NEW_LINE return True NEW_LINE DEDENT solveNQ ( ) NEW_LINE |
Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Function to print pairs ; Initializing the rem values with 0 's. ; Perform the remainder operation only if the element is x , as numbers greater than x can 't be used to get a sum x.Updating the count of remainders. ; Traversing the remainder list from start to middle to find pairs ; The elements with remainders i and x - i will result to a sum of x . Once we get two elements which add up to x , we print x and break . ; Once we reach middle of remainder array , we have to do operations based on x . ; If x is even and we have more than 1 elements with remainder x / 2 , then we will have two distinct elements which add up to x . if we dont have than 1 element , print " No " . ; When x is odd we continue the same process which we did in previous loop . ; Driver Code ; Function calling | def printPairs ( a , n , x ) : NEW_LINE INDENT rem = [ ] NEW_LINE for i in range ( x ) : NEW_LINE INDENT rem . append ( 0 ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] < x ) : NEW_LINE INDENT rem [ a [ i ] % x ] += 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , x // 2 ) : NEW_LINE INDENT if ( rem [ i ] > 0 and rem [ x - i ] > 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE break NEW_LINE DEDENT DEDENT if ( i >= x // 2 ) : NEW_LINE INDENT if ( x % 2 == 0 ) : NEW_LINE INDENT if ( rem [ x // 2 ] > 1 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( rem [ x // 2 ] > 0 and rem [ x - x // 2 ] > 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT A = [ 1 , 4 , 45 , 6 , 10 , 8 ] NEW_LINE n = 16 NEW_LINE arr_size = len ( A ) NEW_LINE printPairs ( A , arr_size , n ) NEW_LINE |
Find remainder when a number A raised to N factorial is divided by P | Function to calculate factorial of a Number ; Calculating factorial ; Returning factorial ; Function to calculate resultant remainder ; Function call to calculate factorial of n ; Calculating remainder ; Returning resultant remainder ; Driver Code ; Given Input ; Function Call | def fact ( n ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT ans *= i NEW_LINE DEDENT return ans NEW_LINE DEDENT def remainder ( n , a , p ) : NEW_LINE INDENT len1 = fact ( n ) NEW_LINE ans = 1 NEW_LINE for i in range ( 1 , len1 + 1 , 1 ) : NEW_LINE INDENT ans = ( ans * a ) % p NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 2 NEW_LINE N = 1 NEW_LINE P = 2 NEW_LINE print ( remainder ( N , A , P ) ) NEW_LINE DEDENT |
Check if a number N can be expressed in base B | Function to check if a number N can be expressed in base B ; Check if n is greater than 0 ; Initialize a boolean variable ; Check if digit is 0 or 1 ; Subtract the appropriate power of B from it and increment higher digit ; Driver code ; Given number N and base B ; Function call | def check ( n , w ) : NEW_LINE INDENT a = [ 0 for i in range ( 105 ) ] ; NEW_LINE p = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT a [ p ] = n % w NEW_LINE p += 1 NEW_LINE n //= w NEW_LINE DEDENT flag = True NEW_LINE for i in range ( 101 ) : NEW_LINE INDENT if ( a [ i ] == 0 or a [ i ] == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( a [ i ] == w or a [ i ] == w - 1 ) : NEW_LINE INDENT a [ i + 1 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT flag = False NEW_LINE DEDENT DEDENT return flag NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT B = 3 NEW_LINE N = 7 NEW_LINE if ( check ( N , B ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Count of groups among N people having only one leader in each group | Python3 program for the above approach ; Function to find 2 ^ x using modular exponentiation ; Base cases ; If B is even ; If B is odd ; Function to count the number of ways to form the group having one leader ; Find 2 ^ ( N - 1 ) using modular exponentiation ; Count total ways ; Print the total ways ; Driver code ; Given N number of people ; Function call | mod = 1000000007 NEW_LINE def exponentMod ( A , B ) : 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 ) ; NEW_LINE y = ( y * y ) % mod ; NEW_LINE DEDENT else : NEW_LINE INDENT y = A % mod ; NEW_LINE y = ( y * exponentMod ( A , B - 1 ) % mod ) % mod ; NEW_LINE DEDENT return ( ( y + mod ) % mod ) ; NEW_LINE DEDENT def countWays ( N ) : NEW_LINE INDENT select = exponentMod ( 2 , N - 1 ) ; NEW_LINE ways = ( ( N % mod ) * ( select % mod ) ) ; NEW_LINE ways %= mod ; NEW_LINE print ( ways ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE countWays ( N ) ; NEW_LINE DEDENT |
Array range queries to find the number of perfect square elements with updates | Python program to find number of perfect square numbers in a subarray and performing updates ; Function to check if a number is a perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; A utility function to get the middle index from corner indexes . ; where st -- > Pointer to segment tree index -- > Index of current node in the segment tree . Initially 0 is passed as root is always at index 0 ss & se -- > Starting and ending indexes of the segment represented by current node i . e . st [ index ] qs & qe -- > Starting and ending indexes of query range ; If segment of this node is a part of given range , then return the number of perfect square numbers in the segment ; If segment of this node is outside the given range ; If a part of this segment overlaps with the given range ; where st , si , ss & se are same as getSumUtil ( ) i -- > index of the element to be updated . This index is in input array . diff -- > Value to be added to all nodes which have i in range ; Base Case : If the input index lies outside the range of this segment ; If the input index is in range of this node , then update the value of the node and its children ; Function to update a value in the input array and segment tree . It uses updateValueUtil ( ) to update the value in segment tree ; Check for erroneous input index ; Update the value in array ; Case 1 : Old and new values both are perfect square numbers ; Case 2 : Old and new values both not perfect square numbers ; Case 3 : Old value was perfect square , new value is not a perfect square ; Case 4 : Old value was non - perfect square , new_val is perfect square ; Update values of nodes in segment tree ; Return no . of perfect square numbers in range from index qs ( query start ) to qe ( query end ) . It mainly uses queryUtil ( ) ; Recursive function that constructs Segment Tree for array [ ss . . se ] . si is index of current node in segment tree st ; If there is one element in array , check if it is perfect square number then store 1 in the segment tree else store 0 and return ; if arr [ ss ] is a perfect square number ; If there are more than one elements , then recur for left and right subtrees and store the sum of the two values in this node ; Function to construct a segment tree from given array . This function allocates memory for segment tree and calls constructSTUtil ( ) to fill the allocated memory ; Allocate memory for segment tree Height of segment tree ; Maximum size of segment tree ; Fill the allocated memory st ; Return the constructed segment tree ; Driver Code ; Build segment tree from given array ; Query 1 : Query ( start = 0 , end = 4 ) ; Query 2 : Update ( i = 3 , x = 11 ) , i . e Update a [ i ] to x ; Query 3 : Query ( start = 0 , end = 4 ) | from math import sqrt , floor , ceil , log2 NEW_LINE from typing import List NEW_LINE MAX = 1000 NEW_LINE def isPerfectSquare ( x : int ) -> bool : NEW_LINE INDENT sr = sqrt ( x ) NEW_LINE return True if ( ( sr - floor ( sr ) ) == 0 ) else False NEW_LINE DEDENT def getMid ( s : int , e : int ) -> int : NEW_LINE INDENT return s + ( e - s ) // 2 NEW_LINE DEDENT def queryUtil ( st : List [ int ] , ss : int , se : int , qs : int , qe : int , index : int ) -> int : NEW_LINE INDENT if ( qs <= ss and qe >= se ) : NEW_LINE INDENT return st [ index ] NEW_LINE DEDENT if ( se < qs or ss > qe ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT mid = getMid ( ss , se ) NEW_LINE return queryUtil ( st , ss , mid , qs , qe , 2 * index + 1 ) + queryUtil ( st , mid + 1 , se , qs , qe , 2 * index + 2 ) NEW_LINE DEDENT def updateValueUtil ( st : List [ int ] , ss : int , se : int , i : int , diff : int , si : int ) -> None : NEW_LINE INDENT if ( i < ss or i > se ) : NEW_LINE INDENT return NEW_LINE DEDENT st [ si ] = st [ si ] + diff NEW_LINE if ( se != ss ) : NEW_LINE INDENT mid = getMid ( ss , se ) NEW_LINE updateValueUtil ( st , ss , mid , i , diff , 2 * si + 1 ) NEW_LINE updateValueUtil ( st , mid + 1 , se , i , diff , 2 * si + 2 ) NEW_LINE DEDENT DEDENT def updateValue ( arr : List [ int ] , st : List [ int ] , n : int , i : int , new_val : int ) -> None : NEW_LINE INDENT if ( i < 0 or i > n - 1 ) : NEW_LINE INDENT print ( " Invalid β Input " ) NEW_LINE return NEW_LINE DEDENT diff = 0 NEW_LINE oldValue = 0 NEW_LINE oldValue = arr [ i ] NEW_LINE arr [ i ] = new_val NEW_LINE if ( isPerfectSquare ( oldValue ) and isPerfectSquare ( new_val ) ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( not isPerfectSquare ( oldValue ) and not isPerfectSquare ( new_val ) ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( isPerfectSquare ( oldValue ) and not isPerfectSquare ( new_val ) ) : NEW_LINE INDENT diff = - 1 NEW_LINE DEDENT if ( not isPerfectSquare ( oldValue ) and not isPerfectSquare ( new_val ) ) : NEW_LINE INDENT diff = 1 NEW_LINE DEDENT updateValueUtil ( st , 0 , n - 1 , i , diff , 0 ) NEW_LINE DEDENT def query ( st : List [ int ] , n : int , qs : int , qe : int ) -> None : NEW_LINE INDENT perfectSquareInRange = queryUtil ( st , 0 , n - 1 , qs , qe , 0 ) NEW_LINE print ( perfectSquareInRange ) NEW_LINE DEDENT def constructSTUtil ( arr : List [ int ] , ss : int , se : int , st : List [ int ] , si : int ) -> int : NEW_LINE INDENT if ( ss == se ) : NEW_LINE INDENT if ( isPerfectSquare ( arr [ ss ] ) ) : NEW_LINE INDENT st [ si ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT st [ si ] = 0 NEW_LINE DEDENT return st [ si ] NEW_LINE DEDENT mid = getMid ( ss , se ) NEW_LINE st [ si ] = constructSTUtil ( arr , ss , mid , st , si * 2 + 1 ) + constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 ) NEW_LINE return st [ si ] NEW_LINE DEDENT def constructST ( arr : List [ int ] , n : int ) -> List [ int ] : NEW_LINE INDENT x = ( ceil ( log2 ( n ) ) ) NEW_LINE max_size = 2 * pow ( 2 , x ) - 1 NEW_LINE st = [ 0 for _ in range ( max_size ) ] NEW_LINE constructSTUtil ( arr , 0 , n - 1 , st , 0 ) NEW_LINE return st NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 16 , 15 , 8 , 9 , 14 , 25 ] NEW_LINE n = len ( arr ) NEW_LINE st = constructST ( arr , n ) NEW_LINE start = 0 NEW_LINE end = 4 NEW_LINE query ( st , n , start , end ) NEW_LINE i = 3 NEW_LINE x = 11 NEW_LINE updateValue ( arr , st , n , i , x ) NEW_LINE start = 0 NEW_LINE end = 4 NEW_LINE query ( st , n , start , end ) NEW_LINE DEDENT |
Find the element having maximum set bits in the given range for Q queries | Structure to store two values in one node ; Function that returns the count of set bits in a number ; Parity will store the count of set bits ; Function to build the segment tree ; Condition to check if there is only one element in the array ; If there are more than one elements , then recur for left and right subtrees ; Condition to check the maximum set bits is greater in two subtrees ; Condition when maximum set bits are equal in both subtrees ; Function to do the range query in the segment tree ; If segment of this node is outside the given range , then return the minimum value . ; If segment of this node is a part of given range , then return the node of the segment ; If left segment of this node falls out of range , then recur in the right side of the tree ; If right segment of this node falls out of range , then recur in the left side of the tree ; If a part of this segment overlaps with the given range ; Returns the value ; Driver code ; Calculates the length of array ; Build Segment Tree ; Find the max set bits value between 1 st and 4 th index of array ; Find the max set bits value between 0 th and 2 nd index of array | from typing import List NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self ) -> None : NEW_LINE INDENT self . value = 0 NEW_LINE self . max_set_bits = 0 NEW_LINE DEDENT DEDENT tree = [ Node ( ) for _ in range ( 4 * 10000 ) ] NEW_LINE def setBits ( x : int ) -> int : NEW_LINE INDENT parity = 0 NEW_LINE while ( x != 0 ) : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT parity += 1 NEW_LINE DEDENT x = x >> 1 NEW_LINE DEDENT return parity NEW_LINE DEDENT def buildSegmentTree ( a : List [ int ] , index : int , beg : int , end : int ) -> None : NEW_LINE INDENT if ( beg == end ) : NEW_LINE INDENT tree [ index ] . value = a [ beg ] NEW_LINE tree [ index ] . max_set_bits = setBits ( a [ beg ] ) NEW_LINE DEDENT else : NEW_LINE INDENT mid = ( beg + end ) // 2 NEW_LINE buildSegmentTree ( a , 2 * index + 1 , beg , mid ) NEW_LINE buildSegmentTree ( a , 2 * index + 2 , mid + 1 , end ) NEW_LINE if ( tree [ 2 * index + 1 ] . max_set_bits > tree [ 2 * index + 2 ] . max_set_bits ) : NEW_LINE INDENT tree [ index ] . max_set_bits = tree [ 2 * index + 1 ] . max_set_bits NEW_LINE tree [ index ] . value = tree [ 2 * index + 1 ] . value NEW_LINE DEDENT elif ( tree [ 2 * index + 2 ] . max_set_bits > tree [ 2 * index + 1 ] . max_set_bits ) : NEW_LINE INDENT tree [ index ] . max_set_bits = tree [ 2 * index + 2 ] . max_set_bits NEW_LINE tree [ index ] . value = tree [ 2 * index + 2 ] . value NEW_LINE DEDENT else : NEW_LINE INDENT tree [ index ] . max_set_bits = tree [ 2 * index + 2 ] . max_set_bits NEW_LINE tree [ index ] . value = max ( tree [ 2 * index + 2 ] . value , tree [ 2 * index + 1 ] . value ) NEW_LINE DEDENT DEDENT DEDENT def query ( index : int , beg : int , end : int , l : int , r : int ) -> Node : NEW_LINE INDENT result = Node ( ) NEW_LINE result . value = result . max_set_bits = - 1 NEW_LINE if ( beg > r or end < l ) : NEW_LINE INDENT return result NEW_LINE DEDENT if ( beg >= l and end <= r ) : NEW_LINE INDENT return tree [ index ] NEW_LINE DEDENT mid = ( beg + end ) // 2 NEW_LINE if ( l > mid ) : NEW_LINE INDENT return query ( 2 * index + 2 , mid + 1 , end , l , r ) NEW_LINE DEDENT if ( r <= mid ) : NEW_LINE INDENT return query ( 2 * index + 1 , beg , mid , l , r ) NEW_LINE DEDENT left = query ( 2 * index + 1 , beg , mid , l , r ) NEW_LINE right = query ( 2 * index + 2 , mid + 1 , end , l , r ) NEW_LINE if ( left . max_set_bits > right . max_set_bits ) : NEW_LINE INDENT result . max_set_bits = left . max_set_bits NEW_LINE result . value = left . value NEW_LINE DEDENT elif ( right . max_set_bits > left . max_set_bits ) : NEW_LINE INDENT result . max_set_bits = right . max_set_bits NEW_LINE result . value = right . value NEW_LINE DEDENT else : NEW_LINE INDENT result . max_set_bits = left . max_set_bits NEW_LINE result . value = max ( right . value , left . value ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 18 , 9 , 8 , 15 , 14 , 5 ] NEW_LINE N = len ( a ) NEW_LINE buildSegmentTree ( a , 0 , 0 , N - 1 ) NEW_LINE print ( query ( 0 , 0 , N - 1 , 1 , 4 ) . value ) NEW_LINE print ( query ( 0 , 0 , N - 1 , 0 , 2 ) . value ) NEW_LINE DEDENT |
Range Update Queries to XOR with 1 in a Binary Array . | Python program for the given problem ; Class for each node in the segment tree ; A utility function for merging two nodes ; utility function for updating a node ; A recursive function that constructs Segment Tree for given string ; If start is equal to end then insert the array element ; Build the segment tree for range qs to mid ; Build the segment tree for range mid + 1 to qe ; merge the two child nodes to obtain the parent node ; Query in a range qs to qe ; If the range lies in this segment ; If the range is out of the bounds of this segment ; Else query for the right and left child node of this subtree and merge them ; range update using lazy prpagation ; If the range is out of the bounds of this segment ; If the range lies in this segment ; Else query for the right and left child node of this subtree and merge them ; Driver code ; Build the segment tree ; Query of Type 2 in the range 3 to 7 ; Query of Type 3 in the range 2 to 5 ; Query of Type 1 in the range 1 to 4 ; Query of Type 4 in the range 3 to 7 ; Query of Type 5 in the range 4 to 9 | from sys import maxsize NEW_LINE from typing import List NEW_LINE INT_MAX = maxsize NEW_LINE INT_MIN = - maxsize NEW_LINE lazy = [ 0 for _ in range ( 100001 ) ] NEW_LINE class node : NEW_LINE INDENT def __init__ ( self ) -> None : NEW_LINE INDENT self . l1 = self . r1 = self . l0 = self . r0 = - 1 NEW_LINE self . max0 = self . max1 = INT_MIN NEW_LINE self . min0 = self . min1 = INT_MAX NEW_LINE DEDENT DEDENT seg = [ node ( ) for _ in range ( 100001 ) ] NEW_LINE def MergeUtil ( l : node , r : node ) -> node : NEW_LINE INDENT x = node ( ) NEW_LINE x . l0 = l . l0 if ( l . l0 != - 1 ) else r . l0 NEW_LINE x . r0 = r . r0 if ( r . r0 != - 1 ) else l . r0 NEW_LINE x . l1 = l . l1 if ( l . l1 != - 1 ) else r . l1 NEW_LINE x . r1 = r . r1 if ( r . r1 != - 1 ) else l . r1 NEW_LINE x . min0 = min ( l . min0 , r . min0 ) NEW_LINE if ( l . r0 != - 1 and r . l0 != - 1 ) : NEW_LINE INDENT x . min0 = min ( x . min0 , r . l0 - l . r0 ) NEW_LINE DEDENT x . min1 = min ( l . min1 , r . min1 ) NEW_LINE if ( l . r1 != - 1 and r . l1 != - 1 ) : NEW_LINE INDENT x . min1 = min ( x . min1 , r . l1 - l . r1 ) NEW_LINE DEDENT x . max0 = max ( l . max0 , r . max0 ) NEW_LINE if ( l . l0 != - 1 and r . r0 != - 1 ) : NEW_LINE INDENT x . max0 = max ( x . max0 , r . r0 - l . l0 ) NEW_LINE DEDENT x . max1 = max ( l . max1 , r . max1 ) NEW_LINE if ( l . l1 != - 1 and r . r1 != - 1 ) : NEW_LINE INDENT x . max1 = max ( x . max1 , r . r1 - l . l1 ) NEW_LINE DEDENT return x NEW_LINE DEDENT def UpdateUtil ( x : node ) -> node : NEW_LINE INDENT x . l0 , x . l1 = x . l1 , x . l0 NEW_LINE x . r0 , x . r1 = x . r1 , x . r0 NEW_LINE x . min1 , x . min0 = x . min0 , x . min1 NEW_LINE x . max0 , x . max1 = x . max1 , x . max0 NEW_LINE return x NEW_LINE DEDENT def Build ( qs : int , qe : int , ind : int , arr : List [ int ] ) -> None : NEW_LINE INDENT if ( qs == qe ) : NEW_LINE INDENT if ( arr [ qs ] == 1 ) : NEW_LINE INDENT seg [ ind ] . l1 = seg [ ind ] . r1 = qs NEW_LINE DEDENT else : NEW_LINE INDENT seg [ ind ] . l0 = seg [ ind ] . r0 = qs NEW_LINE DEDENT lazy [ ind ] = 0 NEW_LINE return NEW_LINE DEDENT mid = ( qs + qe ) >> 1 NEW_LINE Build ( qs , mid , ind << 1 , arr ) NEW_LINE Build ( mid + 1 , qe , ind << 1 1 , arr ) NEW_LINE seg [ ind ] = MergeUtil ( seg [ ind << 1 ] , seg [ ind << 1 1 ] ) NEW_LINE DEDENT def Query ( qs : int , qe : int , ns : int , ne : int , ind : int ) -> node : NEW_LINE INDENT if ( lazy [ ind ] != 0 ) : NEW_LINE INDENT seg [ ind ] = UpdateUtil ( seg [ ind ] ) NEW_LINE if ( ns != ne ) : NEW_LINE INDENT lazy [ ind * 2 ] ^= lazy [ ind ] NEW_LINE lazy [ ind * 2 + 1 ] ^= lazy [ ind ] NEW_LINE DEDENT lazy [ ind ] = 0 NEW_LINE DEDENT x = node ( ) NEW_LINE if ( qs <= ns and qe >= ne ) : NEW_LINE INDENT return seg [ ind ] NEW_LINE DEDENT if ( ne < qs or ns > qe or ns > ne ) : NEW_LINE INDENT return x NEW_LINE DEDENT mid = ( ns + ne ) >> 1 NEW_LINE l = Query ( qs , qe , ns , mid , ind << 1 ) NEW_LINE r = Query ( qs , qe , mid + 1 , ne , ind << 1 1 ) NEW_LINE x = MergeUtil ( l , r ) NEW_LINE return x NEW_LINE DEDENT def RangeUpdate ( us : int , ue : int , ns : int , ne : int , ind : int ) -> None : NEW_LINE INDENT if ( lazy [ ind ] != 0 ) : NEW_LINE INDENT seg [ ind ] = UpdateUtil ( seg [ ind ] ) NEW_LINE if ( ns != ne ) : NEW_LINE INDENT lazy [ ind * 2 ] ^= lazy [ ind ] NEW_LINE lazy [ ind * 2 + 1 ] ^= lazy [ ind ] NEW_LINE DEDENT lazy [ ind ] = 0 NEW_LINE DEDENT if ( ns > ne or ns > ue or ne < us ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( ns >= us and ne <= ue ) : NEW_LINE INDENT seg [ ind ] = UpdateUtil ( seg [ ind ] ) NEW_LINE if ( ns != ne ) : NEW_LINE INDENT lazy [ ind * 2 ] ^= 1 NEW_LINE lazy [ ind * 2 + 1 ] ^= 1 NEW_LINE DEDENT return NEW_LINE DEDENT mid = ( ns + ne ) >> 1 NEW_LINE RangeUpdate ( us , ue , ns , mid , ind << 1 ) NEW_LINE RangeUpdate ( us , ue , mid + 1 , ne , ind << 1 1 ) NEW_LINE l = seg [ ind << 1 ] NEW_LINE r = seg [ ind << 1 1 ] NEW_LINE seg [ ind ] = MergeUtil ( l , r ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE Build ( 0 , n - 1 , 1 , arr ) NEW_LINE ans = Query ( 3 , 7 , 0 , n - 1 , 1 ) NEW_LINE print ( ans . min1 ) NEW_LINE ans = Query ( 2 , 5 , 0 , n - 1 , 1 ) NEW_LINE print ( ans . max1 ) NEW_LINE RangeUpdate ( 1 , 4 , 0 , n - 1 , 1 ) NEW_LINE ans = Query ( 3 , 7 , 0 , n - 1 , 1 ) NEW_LINE print ( ans . min0 ) NEW_LINE ans = Query ( 4 , 9 , 0 , n - 1 , 1 ) NEW_LINE print ( ans . max0 ) NEW_LINE DEDENT |
Expected number of moves to reach the end of a board | Matrix Exponentiation | Python3 implementation of the approach ; Function to multiply two 7 * 7 matrix ; Function to perform matrix exponentiation ; 7 * 7 identity matrix ; Loop to find the power ; Function to return the required count ; Base cases ; Multiplier matrix ; Finding the required multiplier i . e mul ^ ( X - 6 ) ; Final answer ; Driver code | import numpy as np NEW_LINE maxSize = 50 NEW_LINE def matrix_product ( a , b ) : NEW_LINE INDENT c = np . zeros ( ( 7 , 7 ) ) ; NEW_LINE for i in range ( 7 ) : NEW_LINE INDENT for j in range ( 7 ) : NEW_LINE INDENT for k in range ( 7 ) : NEW_LINE INDENT c [ i ] [ j ] += a [ i ] [ k ] * b [ k ] [ j ] ; NEW_LINE DEDENT DEDENT DEDENT return c NEW_LINE DEDENT def mul_expo ( mul , p ) : NEW_LINE INDENT s = [ [ 1 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 1 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 1 ] ] ; NEW_LINE while ( p != 1 ) : NEW_LINE INDENT if ( p % 2 == 1 ) : NEW_LINE INDENT s = matrix_product ( s , mul ) ; NEW_LINE DEDENT mul = matrix_product ( mul , mul ) ; NEW_LINE p //= 2 ; NEW_LINE DEDENT return matrix_product ( mul , s ) ; NEW_LINE DEDENT def expectedSteps ( x ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( x <= 6 ) : NEW_LINE INDENT return 6 ; NEW_LINE DEDENT mul = [ [ 7 / 6 , 1 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 1 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 1 , 0 ] , [ 0 , 0 , 0 , 0 , 0 , 0 , 1 ] , [ - 1 / 6 , 0 , 0 , 0 , 0 , 0 , 0 ] ] ; NEW_LINE mul = mul_expo ( mul , x - 6 ) ; NEW_LINE return ( mul [ 0 ] [ 0 ] + mul [ 1 ] [ 0 ] + mul [ 2 ] [ 0 ] + mul [ 3 ] [ 0 ] + mul [ 4 ] [ 0 ] + mul [ 5 ] [ 0 ] ) * 6 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 10 ; NEW_LINE print ( expectedSteps ( n - 1 ) ) ; NEW_LINE DEDENT |
Place the prisoners into cells to maximize the minimum difference between any two | Function that returns true if the prisoners can be placed such that the minimum distance between any two prisoners is at least sep ; Considering the first prisoner is placed at 1 st cell ; If the first prisoner is placed at the first cell then the last_prisoner_placed will be the first prisoner placed and that will be in cell [ 0 ] ; Checking if the prisoner can be placed at ith cell or not ; If all the prisoners got placed then return true ; Function to return the maximized distance ; Sort the array so that binary search can be applied on it ; Minimum possible distance for the search space ; Maximum possible distance for the search space ; To store the result ; Binary search ; If the prisoners can be placed such that the minimum distance between any two prisoners is at least mid ; Update the answer ; Driver code | def canPlace ( a , n , p , sep ) : NEW_LINE INDENT prisoners_placed = 1 NEW_LINE last_prisoner_placed = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT current_cell = a [ i ] NEW_LINE if ( current_cell - last_prisoner_placed >= sep ) : NEW_LINE INDENT prisoners_placed += 1 NEW_LINE last_prisoner_placed = current_cell NEW_LINE if ( prisoners_placed == p ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT def maxDistance ( cell , n , p ) : NEW_LINE INDENT cell = sorted ( cell ) NEW_LINE start = 0 NEW_LINE end = cell [ n - 1 ] - cell [ 0 ] NEW_LINE ans = 0 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = start + ( ( end - start ) // 2 ) NEW_LINE if ( canPlace ( cell , n , p , mid ) ) : NEW_LINE INDENT ans = mid NEW_LINE start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT cell = [ 1 , 2 , 8 , 4 , 9 ] NEW_LINE n = len ( cell ) NEW_LINE p = 3 NEW_LINE print ( maxDistance ( cell , n , p ) ) NEW_LINE |
Find N in the given matrix that follows a pattern | Function to return the row and the column of the given integer ; Binary search for the row number ; Condition to get the maximum x that satisfies the criteria ; Binary search for the column number ; Condition to get the maximum y that satisfies the criteria ; Get the row and the column number ; Return the pair ; Driver code | def solve ( n ) : NEW_LINE INDENT low = 1 NEW_LINE high = 10 ** 4 NEW_LINE x , p = n , 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE sum = ( mid * ( mid + 1 ) ) // 2 NEW_LINE if ( x - sum >= 1 ) : NEW_LINE INDENT p = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT start , end , y , q = 1 , 10 ** 4 , 1 , 0 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE sum = ( mid * ( mid + 1 ) ) // 2 NEW_LINE if ( y + sum <= n ) : NEW_LINE INDENT q = mid NEW_LINE start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT x = x - ( p * ( p + 1 ) ) // 2 NEW_LINE y = y + ( q * ( q + 1 ) ) // 2 NEW_LINE r = x NEW_LINE c = q + 1 - n + y NEW_LINE return r , c NEW_LINE DEDENT n = 5 NEW_LINE r , c = solve ( n ) NEW_LINE print ( r , c ) NEW_LINE |
Find the count of distinct numbers in a range | Function to perform queries in a range ; No overlap ; Totally Overlap ; Partial Overlap ; Finding the Answer for the left Child ; Finding the Answer for the right Child ; Combining the BitMasks ; Function to perform update operation in the Segment seg ; Forming the BitMask ; Updating the left Child ; Updating the right Child ; Updating the BitMask ; Building the Segment Tree ; Building the Initial BitMask ; Building the left seg tree ; Building the right seg tree ; Forming the BitMask ; Utility Function to answer the queries ; Counting the set bits which denote the distinct elements ; Updating the value ; Driver Code | def query ( start , end , left , right , node , seg ) : NEW_LINE INDENT if ( end < left or start > right ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( start >= left and end <= right ) : NEW_LINE INDENT return seg [ node ] NEW_LINE DEDENT else : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE leftChild = query ( start , mid , left , right , 2 * node , seg ) NEW_LINE rightChild = query ( mid + 1 , end , left , right , 2 * node + 1 , seg ) NEW_LINE return ( leftChild rightChild ) NEW_LINE DEDENT DEDENT def update ( left , right , index , Value , node , ar , seg ) : NEW_LINE INDENT if ( left == right ) : NEW_LINE INDENT ar [ index ] = Value NEW_LINE seg [ node ] = ( 1 << Value ) NEW_LINE return NEW_LINE DEDENT mid = ( left + right ) // 2 NEW_LINE if ( index > mid ) : NEW_LINE INDENT update ( mid + 1 , right , index , Value , 2 * node + 1 , ar , seg ) NEW_LINE DEDENT else : NEW_LINE INDENT update ( left , mid , index , Value , 2 * node , ar , seg ) NEW_LINE DEDENT seg [ node ] = ( seg [ 2 * node ] seg [ 2 * node + 1 ] ) NEW_LINE DEDENT def build ( left , right , node , ar , eg ) : NEW_LINE INDENT if ( left == right ) : NEW_LINE INDENT seg [ node ] = ( 1 << ar [ left ] ) NEW_LINE return NEW_LINE DEDENT mid = ( left + right ) // 2 NEW_LINE build ( left , mid , 2 * node , ar , seg ) NEW_LINE build ( mid + 1 , right , 2 * node + 1 , ar , seg ) NEW_LINE seg [ node ] = ( seg [ 2 * node ] seg [ 2 * node + 1 ] ) NEW_LINE DEDENT def getDistinctCount ( queries , ar , seg , n ) : NEW_LINE INDENT for i in range ( len ( queries ) ) : NEW_LINE INDENT op = queries [ i ] [ 0 ] NEW_LINE if ( op == 2 ) : NEW_LINE INDENT l = queries [ i ] [ 1 ] NEW_LINE r = queries [ i ] [ 2 ] NEW_LINE tempMask = query ( 0 , n - 1 , l - 1 , r - 1 , 1 , seg ) NEW_LINE countOfBits = 0 NEW_LINE for i in range ( 63 , - 1 , - 1 ) : NEW_LINE INDENT if ( tempMask & ( 1 << i ) ) : NEW_LINE INDENT countOfBits += 1 NEW_LINE DEDENT DEDENT print ( countOfBits ) NEW_LINE DEDENT else : NEW_LINE INDENT index = queries [ i ] [ 1 ] NEW_LINE val = queries [ i ] [ 2 ] NEW_LINE update ( 0 , n - 1 , index - 1 , val , 1 , ar , seg ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 NEW_LINE ar = [ 1 , 2 , 1 , 3 , 1 , 2 , 1 ] NEW_LINE seg = [ 0 ] * 4 * n NEW_LINE build ( 0 , n - 1 , 1 , ar , seg ) NEW_LINE q = 5 NEW_LINE queries = [ [ 2 , 1 , 4 ] , [ 1 , 4 , 2 ] , [ 1 , 5 , 2 ] , [ 2 , 4 , 6 ] , [ 2 , 1 , 7 ] ] NEW_LINE getDistinctCount ( queries , ar , seg , n ) NEW_LINE DEDENT |
Smallest subarray with GCD as 1 | Segment Tree | Python3 implementation of the approach ; Array to store segment - tree ; Function to build segment - tree to answer range GCD queries ; Base - case ; Mid element of the range ; Merging the result of left and right sub - tree ; Function to perform range GCD queries ; Base - cases ; Mid - element ; Calling left and right child ; Function to find the required length ; Buildinng the segment tree ; Two pointer variables ; To store the final answer ; Loopinng ; Incrementing j till we don 't get a gcd value of 1 ; Updating the final answer ; Incrementing i ; Updating j ; Returning the final answer ; Driver code | from math import gcd as __gcd NEW_LINE maxLen = 30 NEW_LINE seg = [ 0 for i in range ( 3 * maxLen ) ] NEW_LINE def build ( l , r , inn , arr ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT seg [ inn ] = arr [ l ] NEW_LINE return seg [ inn ] NEW_LINE DEDENT mid = ( l + r ) // 2 NEW_LINE seg [ inn ] = __gcd ( build ( l , mid , 2 * inn + 1 , arr ) , build ( mid + 1 , r , 2 * inn + 2 , arr ) ) NEW_LINE return seg [ inn ] NEW_LINE DEDENT def query ( l , r , l1 , r1 , inn ) : NEW_LINE INDENT if ( l1 <= l and r <= r1 ) : NEW_LINE INDENT return seg [ inn ] NEW_LINE DEDENT if ( l > r1 or r < l1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT mid = ( l + r ) // 2 NEW_LINE x = __gcd ( query ( l , mid , l1 , r1 , 2 * inn + 1 ) , query ( mid + 1 , r , l1 , r1 , 2 * inn + 2 ) ) NEW_LINE return x NEW_LINE DEDENT def findLen ( arr , n ) : NEW_LINE INDENT build ( 0 , n - 1 , 0 , arr ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE ans = 10 ** 9 NEW_LINE while ( i < n ) : NEW_LINE INDENT while ( j < n and query ( 0 , n - 1 , i , j , 0 ) != 1 ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT if ( j == n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT ans = minn ( ( j - i + 1 ) , ans ) NEW_LINE i += 1 NEW_LINE j = max ( j , i ) NEW_LINE DEDENT if ( ans == 10 ** 9 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ans NEW_LINE DEDENT DEDENT arr = [ 2 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findLen ( arr , n ) ) NEW_LINE |
Find an N x N grid whose xor of every row and column is equal | Function to find the n x n matrix that satisfies the given condition ; Initialize x to 0 ; Divide the n x n matrix into n / 4 matrices for each of the n / 4 rows where each matrix is of size 4 x 4 ; Print the generated matrix ; Driver code | def findGrid ( n ) : NEW_LINE INDENT arr = [ [ 0 for k in range ( n ) ] for l in range ( n ) ] NEW_LINE x = 0 NEW_LINE for i in range ( n // 4 ) : NEW_LINE INDENT for j in range ( n // 4 ) : NEW_LINE INDENT for k in range ( 4 ) : NEW_LINE INDENT for l in range ( 4 ) : NEW_LINE INDENT arr [ i * 4 + k ] [ j * 4 + l ] = x NEW_LINE x += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT 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 n = 4 NEW_LINE findGrid ( n ) NEW_LINE |
Cartesian tree from inorder traversal | Segment Tree | Node of a linked list ; Array to store segment tree ; Function to create segment - tree to answer range - max query ; Base case ; Maximum index in left range ; Maximum index in right range ; If value at l1 > r1 ; Else ; Returning the maximum in range ; Function to answer range max query ; Base cases ; Maximum in left range ; Maximum in right range ; l1 = - 1 means left range was out - side required range ; Returning the maximum among two ranges ; Function to print the inorder traversal of the binary tree ; Base case ; Traversing the left sub - tree ; Printing current node ; Traversing the right sub - tree ; Function to build cartesian tree ; Base case ; Maximum in the range ; Creating current node ; Creating left sub - tree ; Creating right sub - tree ; Returning current node ; In - order traversal of cartesian tree ; Size of the array ; Building the segment tree ; Building && printing cartesian tree | class Node : NEW_LINE INDENT def __init__ ( self , data = None , left = None , right = None ) : NEW_LINE INDENT self . data = data NEW_LINE self . right = right NEW_LINE self . left = left NEW_LINE DEDENT DEDENT maxLen = 30 NEW_LINE segtree = [ 0 ] * ( maxLen * 4 ) NEW_LINE def buildTree ( l , r , i , arr ) : NEW_LINE INDENT global segtree NEW_LINE global maxLen NEW_LINE if ( l == r ) : NEW_LINE INDENT segtree [ i ] = l NEW_LINE return l NEW_LINE DEDENT l1 = buildTree ( l , int ( ( l + r ) / 2 ) , 2 * i + 1 , arr ) NEW_LINE r1 = buildTree ( int ( ( l + r ) / 2 ) + 1 , r , 2 * i + 2 , arr ) NEW_LINE if ( arr [ l1 ] > arr [ r1 ] ) : NEW_LINE INDENT segtree [ i ] = l1 NEW_LINE DEDENT else : NEW_LINE INDENT segtree [ i ] = r1 NEW_LINE DEDENT return segtree [ i ] NEW_LINE DEDENT def rangeMax ( l , r , rl , rr , i , arr ) : NEW_LINE INDENT global segtree NEW_LINE global maxLen NEW_LINE if ( r < rl or l > rr ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( l >= rl and r <= rr ) : NEW_LINE INDENT return segtree [ i ] NEW_LINE DEDENT l1 = rangeMax ( l , int ( ( l + r ) / 2 ) , rl , rr , 2 * i + 1 , arr ) NEW_LINE r1 = rangeMax ( int ( ( l + r ) / 2 ) + 1 , r , rl , rr , 2 * i + 2 , arr ) NEW_LINE if ( l1 == - 1 ) : NEW_LINE INDENT return r1 NEW_LINE DEDENT if ( r1 == - 1 ) : NEW_LINE INDENT return l1 NEW_LINE DEDENT if ( arr [ l1 ] > arr [ r1 ] ) : NEW_LINE INDENT return l1 NEW_LINE DEDENT else : NEW_LINE INDENT return r1 NEW_LINE DEDENT DEDENT def inorder ( curr ) : NEW_LINE INDENT if ( curr == None ) : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( curr . left ) NEW_LINE print ( curr . data , end = " β " ) NEW_LINE inorder ( curr . right ) NEW_LINE DEDENT def createCartesianTree ( l , r , arr , n ) : NEW_LINE INDENT if ( r < l ) : NEW_LINE INDENT return None NEW_LINE DEDENT m = rangeMax ( 0 , n - 1 , l , r , 0 , arr ) NEW_LINE curr = Node ( arr [ m ] ) NEW_LINE curr . left = createCartesianTree ( l , m - 1 , arr , n ) NEW_LINE curr . right = createCartesianTree ( m + 1 , r , arr , n ) NEW_LINE return curr NEW_LINE DEDENT arr = [ 8 , 11 , 21 , 100 , 5 , 70 , 55 ] NEW_LINE n = len ( arr ) NEW_LINE buildTree ( 0 , n - 1 , 0 , arr ) NEW_LINE inorder ( createCartesianTree ( 0 , n - 1 , arr , n ) ) NEW_LINE |
Kth smallest element in the array using constant space when array can 't be modified | Function to return the kth smallest element from the array ; Minimum and maximum element from the array ; Modified binary search ; To store the count of elements from the array which are less than mid and the elements which are equal to mid ; If mid is the kth smallest ; If the required element is less than mid ; If the required element is greater than mid ; Driver code | def kthSmallest ( arr , k , n ) : NEW_LINE INDENT low = min ( arr ) ; NEW_LINE high = max ( arr ) ; NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 ; NEW_LINE countless = 0 ; countequal = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < mid ) : NEW_LINE INDENT countless += 1 ; NEW_LINE DEDENT elif ( arr [ i ] == mid ) : NEW_LINE INDENT countequal += 1 ; NEW_LINE DEDENT DEDENT if ( countless < k and ( countless + countequal ) >= k ) : NEW_LINE INDENT return mid ; NEW_LINE DEDENT elif ( countless >= k ) : NEW_LINE INDENT high = mid - 1 ; NEW_LINE DEDENT elif ( countless < k and countless + countequal < k ) : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 10 , 4 , 3 , 20 , 15 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 3 ; NEW_LINE print ( kthSmallest ( arr , k , n ) ) ; NEW_LINE DEDENT |
Interactive Problems in Competitive Programming | ; Iterating from lower_bound to upper_bound ; Input the response from the judge | if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT lower_bound = 2 ; NEW_LINE upper_bound = 10 ; NEW_LINE for i in range ( lower_bound , upper_bound + 1 ) : NEW_LINE INDENT print ( i ) NEW_LINE response = int ( input ( ) ) NEW_LINE if ( response == 0 ) : NEW_LINE INDENT print ( " Number β guessed β is β : " , i , end = ' ' ) NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT |
Lazy Propagation in Segment Tree | Set 2 | Python3 implementation of the approach ; To store segment tree ; To store pending updates ; si -> index of current node in segment tree ss and se -> Starting and ending indexes of elements for which current nodes stores sum us and ue -> starting and ending indexes of update query diff -> which we need to add in the range us to ue ; If lazy value is non - zero for current node of segment tree , then there are some pending updates . So we need to make sure that the pending updates are done before making new updates . Because this value may be used by parent after recursive calls ( See last line of this function ) ; Make pending updates using value stored in lazy nodes ; Checking if it is not leaf node because if it is leaf node then we cannot go further ; We can postpone updating children we don 't need their new values now. Since we are not yet updating children of si, we need to set lazy flags for the children ; Set the lazy value for current node as 0 as it has been updated ; Out of range ; Current segment is fully in range ; Add the difference to current node ; Same logic for checking leaf node or not ; This is where we store values in lazy nodes , rather than updating the segment tree itelf Since we don 't need these updated values now we postpone updates by storing values in lazy[] ; If not completely in range , but overlaps recur for children ; And use the result of children calls to update this node ; Function to update a range of values in segment tree us and eu -> starting and ending indexes of update query ue -> ending index of update query diff -> which we need to add in the range us to ue ; A recursive function to get the sum of values in a given range of the array . The following are the parameters for this function si -- > Index of the current node in the segment tree Initially , 0 is passed as root is always at index 0 ss & se -- > Starting and ending indexes of the segment represented by current node i . e . , tree [ si ] qs & qe -- > Starting and ending indexes of query range ; If lazy flag is set for current node of segment tree then there are some pending updates . So we need to make sure that the pending updates are done before processing the sub sum query ; Make pending updates to this node . Note that this node represents sum of elements in arr [ ss . . se ] and all these elements must be increased by lazy [ si ] ; Checking if it is not leaf node because if it is leaf node then we cannot go further ; Since we are not yet updating children os si , we need to set lazy values for the children ; Unset the lazy value for current node as it has been updated ; Out of range ; If this segment lies in range ; If a part of this segment overlaps with the given range ; Return sum of elements in range from index qs ( querystart ) to qe ( query end ) . It mainly uses getSumUtil ( ) ; Check for erroneous input values ; A recursive function that constructs Segment Tree for array [ ss . . se ] . si is index of current node in segment tree st . ; out of range as ss can never be greater than se ; If there is one element in array , store it in current node of segment tree and return ; If there are more than one elements , then recur for left and right subtrees and store the sum of values in this node ; Function to construct a segment tree from a given array . This function allocates memory for segment tree and calls constructSTUtil ( ) to fill the allocated memory ; Fill the allocated memory st ; Driver code ; Build segment tree from given array ; Add 4 to all nodes in index range [ 0 , 3 ] ; Print maximum element in index range [ 1 , 4 ] | MAX = 1000 NEW_LINE tree = [ 0 ] * MAX ; NEW_LINE lazy = [ 0 ] * MAX ; NEW_LINE def updateRangeUtil ( si , ss , se , us , ue , diff ) : NEW_LINE INDENT if ( lazy [ si ] != 0 ) : NEW_LINE INDENT tree [ si ] += lazy [ si ] ; NEW_LINE if ( ss != se ) : NEW_LINE INDENT lazy [ si * 2 + 1 ] += lazy [ si ] ; NEW_LINE lazy [ si * 2 + 2 ] += lazy [ si ] ; NEW_LINE DEDENT lazy [ si ] = 0 ; NEW_LINE DEDENT if ( ss > se or ss > ue or se < us ) : NEW_LINE INDENT return ; NEW_LINE DEDENT if ( ss >= us and se <= ue ) : NEW_LINE INDENT tree [ si ] += diff ; NEW_LINE if ( ss != se ) : NEW_LINE INDENT lazy [ si * 2 + 1 ] += diff ; NEW_LINE lazy [ si * 2 + 2 ] += diff ; NEW_LINE DEDENT return ; NEW_LINE DEDENT mid = ( ss + se ) // 2 ; NEW_LINE updateRangeUtil ( si * 2 + 1 , ss , mid , us , ue , diff ) ; NEW_LINE updateRangeUtil ( si * 2 + 2 , mid + 1 , se , us , ue , diff ) ; NEW_LINE tree [ si ] = max ( tree [ si * 2 + 1 ] , tree [ si * 2 + 2 ] ) ; NEW_LINE DEDENT def updateRange ( n , us , ue , diff ) : NEW_LINE INDENT updateRangeUtil ( 0 , 0 , n - 1 , us , ue , diff ) ; NEW_LINE DEDENT def getSumUtil ( ss , se , qs , qe , si ) : NEW_LINE INDENT if ( lazy [ si ] != 0 ) : NEW_LINE INDENT tree [ si ] += lazy [ si ] ; NEW_LINE if ( ss != se ) : NEW_LINE INDENT lazy [ si * 2 + 1 ] += lazy [ si ] ; NEW_LINE lazy [ si * 2 + 2 ] += lazy [ si ] ; NEW_LINE DEDENT lazy [ si ] = 0 ; NEW_LINE DEDENT if ( ss > se or ss > qe or se < qs ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( ss >= qs and se <= qe ) : NEW_LINE INDENT return tree [ si ] ; NEW_LINE DEDENT mid = ( ss + se ) // 2 ; NEW_LINE return max ( getSumUtil ( ss , mid , qs , qe , 2 * si + 1 ) , getSumUtil ( mid + 1 , se , qs , qe , 2 * si + 2 ) ) ; NEW_LINE DEDENT def getSum ( n , qs , qe ) : NEW_LINE INDENT if ( qs < 0 or qe > n - 1 or qs > qe ) : NEW_LINE INDENT print ( " Invalid β Input " , end = " " ) ; NEW_LINE return - 1 ; NEW_LINE DEDENT return getSumUtil ( 0 , n - 1 , qs , qe , 0 ) ; NEW_LINE DEDENT def constructSTUtil ( arr , ss , se , si ) : NEW_LINE INDENT if ( ss > se ) : NEW_LINE INDENT return ; NEW_LINE DEDENT if ( ss == se ) : NEW_LINE INDENT tree [ si ] = arr [ ss ] ; NEW_LINE return ; NEW_LINE DEDENT mid = ( ss + se ) // 2 ; NEW_LINE constructSTUtil ( arr , ss , mid , si * 2 + 1 ) ; NEW_LINE constructSTUtil ( arr , mid + 1 , se , si * 2 + 2 ) ; NEW_LINE tree [ si ] = max ( tree [ si * 2 + 1 ] , tree [ si * 2 + 2 ] ) ; NEW_LINE DEDENT def constructST ( arr , n ) : NEW_LINE INDENT constructSTUtil ( arr , 0 , n - 1 , 0 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE constructST ( arr , n ) ; NEW_LINE updateRange ( n , 0 , 3 , 4 ) ; NEW_LINE print ( getSum ( n , 1 , 4 ) ) ; NEW_LINE DEDENT |
Find 2 ^ ( 2 ^ A ) % B | Function to return 2 ^ ( 2 ^ A ) % B ; Base case , 2 ^ ( 2 ^ 1 ) % B = 4 % B ; Driver code ; Print 2 ^ ( 2 ^ A ) % B | def F ( A , B ) : NEW_LINE INDENT if ( A == 1 ) : NEW_LINE INDENT return ( 4 % B ) ; NEW_LINE DEDENT else : NEW_LINE INDENT temp = F ( A - 1 , B ) ; NEW_LINE return ( temp * temp ) % B ; NEW_LINE DEDENT DEDENT A = 25 ; NEW_LINE B = 50 ; NEW_LINE print ( F ( A , B ) ) ; NEW_LINE |
Sum of i * countDigits ( i ) ^ 2 for all i in range [ L , R ] | Python3 implementation of the approach ; Function to return the required sum ; If range is valid ; Sum of AP ; Driver code | MOD = 1000000007 ; NEW_LINE def rangeSum ( l , r ) : NEW_LINE INDENT a = 1 ; b = 9 ; res = 0 ; NEW_LINE for i in range ( 1 , 11 ) : NEW_LINE INDENT L = max ( l , a ) ; NEW_LINE R = min ( r , b ) ; NEW_LINE if ( L <= R ) : NEW_LINE INDENT sum = ( L + R ) * ( R - L + 1 ) // 2 ; NEW_LINE res += ( i * i ) * ( sum % MOD ) ; NEW_LINE res %= MOD ; NEW_LINE DEDENT a *= 10 ; NEW_LINE b = b * 10 + 9 ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 98 ; r = 102 ; NEW_LINE print ( rangeSum ( l , r ) ) ; NEW_LINE DEDENT |
Generate a random permutation of elements from range [ L , R ] ( Divide and Conquer ) | Python3 implementation of the approach ; To store the random permutation ; Utility function to print the generated permutation ; Function to return a random number between x and y ; Recursive function to generate the random permutation ; Base condition ; Random number returned from the function ; Inserting random number in vector ; Recursion call for [ l , n - 1 ] ; Recursion call for [ n + 1 , r ] ; Driver code ; Generate permutation ; Print the generated permutation | import random NEW_LINE permutation = [ ] NEW_LINE def printPermutation ( ) : NEW_LINE INDENT for i in permutation : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT def give_random_number ( l , r ) : NEW_LINE INDENT x = random . randint ( l , r ) NEW_LINE return x NEW_LINE DEDENT def generate_random_permutation ( l , r ) : NEW_LINE INDENT if ( l > r ) : NEW_LINE INDENT return NEW_LINE DEDENT n = give_random_number ( l , r ) NEW_LINE permutation . append ( n ) NEW_LINE generate_random_permutation ( l , n - 1 ) NEW_LINE generate_random_permutation ( n + 1 , r ) NEW_LINE DEDENT l = 5 NEW_LINE r = 15 NEW_LINE generate_random_permutation ( l , r ) NEW_LINE printPermutation ( ) NEW_LINE |
Minimum number N such that total set bits of all numbers from 1 to N is at | Python3 implementation of the above approach ; Function to count sum of set bits of all numbers till N ; Function to find the minimum number ; Binary search for the lowest number ; Find mid number ; Check if it is atleast x ; Driver Code | INF = 99999 NEW_LINE size = 10 NEW_LINE def getSetBitsFromOneToN ( N ) : NEW_LINE INDENT two , ans = 2 , 0 NEW_LINE n = N NEW_LINE while ( n > 0 ) : NEW_LINE INDENT ans += ( N // two ) * ( two >> 1 ) NEW_LINE if ( ( N & ( two - 1 ) ) > ( two >> 1 ) - 1 ) : NEW_LINE INDENT ans += ( N & ( two - 1 ) ) - ( two >> 1 ) + 1 NEW_LINE DEDENT two <<= 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def findMinimum ( x ) : NEW_LINE INDENT low = 0 NEW_LINE high = 100000 NEW_LINE ans = high NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) >> 1 NEW_LINE if ( getSetBitsFromOneToN ( mid ) >= x ) : NEW_LINE INDENT ans = min ( ans , mid ) NEW_LINE high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT x = 20 NEW_LINE print ( findMinimum ( x ) ) NEW_LINE |
Range and Update Sum Queries with Factorial | Python3 program to calculate sum of factorials in an interval and update with two types of operations ; Modulus ; Maximum size of input array ; Size for factorial array ; structure for queries with members type , leftIndex , rightIndex of the query ; function for updating the value ; function for calculating the required sum between two indexes ; function to return answer to queries ; Precomputing factorials ; Declaring a Set ; inserting indexes of those numbers which are lesser than 40 ; update query of the 1 st type ; find the left index of query in the set using binary search ; if it crosses the right index of query or end of set , then break ; update the value of arr [ i ] to its new value ; if updated value becomes greater than or equal to 40 remove it from the set ; increment the index ; update query of the 2 nd type ; update the value to its new value ; If the value is less than 40 , insert it into set , otherwise remove it ; sum query of the 3 rd type ; Driver Code ; input array using 1 - based indexing ; declaring array of structure of type queries ; answer the Queries | from bisect import bisect_left as lower_bound NEW_LINE MOD = 1e9 NEW_LINE MAX = 100 NEW_LINE SZ = 40 NEW_LINE BIT = [ 0 ] * ( MAX + 1 ) NEW_LINE fact = [ 0 ] * ( SZ + 1 ) NEW_LINE class queries : NEW_LINE INDENT def __init__ ( self , tpe , l , r ) : NEW_LINE INDENT self . type = tpe NEW_LINE self . l = l NEW_LINE self . r = r NEW_LINE DEDENT DEDENT def update ( x , val , n ) : NEW_LINE INDENT global BIT NEW_LINE while x <= n : NEW_LINE INDENT BIT [ x ] += val NEW_LINE x += x & - x NEW_LINE DEDENT DEDENT def summ ( x ) : NEW_LINE INDENT global BIT NEW_LINE s = 0 NEW_LINE while x > 0 : NEW_LINE INDENT s += BIT [ x ] NEW_LINE x -= x & - x NEW_LINE DEDENT return s NEW_LINE DEDENT def answerQueries ( arr : list , que : list , n : int , q : int ) : NEW_LINE INDENT global fact NEW_LINE fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , 41 ) : NEW_LINE INDENT fact [ i ] = int ( ( fact [ i - 1 ] * i ) % MOD ) NEW_LINE DEDENT s = set ( ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] < 40 : NEW_LINE INDENT s . add ( i ) NEW_LINE update ( i , fact [ arr [ i ] ] , n ) NEW_LINE DEDENT else : NEW_LINE INDENT update ( i , 0 , n ) NEW_LINE DEDENT DEDENT for i in range ( q ) : NEW_LINE INDENT if que [ i ] . type == 1 : NEW_LINE INDENT while True : NEW_LINE INDENT s = list ( s ) NEW_LINE s . sort ( ) NEW_LINE it = lower_bound ( s , que [ i ] . l ) NEW_LINE if it == len ( s ) or s [ it ] > que [ i ] . r : NEW_LINE INDENT break NEW_LINE DEDENT que [ i ] . l = s [ it ] NEW_LINE val = arr [ s [ it ] ] + 1 NEW_LINE update ( s [ it ] , fact [ val ] - fact [ arr [ s [ it ] ] ] , n ) NEW_LINE arr [ s [ it ] ] += 1 NEW_LINE if arr [ s [ it ] ] >= 40 : NEW_LINE INDENT s . remove ( it ) NEW_LINE DEDENT que [ i ] . l += 1 NEW_LINE DEDENT DEDENT elif que [ i ] . type == 2 : NEW_LINE INDENT s = set ( s ) NEW_LINE idx = que [ i ] . l NEW_LINE val = que [ i ] . r NEW_LINE update ( idx , fact [ val ] - fact [ arr [ idx ] ] , n ) NEW_LINE arr [ idx ] = val NEW_LINE if val < 40 : NEW_LINE INDENT s . add ( idx ) NEW_LINE DEDENT else : NEW_LINE INDENT s . remove ( idx ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( ( summ ( que [ i ] . r ) - summ ( que [ i ] . l - 1 ) ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT q = 6 NEW_LINE arr = [ 0 , 1 , 2 , 1 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE que = [ queries ( 3 , 1 , 5 ) , queries ( 1 , 1 , 3 ) , queries ( 2 , 2 , 4 ) , queries ( 3 , 2 , 4 ) , queries ( 1 , 2 , 5 ) , queries ( 3 , 1 , 5 ) ] NEW_LINE answerQueries ( arr , que , n , q ) NEW_LINE DEDENT |
Numbers whose factorials end with n zeros | Function to calculate trailing zeros ; binary search for first number with n trailing zeros ; Print all numbers after low with n trailing zeros . ; Print result ; Driver code | def trailingZeroes ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE while n > 0 : NEW_LINE INDENT n = int ( n / 5 ) NEW_LINE cnt += n NEW_LINE DEDENT return cnt NEW_LINE DEDENT def binarySearch ( n ) : NEW_LINE INDENT low = 0 NEW_LINE while low < high : NEW_LINE INDENT mid = int ( ( low + high ) / 2 ) NEW_LINE count = trailingZeroes ( mid ) NEW_LINE if count < n : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid NEW_LINE DEDENT DEDENT result = list ( ) NEW_LINE while trailingZeroes ( low ) == n : NEW_LINE INDENT result . append ( low ) NEW_LINE low += 1 NEW_LINE DEDENT for i in range ( len ( result ) ) : NEW_LINE INDENT print ( result [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT n = 2 NEW_LINE binarySearch ( n ) NEW_LINE |
Number of days after which tank will become empty | Utility method to get sum of first n numbers ; Method returns minimum number of days after which tank will become empty ; if water filling is more than capacity then after C days only tank will become empty ; initialize binary search variable ; loop until low is less than high ; if cumulate sum is greater than ( C - l ) then search on left side ; if ( C - l ) is more then search on right side ; Final answer will be obtained by adding l to binary search result ; Driver code | def getCumulateSum ( n ) : NEW_LINE INDENT return int ( ( n * ( n + 1 ) ) / 2 ) NEW_LINE DEDENT def minDaysToEmpty ( C , l ) : NEW_LINE INDENT if ( C <= l ) : return C NEW_LINE lo , hi = 0 , 1e4 NEW_LINE while ( lo < hi ) : NEW_LINE INDENT mid = int ( ( lo + hi ) / 2 ) NEW_LINE if ( getCumulateSum ( mid ) >= ( C - l ) ) : NEW_LINE INDENT hi = mid NEW_LINE DEDENT else : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT DEDENT return ( l + lo ) NEW_LINE DEDENT C , l = 5 , 2 NEW_LINE print ( minDaysToEmpty ( C , l ) ) NEW_LINE |
Number of days after which tank will become empty | Python3 code to find number of days after which tank will become empty ; Method returns minimum number of days after which tank will become empty ; Driver code | import math NEW_LINE def minDaysToEmpty ( C , l ) : NEW_LINE INDENT if ( l >= C ) : return C NEW_LINE eq_root = ( math . sqrt ( 1 + 8 * ( C - l ) ) - 1 ) / 2 NEW_LINE return math . ceil ( eq_root ) + l NEW_LINE DEDENT print ( minDaysToEmpty ( 5 , 2 ) ) NEW_LINE print ( minDaysToEmpty ( 6514683 , 4965 ) ) NEW_LINE |
K | Program to find kth element from two sorted arrays ; Driver code | def kth ( arr1 , arr2 , m , n , k ) : NEW_LINE INDENT sorted1 = [ 0 ] * ( m + n ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE d = 0 NEW_LINE while ( i < m and j < n ) : NEW_LINE INDENT if ( arr1 [ i ] < arr2 [ j ] ) : NEW_LINE INDENT sorted1 [ d ] = arr1 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT sorted1 [ d ] = arr2 [ j ] NEW_LINE j += 1 NEW_LINE DEDENT d += 1 NEW_LINE DEDENT while ( i < m ) : NEW_LINE INDENT sorted1 [ d ] = arr1 [ i ] NEW_LINE d += 1 NEW_LINE i += 1 NEW_LINE DEDENT while ( j < n ) : NEW_LINE INDENT sorted1 [ d ] = arr2 [ j ] NEW_LINE d += 1 NEW_LINE j += 1 NEW_LINE DEDENT return sorted1 [ k - 1 ] NEW_LINE DEDENT arr1 = [ 2 , 3 , 6 , 7 , 9 ] NEW_LINE arr2 = [ 1 , 4 , 8 , 10 ] NEW_LINE k = 5 NEW_LINE print ( kth ( arr1 , arr2 , 5 , 4 , k ) ) NEW_LINE |
K | Python program to find k - th element from two sorted arrays | def kth ( arr1 , arr2 , n , m , k ) : NEW_LINE INDENT if n == 1 or m == 1 : NEW_LINE INDENT if m == 1 : NEW_LINE INDENT arr2 , arr1 = arr1 , arr2 NEW_LINE m = n NEW_LINE DEDENT if k == 1 : NEW_LINE INDENT return min ( arr1 [ 0 ] , arr2 [ 0 ] ) NEW_LINE DEDENT elif k == m + 1 : NEW_LINE INDENT return max ( arr1 [ 0 ] , arr2 [ 0 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT if arr2 [ k - 1 ] < arr1 [ 0 ] : NEW_LINE INDENT return arr2 [ k - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return max ( arr1 [ 0 ] , arr2 [ k - 2 ] ) NEW_LINE DEDENT DEDENT DEDENT mid1 = ( n - 1 ) // 2 NEW_LINE mid2 = ( m - 1 ) // 2 NEW_LINE if mid1 + mid2 + 1 < k : NEW_LINE INDENT if arr1 [ mid1 ] < arr2 [ mid2 ] : NEW_LINE INDENT return kth ( arr1 [ mid1 + 1 : ] , arr2 , n - mid1 - 1 , m , k - mid1 - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return kth ( arr1 , arr2 [ mid2 + 1 : ] , n , m - mid2 - 1 , k - mid2 - 1 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if arr1 [ mid1 ] < arr2 [ mid2 ] : NEW_LINE INDENT return kth ( arr1 , arr2 [ : mid2 + 1 ] , n , mid2 + 1 , k ) NEW_LINE DEDENT else : NEW_LINE INDENT return kth ( arr1 [ : mid1 + 1 ] , arr2 , mid1 + 1 , m , k ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr1 = [ 2 , 3 , 6 , 7 , 9 ] NEW_LINE arr2 = [ 1 , 4 , 8 , 10 ] NEW_LINE k = 5 NEW_LINE print ( kth ( arr1 , arr2 , 5 , 4 , k ) ) NEW_LINE DEDENT |
K | Python3 program to find kth element from two sorted arrays ; In case we have reached end of array 1 ; In case we have reached end of array 2 ; k should never reach 0 or exceed sizes of arrays ; Compare first elements of arrays and return ; Size of array 1 is less than k / 2 ; Last element of array 1 is not kth We can directly return the ( k - m ) th element in array 2 ; Size of array 2 is less than k / 2 ; Normal comparison , move starting index of one array k / 2 to the right ; Driver code | def kth ( arr1 , arr2 , m , n , k , st1 = 0 , st2 = 0 ) : NEW_LINE INDENT if ( st1 == m ) : NEW_LINE INDENT return arr2 [ st2 + k - 1 ] NEW_LINE DEDENT if ( st2 == n ) : NEW_LINE INDENT return arr1 [ st1 + k - 1 ] NEW_LINE DEDENT if ( k == 0 or k > ( m - st1 ) + ( n - st2 ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( k == 1 ) : NEW_LINE INDENT if ( arr1 [ st1 ] < arr2 [ st2 ] ) : NEW_LINE INDENT return arr1 [ st1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return arr2 [ st2 ] NEW_LINE DEDENT DEDENT curr = int ( k / 2 ) NEW_LINE if ( curr - 1 >= m - st1 ) : NEW_LINE INDENT if ( arr1 [ m - 1 ] < arr2 [ st2 + curr - 1 ] ) : NEW_LINE INDENT return arr2 [ st2 + ( k - ( m - st1 ) - 1 ) ] NEW_LINE DEDENT else : NEW_LINE INDENT return kth ( arr1 , arr2 , m , n , k - curr , st1 , st2 + curr ) NEW_LINE DEDENT DEDENT if ( curr - 1 >= n - st2 ) : NEW_LINE INDENT if ( arr2 [ n - 1 ] < arr1 [ st1 + curr - 1 ] ) : NEW_LINE INDENT return arr1 [ st1 + ( k - ( n - st2 ) - 1 ) ] NEW_LINE DEDENT else : NEW_LINE INDENT return kth ( arr1 , arr2 , m , n , k - curr , st1 + curr , st2 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( arr1 [ curr + st1 - 1 ] < arr2 [ curr + st2 - 1 ] ) : NEW_LINE INDENT return kth ( arr1 , arr2 , m , n , k - curr , st1 + curr , st2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return kth ( arr1 , arr2 , m , n , k - curr , st1 , st2 + curr ) NEW_LINE DEDENT DEDENT DEDENT arr1 = [ 2 , 3 , 6 , 7 , 9 ] NEW_LINE arr2 = [ 1 , 4 , 8 , 10 ] NEW_LINE k = 5 NEW_LINE print ( kth ( arr1 , arr2 , 5 , 4 , k ) ) NEW_LINE |
Search element in a sorted matrix | Python3 implementation to search an element in a sorted matrix ; This function does Binary search for x in i - th row . It does the search from mat [ i ] [ j_low ] to mat [ i ] [ j_high ] ; Element found ; Element not found ; Function to perform binary search on the mid values of row to get the desired pair of rows where the element can be found ; Single row matrix ; Do binary search in middle column . Condition to terminate the loop when the 2 desired rows are found ; element found ; If element is present on the mid of the two rows ; search element on 1 st half of 1 st row ; Search element on 2 nd half of 1 st row ; Search element on 1 st half of 2 nd row ; Search element on 2 nd half of 2 nd row ; Driver program to test above | MAX = 100 NEW_LINE def binarySearch ( mat , i , j_low , j_high , x ) : NEW_LINE INDENT while ( j_low <= j_high ) : NEW_LINE INDENT j_mid = ( j_low + j_high ) // 2 NEW_LINE if ( mat [ i ] [ j_mid ] == x ) : NEW_LINE INDENT print ( " Found β at β ( " , i , " , β " , j_mid , " ) " ) NEW_LINE return NEW_LINE DEDENT elif ( mat [ i ] [ j_mid ] > x ) : NEW_LINE INDENT j_high = j_mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT j_low = j_mid + 1 NEW_LINE DEDENT DEDENT print ( " Element β no β found " ) NEW_LINE DEDENT def sortedMatrixSearch ( mat , n , m , x ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT binarySearch ( mat , 0 , 0 , m - 1 , x ) NEW_LINE return NEW_LINE DEDENT i_low = 0 NEW_LINE i_high = n - 1 NEW_LINE j_mid = m // 2 NEW_LINE while ( ( i_low + 1 ) < i_high ) : NEW_LINE INDENT i_mid = ( i_low + i_high ) // 2 NEW_LINE if ( mat [ i_mid ] [ j_mid ] == x ) : NEW_LINE INDENT print ( " Found β at β ( " , i_mid , " , β " , j_mid , " ) " ) NEW_LINE return NEW_LINE DEDENT elif ( mat [ i_mid ] [ j_mid ] > x ) : NEW_LINE INDENT i_high = i_mid NEW_LINE DEDENT else : NEW_LINE INDENT i_low = i_mid NEW_LINE DEDENT DEDENT if ( mat [ i_low ] [ j_mid ] == x ) : NEW_LINE INDENT print ( " Found β at β ( " , i_low , " , " , j_mid , " ) " ) NEW_LINE DEDENT elif ( mat [ i_low + 1 ] [ j_mid ] == x ) : NEW_LINE INDENT print ( " Found β at β ( " , ( i_low + 1 ) , " , β " , j_mid , " ) " ) NEW_LINE DEDENT elif ( x <= mat [ i_low ] [ j_mid - 1 ] ) : NEW_LINE INDENT binarySearch ( mat , i_low , 0 , j_mid - 1 , x ) NEW_LINE DEDENT elif ( x >= mat [ i_low ] [ j_mid + 1 ] and x <= mat [ i_low ] [ m - 1 ] ) : NEW_LINE binarySearch ( mat , i_low , j_mid + 1 , m - 1 , x ) NEW_LINE elif ( x <= mat [ i_low + 1 ] [ j_mid - 1 ] ) : NEW_LINE INDENT binarySearch ( mat , i_low + 1 , 0 , j_mid - 1 , x ) NEW_LINE DEDENT else : NEW_LINE INDENT binarySearch ( mat , i_low + 1 , j_mid + 1 , m - 1 , x ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE m = 5 NEW_LINE x = 8 NEW_LINE mat = [ [ 0 , 6 , 8 , 9 , 11 ] , [ 20 , 22 , 28 , 29 , 31 ] , [ 36 , 38 , 50 , 61 , 63 ] , [ 64 , 66 , 100 , 122 , 128 ] ] NEW_LINE sortedMatrixSearch ( mat , n , m , x ) NEW_LINE DEDENT |
Minimum difference between adjacent elements of array which contain elements from each row of a matrix | Return smallest element greater than or equal to the current element . ; Return the minimum absolute difference adjacent elements of array ; arr = [ 0 for i in range ( R ) ] [ for j in range ( C ) ] Sort each row of the matrix . ; For each matrix element ; Search smallest element in the next row which is greater than or equal to the current element ; largest element which is smaller than the current element in the next row must be just before smallest element which is greater than or equal to the current element because rows are sorted . ; Driver Program | def bsearch ( low , high , n , arr ) : NEW_LINE INDENT mid = ( low + high ) / 2 NEW_LINE if ( low <= high ) : NEW_LINE INDENT if ( arr [ mid ] < n ) : NEW_LINE INDENT return bsearch ( mid + 1 , high , n , arr ) ; NEW_LINE DEDENT return bsearch ( low , mid - 1 , n , arr ) ; NEW_LINE DEDENT return low ; NEW_LINE DEDENT def mindiff ( arr , n , m ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT sorted ( arr ) NEW_LINE DEDENT ans = 2147483647 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT p = bsearch ( 0 , m - 1 , arr [ i ] [ j ] , arr [ i + 1 ] ) NEW_LINE ans = min ( ans , abs ( arr [ i + 1 ] [ p ] - arr [ i ] [ j ] ) ) NEW_LINE if ( p - 1 >= 0 ) : NEW_LINE INDENT ans = min ( ans , abs ( arr [ i + 1 ] [ p - 1 ] - arr [ i ] [ j ] ) ) NEW_LINE DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT m = [ 8 , 5 ] , [ 6 , 8 ] NEW_LINE print mindiff ( m , 2 , 2 ) NEW_LINE |
Find bitonic point in given bitonic sequence | Function to find bitonic point using binary search ; base condition to check if arr [ mid ] is bitonic point or not ; We assume that sequence is bitonic . We go to right subarray if middle point is part of increasing subsequence . Else we go to left subarray . ; Driver Code | def binarySearch ( arr , left , right ) : NEW_LINE INDENT if ( left <= right ) : NEW_LINE INDENT mid = ( left + right ) // 2 ; NEW_LINE if ( arr [ mid - 1 ] < arr [ mid ] and arr [ mid ] > arr [ mid + 1 ] ) : NEW_LINE INDENT return mid ; NEW_LINE DEDENT if ( arr [ mid ] < arr [ mid + 1 ] ) : NEW_LINE INDENT return binarySearch ( arr , mid + 1 , right ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return binarySearch ( arr , left , mid - 1 ) ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT arr = [ 6 , 7 , 8 , 11 , 9 , 5 , 2 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE index = binarySearch ( arr , 1 , n - 2 ) ; NEW_LINE if ( index != - 1 ) : NEW_LINE INDENT print ( arr [ index ] ) ; NEW_LINE DEDENT |
Find the only repeating element in a sorted array of size n | Returns index of second appearance of a repeating element The function assumes that array elements are in range from 1 to n - 1. ; low = 0 , high = n - 1 ; Check if the mid element is the repeating one ; If mid element is not at its position that means the repeated element is in left ; If mid is at proper position then repeated one is in right . ; Driver code | def findRepeatingElement ( arr , low , high ) : NEW_LINE INDENT if low > high : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mid = ( low + high ) / 2 NEW_LINE if ( arr [ mid ] != mid + 1 ) : NEW_LINE INDENT if ( mid > 0 and arr [ mid ] == arr [ mid - 1 ] ) : NEW_LINE INDENT return mid NEW_LINE DEDENT return findRepeatingElement ( arr , low , mid - 1 ) NEW_LINE DEDENT return findRepeatingElement ( arr , mid + 1 , high ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE index = findRepeatingElement ( arr , 0 , n - 1 ) NEW_LINE if ( index is not - 1 ) : NEW_LINE INDENT print arr [ index ] NEW_LINE DEDENT |
Find cubic root of a number | Returns the absolute value of n - mid * mid * mid ; Returns cube root of a no n ; Set start and end for binary search ; Set precision ; If error is less than e then mid is our answer so return mid ; If mid * mid * mid is greater than n set end = mid ; If mid * mid * mid is less than n set start = mid ; Driver code | def diff ( n , mid ) : NEW_LINE INDENT if ( n > ( mid * mid * mid ) ) : NEW_LINE INDENT return ( n - ( mid * mid * mid ) ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( mid * mid * mid ) - n ) NEW_LINE DEDENT DEDENT def cubicRoot ( n ) : NEW_LINE INDENT start = 0 NEW_LINE end = n NEW_LINE e = 0.0000001 NEW_LINE while ( True ) : NEW_LINE INDENT mid = ( start + end ) / 2 NEW_LINE error = diff ( n , mid ) NEW_LINE if ( error <= e ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( ( mid * mid * mid ) > n ) : NEW_LINE INDENT end = mid NEW_LINE DEDENT else : NEW_LINE INDENT start = mid NEW_LINE DEDENT DEDENT DEDENT n = 3 NEW_LINE print ( " Cubic β root β of " , n , " is " , round ( cubicRoot ( n ) , 6 ) ) NEW_LINE |
Find frequency of each element in a limited range array in less than O ( n ) time | A recursive function to count number of occurrences for each element in the array without traversing the whole array ; If element at index low is equal to element at index high in the array ; increment the frequency of the element by count of elements between high and low ; Find mid and recurse for left and right subarray ; A wrapper over recursive function findFrequencyUtil ( ) . It print number of occurrences of each element in the array . ; create a empty vector to store frequencies and initialize it by 0. Size of vector is maximum value ( which is last value in sorted array ) plus 1. ; Fill the vector with frequency ; Print the frequencies ; Driver Code | def findFrequencyUtil ( arr , low , high , freq ) : NEW_LINE INDENT if ( arr [ low ] == arr [ high ] ) : NEW_LINE INDENT freq [ arr [ low ] ] += high - low + 1 NEW_LINE DEDENT else : NEW_LINE INDENT mid = int ( ( low + high ) / 2 ) NEW_LINE findFrequencyUtil ( arr , low , mid , freq ) NEW_LINE findFrequencyUtil ( arr , mid + 1 , high , freq ) NEW_LINE DEDENT DEDENT def findFrequency ( arr , n ) : NEW_LINE INDENT freq = [ 0 for i in range ( n - 1 + 1 ) ] NEW_LINE findFrequencyUtil ( arr , 0 , n - 1 , freq ) NEW_LINE for i in range ( 0 , arr [ n - 1 ] + 1 , 1 ) : NEW_LINE INDENT if ( freq [ i ] != 0 ) : NEW_LINE INDENT print ( " Element " , i , " occurs " , freq [ i ] , " times " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 , 8 , 8 , 8 , 9 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE findFrequency ( arr , n ) NEW_LINE DEDENT |
Square root of an integer | Returns floor of square root of x ; Base cases ; Starting from 1 , try all numbers until i * i is greater than or equal to x . ; Driver Code | def floorSqrt ( x ) : NEW_LINE INDENT if ( x == 0 or x == 1 ) : NEW_LINE INDENT return x NEW_LINE DEDENT i = 1 ; result = 1 NEW_LINE while ( result <= x ) : NEW_LINE INDENT i += 1 NEW_LINE result = i * i NEW_LINE DEDENT return i - 1 NEW_LINE DEDENT x = 11 NEW_LINE print ( floorSqrt ( x ) ) NEW_LINE |
Maximum number of overlapping rectangles with at least one common point | Function to find the maximum number of overlapping rectangles ; Stores the maximum count of overlapping rectangles ; Stores the X and Y coordinates ; Iterate over all pairs of Xs and Ys ; Store the count for the current X and Y ; Update the maximum count of rectangles ; Returns the total count ; Driver Code | def maxOverlappingRectangles ( x1 , y1 , x2 , y2 , N ) : NEW_LINE INDENT max_rectangles = 0 NEW_LINE X = [ ] NEW_LINE Y = [ ] NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT X . append ( x1 [ i ] ) NEW_LINE X . append ( x2 [ i ] - 1 ) NEW_LINE Y . append ( y1 [ i ] ) NEW_LINE Y . append ( y2 [ i ] - 1 ) NEW_LINE DEDENT for i in range ( 0 , len ( X ) ) : NEW_LINE INDENT for j in range ( 0 , len ( Y ) ) : NEW_LINE INDENT cnt = 0 NEW_LINE for k in range ( 0 , N ) : NEW_LINE INDENT if ( X [ i ] >= x1 [ k ] and X [ i ] + 1 <= x2 [ k ] and Y [ j ] >= y1 [ k ] and Y [ j ] + 1 <= y2 [ k ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT max_rectangles = max ( max_rectangles , cnt ) NEW_LINE DEDENT DEDENT print ( max_rectangles ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x1 = [ 0 , 50 ] NEW_LINE y1 = [ 0 , 50 ] NEW_LINE x2 = [ 100 , 60 ] NEW_LINE y2 = [ 100 , 60 ] NEW_LINE N = len ( x1 ) NEW_LINE maxOverlappingRectangles ( x1 , y1 , x2 , y2 , N ) NEW_LINE DEDENT |
Form a Rectangle from boundary elements of Matrix using Linked List | Python program for above approach Node Class ; Constructor to initialize the node object ; Linked List class ; Constructor to initialize head ; function to form square linked list of matrix . ; initialising A [ 0 ] [ 0 ] as head . ; head is assigned to head . ; i is row index , j is column index ; loop till temp . top become equal to head . ; iterating over first i . e 0 th row and connecting node . ; iterating over last i . e ( m - 1 ) th column and connecting Node . ; iterating over last i . e ( n - 1 ) th row and connecting Node . ; iterating over first i . e 0 th column and connecting Node . ; function to print Linked list . ; printing head of linked list ; loop till temp . top become equal to head ; printing the node ; Driver Code ; n is number of rows ; m is number of column ; creation of object ; Call Quad method to create Linked List . ; Call printList method to print list . | class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . data = val NEW_LINE self . next = None NEW_LINE self . prev = None NEW_LINE self . top = None NEW_LINE self . bottom = None NEW_LINE DEDENT DEDENT class LinkedList : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT def Quad ( self , grid , n , m ) : NEW_LINE INDENT self . head = Node ( grid [ 0 ] [ 0 ] ) NEW_LINE temp = self . head NEW_LINE i = 0 NEW_LINE j = 1 NEW_LINE while temp . top != self . head : NEW_LINE INDENT if j < m and i == 0 : NEW_LINE INDENT temp . next = Node ( grid [ i ] [ j ] ) NEW_LINE temp = temp . next NEW_LINE j += 1 NEW_LINE DEDENT elif j == m and i < n - 1 : NEW_LINE INDENT i = i + 1 NEW_LINE temp . bottom = Node ( grid [ i ] [ j - 1 ] ) NEW_LINE temp = temp . bottom NEW_LINE DEDENT elif i == n - 1 and j <= m and j >= 1 : NEW_LINE INDENT if j == m : j = j - 1 NEW_LINE j = j - 1 NEW_LINE temp . prev = Node ( grid [ i ] [ j ] ) NEW_LINE temp = temp . prev NEW_LINE DEDENT elif i <= n - 1 and j == 0 : NEW_LINE INDENT i = i - 1 NEW_LINE temp . top = Node ( grid [ i ] [ j ] ) NEW_LINE temp = temp . top NEW_LINE if i == 1 : NEW_LINE INDENT temp . top = self . head NEW_LINE DEDENT DEDENT DEDENT DEDENT def printList ( self , root ) : NEW_LINE INDENT temp = root NEW_LINE print ( temp . data , end = " β " ) NEW_LINE while temp . top != root : NEW_LINE INDENT if temp . next : NEW_LINE INDENT print ( temp . next . data , end = " β " ) NEW_LINE temp = temp . next NEW_LINE DEDENT if temp . prev : NEW_LINE INDENT print ( temp . prev . data , end = " β " ) NEW_LINE temp = temp . prev NEW_LINE DEDENT if temp . bottom : NEW_LINE INDENT print ( temp . bottom . data , end = " β " ) NEW_LINE temp = temp . bottom NEW_LINE DEDENT if temp . top : NEW_LINE INDENT print ( temp . top . data , end = " β " ) NEW_LINE temp = temp . top NEW_LINE DEDENT DEDENT DEDENT DEDENT grid = [ [ 13 , 42 , 93 , 88 ] , [ 26 , 38 , 66 , 42 ] , [ 75 , 63 , 78 , 12 ] ] NEW_LINE n = len ( grid ) NEW_LINE m = len ( grid [ 0 ] ) NEW_LINE l = LinkedList ( ) NEW_LINE l . Quad ( grid , n , m ) NEW_LINE l . printList ( l . head ) NEW_LINE |
Check if it is possible to reach the point ( X , Y ) using distances given in an array | Python program for the above approach ; Function to check if the po ( X , Y ) is reachable from ( 0 , 0 ) or not ; Find the Euclidian Distance ; Calculate the maximum distance ; Case 1. ; Case 2. ; Otherwise , check for the polygon condition for each side ; Otherwise , prYes ; Driver Code | import math NEW_LINE def isPossibleToReach ( A , N , X , Y ) : NEW_LINE INDENT distance = math . sqrt ( X * X + Y * Y ) NEW_LINE mx = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT mx += A [ i ] NEW_LINE DEDENT if ( mx < distance ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE return 0 NEW_LINE DEDENT if ( ( mx - distance ) < 0.000001 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE return 0 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( distance + mx < ( 2 ) * ( A [ i ] ) ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return 0 NEW_LINE DEDENT DEDENT print ( " Yes " ) NEW_LINE return 0 NEW_LINE DEDENT A = [ 2 , 5 ] NEW_LINE X = 5 NEW_LINE Y = 4 NEW_LINE N = len ( A ) NEW_LINE isPossibleToReach ( A , N , X , Y ) NEW_LINE |
Check if it is possible to reach ( X , Y ) from origin such that in each ith move increment x or y coordinate with 3 ^ i | Function to find whether ( 0 , 0 ) can be reached from ( X , Y ) by decrementing 3 ^ i at each ith step ; Termination Condition ; Otherwise , recursively call by decrementing 3 ^ i at each step ; Driver Code | def canReach ( X , Y , steps ) : NEW_LINE INDENT if ( X == 0 and Y == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( X < 0 or Y < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( canReach ( X - int ( pow ( 3 , steps ) ) , Y , steps + 1 ) | canReach ( X , Y - int ( pow ( 3 , steps ) ) , steps + 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 10 NEW_LINE Y = 30 NEW_LINE if ( canReach ( X , Y , 0 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Check if it is possible to reach ( X , Y ) from origin such that in each ith move increment x or y coordinate with 3 ^ i | Function to find whether ( 0 , 0 ) can be reached from ( X , Y ) by decrementing 3 ^ i at each ith step ; Stores the number of steps performed to reach ( X , Y ) ; Value of X in base 3 ; Value of Y in base 3 ; Check if any has value 2 ; If both have value 1 ; If both have value 0 ; Otherwise , return true ; Driver Code | def canReach ( X , Y ) : NEW_LINE INDENT steps = 0 NEW_LINE while ( X != 0 or Y != 0 ) : NEW_LINE INDENT pos1 = X % 3 NEW_LINE pos2 = Y % 3 NEW_LINE if ( pos1 == 2 or pos2 == 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( pos1 == 1 and pos2 == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( pos1 == 0 and pos2 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT X /= 3 NEW_LINE Y /= 3 NEW_LINE steps += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT X = 10 NEW_LINE Y = 30 NEW_LINE if ( canReach ( X , Y ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Program to calculate Surface Area of Ellipsoid | Python3 program for the above approach ; Function to find the surface area of the given Ellipsoid ; Formula to find surface area of an Ellipsoid ; Print the area ; Driver Code | from math import pow NEW_LINE def findArea ( a , b , c ) : NEW_LINE INDENT area = ( 4 * 3.141592653 * pow ( ( pow ( a * b , 1.6 ) + pow ( a * c , 1.6 ) + pow ( b * c , 1.6 ) ) / 3 , 1 / 1.6 ) ) NEW_LINE print ( " { : . 2f } " . format ( round ( area , 2 ) ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 11 NEW_LINE B = 12 NEW_LINE C = 13 NEW_LINE findArea ( A , B , C ) NEW_LINE DEDENT |
Descartes ' Circle Theorem with implementation | Python 3 implementation of the above formulae ; Function to find the fourth circle 's when three radius are given ; Driver code ; Radius of three circles ; Calculation of r4 using formula given above | from math import sqrt NEW_LINE def findRadius ( r1 , r2 , r3 ) : NEW_LINE INDENT r4 = ( r1 * r2 * r3 ) / ( r1 * r2 + r2 * r3 + r1 * r3 + 2.0 * sqrt ( r1 * r2 * r3 * ( r1 + r2 + r3 ) ) ) NEW_LINE return r4 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT r1 = 1 NEW_LINE r2 = 1 NEW_LINE r3 = 1 NEW_LINE r4 = findRadius ( r1 , r2 , r3 ) NEW_LINE print ( " The β radius β of β fourth β circle : " , r4 ) NEW_LINE DEDENT |
Make N pairs from Array as ( X , Y ) coordinate point that are enclosed inside a minimum area rectangle | Function to make N pairs of coordinates such that they are enclosed in a minimum area rectangle with sides parallel to the X and Y axes ; A variable to store the answer ; For the case where the maximum and minimum are in different partitions ; For the case where the maximum and minimum are in the same partition ; Return the answer ; Driver code ; Given Input ; Function call | def minimumRectangleArea ( A , N ) : NEW_LINE INDENT ans = 0 NEW_LINE A . sort ( ) NEW_LINE ans = ( A [ N - 1 ] - A [ 0 ] ) * ( A [ 2 * N - 1 ] - A [ N ] ) NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT ans = min ( ans , ( A [ 2 * N - 1 ] - A [ 0 ] ) * ( A [ i + N - 1 ] - A [ i ] ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 2 , 4 , 1 , 5 , 3 , 6 , 7 , 8 ] NEW_LINE N = len ( A ) NEW_LINE N //= 2 NEW_LINE print ( minimumRectangleArea ( A , N ) ) NEW_LINE DEDENT |
Program to find the length of Latus Rectum of a Hyperbola | Function to calculate the length of the latus rectum of a hyperbola ; Store the length of major axis ; Store the length of minor axis ; Store the length of the latus rectum ; Return the length of the latus rectum ; Driver Code | def lengthOfLatusRectum ( A , B ) : NEW_LINE INDENT major = 2.0 * A NEW_LINE minor = 2.0 * B NEW_LINE latus_rectum = ( minor * minor ) / major NEW_LINE return latus_rectum NEW_LINE DEDENT A = 3.0 NEW_LINE B = 2.0 NEW_LINE print ( round ( lengthOfLatusRectum ( A , B ) , 5 ) ) NEW_LINE |
Length of intercept cut off from a line by a Circle | Python3 program for the above approach ; Function to find the radius of a circle ; g and f are the coordinates of the center ; Case of invalid circle ; Apply the radius formula ; Function to find the perpendicular distance between circle center and the line ; Store the coordinates of center ; Stores the perpendicular distance between the line and the point ; Invalid Case ; Return the distance ; Function to find the length of intercept cut off from a line by a circle ; Calculate the value of radius ; Calculate the perpendicular distance between line and center ; Invalid Case ; If line do not cut circle ; Print the intercept length ; Driver Code ; Given Input ; Function Call | import math NEW_LINE def radius ( a , b , c ) : NEW_LINE INDENT g = a / 2 NEW_LINE f = b / 2 NEW_LINE if ( g * g + f * f - c < 0 ) : NEW_LINE INDENT return ( - 1 ) NEW_LINE DEDENT return ( math . sqrt ( g * g + f * f - c ) ) NEW_LINE DEDENT def centerDistanceFromLine ( a , b , i , j , k ) : NEW_LINE INDENT g = a / 2 NEW_LINE f = b / 2 NEW_LINE distance = ( abs ( i * g + j * f + k ) / ( math . sqrt ( i * i + j * j ) ) ) NEW_LINE if ( distance < 0 ) : NEW_LINE INDENT return ( - 1 ) NEW_LINE DEDENT return distance NEW_LINE DEDENT def interceptLength ( a , b , c , i , j , k ) : NEW_LINE INDENT rad = radius ( a , b , c ) NEW_LINE dist = centerDistanceFromLine ( a , b , i , j , k ) NEW_LINE if ( rad < 0 or dist < 0 ) : NEW_LINE INDENT print ( " circle β not β possible " ) NEW_LINE return NEW_LINE DEDENT if ( dist > rad ) : NEW_LINE INDENT print ( " Line β not β cutting β circle " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 2 * math . sqrt ( rad * rad - dist * dist ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 0 NEW_LINE b = 0 NEW_LINE c = - 4 NEW_LINE i = 2 NEW_LINE j = - 1 NEW_LINE k = 1 NEW_LINE interceptLength ( a , b , c , i , j , k ) NEW_LINE DEDENT |
Determine position of two points with respect to a 3D plane | Function to check position of two points with respect to a plane in 3D ; Put coordinates in plane equation ; If both values have same sign ; If both values have different sign ; If both values are zero ; If either of the two values is zero ; Driver Code ; Given Input ; Coordinates of points ; Function Call | def check_position ( a , b , c , d , x1 , y1 , z1 , x2 , y2 , z2 ) : NEW_LINE INDENT value_1 = a * x1 + b * y1 + c * z1 + d NEW_LINE value_2 = a * x2 + b * y2 + c * z2 + d NEW_LINE if ( ( value_1 > 0 and value_2 > 0 ) or ( value_1 < 0 and value_2 < 0 ) ) : NEW_LINE INDENT print ( " On β same β side " ) NEW_LINE DEDENT if ( ( value_1 > 0 and value_2 < 0 ) or ( value_1 < 0 and value_2 > 0 ) ) : NEW_LINE INDENT print ( " On β different β sides " ) NEW_LINE DEDENT if ( value_1 == 0 and value_2 == 0 ) : NEW_LINE INDENT print ( " Both β on β the β plane " ) NEW_LINE DEDENT if ( value_1 == 0 and value_2 != 0 ) : NEW_LINE INDENT print ( " Point β 1 β on β the β plane " ) NEW_LINE DEDENT if ( value_1 != 0 and value_2 == 0 ) : NEW_LINE INDENT print ( " Point β 2 β on β the β plane " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a , b , c , d = 1 , 2 , 3 , 4 NEW_LINE x1 , y1 , z1 = - 2 , - 2 , 1 NEW_LINE x2 , y2 , z2 = - 4 , 11 , - 1 NEW_LINE check_position ( a , b , c , d , x1 , y1 , z1 , x2 , y2 , z2 ) NEW_LINE DEDENT |
Check if any pair of semicircles intersect or not | Function to check if any pairs of the semicircles intersects or not ; Stores the coordinates of all the semicircles ; x and y are coordinates ; Store the minimum and maximum value of the pair ; Push the pair in vector ; Compare one pair with other pairs ; Generating the second pair ; Extract all the second pairs one by one ; 1 st condition ; 2 nd condition ; If any one condition is true ; If any pair of semicircles doesn 't exists ; Driver Code | def checkIntersection ( arr , N ) : NEW_LINE INDENT vec = [ ] NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT x = arr [ i ] NEW_LINE y = arr [ i + 1 ] NEW_LINE minn = min ( x , y ) NEW_LINE maxx = max ( x , y ) NEW_LINE vec . append ( [ minn , maxx ] ) NEW_LINE DEDENT for i in range ( len ( vec ) ) : NEW_LINE INDENT x = vec [ i ] NEW_LINE for j in range ( len ( vec ) ) : NEW_LINE INDENT y = vec [ j ] NEW_LINE cond1 = ( x [ 0 ] < y [ 0 ] and x [ 1 ] < y [ 1 ] and y [ 0 ] < x [ 1 ] ) NEW_LINE cond2 = ( y [ 0 ] < x [ 0 ] and y [ 1 ] < x [ 1 ] and x [ 0 ] < y [ 1 ] ) NEW_LINE if ( cond1 or cond2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 15 , 5 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE if ( checkIntersection ( arr , N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Find the angle between tangents drawn from a given external point to a Circle | Python 3 program for the above approach ; Function to find the distance between center and the exterior point ; Find the difference between the x and y coordinates ; Using the distance formula ; Function to find the angle between the pair of tangents drawn from the point ( X2 , Y2 ) to the circle . ; Calculate the distance between the center and exterior point ; Invalid Case ; Find the angle using the formula ; Print the resultant angle ; Driver Code | import math NEW_LINE def point_distance ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT p = ( x2 - x1 ) NEW_LINE q = ( y2 - y1 ) NEW_LINE distance = math . sqrt ( p * p + q * q ) NEW_LINE return distance NEW_LINE DEDENT def tangentAngle ( x1 , y1 , x2 , y2 , radius ) : NEW_LINE INDENT distance = point_distance ( x1 , y1 , x2 , y2 ) NEW_LINE if ( radius / distance > 1 or radius / distance < - 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT result = 2 * math . asin ( radius / distance ) * 180 / 3.1415 NEW_LINE print ( result , " β degrees " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT radius = 4 NEW_LINE x1 = 7 NEW_LINE y1 = 12 NEW_LINE x2 = 3 NEW_LINE y2 = 4 NEW_LINE tangentAngle ( x1 , y1 , x2 , y2 , radius ) NEW_LINE DEDENT |
Ratio of area of two nested polygons formed by connecting midpoints of sides of a regular N | Python3 code for the above approach ; Function to calculate the ratio of area of N - th and ( N + 1 ) - th nested polygons formed by connecting midpoints ; Stores the value of PI ; Calculating area the factor ; Printing the ratio precise upto 6 decimal places ; Driver Code | import math NEW_LINE def AreaFactor ( n ) : NEW_LINE INDENT pi = 3.14159265 NEW_LINE areaf = 1 / ( math . cos ( pi / n ) * math . cos ( pi / n ) ) NEW_LINE print ( ' % .6f ' % areaf ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE AreaFactor ( n ) NEW_LINE DEDENT |
Find the length of Kth N | Python3 program for the above approach ; Function to calculate the interior angle of a N - sided regular polygon ; Function to find the K - th polygon formed inside the ( K - 1 ) th polygon ; Stores the interior angle ; Stores the side length of K - th regular polygon ; Return the length ; Driver Code | import math NEW_LINE PI = 3.14159265 NEW_LINE def findInteriorAngle ( n ) : NEW_LINE INDENT return ( n - 2 ) * PI / n NEW_LINE DEDENT def calculateSideLength ( L , N , K ) : NEW_LINE INDENT angle = findInteriorAngle ( N ) NEW_LINE length = L * pow ( math . sin ( angle / 2 ) , ( K - 1 ) ) NEW_LINE return length NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE L = 21 NEW_LINE K = 7 NEW_LINE print ( calculateSideLength ( L , N , K ) ) NEW_LINE DEDENT |
Angle between a Pair of Lines | Python3 program for the above approach ; Function to find the angle between two lines ; Store the tan value of the angle ; Calculate tan inverse of the angle ; Convert the angle from radian to degree ; Print the result ; Driver Code | from math import atan NEW_LINE def findAngle ( M1 , M2 ) : NEW_LINE INDENT PI = 3.14159265 NEW_LINE angle = abs ( ( M2 - M1 ) / ( 1 + M1 * M2 ) ) NEW_LINE ret = atan ( angle ) NEW_LINE val = ( ret * 180 ) / PI NEW_LINE print ( round ( val , 4 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M1 = 1.75 NEW_LINE M2 = 0.27 NEW_LINE findAngle ( M1 , M2 ) NEW_LINE DEDENT |
Subsets and Splits