text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
How to validate Visa Card number using Regular Expression | Python3 program to validate Visa Card number using regular expression ; Function to validate Visa Card number using regular expression . ; Regex to check valid Visa Card number ; Compile the ReGex ; If the string is empty return false ; Pattern class contains ...
import re NEW_LINE def isValidVisaCardNo ( string ) : NEW_LINE INDENT regex = " ^ 4[0-9 ] { 12 } ( ? : [0-9 ] { 3 } ) ? $ " ; NEW_LINE p = re . compile ( regex ) ; NEW_LINE if ( string == ' ' ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT m = re . match ( p , string ) ; NEW_LINE if m is None : NEW_LINE INDENT retur...
How to validate MasterCard number using Regular Expression | Python3 program to validate Master Card number using regular expression ; Function to validate Master Card number using regular expression . ; Regex to check valid Master Card number . ; Compile the ReGex ; If the string is empty return false ; Return if the ...
import re NEW_LINE def isValidMasterCardNo ( str ) : NEW_LINE INDENT regex = " ^ 5[1-5 ] [ 0-9 ] { 14 } | " + NEW_LINE INDENT " ^ ( 222[1-9 ] ▁ 22[3-9 ] \\d ▁ " + "2[3-6 ] \\d { 2 } ▁ 27[0-1 ] \\d ▁ " + "2720 ) [ 0-9 ] { 12 } $ " NEW_LINE DEDENT p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT r...
How to validate CVV number using Regular Expression | Python3 program to validate CVV ( Card Verification Value ) number using regex . ; Function to validate CVV ( Card Verification Value ) number . using regular expression . ; Regex to check valid CVV number . ; Compile the ReGex ; If the string is empty return false ...
import re NEW_LINE def isValidCVVNumber ( str ) : NEW_LINE INDENT regex = " ^ [ 0-9 ] { 3,4 } $ " NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return Fals...
How to validate IFSC Code using Regular Expression | Python3 program to validate IFSC ( Indian Financial System ) Code using regular expression ; Function to validate IFSC ( Indian Financial System ) Code using regular expression . ; Regex to check valid IFSC Code . ; Compile the ReGex ; If the string is empty return f...
import re NEW_LINE def isValidIFSCode ( str ) : NEW_LINE INDENT regex = " ^ [ A - Z ] {4}0 [ A - Z0-9 ] { 6 } $ " NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE IN...
How to validate GST ( Goods and Services Tax ) number using Regular Expression | Python3 program to validate GST ( Goods and Services Tax ) number using regular expression ; Function to validate GST ( Goods and Services Tax ) number . ; Regex to check valid GST ( Goods and Services Tax ) number ; Compile the ReGex ; If...
import re NEW_LINE def isValidMasterCardNo ( str ) : NEW_LINE INDENT regex = " ^ [ 0-9 ] { 2 } [ A - Z ] {5 } [ 0-9 ] { 4 } " + NEW_LINE INDENT " [ A - Z ] {1 } [ 1-9A - Z ] {1 } " + NEW_LINE DEDENT p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( ...
How to validate HTML tag using Regular Expression | Python3 program to validate HTML tag using regex . using regular expression ; Function to validate HTML tag using regex . ; Regex to check valid HTML tag using regex . ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ;...
import re NEW_LINE def isValidHTMLTag ( str ) : NEW_LINE INDENT regex = " < ( \ " [ ^ \ " ] * \ " ▁ ' [ ^ ' ] * ' ▁ [ ^ ' \ " > ] ) * > " NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE D...
How to validate a domain name using Regular Expression | Python3 program to validate domain name using regular expression ; Function to validate domain name . ; Regex to check valid domain name . ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : ; Test Ca...
import re NEW_LINE def isValidDomain ( str ) : NEW_LINE INDENT regex = " ^ ( ( ? ! - ) [ A - Za - z0-9 - ] " + NEW_LINE INDENT " { 1,63 } ( ? < ! - ) \\ . ) " + NEW_LINE DEDENT p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE...
How to validate SSN ( Social Security Number ) using Regular Expression | Python3 program to validate SSN ( Social Security Number ) using regular expression ; Function to validate SSN ( Social Security Number ) . ; Regex to check valid SSN ( Social Security Number ) . ; Compile the ReGex ; If the string is empty retur...
import re NEW_LINE def isValidSSN ( str ) : NEW_LINE INDENT regex = " ^ ( ? ! 666 ▁ 000 ▁ 9\\d { 2 } ) \\d { 3 } - ( ? !00 ) \\d { 2 } - ( ? !0{4 } ) \\d { 4 } $ " NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE IND...
How to validate image file extension using Regular Expression | Python3 program to validate image file extension using regex ; Function to validate image file extension . ; Regex to check valid image file extension . ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Te...
import re NEW_LINE def imageFile ( str ) : NEW_LINE INDENT regex = " ( [ ^ \\s ] + ( \\ . ( ? i ) ( jpe ? g ▁ png ▁ gif ▁ bmp ) ) $ ) " NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DED...
How to check Aadhar number is valid or not using Regular Expression | Python3 program to validate Aadhar number using regex . ; Function to validate Aadhar number . ; Regex to check valid Aadhar number . ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : ;...
import re NEW_LINE def isValidAadharNumber ( str ) : NEW_LINE INDENT regex = ( " ^ [ 2-9 ] { 1 } [ 0-9 ] { 3 } \\ " + " s [ 0-9 ] { 4 } \\s [ 0-9 ] { 4 } $ " ) NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT ...
How to validate pin code of India using Regular Expression | Python3 program to validate the pin code of India using Regular Expression . ; Function to validate the pin code of India . ; Regex to check valid pin code of India . ; Compile the ReGex ; If the pin code is empty return false ; Pattern class contains matcher...
import re NEW_LINE def isValidPinCode ( pinCode ) : NEW_LINE INDENT regex = " ^ [ 1-9 ] { 1 } [ 0-9 ] { 2 } \\s { 0,1 } [ 0-9 ] { 3 } $ " ; NEW_LINE p = re . compile ( regex ) ; NEW_LINE if ( pinCode == ' ' ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT m = re . match ( p , pinCode ) ; NEW_LINE if m is None : NEW_L...
How to validate time in 24 | Python3 program to validate the time in 24 - hour format using Regular Expression . ; Function to validate the time in 24 - hour format ; Regex to check valid time in 24 - hour format . ; Compile the ReGex ; If the time is empty return false ; Pattern class contains matcher ( ) method to fi...
import re NEW_LINE def isValidTime ( time ) : NEW_LINE INDENT regex = " ^ ( [01 ] ? [0-9 ] ▁ 2[0-3 ] ) : [ 0-5 ] [ 0-9 ] $ " ; NEW_LINE p = re . compile ( regex ) ; NEW_LINE if ( time == " " ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT m = re . search ( p , time ) ; NEW_LINE if m is None : NEW_LINE INDENT return ...
How to validate Hexadecimal Color Code using Regular Expression | Python3 program to validate hexadecimal colour code using Regular Expression ; Function to validate hexadecimal color code . ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : str1 = "1AFFa1...
import re NEW_LINE def isValidHexaCode ( str ) : NEW_LINE INDENT p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT print ( str1 , " ...
How to validate PAN Card number using Regular Expression | Python3 program to validate the PAN Card number using Regular Expression ; Function to validate the PAN Card number . ; Regex to check valid PAN Card number ; Compile the ReGex ; If the PAN Card number is empty return false ; Return if the PAN Card number match...
import re NEW_LINE def isValidPanCardNo ( panCardNo ) : NEW_LINE INDENT regex = " [ A - Z ] {5 } [ 0-9 ] { 4 } [ A - Z ] {1 } " NEW_LINE p = re . compile ( regex ) NEW_LINE if ( panCardNo == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , panCardNo ) and len ( panCardNo ) == 10 ) : NEW_LINE...
How to validate time in 12 | Python3 program to validate the time in 12 - hour format using Regular Expression . ; Function to validate the time in 12 - hour format . ; Regex to check valid time in 12 - hour format . ; Compile the ReGex ; If the time is empty return false ; Return if the time matched the ReGex ; Driver...
import re NEW_LINE def isValidTime ( time ) : NEW_LINE INDENT regexPattern = " ( 1[012 ] ▁ [ 1-9 ] ) : " + " [ 0-5 ] [ 0-9 ] ( \\s ) " + " ? ( ? i ) ( am ▁ pm ) " ; NEW_LINE compiledPattern = re . compile ( regexPattern ) ; NEW_LINE if ( time == None ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if re . search ( c...
Program to build a DFA that checks if a string ends with "01" or "10" | End position is checked using the string length value . q0 is the starting state . q1 and q2 are intermediate states . q3 and q4 are final states . ; state transitions 0 takes to q1 , 1 takes to q3 ; state transitions 0 takes to q4 , 1 takes to q2 ...
def q1 ( s , i ) : NEW_LINE INDENT print ( " q1 - > " , end = " " ) ; NEW_LINE if ( i == len ( s ) ) : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE return ; NEW_LINE DEDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT q1 ( s , i + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT q3 ( s , i + 1 ) ; NEW_LINE DEDENT DEDENT def q2 (...
Check whether two strings contain same characters in same order | Python3 implementation of approach ; if length of the b = 0 then we return true ; if length of a = 0 that means b is not present in a so we return false ; Driver code
def checkSequence ( a , b ) : NEW_LINE INDENT if len ( b ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT if len ( a ) == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if ( a [ 0 ] == b [ 0 ] ) : NEW_LINE INDENT return checkSequence ( a [ 1 : ] , b [ 1 : ] ) NEW_LINE DEDENT else : NEW_LINE INDENT return checkSeq...
String matching with * ( that matches with any ) in any of the two strings | Function to check if the two strings can be matched or not ; if the string don 't have * then character t that position must be same. ; Driver code
def doMatch ( A , B ) : NEW_LINE INDENT for i in range ( len ( A ) ) : NEW_LINE INDENT if A [ i ] != ' * ' and B [ i ] != ' * ' : NEW_LINE INDENT if A [ i ] != B [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = " gee * s...
Find Nth term of the series 0 , 2 , 4 , 8 , 12 , 18. . . | Calculate Nth term of series ; Driver Code
def nthTerm ( N ) : NEW_LINE INDENT return ( N + N * ( N - 1 ) ) // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE print ( nthTerm ( N ) ) NEW_LINE DEDENT
Find Nth term of series 1 , 4 , 15 , 72 , 420. . . | Function for finding factorial of N ; return factorial of N ; Function for calculating Nth term of series ; Driver code
def factorial ( N ) : NEW_LINE INDENT fact = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT fact = fact * i NEW_LINE DEDENT return fact NEW_LINE DEDENT def nthTerm ( N ) : NEW_LINE INDENT return ( factorial ( N ) * ( N + 2 ) // 2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_L...
Sum of nodes at maximum depth of a Binary Tree | Python3 code to find the sum of the nodes which are present at the maximum depth . ; Binary tree node ; Function to find the sum of the node which are present at the maximum depth . While traversing the nodes compare the level of the node with max_level ( Maximum level t...
sum = [ 0 ] NEW_LINE max_level = [ - ( 2 ** 32 ) ] NEW_LINE class createNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . d = data NEW_LINE self . l = None NEW_LINE self . r = None NEW_LINE DEDENT DEDENT def sumOfNodesAtMaxDepth ( ro , level ) : NEW_LINE INDENT if ( ro == None ) : NEW_LINE IN...
Sum of nodes at maximum depth of a Binary Tree | Constructor ; Function to find the sum of nodes at maximum depth arguments are node and max , where Max is to match the depth of node at every call to node , if Max will be equal to 1 , means we are at deepest node . ; base case ; Max == 1 to track the node at deepest le...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def sumMaxLevelRec ( node , Max ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if Max == 1 : NEW_LINE INDENT retu...
Sum of Manhattan distances between repetitions in a String | Function to find the sum of the manhattan distances between same characters in string ; Vector to store indices for each unique character of the string ; Append the position of each character in their respective vectors ; Store the required result ; Iterate o...
def SumofDistances ( s ) : NEW_LINE INDENT v = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT v [ ord ( s [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( len ( v [ i ] ) ) : NEW_LIN...
Minimum prefixes required to be flipped to convert a Binary String to another | Function to count flips required to make strings A and B equal ; Stores the count of the number of operations ; Stores the length of the chosen prefixes ; Stores if operations are performed even or odd times ; Traverse the given string ; If...
def findOperations ( A , B , N ) : NEW_LINE INDENT operations = 0 NEW_LINE ops = [ ] NEW_LINE invert = False NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] ) : NEW_LINE INDENT if ( not invert ) : NEW_LINE INDENT operations += 1 NEW_LINE ops . append ( i + 1 ) NEW_LINE invert = T...
Maximize cost of forming a set of words using given set of characters | Function to find the maximum cost of any valid set of words formed by using the given letters ; Stores frequency of characters ; Find the maximum cost ; Utility function to find maximum cost of generating any possible subsets of strings ; Base Case...
def maxScoreWords ( words , letters , score ) : NEW_LINE INDENT letterCounts = [ 0 ] * ( 26 ) NEW_LINE for letter in letters : NEW_LINE INDENT letterCounts [ ord ( letter ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT return helper ( words , 0 , letterCounts , score ) NEW_LINE DEDENT def helper ( words , start , letterCounts...
Modify string by sorting characters after removal of characters whose frequency is not equal to power of 2 | Python3 program for the above approach ; Function to remove all the characters from a that whose frequencies are not equal to a perfect power of 2 ; Stores the frequency of each character in S ; Iterate over cha...
from math import log2 NEW_LINE def countFrequency ( S , N ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ ord ( S [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT lg = int...
Queries to calculate sum of squares of ASCII values of characters of a substring with updates | Structure of a node of a Segment Tree ; Function to construct the Segment Tree ; If start and end are equa ; Assign squares of positions of the characters ; Stores the mid value of the range [ start , end ] ; Recursive call ...
class treeNode : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . square_sum = x NEW_LINE DEDENT DEDENT def buildTree ( s , tree , start , end , treeNode ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT tree [ treeNode ] . square_sum = pow ( ord ( s [ start ] ) - ord ( ' a ' ) + 1 , 2 ) NEW_L...
Longest Common Subsequence ( LCS ) by repeatedly swapping characters of a string with characters of another string | Function to find the length of LCS possible by swapping any character of a with that of another string ; Store the size of the strings ; Stores frequency of characters ; Iterate over characters of the A ...
def lcsBySwapping ( A , B ) : NEW_LINE INDENT N = len ( A ) NEW_LINE M = len ( B ) NEW_LINE freq = [ 0 ] * 26 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT freq [ ord ( A [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( len ( B ) ) : NEW_LINE INDENT freq [ ord ( B [ i ] ) - ord ( ' a ' ) ] += 1...
Length of longest subsequence whose difference between maximum and minimum ASCII value of characters is exactly one | Function to find the maximum length of subsequence having difference of ASCII value of longest and smallest character as 1 ; Stores frequency of characters ; Iterate over characters of the string ; Stor...
def maximumLengthSubsequence ( str ) : NEW_LINE INDENT mp = { } NEW_LINE for ch in str : NEW_LINE INDENT if ch in mp . keys ( ) : NEW_LINE INDENT mp [ ch ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ ch ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for ch in str : NEW_LINE INDENT if chr ( ord ( ch ) - 1 ) in mp . ...
Minimum increments by 1 or K required to convert a string into another given string | Function to count minimum increments by 1 or K required to convert X to Y ; Traverse the string X ; Case 1 ; Case 2 ; Add the difference / K to the count ; Add the difference % K to the count ; Case 3 ; Add the difference / K to the c...
def countOperations ( X , Y , K ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( X ) ) : NEW_LINE INDENT c = 0 NEW_LINE if ( X [ i ] == Y [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( X [ i ] < Y [ i ] ) : NEW_LINE INDENT if ( ( ord ( Y [ i ] ) - ord ( X [ i ] ) ) >= K ) : NEW_LINE INDENT c = (...
Minimum number of swaps required such that a given substring consists of exactly K 1 s | Function to find the minimum number of swaps required such that the substring { s [ l ] , . . , s [ r ] } consists of exactly k 1 s ; Store the size of the string ; Store the total number of 1 s and 0 s in the entire string ; Trave...
def minimumSwaps ( s , l , r , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE tot_ones , tot_zeros = 0 , 0 NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT tot_ones += 1 NEW_LINE DEDENT else : NEW_LINE INDENT tot_zeros += 1 NEW_LINE DEDENT DEDENT ones , zeros , Sum = 0 ,...
Check if given number contains only β€œ 01 ” and β€œ 10 ” as substring in its binary representation | Python3 program to implement the above approach ; Function to generate all numbers having "01" and "10" as a substring ; Insert 2 and 5 ; Iterate till x is 10 ^ 15 ; Multiply x by 2 ; Update x as x * 2 + 1 ; Function to ch...
Ans = [ ] NEW_LINE def populateNumber ( ) : NEW_LINE INDENT Ans . append ( 2 ) NEW_LINE Ans . append ( 5 ) NEW_LINE x = 5 NEW_LINE while ( x < 1000000000001 ) : NEW_LINE INDENT x *= 2 NEW_LINE Ans . append ( x ) NEW_LINE x = x * 2 + 1 NEW_LINE Ans . append ( x ) NEW_LINE DEDENT DEDENT def checkString ( N ) : NEW_LINE I...
Count minimum substring removals required to reduce string to a single distinct character | Python3 program for the above approach ; Function to find minimum removals required to convert given string to single distinct characters only ; Unordered map to store positions of characters X , Y and Z ; Update indices of X , ...
import sys ; NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def minimumOperations ( s , n ) : NEW_LINE INDENT mp = { } ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] in mp : NEW_LINE INDENT mp [ s [ i ] ] . append ( i ) ; NEW_LINE DEDENT else : NEW_LINE INDENT mp [ s [ i ] ] = [ i ] ; NEW_LINE DEDENT DEDENT ...
Program to construct DFA accepting odd number of 0 s and odd number of 1 s | Function to check whether the given is accepted by DFA or not ; Stores initial state of DFA ; Stores final state of DFA ; Stores previous state of DFA ; Iterate through the string ; Checking for all combinations ; Update the previous_state ; I...
def checkValidDFA ( s ) : NEW_LINE INDENT initial_state = 0 NEW_LINE final_state = 0 NEW_LINE previous_state = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( ( s [ i ] == '0' and previous_state == 0 ) or ( s [ i ] == '1' and previous_state == 3 ) ) : NEW_LINE INDENT final_state = 1 NEW_LINE DEDENT elif ...
Difference between sums of odd level and even level nodes of a Binary Tree | Helper function that allocates a new node with the given data and None left and right poers . ; Construct to create a new node ; return difference of sums of odd level and even level ; create a queue for level order traversal ; traverse until ...
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def evenOddLevelDifference ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( r...
Difference between sums of odd level and even level nodes of a Binary Tree | A Binary Tree node ; The main function that returns difference between odd and even level nodes ; Base Case ; Difference for root is root 's data - difference for left subtree - difference for right subtree ; Driver program to test above func...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getLevelDiff ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( root . data - getLevelDiff ( root...
Sum of all leaf nodes of binary tree | Class for node creation ; constructor ; Utility function to calculate the sum of all leaf nodes ; add root data to sum if root is a leaf node ; propagate recursively in left and right subtree ; Binary tree Fromation ; Variable to store the sum of leaf nodes
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def leafSum ( root ) : NEW_LINE INDENT global total NEW_LINE if root is None : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left is None an...
Inorder Tree Traversal without recursion and without stack ! | A binary tree node ; Generator function for iterative inorder tree traversal ; Find the inorder predecessor of current ; Make current as right child of its inorder predecessor ; Revert the changes made in the ' if ' part to restore the original tree . i . e...
class Node : NEW_LINE INDENT def __init__ ( self , data , left = None , right = None ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def morris_traversal ( root ) : NEW_LINE INDENT current = root NEW_LINE while current is not None : NEW_LINE INDENT...
Sum of leaf nodes at minimum level | Python3 implementation to find the sum of leaf node at minimum level ; Structure of a node in binary tree ; function to find the sum of leaf nodes at minimum level ; if tree is empty ; if there is only root node ; Queue used for level order traversal ; push rioot node in the queue ;...
from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def sumOfLeafNodesAtLeafLevel ( root ) : NEW_LINE INDENT if not root : NEW_LINE INDENT return 0 NEW_LINE D...
Root to leaf path sum equal to a given number | A binary tree node ; Given a tree and a sum , return true if there is a path from the root down to a leaf , such that adding up all the values along the path equals the given sum . Strategy : subtract the node value from the sum when recurring down , and check to see if t...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def hasPathSum ( node , s ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return ( s == 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = 0 ...
Sum of all the numbers that are formed from root to leaf paths | Python program to find sum of all paths from root to leaves A Binary tree node ; Returs sums of all root to leaf paths . The first parameter is root of current subtree , the second paramete "r is value of the number formed by nodes from root to this node ...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def treePathsSumUtil ( root , val ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT val = ( val * 10 + root . data )...
Merge Two Binary Trees by doing Node Sum ( Recursive and Iterative ) | Helper class that allocates a new node with the given data and None left and right pointers . ; Given a binary tree , prits nodes in inorder ; first recur on left child ; then print the data of node ; now recur on right child ; Function to merge giv...
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def inorder ( node ) : NEW_LINE INDENT if ( not node ) : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( node . left ) NEW_LINE print ( node . data , end =...
Merge Two Binary Trees by doing Node Sum ( Recursive and Iterative ) | A binary tree node has data , pointer to left child and a pointer to right child ; Structure to store node pair onto stack ; Helper function that allocates a new node with the given data and None left and right pointers . ; Given a binary tree , pri...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT class snode : NEW_LINE INDENT def __init__ ( self , l , r ) : NEW_LINE INDENT self . l = l NEW_LINE self . r = r NEW_LINE DEDENT DEDENT def newNo...
Find root of the tree where children id sum for every node is given | Find root of tree where children sum for every node id is given ; Every node appears once as an id , and every node except for the root appears once in a sum . So if we subtract all the sums from all the ids , we 're left with the root id. ; Driver ...
def findRoot ( arr , n ) : NEW_LINE INDENT root = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT root += ( arr [ i ] [ 0 ] - arr [ i ] [ 1 ] ) NEW_LINE DEDENT return root NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 5 ] , [ 2 , 0 ] , [ 3 , 0 ] , [ 4 , 0 ] , [ 5 , 5 ] , [ 6 , 5 ] ] ...
Print Postorder traversal from given Inorder and Preorder traversals | A utility function to search x in arr [ ] of size n ; Prints postorder traversal from given inorder and preorder traversals ; The first element in pre [ ] is always root , search it in in [ ] to find left and right subtrees ; If left subtree is not ...
def search ( arr , x , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == x ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def printPostOrder ( In , pre , n ) : NEW_LINE INDENT root = search ( In , pre [ 0 ] , n ) NEW_LINE if ( root != 0 ) : NEW_LINE INDENT pr...
Lowest Common Ancestor in a Binary Tree | Set 1 | A binary tree node ; This function returns pointer to LCA of two given values n1 and n2 This function assumes that n1 and n2 are present in Binary Tree ; Base Case ; If either n1 or n2 matches with root 's key, report the presence by returning root (Note that if a key ...
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def findLCA ( root , n1 , n2 ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return None NEW_LINE DEDENT if root . key == n1 or root . key == ...
Lowest Common Ancestor in a Binary Tree | Set 1 | A binary tree node ; This function retturn pointer to LCA of two given values n1 and n2 v1 is set as true by this function if n1 is found v2 is set as true by this function if n2 is found ; Base Case ; IF either n1 or n2 matches ith root 's key, report the presence by ...
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def findLCAUtil ( root , n1 , n2 , v ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return None NEW_LINE DEDENT if root . key == n1 : NEW_LIN...
Lowest Common Ancestor in a Binary Tree | Set 3 ( Using RMQ ) | Python code to find LCA of given two nodes in a tree ; the graph ; level of each node ; the segment tree ; adding edges to the graph ( tree ) ; assigning level to nodes ; storing the dfs traversal in the array e ; making the array l ; making the array h ; ...
maxn = 100005 NEW_LINE g = [ [ ] for i in range ( maxn ) ] NEW_LINE level = [ 0 ] * maxn NEW_LINE e = [ ] NEW_LINE l = [ ] NEW_LINE h = [ 0 ] * maxn NEW_LINE st = [ 0 ] * ( 5 * maxn ) NEW_LINE def add_edge ( u : int , v : int ) : NEW_LINE INDENT g [ u ] . append ( v ) NEW_LINE g [ v ] . append ( u ) NEW_LINE DEDENT def...
Print common nodes on path from root ( or common ancestors ) | Utility class to create a new tree Node ; Utility function to find the LCA of two given values n1 and n2 . ; Base case ; If either n1 or n2 matches with root 's key, report the presence by returning root (Note that if a key is ancestor of other, then th...
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def findLCA ( root , n1 , n2 ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( root . key == n1 or root . key == n2 ) ...
Binary Tree | Set 1 ( Introduction ) | A Python class that represents an individual node in a Binary Tree
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . val = key NEW_LINE DEDENT DEDENT
Maximum difference between node and its ancestor in Binary Tree | Python3 program to find maximum difference between node and its ancestor ; Helper function that allocates a new node with the given data and None left and right poers . ; Recursive function to calculate maximum ancestor - node difference in binary tree ....
_MIN = - 2147483648 NEW_LINE _MAX = 2147483648 NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def maxDiffUtil ( t , res ) : NEW_LINE INDENT if ( t == None ) : NEW_LINE INDENT return _...
Print the path common to the two paths from the root to the two given nodes | Initialize n1 and n2 as not visited ; structure of a node of binary tree ; This function returns pointer to LCA of two given values n1 and n2 . v1 is set as True by this function if n1 is found v2 is set as True by this function if n2 is foun...
v1 = False NEW_LINE INDENT v2 = False NEW_LINE DEDENT class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def findLCAUtil ( root : Node , n1 : int , n2 : int ) -> Node : NEW_LINE INDENT global v1 ,...
Query for ancestor | Python program to query whether two node has ancestor - descendant relationship or not ; Utility dfs method to assign in and out time to each node ; assign In - time to node u ; call dfs over all neighbors except parent ; assign Out - time to node u ; method to preprocess all nodes for assigning ti...
cnt = 0 NEW_LINE def dfs ( g : list , u : int , parent : int , timeIn : list , timeOut : list ) : NEW_LINE INDENT global cnt NEW_LINE timeIn [ u ] = cnt NEW_LINE cnt += 1 NEW_LINE for i in range ( len ( g [ u ] ) ) : NEW_LINE INDENT v = g [ u ] [ i ] NEW_LINE if v != parent : NEW_LINE INDENT dfs ( g , v , u , timeIn , ...
Print path from root to a given node in a binary tree | Helper Class that allocates a new node with the given data and None left and right pointers . ; Returns true if there is a path from root to the given node . It also populates ' arr ' with the given path ; if root is None there is no path ; push the node ' s ▁ val...
class getNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def hasPath ( root , arr , x ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return False NEW_LINE DEDENT arr . append ( root . data ) NEW_LINE if ( r...
Print Ancestors of a given node in Binary Tree | A Binary Tree node ; If target is present in tree , then prints the ancestors and returns true , otherwise returns false ; Base case ; If target is present in either left or right subtree of this node , then print this node ; Else return False ; Construct the following b...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printAncestors ( root , target ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return False NEW_LINE DEDENT if root . data == target : ...
Kth ancestor of a node in binary tree | Set 2 | A Binary Tree Node ; recursive function to calculate Kth ancestor ; Base case ; print the kth ancestor ; return None to stop further backtracking ; return current node to previous call ; Driver Code ; prkth ancestor of given node ; check if parent is not None , it means t...
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def kthAncestorDFS ( root , node , k ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( root . data == nod...
Succinct Encoding of Binary Tree | Node structure ; This function fills lists ' struc ' and ' data ' . ' struc ' list stores structure information . ' data ' list stores tree data ; If root is None , put 0 in structure array and return ; Else place 1 in structure array , key in ' data ' array and recur for left and rig...
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def EncodeSuccint ( root , struc , data ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT struc . append ( 0 ) NEW_LINE return NEW_LINE DEDENT s...
Binary Indexed Tree : Range Updates and Point Queries | Updates such that getElement ( ) gets an increased value when queried from l to r . ; Get the element indexed at i ; To get ith element sum of all the elements from 0 to i need to be computed ; Driver Code ; Find the element at Index 4 ; Find the element at Index ...
def update ( arr , l , r , val ) : NEW_LINE INDENT arr [ l ] += val NEW_LINE if r + 1 < len ( arr ) : NEW_LINE INDENT arr [ r + 1 ] -= val NEW_LINE DEDENT DEDENT def getElement ( arr , i ) : NEW_LINE INDENT res = 0 NEW_LINE for j in range ( i + 1 ) : NEW_LINE INDENT res += arr [ j ] NEW_LINE DEDENT return res NEW_LINE ...
Binary Indexed Tree : Range Updates and Point Queries | Updates a node in Binary Index Tree ( BITree ) at given index in BITree . The given value ' val ' is added to BITree [ i ] and all of its ancestors in tree . ; index in BITree [ ] is 1 more than the index in arr [ ] ; Traverse all ancestors and add 'val ; Add ' ...
def updateBIT ( BITree , n , index , val ) : NEW_LINE INDENT index = index + 1 NEW_LINE while ( index <= n ) : NEW_LINE INDENT BITree [ index ] += val NEW_LINE index += index & ( - index ) NEW_LINE DEDENT DEDENT def constructBITree ( arr , n ) : NEW_LINE INDENT BITree = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n ) :...
Print Postorder traversal from given Inorder and Preorder traversals | Python3 program to prPostorder traversal from given Inorder and Preorder traversals . ; Find index of next item in preorder traversal in inorder . ; traverse left tree ; traverse right tree ; prroot node at the end of traversal ; Driver code
def printPost ( inn , pre , inStrt , inEnd ) : NEW_LINE INDENT global preIndex , hm NEW_LINE if ( inStrt > inEnd ) : NEW_LINE INDENT return NEW_LINE DEDENT inIndex = hm [ pre [ preIndex ] ] NEW_LINE preIndex += 1 NEW_LINE printPost ( inn , pre , inStrt , inIndex - 1 ) NEW_LINE printPost ( inn , pre , inIndex + 1 , inEn...
Coordinates of the last cell in a Matrix on which performing given operations exits from the Matrix | Function to check if the indices ( i , j ) are valid indices in a Matrix or not ; Cases for invalid cells ; Return true if valid ; Function to find indices of cells of a matrix from which traversal leads to out of the ...
def issafe ( m , n , i , j ) : NEW_LINE INDENT if i < 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if j < 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if i >= m : NEW_LINE INDENT return False NEW_LINE DEDENT if j >= n : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def endpoints ( arr...
Check if a number can be represented as sum of two positive perfect cubes | Function to check if N can be represented as sum of two perfect cubes or not ; Stores the perfect cubes of first N natural numbers ; Traverse the map ; Stores first number ; Stores second number ; Search the pair for the first number to obtain ...
def sumOfTwoPerfectCubes ( N ) : NEW_LINE INDENT cubes = { } NEW_LINE i = 1 NEW_LINE while i * i * i <= N : NEW_LINE INDENT cubes [ i * i * i ] = i NEW_LINE i += 1 NEW_LINE DEDENT for itr in cubes : NEW_LINE INDENT firstNumber = itr NEW_LINE secondNumber = N - itr NEW_LINE if secondNumber in cubes : NEW_LINE INDENT pri...
Count subsets consisting of each element as a factor of the next element in that subset | Function to find number of subsets satisfying the given condition ; Stores number of required sets ; Stores maximum element of arr [ ] that defines the size of sieve ; Iterate through the arr [ ] ; If current element > maxE , then...
def countSets ( arr , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE maxE = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( maxE < arr [ i ] ) : NEW_LINE INDENT maxE = arr [ i ] NEW_LINE DEDENT DEDENT sieve = [ 0 ] * ( maxE + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT sieve [ arr [ i ] ] = 1 NEW_LINE DEDENT f...
Find the first day of a given year from a base year having first day as Monday | Function to find the day of 1 st January of Y year ; Count years between years Y and B ; Count leap years ; Non leap years ; Total number of days in the years lying between the years Y and B ; Actual day ; Driver code
def findDay ( Y , B ) : NEW_LINE INDENT lyear , rest , totaldays , day = 0 , 0 , 0 , 0 ; NEW_LINE Y = ( Y - 1 ) - B ; NEW_LINE lyear = Y // 4 ; NEW_LINE rest = Y - lyear ; NEW_LINE totaldays = ( rest * 365 ) + ( lyear * 366 ) + 1 ; NEW_LINE day = ( totaldays % 7 ) ; NEW_LINE if ( day == 0 ) : NEW_LINE INDENT print ( " ...
Queries to update array elements in a range [ L , R ] to satisfy given conditions | Function to prthe array ; Function to perform the query in range [ L , R ] such that arr [ i ] += i - L + 1 ; Initialize array ; Traverse the query array ; Stores range in 1 - based index ; Update arr1 [ L ] ; Update arr1 [ R + 1 ] ; Up...
def printArray ( arr , N ) : NEW_LINE INDENT print ( * arr ) NEW_LINE DEDENT def modifyArray ( arr , N , Q , cntQuery ) : NEW_LINE INDENT arr1 = [ 0 for i in range ( N + 2 ) ] NEW_LINE arr2 = [ 0 for i in range ( N + 2 ) ] NEW_LINE for i in range ( cntQuery ) : NEW_LINE INDENT L = Q [ i ] [ 0 ] + 1 NEW_LINE R = Q [ i ]...
Maximize product obtained by taking one element from each array of a given list | Function to return the product of 2 numbers ; If any of the two numbers is None ; Otherwise , return the product ; Function to calculate maximum product by taking only one element from each array present in the list ; Find the maximum and...
def findProduct ( number_1 , number_2 ) : NEW_LINE INDENT if ( number_1 == None or number_2 == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return number_1 * number_2 NEW_LINE DEDENT DEDENT def calculateProduct ( List , index ) : NEW_LINE INDENT highest = max ( List [ index ] ) NEW_LINE lowe...
Reduce a number N by at most D to maximize count of trailing nines | Python3 program for the above approach ; Function to find a number with maximum count of trailing nine ; Stores count of digits in n ; Stores power of 10 ; If last i digits greater than or equal to d ; Update res ; Update p10 ; Driver Code ; Function ...
from math import log10 NEW_LINE def maxNumTrailNine ( n , d ) : NEW_LINE INDENT res = n NEW_LINE cntDigits = int ( log10 ( n ) + 1 ) NEW_LINE p10 = 10 NEW_LINE for i in range ( 1 , cntDigits + 1 ) : NEW_LINE INDENT if ( n % p10 >= d ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT res = n - n % p10 - 1 ...
Split array into minimum number of subsets such that elements of all pairs are present in different subsets at least once | Function to find minimum count of ways to split the array into two subset such that elements of each pair occurs in two different subset ; Stores minimum count of ways to split array into two subs...
def MinimumNoOfWays ( arr , n ) : NEW_LINE INDENT min_no_of_ways = 0 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT mini_no_of_ways = n // 2 NEW_LINE DEDENT else : NEW_LINE INDENT mini_no_of_ways = n // 2 + 1 NEW_LINE DEDENT return mini_no_of_ways NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ ...
Chocolate Distribution Problem | Set 2 | Function to return minimum number of chocolates ; decreasing sequence ; add the chocolates received by that person ; end point of decreasing sequence ; val = 1 reset value at that index ; increasing sequence ; flat sequence ; add value of chocolates at position n - 1 ; Helper fu...
def minChocolates ( a , n ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE val , res = 1 , 0 NEW_LINE while ( j < n - 1 ) : NEW_LINE INDENT if ( a [ j ] > a [ j + 1 ] ) : NEW_LINE INDENT j += 1 NEW_LINE continue NEW_LINE DEDENT if ( i == j ) : NEW_LINE INDENT res += val NEW_LINE DEDENT else : NEW_LINE INDENT res += get_sum (...
Remove array elements to reduce frequency of each array element to at most K | Function to remove array elements such that frequency of each distinct array element is at most K ; Base Case ; Stores index of array element by removing the array element such that the frequency of array elements is at most K ; Traverse the...
def RemoveElemArr ( arr , n , k ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return arr NEW_LINE DEDENT j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( j < k or arr [ i ] > arr [ j - k ] ) : NEW_LINE INDENT arr [ j ] , j = arr [ i ] , j + 1 NEW_LINE DEDENT DEDENT while ( len ( arr ) > j ) : ...
Count pairs of equal array elements remaining after every removal | Function to count pairs of equal elements by removing arr [ i ] from the array ; Stores total count of pairs of equal elements ; Store frequency of each distinct array element ; Traverse the array ; Update frequency of arr [ i ] ; Traverse the map ; St...
def pairs_after_removing ( arr , N ) : NEW_LINE INDENT cntPairs = 0 NEW_LINE mp = { } NEW_LINE for i in arr : NEW_LINE INDENT mp [ i ] = mp . get ( i , 0 ) + 1 NEW_LINE DEDENT for element in mp : NEW_LINE INDENT i = element NEW_LINE cntPairs += mp [ i ] * ( mp [ i ] - 1 ) // 2 NEW_LINE DEDENT for i in range ( N ) : NEW...
Modify N by adding its smallest positive divisor exactly K times | Function to find the smallest divisor of N greater than 1 ; If i is a divisor of N ; If N is a prime number ; Function to find the value of N by performing the operations K times ; If N is an even number ; Update N ; If N is an odd number ; Update N ; D...
def smallestDivisorGr1 ( N ) : NEW_LINE INDENT for i in range ( sqrt ( N ) ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if ( N % i == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT return N NEW_LINE DEDENT def findValOfNWithOperat ( N , K ) : NEW_LINE INDENT if ( N % 2 == 0 ) : NEW_LINE INDENT N += K * 2 NEW_LINE DEDENT ...
Partition array into minimum number of equal length subsets consisting of a single distinct value | Python3 program to implement the above approach ; Function to find the minimum count of subsets by partitioning the array with given conditions ; Store frequency of each distinct element of the array ; Traverse the array...
from math import gcd NEW_LINE def CntOfSubsetsByPartitioning ( arr , N ) : NEW_LINE INDENT freq = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ arr [ i ] ] = freq . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT freqGCD = 0 NEW_LINE for i in freq : NEW_LINE INDENT freqGCD = gcd ( freqGCD , freq [ i ] ) NEW_LINE...
Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix | Initialize rows and columns ; Store all 8 directions ; Function to check if a cell ( i , j ) is valid or not ; Function to find sum of adjacent cells for cell ( i , j ) ; Initialize sum ; Visit all 8 direct...
r , c = 0 , 0 ; NEW_LINE dir = [ [ 1 , 0 ] , [ - 1 , 0 ] , [ 0 , 1 ] , [ 0 , - 1 ] , [ - 1 , - 1 ] , [ - 1 , 1 ] , [ 1 , 1 ] , [ 1 , - 1 ] ] ; NEW_LINE def valid ( i , j ) : NEW_LINE INDENT if ( i >= 0 and j >= 0 and i < r and j < c ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def fi...
Nth term of a recurrence relation generated by two given arrays | Python3 program for the above approach ; Declare T [ ] [ ] as global matrix ; Result matrix ; Function to multiply two matrices ; Create an auxiliary matrix to store elements of the multiplication matrix ; Iterate over range [ 0 , K ] ; Update temp [ i ]...
mod = 1e9 + 7 NEW_LINE T = [ [ 0 for x in range ( 2000 ) ] for y in range ( 2000 ) ] NEW_LINE result = [ [ 0 for x in range ( 2000 ) ] for y in range ( 2000 ) ] NEW_LINE def mul_2 ( K ) : NEW_LINE INDENT temp = [ [ 0 for x in range ( K + 1 ) ] for y in range ( K + 1 ) ] NEW_LINE for i in range ( 1 , K + 1 ) : NEW_LINE ...
Calculate Root Mean Kth power of all array elements | Python3 program for the above approach ; Function to find the Nth root ; Initially guessing random numberbetween 0 and 9 ; Smaller eps for more accuracy ; Initialize difference between the two roots by INT_MAX ; xK denotes current value of x ; Iterate until desired ...
import sys NEW_LINE import random NEW_LINE def nthRoot ( A , N ) : NEW_LINE INDENT xPre = random . random ( ) % 10 NEW_LINE eps = 1e-3 NEW_LINE delX = sys . maxsize NEW_LINE xK = 0 NEW_LINE while ( delX > eps ) : NEW_LINE INDENT xK = ( ( ( N - 1.0 ) * xPre + A / pow ( xPre , N - 1 ) ) / N ) NEW_LINE delX = abs ( xK - x...
Add two numbers represented by Stacks | Function to return the stack that contains the sum of two numbers ; Calculate the sum of the top elements of both the stacks ; Push the sum into the stack ; Store the carry ; Pop the top elements ; If N1 is not empty ; If N2 is not empty ; If carry remains ; Reverse the stack . s...
def addStack ( N1 , N2 ) : NEW_LINE INDENT res = [ ] NEW_LINE s = 0 NEW_LINE rem = 0 NEW_LINE while ( len ( N1 ) != 0 and len ( N2 ) != 0 ) : NEW_LINE INDENT s = ( rem + N1 [ - 1 ] + N2 [ - 1 ] ) NEW_LINE res . append ( s % 10 ) NEW_LINE rem = s // 10 NEW_LINE N1 . pop ( - 1 ) NEW_LINE N2 . pop ( - 1 ) NEW_LINE DEDENT ...
Check if a number has an odd count of odd divisors and even count of even divisors | Python3 implementation of the above approach ; Function to check if the number is a perfect square ; Find floating povalue of square root of x . ; If square root is an integer ; Function to check if count of even divisors is even and c...
import math NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sr = pow ( x , 1 / 2 ) ; NEW_LINE return ( ( sr - math . floor ( sr ) ) == 0 ) ; NEW_LINE DEDENT def checkFactors ( x ) : NEW_LINE INDENT if ( isPerfectSquare ( x ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " N...
Queries to find the XOR of an Array after replacing all occurrences of X by Y | Stores the bitwise XOR of array elements ; Function to find the total xor ; Loop to find the xor of all the elements ; Function to find the XOR after replacing all occurrences of X by Y for Q queries ; Remove contribution of X from total_xo...
global total_xor NEW_LINE total_xor = 0 NEW_LINE def initialize_xor ( arr , n ) : NEW_LINE INDENT global total_xor NEW_LINE for i in range ( n ) : NEW_LINE INDENT total_xor = total_xor ^ arr [ i ] NEW_LINE DEDENT DEDENT def find_xor ( X , Y ) : NEW_LINE INDENT global total_xor NEW_LINE total_xor = total_xor ^ X NEW_LIN...
Check whether a given number is an ugly number or not | Function to check if a number is an ugly number or not ; Base Cases ; Condition to check if the number is divided by 2 , 3 , or 5 ; Driver Code
def isUgly ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return ( isUgly ( n // 2 ) ) NEW_LINE DEDENT if ( n % 3 == 0 ) : NEW_LINE INDENT return ( isUgly ( n // 3 ) ) NEW_LINE DEDENT if ( n % ...
Maximum possible GCD for a pair of integers with sum N | Function to find the required GCD value ; If i is a factor of N ; Return the largest factor possible ; If N is a prime number ; Driver Code
def maxGCD ( N ) : NEW_LINE INDENT i = 2 NEW_LINE while ( i * i <= N ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT return N // i NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return 1 NEW_LINE DEDENT N = 33 NEW_LINE print ( " Maximum ▁ Possible ▁ GCD ▁ value ▁ is ▁ : ▁ " , maxGCD ( N ) ) NEW_LINE
Minimize K whose XOR with given array elements leaves array unchanged | Function to find the minimum value of K in given range ; Declare a set ; Initialize count variable ; Iterate in range [ 1 , 1024 ] ; counter set as 0 ; Iterating through the Set ; Check if the XOR calculated is present in the Set ; If the value of ...
def min_value ( arr , N ) : NEW_LINE INDENT x , X , K = 0 , 0 , 0 NEW_LINE S = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT S . add ( arr [ i ] ) NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 1 , 1024 ) : NEW_LINE INDENT count = 0 NEW_LINE for it in S : NEW_LINE INDENT X = ( ( i it ) - ( i & it ) ) NEW...
Junction Numbers | Python3 program for the above approach ; Function to find the sum Of digits of N ; To store sum of N and sumOfdigitsof ( N ) ; extracting digit ; Function to check Junction numbers ; To store count of ways n can be represented as i + SOD ( i ) ; Driver Code ; Function Call
import math NEW_LINE def sum1 ( n ) : NEW_LINE INDENT sum1 = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT r = n % 10 NEW_LINE sum1 = sum1 + r NEW_LINE n = n // 10 NEW_LINE DEDENT return sum1 NEW_LINE DEDENT def isJunction ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i ...
Pointer | Function to find the product of digits of a number N ; Function that returns true if n is prime else returns false ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to return the smallest prime number greater than N ; Base case ; Loop continuously until isPrime ...
def digProduct ( n ) : NEW_LINE INDENT product = 1 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT product = product * ( n % 10 ) NEW_LINE n = int ( n / 10 ) NEW_LINE DEDENT return product NEW_LINE DEDENT def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LI...
Perfect Digital Invariants number | Function to find the sum of divisors ; Function to check whether the given number is Perfect Digital Invariant number or not ; For each digit in temp ; If satisfies Perfect Digital Invariant condition ; If sum exceeds n , then not possible ; Given Number N ; Function Call
def power ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( y % 2 == 0 ) : NEW_LINE INDENT return ( power ( x , y // 2 ) * power ( x , y // 2 ) ) NEW_LINE DEDENT return ( x * power ( x , y // 2 ) * power ( x , y // 2 ) ) NEW_LINE DEDENT def isPerfectDigitalInvariant ( x ) : NEW_L...
Brilliant Numbers | Python3 program for the above approach ; Function to generate all prime numbers less than n ; Initialize all entries of boolean array as true . A value in isPrime [ i ] will finally be false if i is Not a prime ; If isPrime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Func...
import math NEW_LINE def SieveOfEratosthenes ( n , isPrime ) : NEW_LINE INDENT isPrime [ 0 ] = isPrime [ 1 ] = False NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT isPrime [ i ] = True NEW_LINE DEDENT p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( isPrime [ p ] == True ) : NEW_LINE INDENT for i...
Icosikaienneagonal Number | Function to Find the Nth icosikaienneagonal Number ; Driver Code
def icosikaienneagonalNum ( n ) : NEW_LINE INDENT return ( 27 * n * n - 25 * n ) // 2 NEW_LINE DEDENT N = 3 NEW_LINE print ( icosikaienneagonalNum ( N ) ) NEW_LINE
Find the largest contiguous pair sum in given Array | Python3 program to find the a contiguous pair from the which has the largest sum ; Function to find and return the largest sum contiguous pair ; Stores the contiguous pair ; Initialize maximum sum ; Compare sum of pair with max_sum ; Insert the pair ; Driver Code
import sys NEW_LINE def largestSumpair ( arr , n ) : NEW_LINE INDENT pair = [ ] NEW_LINE max_sum = - sys . maxsize - 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if max_sum < ( arr [ i ] + arr [ i - 1 ] ) : NEW_LINE INDENT max_sum = arr [ i ] + arr [ i - 1 ] NEW_LINE if pair == [ ] : NEW_LINE INDENT pair . app...
Sum of minimum value of x and y satisfying the equation ax + by = c | Python3 program for the above approach ; x and y store solution of equation ax + by = g ; Euclidean Algorithm ; store_gcd returns the gcd of a and b ; Function to find any possible solution ; Condition if solution does not exists ; Adjusting the sign...
x , y , x1 , y1 = 0 , 0 , 0 , 0 NEW_LINE x0 , y0 , g = 0 , 0 , 0 NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT global x , y , x1 , y1 NEW_LINE if ( b == 0 ) : NEW_LINE INDENT x = 1 NEW_LINE y = 0 NEW_LINE return a NEW_LINE DEDENT store_gcd = gcd ( b , a % b ) NEW_LINE x = y1 NEW_LINE y = x1 - y1 * ( a // b ) NEW_LINE re...
Super | Function to check if N is a super - d number ; Driver Code
def isSuperdNum ( n ) : NEW_LINE INDENT for d in range ( 2 , 10 ) : NEW_LINE INDENT substring = str ( d ) * d ; NEW_LINE if substring in str ( d * pow ( n , d ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT n = 261 NEW_LINE if isSuperdNum ( n ) == True : NEW_LINE INDENT print ( " Y...
Second hexagonal numbers | Function to find N - th term in the series ; Driver code
def findNthTerm ( n ) : NEW_LINE INDENT print ( n * ( 2 * n + 1 ) ) NEW_LINE DEDENT N = 4 NEW_LINE findNthTerm ( N ) NEW_LINE
Apocalyptic Number | Function to check if a number N is Apocalyptic ; Given Number N ; Function Call
def isApocalyptic ( n ) : NEW_LINE INDENT if '666' in str ( 2 ** n ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT N = 157 NEW_LINE if ( isApocalyptic ( 157 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Kummer Numbers | Python3 program to find Kummer number upto n terms ; list to store all prime less than and equal to 10 ^ 6 ; Function for the Sieve of Sundaram . This function stores all prime numbers less than MAX in primes ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given...
import math NEW_LINE MAX = 1000000 NEW_LINE primes = [ ] NEW_LINE def sieveSundaram ( ) : NEW_LINE INDENT marked = [ 0 ] * int ( MAX / 2 + 1 ) NEW_LINE for i in range ( 1 , int ( ( math . sqrt ( MAX ) - 1 ) // 2 ) + 1 ) : NEW_LINE INDENT for j in range ( ( i * ( i + 1 ) ) << 1 , MAX // 2 + 1 , 2 * i + 1 ) : NEW_LINE IN...
Check if given number contains a digit which is the average of all other digits | Function which checks if a digits exists in n which is the average of all other digits ; Calculate sum of digits in n ; Store digits ; Increase the count of digits in n ; If average of all digits is integer ; Otherwise ; Driver code
def check ( n ) : NEW_LINE INDENT digits = set ( ) NEW_LINE temp = n NEW_LINE Sum = 0 NEW_LINE count = 0 NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT Sum += temp % 10 NEW_LINE digits . add ( temp % 10 ) NEW_LINE count += 1 NEW_LINE temp = temp // 10 NEW_LINE DEDENT if ( ( Sum % count == 0 ) and ( ( int ) ( Sum / count...
Count of lexicographically smaller characters on right | function to count the smaller characters at the right of index i ; store the length of String ; for each index initialize count as zero ; increment the count if characters are smaller than at ith index ; print the count of characters smaller than the index i ; Dr...
def countSmaller ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( str [ j ] < str [ i ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT print ( cnt , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__...
Find the smallest contiguous sum pair in an Array | Python3 program to find the smallest sum contiguous pair ; Function to find the smallest sum contiguous pair ; Contiguous pair ; isntialize minimum sum with maximum value ; checking for minimum value ; Add to pair ; Updating pair ; Driver code
import sys NEW_LINE def smallestSumpair ( arr , n ) : NEW_LINE INDENT pair = [ ] NEW_LINE min_sum = sys . maxsize NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if min_sum > ( arr [ i ] + arr [ i - 1 ] ) : NEW_LINE INDENT min_sum = arr [ i ] + arr [ i - 1 ] NEW_LINE if pair == [ ] : NEW_LINE INDENT pair . append (...
Sum of the products of same placed digits of two numbers | Function to find the sum of the products of their corresponding digits ; Loop until one of the numbers have no digits remaining ; Driver Code
def sumOfProductOfDigits ( n1 , n2 ) : NEW_LINE INDENT sum1 = 0 ; NEW_LINE while ( n1 > 0 and n2 > 0 ) : NEW_LINE INDENT sum1 += ( ( n1 % 10 ) * ( n2 % 10 ) ) ; NEW_LINE n1 = n1 // 10 ; NEW_LINE n2 = n2 // 10 ; NEW_LINE DEDENT return sum1 ; NEW_LINE DEDENT n1 = 25 ; NEW_LINE n2 = 1548 ; NEW_LINE print ( sumOfProductOfD...
Count of ways to represent N as sum of a prime number and twice of a square | Python3 implementation to count the number of ways a number can be written as sum of prime number and twice a square ; Function to mark all the prime numbers using sieve ; Loop to mark the prime numbers upto the Square root of N ; Loop to sto...
import math NEW_LINE n = 500000 - 2 NEW_LINE v = [ ] NEW_LINE def sieveoferanthones ( ) : NEW_LINE INDENT prime = [ 1 ] * ( n + 1 ) NEW_LINE for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( prime [ i ] != 0 ) : NEW_LINE INDENT for j in range ( i * i , n + 1 , i ) : NEW_LINE INDENT prime [ j ]...
Program to convert Degree to Radian | Function for conversion ; Driver code
def Convert ( degree ) : NEW_LINE INDENT pi = 3.14159265359 ; NEW_LINE return ( degree * ( pi / 180 ) ) ; NEW_LINE DEDENT degree = 30 ; NEW_LINE radian = Convert ( degree ) ; NEW_LINE print ( radian ) ; NEW_LINE
Program to convert a Binary Number to Hexa | Function to convert BCD to hexadecimal ; Iterating through the bits backwards ; Computing the hexadecimal number formed so far and storing it in a vector . ; Reinitializing all variables for next group . ; Printing the hexadecimal number formed so far . ; Driver Code ; Funct...
def bcdToHexaDecimal ( s ) : NEW_LINE INDENT len1 = len ( s ) NEW_LINE check = 0 NEW_LINE num = 0 NEW_LINE sum = 0 NEW_LINE mul = 1 NEW_LINE ans = [ ] NEW_LINE i = len1 - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT sum += ( ord ( s [ i ] ) - ord ( '0' ) ) * mul NEW_LINE mul *= 2 NEW_LINE check += 1 NEW_LINE if ( chec...