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 r... | 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 '... |
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 st... | 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... |
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 ( nu... |
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 or... | 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... |
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 ( countToMake... |
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... | 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_LI... |
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 ; Mak... | 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 ( ... |
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 . ;... | 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_... |
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 ... | 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 = fli... |
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... | 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_in... |
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__ =... |
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 ) )... |
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 the... | 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 I... |
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 t... | 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 ]... |
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 ... | 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... |
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 " , "... |
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 + hi... | 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 wo... |
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... |
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 a... | 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 N... |
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 +... |
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 eac... | 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 ] ) )... |
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... | ' 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 . ... |
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_... |
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 charact... | 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 DE... |
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 ... | 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 ( co... |
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 mainA... |
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 ... | 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 ) != l... |
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 t... | 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 ] * ... |
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 = " ... |
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_LI... |
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 ; Give... | 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... |
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 t... | 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... |
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... | 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_L... |
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 al... | 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... |
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 ; Initia... | 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 β collect... |
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 , ... | 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 ) ... |
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 intermedi... | 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 ; NE... |
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 backtrack... | 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 = " , β " ) NE... |
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 ; Rec... | 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 ... |
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 ... | 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 ... |
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... | 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 ) ... |
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 ; Calcul... | 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 m... |
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 ;... | 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... |
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... | 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 m... |
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 ; functio... | 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 Fa... |
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 . ; inve... | 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_LIN... |
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 t... | 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 ... |
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 pla... | 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... |
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 remaind... | 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... |
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 ;... | 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 N... |
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 ; Funct... | 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... |
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 expon... | 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... |
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 ut... | 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 ... |
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 ; ... | 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 ... |
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 i... | 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 ... |
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 mat... | 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 D... |
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 ce... | 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 = cu... |
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 ... | 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 INDE... |
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 BitMas... | 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... |
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... | 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 (... |
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... |
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 ... | 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 ... |
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... | 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 countl... |
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 = ... |
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 qu... | 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 [ s... |
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 ) ;... |
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 permutat... | 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_per... |
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 N... |
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 t... | 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 ... |
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 = trailing... |
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 ... | 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 ) ... |
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 [... |
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 ] , ... |
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 c... | 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 DEDEN... |
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... | 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 ( ... |
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... | 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 d... |
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 Cod... | 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 bina... |
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 r... | 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 findRepeating... |
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 ... | 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 whi... |
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 co... | 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 ,... |
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 maxim... | 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 DE... |
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 ... | 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 = No... |
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... | 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 - dist... |
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 ; D... | 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 ) ) ... |
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... | 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 a... |
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 I... |
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 r... |
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 ... | 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... |
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 ... | 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 NE... |
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 ; Gi... | 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 ... |
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 t... | 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 INDEN... |
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 o... | 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 ,... |
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 ra... | 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 ; Dr... | 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... |
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.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.