text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Populate Inorder Successor for all nodes | Python3 program to populate inorder traversal of all nodes ; A wrapper over populateNextRecur ; The first visited node will be the rightmost node next of the rightmost node will be NULL ; Set next of all descendants of p by traversing them in reverse Inorder ; First set the ne...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE self . next = None NEW_LINE DEDENT DEDENT next = None NEW_LINE def populateNext ( node ) : NEW_LINE INDENT populateNextRecur ( node , next ) NEW_LINE DEDENT de...
Check if a binary string contains consecutive same or not | Function that returns true is str is valid ; Assuming the string is binary If any two consecutive characters are equal then the string is invalid ; If the string is alternating ; Driver code
def isValid ( string , length ) : NEW_LINE INDENT for i in range ( 1 , length ) : NEW_LINE INDENT if string [ i ] == string [ i - 1 ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = "0110" NEW_LINE length = len ( string ) NEW_L...
Minimum K such that every substring of length atleast K contains a character c | This function checks if there exists some character which appears in all K length substrings ; Iterate over all possible characters ; stores the last occurrence ; set answer as true ; No occurrence found of current character in first subst...
def check ( s , K ) : NEW_LINE INDENT for ch in range ( 0 , 26 ) : NEW_LINE INDENT c = chr ( 97 + ch ) NEW_LINE last = - 1 NEW_LINE found = True NEW_LINE for i in range ( 0 , K ) : NEW_LINE INDENT if s [ i ] == c : NEW_LINE INDENT last = i NEW_LINE DEDENT DEDENT if last == - 1 : NEW_LINE INDENT continue NEW_LINE DEDENT...
Check if number can be displayed using seven segment led | Pre - computed values of segment used by digit 0 to 9. ; Check if it is possible to display the number ; Finding sum of the segments used by each digit of the number ; Driver Code ; Function call to print required answer
seg = [ 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 ] NEW_LINE def LedRequired ( s , led ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT count += seg [ ord ( s [ i ] ) - 48 ] NEW_LINE DEDENT if ( count <= led ) : NEW_LINE INDENT return " YES " NEW_LINE DEDENT else : NEW_LINE INDENT retur...
Iterative Search for a key ' x ' in Binary Tree | A binary tree node has data , left child and right child ; Construct to create a newNode ; iterative process to search an element x in a given binary tree ; Base Case ; Create an empty stack and append root to it ; Do iterative preorder traversal to search x ; See the t...
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def iterativeSearch ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT nodeStack = [ ] NEW_LINE n...
Check whether two strings can be made equal by increasing prefixes | check whether the first string can be converted to the second string by increasing the ASCII value of prefix string of first string ; length of two strings ; If lengths are not equal ; store the difference of ASCII values ; difference of first element...
def find ( s1 , s2 ) : NEW_LINE INDENT len__ = len ( s1 ) NEW_LINE len_1 = len ( s2 ) NEW_LINE if ( len__ != len_1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT d = [ 0 for i in range ( len__ ) ] NEW_LINE d [ 0 ] = ord ( s2 [ 0 ] ) - ord ( s1 [ 0 ] ) NEW_LINE for i in range ( 1 , len__ , 1 ) : NEW_LINE INDENT if ( s...
N | Function that returns the N - th character ; initially null string ; starting integer ; add integers in string ; one digit numbers added ; more than 1 digit number , generate equivalent number in a string s1 and concatenate s1 into s . ; add the number in string ; reverse the string ; attach the number ; if the len...
def NthCharacter ( n ) : NEW_LINE INDENT s = " " NEW_LINE c = 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( c < 10 ) : NEW_LINE INDENT s += chr ( 48 + c ) NEW_LINE DEDENT else : NEW_LINE INDENT s1 = " " NEW_LINE dup = c NEW_LINE while ( dup > 0 ) : NEW_LINE INDENT s1 += chr ( ( dup % 10 ) + 48 ) NEW_LINE dup //= 10 ...
Sub | Function that counts all the sub - strings of length ' k ' which have all identical characters ; count of sub - strings , length , initial position of sliding window ; dictionary to store the frequency of the characters of sub - string ; increase the frequency of the character and length of the sub - string ; if ...
def solve ( s , k ) : NEW_LINE INDENT count , length , pos = 0 , 0 , 0 NEW_LINE m = dict . fromkeys ( s , 0 ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT m [ s [ i ] ] += 1 NEW_LINE length += 1 NEW_LINE if length > k : NEW_LINE INDENT m [ s [ pos ] ] -= 1 NEW_LINE pos += 1 NEW_LINE length -= 1 NEW_LINE DEDE...
Program to replace every space in a string with hyphen | Python 3 program to replace space with - ; Get the String ; Traverse the string character by character . ; Changing the ith character to ' - ' if it 's a space. ; Print the modified string .
if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " A ▁ computer ▁ science ▁ portal ▁ for ▁ geeks " NEW_LINE for i in range ( 0 , len ( str ) , 1 ) : NEW_LINE INDENT if ( str [ i ] == ' ▁ ' ) : NEW_LINE INDENT str = str . replace ( str [ i ] , ' - ' ) NEW_LINE DEDENT DEDENT print ( str ) NEW_LINE DEDENT
Minimum operation require to make first and last character same | Python program to find minimum operation require to make first and last character same ; Function to find minimum operation require to make first and last character same ; Base conditions ; If answer found ; If string is already visited ; Decrement endin...
import sys NEW_LINE MAX = sys . maxsize NEW_LINE m = { } NEW_LINE Min = sys . maxsize NEW_LINE def minOperation ( s , i , j , count ) : NEW_LINE INDENT global Min , MAX NEW_LINE if ( ( i >= len ( s ) and j < 0 ) or ( i == j ) ) : NEW_LINE INDENT return MAX NEW_LINE DEDENT if ( s [ i ] == s [ j ] or count >= Min ) : NEW...
Check if any permutation of a large number is divisible by 8 | Function to check if any permutation of a large number is divisible by 8 ; Less than three digit number can be checked directly . ; check for the reverse of a number ; Stores the Frequency of characters in the n . ; Iterates for all three digit numbers divi...
def solve ( n , l ) : NEW_LINE INDENT if l < 3 : NEW_LINE INDENT if int ( n ) % 8 == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT n = n [ : : - 1 ] NEW_LINE if int ( n ) % 8 == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT hash = 10 * [ 0 ] NEW_LINE for i in range ( 0 , l ) : NEW_LINE ...
Lexicographically smallest string formed by appending a character from the first K characters of a given string | Function to find the new string thus formed by removing characters ; new string ; Remove characters until the string is empty ; Traverse to find the smallest character in the first k characters ; append the...
def newString ( s , k ) : NEW_LINE INDENT X = " " NEW_LINE while ( len ( s ) > 0 ) : NEW_LINE INDENT temp = s [ 0 ] NEW_LINE i = 1 NEW_LINE while ( i < k and i < len ( s ) ) : NEW_LINE INDENT if ( s [ i ] < temp ) : NEW_LINE INDENT temp = s [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT X = X + temp NEW_LINE for i in ran...
Given a binary tree , how do you remove all the half nodes ? | A binary tree node ; For inorder traversal ; Removes all nodes with only one child and returns new root ( note that root may change ) ; If current nodes is a half node with left child None then it 's right child is returned and replaces it in the given tr...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printInorder ( root ) : NEW_LINE INDENT if root is not None : NEW_LINE INDENT printInorder ( root . left ) NEW_LINE print root . data , NEW_L...
Palindrome by swapping only one character | Python3 program palindrome by swapping only one character ; counts the number of differences which prevents the string from being palindrome . ; keeps a record of the characters that prevents the string from being palindrome . ; loops from the start of a string till the midpo...
def isPalindromePossible ( input : str ) -> bool : NEW_LINE INDENT length = len ( input ) NEW_LINE diffCount = 0 NEW_LINE i = 0 NEW_LINE diff = [ [ '0' ] * 2 ] * 2 NEW_LINE while i < length // 2 : NEW_LINE INDENT if input [ i ] != input [ length - i - 1 ] : NEW_LINE INDENT if diffCount == 2 : NEW_LINE INDENT return Fal...
Convert String into Binary Sequence | utility function ; convert each char to ASCII value ; Convert ASCII value to binary ; Driver Code
def strToBinary ( s ) : NEW_LINE INDENT bin_conv = [ ] NEW_LINE for c in s : NEW_LINE INDENT ascii_val = ord ( c ) NEW_LINE binary_val = bin ( ascii_val ) NEW_LINE bin_conv . append ( binary_val [ 2 : ] ) NEW_LINE DEDENT return ( ' ▁ ' . join ( bin_conv ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE IND...
Print distinct sorted permutations with duplicates allowed in input | Python3 program to print all permutations of a string in sorted order . ; Calculating factorial of a number ; Method to find total number of permutations ; Building Map to store frequencies of all characters . ; Traversing map and finding duplicate e...
from collections import defaultdict NEW_LINE def factorial ( n ) : NEW_LINE INDENT f = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT f = f * i NEW_LINE DEDENT return f NEW_LINE DEDENT def calculateTotal ( temp , n ) : NEW_LINE INDENT f = factorial ( n ) NEW_LINE hm = defaultdict ( int ) NEW_LINE for i in ra...
Swap Nodes in Binary tree of every k 'th level | constructor to create a new node ; A utility function swap left node and right node of tree of every k 'th level ; Base Case ; If current level + 1 is present in swap vector then we swap left and right node ; Recur for left and right subtree ; This function mainly calls...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def swapEveryKLevelUtil ( root , level , k ) : NEW_LINE INDENT if ( root is None or ( root . left is None and root . right is None ) ) : NEW_LINE...
Convert a sentence into its equivalent mobile numeric keypad sequence | Function which computes the sequence ; length of input string ; checking for space ; calculating index for each character ; output sequence ; storing the sequence in array
def printSequence ( arr , input ) : NEW_LINE INDENT n = len ( input ) NEW_LINE output = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( input [ i ] == ' ▁ ' ) : NEW_LINE INDENT output = output + "0" NEW_LINE DEDENT else : NEW_LINE INDENT position = ord ( input [ i ] ) - ord ( ' A ' ) NEW_LINE output = output +...
Longest Uncommon Subsequence | function to calculate length of longest uncommon subsequence ; creating an unordered map to map strings to their frequency ; traversing all elements of vector strArr ; Creating all possible subsequences , i . e 2 ^ n ; ( ( i >> j ) & 1 ) determines which character goes into t ; If common ...
def findLUSlength ( a , b ) : NEW_LINE INDENT map = dict ( ) NEW_LINE strArr = [ ] NEW_LINE strArr . append ( a ) NEW_LINE strArr . append ( b ) NEW_LINE for s in strArr : NEW_LINE INDENT for i in range ( 1 << len ( s ) ) : NEW_LINE INDENT t = " " NEW_LINE for j in range ( len ( s ) ) : NEW_LINE INDENT if ( ( ( i >> j ...
Round the given number to nearest multiple of 10 | Function to round the number to the nearest number having one 's digit 0 ; Last character is 0 then return the original string ; If last character is 1 or 2 or 3 or 4 or 5 make it 0 ; Process carry ; Return final string ; Driver code ; Function call
def Round ( s , n ) : NEW_LINE INDENT s = list ( s ) NEW_LINE c = s . copy ( ) NEW_LINE if ( c [ n - 1 ] == '0' ) : NEW_LINE INDENT return ( " " . join ( s ) ) NEW_LINE DEDENT elif ( c [ n - 1 ] == '1' or c [ n - 1 ] == '2' or c [ n - 1 ] == '3' or c [ n - 1 ] == '4' or c [ n - 1 ] == '5' ) : NEW_LINE INDENT c [ n - 1 ...
Check whether given floating point number is even or odd | Function to check even or odd . ; Loop to traverse number from LSB ; We ignore trailing 0 s after dot ; If it is ' . ' we will check next digit and it means decimal part is traversed . ; If digit is divisible by 2 means even number . ; Driver Function
def isEven ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE dotSeen = False NEW_LINE for i in range ( l - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == '0' and dotSeen == False ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( s [ i ] == ' . ' ) : NEW_LINE INDENT dotSeen = True NEW_LINE continue NEW_LINE DEDENT if ( ...
Minimum cost to construct a string | Python 3 Program to find minimum cost to construct a string ; Initially all characters are un - seen ; Marking seen characters ; Count total seen character , and that is the cost ; Driver Code ; s is the string that needs to be constructed
def minCost ( s ) : NEW_LINE INDENT alphabets = [ False for i in range ( 26 ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT alphabets [ ord ( s [ i ] ) - 97 ] = True NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( alphabets [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT...
Root to leaf paths having equal lengths in a Binary Tree | utility that allocates a newNode with the given key ; Function to store counts of different root to leaf path lengths in hash map m . ; Base condition ; If leaf node reached , increment count of path length of this root to leaf path . ; Recursively call for lef...
class newnode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def pathCountUtil ( node , m , path_len ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( node . left == None...
Possibility of moving out of maze | Function to check whether it will stay inside or come out ; marks all the positions that is visited ; Initial starting point ; initial assumption is it comes out ; runs till it is inside or comes out ; if the movement is towards left then we move left . The start variable and mark th...
def checkingPossibility ( a , n , s ) : NEW_LINE INDENT mark = [ 0 ] * n NEW_LINE start = 0 NEW_LINE possible = 1 NEW_LINE while start >= 0 and start < n : NEW_LINE INDENT if s [ start ] == " < " : NEW_LINE INDENT if mark [ start ] == 0 : NEW_LINE INDENT mark [ start ] = 1 NEW_LINE start -= a [ start ] NEW_LINE DEDENT ...
a | A iterative function that removes consecutive duplicates from string S ; We don 't need to do anything for empty or single character string. ; j is used to store index is result string ( or index of current distinct character ) ; Traversing string ; If current character S [ i ] is different from S [ j ] ; Driver C...
def removeDuplicates ( S ) : NEW_LINE INDENT n = len ( S ) NEW_LINE if ( n < 2 ) : NEW_LINE INDENT return NEW_LINE DEDENT j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( S [ j ] != S [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE S [ j ] = S [ i ] NEW_LINE DEDENT DEDENT j += 1 NEW_LINE S = S [ : j ] NEW_LINE retu...
Simplify the directory path ( Unix like ) | function to simplify a Unix - styled absolute path ; using vector in place of stack ; forming the current directory . ; if " . . " , we pop . ; do nothing ( added for better understanding . ) ; push the current directory into the vector . ; forming the ans ; vector is empty ;...
def simplify ( path ) : NEW_LINE INDENT v = [ ] NEW_LINE n = len ( path ) NEW_LINE ans = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT Dir = " " NEW_LINE while ( i < n and path [ i ] != ' / ' ) : NEW_LINE INDENT Dir += path [ i ] NEW_LINE i += 1 NEW_LINE DEDENT if ( Dir == " . . " ) : NEW_LINE INDENT if ( len ( v...
Evaluate a boolean expression represented as string | Python3 program to evaluate value of an expression . ; Evaluates boolean expression and returns the result ; Traverse all operands by jumping a character after every iteration . ; If operator next to current operand is AND . ; If operator next to current operand is ...
import math as mt NEW_LINE def evaluateBoolExpr ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( 0 , n - 2 , 2 ) : NEW_LINE INDENT if ( s [ i + 1 ] == " A " ) : NEW_LINE INDENT if ( s [ i + 2 ] == "0" or s [ i ] == "0" ) : NEW_LINE INDENT s [ i + 2 ] = "0" NEW_LINE DEDENT else : NEW_LINE INDENT s [ i + 2...
Efficiently find first repeated character in a string without using any additional data structure in one traversal | Returns - 1 if all characters of str are unique . Assumptions : ( 1 ) str contains only characters from ' a ' to ' z ' ( 2 ) integers are stored using 32 bits ; An integer to store presence / absence of ...
def FirstRepeated ( string ) : NEW_LINE INDENT checker = 0 NEW_LINE pos = 0 NEW_LINE for i in string : NEW_LINE INDENT val = ord ( i ) - ord ( ' a ' ) ; NEW_LINE if ( ( checker & ( 1 << val ) ) > 0 ) : NEW_LINE INDENT return pos NEW_LINE DEDENT checker |= ( 1 << val ) NEW_LINE pos += 1 NEW_LINE DEDENT return - 1 NEW_LI...
Check if a string is Pangrammatic Lipogram | collection of letters ; function to check for a Pangrammatic Lipogram ; ; variable to keep count of all the letters not found in the string ; traverses the string for every letter of the alphabet ; character not found in string then increment count ; Driver program to test ...
alphabets = ' abcdefghijklmnopqrstuvwxyz ' NEW_LINE def panLipogramChecker ( s ) : NEW_LINE / * convert string to lower case * / NEW_LINE INDENT s . lower ( ) NEW_LINE counter = 0 NEW_LINE for ch in alphabets : NEW_LINE INDENT if ( s . find ( ch ) < 0 ) : NEW_LINE INDENT counter += 1 NEW_LINE DEDENT DEDENT if ( counter...
Lexicographically n | Function to print nth permutation using next_permute ( ) ; Sort the string in lexicographically ascending order ; Keep iterating until we reach nth position ; check for nth iteration ; print string after nth iteration ; next_permutation method implementation ; Driver Code
def nPermute ( string , n ) : NEW_LINE INDENT string = list ( string ) NEW_LINE new_string = [ ] NEW_LINE string . sort ( ) NEW_LINE j = 2 NEW_LINE while next_permutation ( string ) : NEW_LINE INDENT new_string = string NEW_LINE if j == n : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT print ( ' ' . join...
Split numeric , alphabetic and special symbols from a String | Python 3 program to split an alphanumeric string using STL ; Driver code
def splitString ( str ) : NEW_LINE INDENT alpha = " " NEW_LINE num = " " NEW_LINE special = " " NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] . isdigit ( ) ) : NEW_LINE INDENT num = num + str [ i ] NEW_LINE DEDENT elif ( ( str [ i ] >= ' A ' and str [ i ] <= ' Z ' ) or ( str [ i ] >= ' a ' an...
Program to print all substrings of a given string | Function to print all sub strings ; Pick starting point in outer loop and lengths of different strings for a given starting point ; Driver program to test above function
def subString ( s , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for len in range ( i + 1 , n + 1 ) : NEW_LINE INDENT print ( s [ i : len ] ) ; NEW_LINE DEDENT DEDENT DEDENT s = " abcd " ; NEW_LINE subString ( s , len ( s ) ) ; NEW_LINE
Program to print all substrings of a given string | Python program for the above approach ; outermost for loop this is for the selection of starting point ; 2 nd for loop is for selection of ending point ; 3 rd loop is for printing from starting point to ending point ; changing the line after printing from starting poi...
def printSubstrings ( string , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT for k in range ( i , ( j + 1 ) ) : NEW_LINE INDENT print ( string [ k ] , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT DEDENT string = " abcd " NEW_LINE printSubstrings ...
Maximum Tip Calculator | Recursive function to calculate sum of maximum tip order taken by X and Y ; When all orders have been taken ; When X cannot take more orders ; When Y cannot take more orders ; When both can take order calculate maximum out of two ; Driver code
def solve ( i , X , Y , a , b , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( X <= 0 ) : NEW_LINE INDENT return ( b [ i ] + solve ( i + 1 , X , Y - 1 , a , b , n ) ) NEW_LINE DEDENT if ( Y <= 0 ) : NEW_LINE INDENT return ( a [ i ] + solve ( i + 1 , X - 1 , Y , a , b , n ) ) NEW_LIN...
Print Kth character in sorted concatenated substrings of a string | Structure to store information of a suffix ; To store original index ; To store ranks and next rank pair ; This is the main function that takes a string ' txt ' of size n as an argument , builds and return the suffix array for the given string ; A stru...
class suffix : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . index = 0 NEW_LINE self . rank = [ 0 ] * 2 NEW_LINE DEDENT DEDENT def buildSuffixArray ( txt : str , n : int ) -> list : NEW_LINE INDENT suffixes = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT suffixes [ i ] = suffix ( ) NEW_LINE...
Number of even substrings in a string of digits | Return the even number substrings . ; If current digit is even , add count of substrings ending with it . The count is ( i + 1 ) ; Driven Program
def evenNumSubstring ( str ) : NEW_LINE INDENT length = len ( str ) NEW_LINE count = 0 NEW_LINE for i in range ( 0 , length , 1 ) : NEW_LINE INDENT temp = ord ( str [ i ] ) - ord ( '0' ) NEW_LINE if ( temp % 2 == 0 ) : NEW_LINE INDENT count += ( i + 1 ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ ==...
Maximum Consecutive Increasing Path Length in Binary Tree | A binary tree node ; Returns the maximum consecutive path length ; Get the vlue of current node The value of the current node will be prev node for its left and right children ; If current node has to be a part of the consecutive path then it should be 1 great...
class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def maxPathLenUtil ( root , prev_val , prev_len ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return prev_len NEW_LINE DEDENT curr_val = roo...
Find largest word in dictionary by deleting some characters of given string | Returns true if str1 [ ] is a subsequence of str2 [ ] . m is length of str1 and n is length of str2 ; Traverse str2 and str1 , and compare current character of str2 with first unmatched char of str1 , if matched then move ahead in str1 ; If a...
def isSubSequence ( str1 , str2 ) : NEW_LINE INDENT m = len ( str1 ) ; NEW_LINE n = len ( str2 ) ; NEW_LINE i = 0 ; NEW_LINE while ( i < n and j < m ) : NEW_LINE INDENT if ( str1 [ j ] == str2 [ i ] ) : NEW_LINE INDENT j += 1 ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT return ( j == m ) ; NEW_LINE DEDENT def findLongest...
XOR Cipher | The same function is used to encrypt and decrypt ; Define XOR key Any character value will work ; calculate length of input string ; perform XOR operation of key with every character in string ; Driver Code ; Encrypt the string ; Decrypt the string
def encryptDecrypt ( inpString ) : NEW_LINE INDENT xorKey = ' P ' ; NEW_LINE length = len ( inpString ) ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT inpString = ( inpString [ : i ] + chr ( ord ( inpString [ i ] ) ^ ord ( xorKey ) ) + inpString [ i + 1 : ] ) ; NEW_LINE print ( inpString [ i ] , end = " " ) ; N...
Repeated subsequence of length 2 or more | Python3 program to check if any repeated subsequence exists in the String ; A function to check if a String Str is palindrome ; l and h are leftmost and rightmost corners of Str Keep comparing characters while they are same ; The main function that checks if repeated subsequen...
MAX_CHAR = 256 NEW_LINE def isPalindrome ( Str , l , h ) : NEW_LINE INDENT while ( h > l ) : NEW_LINE INDENT if ( Str [ l ] != Str [ h ] ) : NEW_LINE INDENT l += 1 NEW_LINE h -= 1 NEW_LINE return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def check ( Str ) : NEW_LINE INDENT n = len ( Str ) NEW_LINE freq =...
How to find Lexicographically previous permutation ? | Function to compute the previous permutation ; Find index of the last element of the string ; Find largest index i such that str [ i - 1 ] > str [ i ] ; if string is sorted in ascending order we 're at the last permutation ; Note - str [ i . . n ] is sorted in asce...
def prevPermutation ( str ) : NEW_LINE INDENT n = len ( str ) - 1 NEW_LINE i = n NEW_LINE while ( i > 0 and str [ i - 1 ] <= str [ i ] ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT if ( i <= 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT j = i - 1 NEW_LINE while ( j + 1 <= n and str [ j + 1 ] <= str [ i - 1 ] ) : NEW_...
Longest Path with Same Values in a Binary Tree | Function to print the longest path of same values ; Recursive calls to check for subtrees ; Variables to store maximum lengths in two directions ; If curr node and it 's left child has same value ; If curr node and it 's right child has same value ; Driver function to ...
def length ( node , ans ) : NEW_LINE INDENT if ( not node ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT left = length ( node . left , ans ) NEW_LINE right = length ( node . right , ans ) NEW_LINE Leftmax = 0 NEW_LINE Rightmax = 0 NEW_LINE if ( node . left and node . left . val == node . val ) : NEW_LINE INDENT Leftmax +...
Check if edit distance between two strings is one | Returns true if edit distance between s1 and s2 is one , else false ; Find lengths of given strings ; If difference between lengths is more than 1 , then strings can 't be at one distance ; count = 0 Count of isEditDistanceOne ; If current characters dont match ; If l...
def isEditDistanceOne ( s1 , s2 ) : NEW_LINE INDENT m = len ( s1 ) NEW_LINE n = len ( s2 ) NEW_LINE if abs ( m - n ) > 1 : NEW_LINE INDENT return false NEW_LINE DEDENT i = 0 NEW_LINE j = 0 NEW_LINE while i < m and j < n : NEW_LINE INDENT if s1 [ i ] != s2 [ j ] : NEW_LINE INDENT if count == 1 : NEW_LINE INDENT return f...
Count of numbers from range [ L , R ] whose sum of digits is Y | Set 2 | Python program for the above approach ; Function to find the sum of digits of numbers in the range [ 0 , X ] ; Check if count of digits in a number greater than count of digits in X ; Check if sum of digits of a number is equal to Y ; Check if cur...
M = 1000 NEW_LINE def cntNum ( X , i , sum , tight , dp ) : NEW_LINE INDENT if ( i >= len ( X ) or sum < 0 ) : NEW_LINE INDENT if ( sum == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( dp [ sum ] [ i ] [ tight ] != - 1 ) : NEW_LINE INDENT return dp [ sum ] [ i ] [ tight ] NEW_LINE DEDENT ...
Remove spaces from a given string | Function to remove all spaces from a given string ; Driver program
def removeSpaces ( string ) : NEW_LINE INDENT string = string . replace ( ' ▁ ' , ' ' ) NEW_LINE return string NEW_LINE DEDENT string = " g ▁ eeks ▁ for ▁ ge ▁ eeks ▁ " NEW_LINE print ( removeSpaces ( string ) ) NEW_LINE
Given a binary string , count number of substrings that start and end with 1. | A simple Python 3 program to count number of substrings starting and ending with 1 ; Initialize result ; Pick a starting point ; Search for all possible ending point ; Driver program to test above function
def countSubStr ( st , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( st [ i ] == '1' ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( st [ j ] == '1' ) : NEW_LINE INDENT res = res + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return res NEW_LINE DEDENT st = "00...
An in | A utility function to reverse string str [ low . . high ] ; Cycle leader algorithm to move all even positioned elements at the end . ; odd index ; even index ; keep the back - up of element at new position ; The main function to transform a string . This function mainly uses cycleLeader ( ) to transform ; Step ...
def Reverse ( string : list , low : int , high : int ) : NEW_LINE INDENT while low < high : NEW_LINE INDENT string [ low ] , string [ high ] = string [ high ] , string [ low ] NEW_LINE low += 1 NEW_LINE high -= 1 NEW_LINE DEDENT DEDENT def cycleLeader ( string : list , shift : int , len : int ) : NEW_LINE INDENT i = 1 ...
Remove nodes on root to leaf paths of length < K | New node of a tree ; Utility method that actually removes the nodes which are not on the pathLen >= k . This method can change the root as well . ; Base condition ; Traverse the tree in postorder fashion so that if a leaf node path length is shorter than k , then that ...
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def removeShortPathNodesUtil ( root , level , k ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT root . left = removeSh...
Remove duplicates from a given string | Python program to remove duplicate character from character array and print in sorted order ; Create a set using String characters ; Print content of the set ; Driver code
def removeDuplicate ( str , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in str : NEW_LINE INDENT s . add ( i ) NEW_LINE DEDENT st = " " NEW_LINE for i in s : NEW_LINE INDENT st = st + i NEW_LINE DEDENT return st NEW_LINE DEDENT str = " geeksforgeeks " NEW_LINE n = len ( str ) NEW_LINE print ( removeDuplicate ( lis...
Shortest path from a source cell to a destination cell of a Binary Matrix through cells consisting only of 1 s | Python3 program for the above approach ; Stores the coordinates of the matrix cell ; Stores coordinates of a cell and its distance ; Check if the given cell is valid or not ; Stores the moves of the directio...
from collections import deque NEW_LINE class Point : NEW_LINE INDENT def __init__ ( self , xx , yy ) : NEW_LINE INDENT self . x = xx NEW_LINE self . y = yy NEW_LINE DEDENT DEDENT class Node : NEW_LINE INDENT def __init__ ( self , P , d ) : NEW_LINE INDENT self . pt = P NEW_LINE self . dist = d NEW_LINE DEDENT DEDENT de...
Check if any King is unsafe on the Chessboard or not | Function to check if any of the two kings is unsafe or not ; Find the position of both the kings ; Check for all pieces which can attack White King ; Check for Knight ; Check for Pawn ; Check for Rook ; Check for Bishop ; Check for Queen ; Check for King ; Check fo...
def checkBoard ( board ) : NEW_LINE INDENT for i in range ( 8 ) : NEW_LINE INDENT for j in range ( 8 ) : NEW_LINE INDENT if board [ i ] [ j ] == ' k ' : NEW_LINE INDENT if lookForn ( board , ' N ' , i , j ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if lookForp ( board , ' P ' , i , j ) : NEW_LINE INDENT return 1 NEW_L...
Sudoku | Backtracking | N is the size of the 2D matrix N * N ; A utility function to print grid ; Checks whether it will be legal to assign num to the given row , col ; Check if we find the same num in the similar row , we return false ; Check if we find the same num in the similar column , we return false ; Check if w...
N = 9 NEW_LINE def printing ( arr ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def isSafe ( grid , row , col , num ) : NEW_LINE INDENT for x in range ( 9 ) : NEW_LINE INDENT if g...
Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | function to check for the given sum in the array ; checking for condition ; driver code
def printPairs ( arr , arr_size , sum ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 0 , arr_size ) : NEW_LINE INDENT temp = sum - arr [ i ] NEW_LINE if ( temp in s ) : NEW_LINE INDENT print " Pair ▁ with ▁ given ▁ sum ▁ " + str ( sum ) + NEW_LINE DEDENT DEDENT " ▁ is ▁ ( " + str ( arr [ i ] ) + " , ▁ " + st...
Longest consecutive sequence in Binary tree | A utility class to create a node ; Utility method to return length of longest consecutive sequence of tree ; if root data has one more than its parent then increase current length ; update the maximum by current length ; recursively call left and right subtree with expected...
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def longestConsecutiveUtil ( root , curLength , expected , res ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . ...
Find remainder when a number A raised to N factorial is divided by P | Function to calculate ( A ^ N ! ) % P in O ( log y ) ; Initialize result ; Update x if it is more than or Equal to p ; In case x is divisible by p ; If y is odd , multiply x with result ; y must be even now ; Returning modular power ; Function to ca...
def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT d...
Find all array elements occurring more than Γ’Ε’Ε N / 3 Γ’Ε’ β€Ή times | ''Function to find Majority element in an array ; '' if this element is previously seen, increment count1. ; '' if this element is previously seen, increment count2. ; '' if current element is different from both the previously seen variables, decreme...
def findMajority ( arr , n ) : NEW_LINE INDENT count1 = 0 NEW_LINE DEDENT count2 = 0 NEW_LINE = first = 2147483647 NEW_LINE INDENT second = 2147483647 NEW_LINE flag = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if first == arr [ i ] : NEW_LINE count1 += 1 NEW_LINE elif second == arr [ i ] : NEW_LINE count2...
Modular exponentiation ( Recursive ) | Recursive Python program to compute modular power ; Base Cases ; If B is Even ; If B is Odd ; Driver Code
def exponentMod ( A , B , C ) : NEW_LINE INDENT if ( A == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( B == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT y = 0 NEW_LINE if ( B % 2 == 0 ) : NEW_LINE INDENT y = exponentMod ( A , B / 2 , C ) NEW_LINE y = ( y * y ) % C NEW_LINE DEDENT else : NEW_LINE INDENT y = A %...
Find frequency of each element in a limited range array in less than O ( n ) time | python program to count number of occurrences of each element in the array in O ( n ) time and O ( 1 ) space ; check if the current element is equal to previous element . ; reset the frequency ; print the last element and its frequency ...
def findFrequencies ( ele , n ) : NEW_LINE INDENT freq = 1 NEW_LINE idx = 1 NEW_LINE element = ele [ 0 ] NEW_LINE while ( idx < n ) : NEW_LINE INDENT if ( ele [ idx - 1 ] == ele [ idx ] ) : NEW_LINE INDENT freq += 1 NEW_LINE idx += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( element , " ▁ " , freq ) ; NEW_LINE ele...
Modular Exponentiation ( Power in Modular Arithmetic ) | Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize result ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Change x to x ^ 2
def power ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) != 0 ) : NEW_LINE INDENT res = res * x NEW_LINE DEDENT DEDENT DEDENT y = y >> 1 NEW_LINE x = x * x NEW_LINE INDENT return res NEW_LINE DEDENT
Modular Exponentiation ( Power in Modular Arithmetic ) | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now ; Driver Code
def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) == 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y >> 1 y = y / 2 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return re...
Path length having maximum number of bends | Utility function to create a new node ; Recursive function to calculate the path Length having maximum number of bends . The following are parameters for this function . node - . pointer to the current node Dir - . determines whether the current node is left or right child o...
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . key = key NEW_LINE DEDENT DEDENT def findMaxBendsUtil ( node , Dir , bends , maxBends , soFar , Len ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDE...
Program to calculate angle between two N | Python3 program for the above approach ; Function to find the magnitude of the given vector ; Stores the final magnitude ; Traverse the array ; Return square root of magnitude ; Function to find the dot product of two vectors ; Stores dot product ; Traverse the array ; Return ...
import math NEW_LINE def magnitude ( arr , N ) : NEW_LINE INDENT magnitude = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT magnitude += arr [ i ] * arr [ i ] NEW_LINE DEDENT return math . sqrt ( magnitude ) NEW_LINE DEDENT def dotProduct ( arr , brr , N ) : NEW_LINE INDENT product = 0 NEW_LINE for i in range ( N ) ...
Sum of sides of largest and smallest child polygons possible from a given polygon | Function to find the sum of largest and smallest secondary polygons if possible ; Count edges of primary polygon ; Calculate edges present in the largest secondary polygon ; Driver Code ; Given Exterior Angle
def secondary_polygon ( Angle ) : NEW_LINE INDENT edges_primary = 360 // Angle NEW_LINE if edges_primary >= 6 : NEW_LINE INDENT edges_max_secondary = edges_primary // 2 NEW_LINE return edges_max_secondary + 3 NEW_LINE DEDENT else : NEW_LINE INDENT return " Not ▁ Possible " NEW_LINE DEDENT DEDENT if __name__ == ' _ _ ma...
Area of Circumcircle of an Equilateral Triangle using Median | Python3 implementation to find the equation of circle which inscribes equilateral triangle of median M ; Function to find the equation of circle whose center is ( x1 , y1 ) and the radius of circle is r ; Function to find the equation of circle which inscri...
pi = 3.14159265358979323846 NEW_LINE def circleArea ( r ) : NEW_LINE INDENT print ( round ( pi * r * r , 4 ) ) NEW_LINE DEDENT def findCircleAreaByMedian ( m ) : NEW_LINE INDENT r = 2 * m / 3 NEW_LINE circleArea ( r ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 3 NEW_LINE findCircleAreaByMedia...
Number of turns to reach from one node to other in binary tree | A Binary Tree Node ; Utility function to create a new tree Node ; Utility function to find the LCA of two given values n1 and n2 . ; Base case ; If either n1 or n2 matches with root 's key, report the presence by returning root (Note that if a key is an...
class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . key = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( key : int ) -> Node : NEW_LINE INDENT temp = Node ( ) NEW_LINE temp . key = key NEW_LINE temp . left = None NEW_LINE temp . right = None NEW_L...
Find the type of triangle from the given sides | Function to find the type of triangle with the help of sides ; Driver Code ; Function Call
def checkTypeOfTriangle ( a , b , c ) : NEW_LINE INDENT sqa = pow ( a , 2 ) NEW_LINE sqb = pow ( b , 2 ) NEW_LINE sqc = pow ( c , 2 ) NEW_LINE if ( sqa == sqa + sqb or sqb == sqa + sqc or sqc == sqa + sqb ) : NEW_LINE INDENT print ( " Right - angled ▁ Triangle " ) NEW_LINE DEDENT elif ( sqa > sqc + sqb or sqb > sqa + s...
Check whether the triangle is valid or not if angles are given | Function to check if sum of the three angles is 180 or not ; Check condition ; Driver code ; function calling and print output
def Valid ( a , b , c ) : NEW_LINE INDENT if ( ( a + b + c == 180 ) and a != 0 and b != 0 and c != 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 60 NEW_LINE b = 40 NEW_LINE c = 80 NEW_LINE if ( Valid ( a...
Area of the Largest Triangle inscribed in a Hexagon | Python3 Program to find the biggest triangle which can be inscribed within the hexagon ; Function to find the area of the triangle ; side cannot be negative ; area of the triangle ; Driver code
import math NEW_LINE def trianglearea ( a ) : NEW_LINE INDENT if ( a < 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT area = ( 3 * math . sqrt ( 3 ) * math . pow ( a , 2 ) ) / 4 ; NEW_LINE return area ; NEW_LINE DEDENT a = 6 ; NEW_LINE print ( trianglearea ( a ) ) NEW_LINE
Equation of ellipse from its focus , directrix , and eccentricity | Function to find equation of ellipse . ; Driver Code
def equation_ellipse ( x1 , y1 , a , b , c , e ) : NEW_LINE INDENT t = a * a + b * b NEW_LINE a1 = t - e * ( a * a ) NEW_LINE b1 = t - e * ( b * b ) NEW_LINE c1 = ( - 2 * t * x1 ) - ( 2 * e * c * a ) NEW_LINE d1 = ( - 2 * t * y1 ) - ( 2 * e * c * b ) NEW_LINE e1 = - 2 * e * a * b NEW_LINE f1 = ( - e * c * c ) + ( t * x...
Create loops of even and odd values in a binary tree | Utility function to create a new node ; preorder traversal to place the node pointer in the respective even_ptrs or odd_ptrs list ; place node ptr in even_ptrs list if node contains even number ; else place node ptr in odd_ptrs list ; function to create the even an...
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE self . abtr = None NEW_LINE DEDENT DEDENT even_ptrs = [ ] NEW_LINE odd_ptrs = [ ] NEW_LINE def preorderTraversal ( root ) : NEW_LINE INDENT global even_ptrs , odd_pt...
Area of circle which is inscribed in equilateral triangle | Python3 program to find the area of circle which is inscribed in equilateral triangle ; Function return the area of circle inscribed in equilateral triangle ; Driver code
from math import pi NEW_LINE def circle_inscribed ( a ) : NEW_LINE INDENT return pi * ( a * a ) / 12 NEW_LINE DEDENT a = 4 NEW_LINE print ( circle_inscribed ( a ) ) NEW_LINE
Program to find the Volume of an irregular tetrahedron | Python 3 implementation of above approach ; Function to find the volume ; Steps to calculate volume of a Tetrahedron using formula ; Driver code ; edge lengths
from math import * NEW_LINE def findVolume ( u , v , w , U , V , W , b ) : NEW_LINE INDENT uPow = pow ( u , 2 ) NEW_LINE vPow = pow ( v , 2 ) NEW_LINE wPow = pow ( w , 2 ) NEW_LINE UPow = pow ( U , 2 ) NEW_LINE VPow = pow ( V , 2 ) NEW_LINE WPow = pow ( W , 2 ) NEW_LINE a = ( 4 * ( uPow * vPow * wPow ) - uPow * pow ( (...
Check if it is possible to create a polygon with a given angle | Function to check whether it is possible to make a regular polygon with a given angle . ; N denotes the number of sides of polygons possible ; Driver Code ; function calling
def makePolygon ( a ) : NEW_LINE INDENT n = 360 / ( 180 - a ) NEW_LINE if n == int ( n ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 90 NEW_LINE makePolygon ( a ) NEW_LINE DEDENT
Finding Quadrant of a Coordinate with respect to a Circle | Python3 Program to find the quadrant of a given coordinate w . rt . the centre of a circle ; Thus function returns the quadrant number ; Coincides with center ; Outside circle ; 1 st quadrant ; 2 nd quadrant ; 3 rd quadrant ; 4 th quadrant ; Coordinates of cen...
import math NEW_LINE def getQuadrant ( X , Y , R , PX , PY ) : NEW_LINE INDENT if ( PX == X and PY == Y ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT val = ( math . pow ( ( PX - X ) , 2 ) + math . pow ( ( PY - Y ) , 2 ) ) ; NEW_LINE if ( val > pow ( R , 2 ) ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( PX > X ...
Hexadecagonal number | Function to calculate hexadecagonal number ; Driver Code
def hexadecagonalNum ( n ) : NEW_LINE INDENT return ( ( 14 * n * n ) - 12 * n ) // 2 NEW_LINE DEDENT n = 5 NEW_LINE print ( " % sth ▁ Hexadecagonal ▁ number ▁ : ▁ " % n , hexadecagonalNum ( n ) ) NEW_LINE n = 9 NEW_LINE print ( " % sth ▁ Hexadecagonal ▁ number ▁ : ▁ " % n , hexadecagonalNum ( n ) ) NEW_LINE
Find first non matching leaves in two binary trees | Utility function to create a new tree Node ; Prints the first non - matching leaf node in two trees if it exists , else prints nothing . ; If any of the tree is empty ; Create two stacks for preorder traversals ; If traversal of one tree is over and other tree still ...
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def isLeaf ( t ) : NEW_LINE INDENT return ( ( t . left == None ) and ( t . right == None ) ) NEW_LINE DEDENT def findFirstUnmatch ( root1 , root2 ) : NEW_LI...
Maximum points of intersection n circles | Returns maximum number of intersections ; Driver code
def intersection ( n ) : NEW_LINE INDENT return n * ( n - 1 ) ; NEW_LINE DEDENT print ( intersection ( 3 ) ) NEW_LINE
Find the perimeter of a cylinder | Function to calculate the perimeter of a cylinder ; Driver function
def perimeter ( diameter , height ) : NEW_LINE INDENT return 2 * ( diameter + height ) NEW_LINE DEDENT diameter = 5 ; NEW_LINE height = 10 ; NEW_LINE print ( " Perimeter ▁ = ▁ " , perimeter ( diameter , height ) ) NEW_LINE
Find all possible coordinates of parallelogram | coordinates of A ; coordinates of B ; coordinates of C
ay = 0 NEW_LINE ax = 5 NEW_LINE by = 1 NEW_LINE bx = 1 NEW_LINE cy = 5 NEW_LINE cx = 2 NEW_LINE print ( ax + bx - cx , " , ▁ " , ay + by - cy ) NEW_LINE print ( ax + cx - bx , " , ▁ " , ay + cy - by ) NEW_LINE print ( cx + bx - ax , " , ▁ " , cy + by - ax ) NEW_LINE
Check whether a given point lies inside a rectangle or not | A utility function to calculate area of triangle formed by ( x1 , y1 ) , ( x2 , y2 ) and ( x3 , y3 ) ; A function to check whether point P ( x , y ) lies inside the rectangle formed by A ( x1 , y1 ) , B ( x2 , y2 ) , C ( x3 , y3 ) and D ( x4 , y4 ) ; Calculat...
def area ( x1 , y1 , x2 , y2 , x3 , y3 ) : NEW_LINE INDENT return abs ( ( x1 * ( y2 - y3 ) + x2 * ( y3 - y1 ) + x3 * ( y1 - y2 ) ) / 2.0 ) NEW_LINE DEDENT def check ( x1 , y1 , x2 , y2 , x3 , y3 , x4 , y4 , x , y ) : NEW_LINE INDENT A = ( area ( x1 , y1 , x2 , y2 , x3 , y3 ) + area ( x1 , y1 , x4 , y4 , x3 , y3 ) ) NEW...
Get maximum left node in binary tree | Get max of left element using Inorder traversal ; Return maximum of three values 1 ) Recursive max in left subtree 2 ) Value in left node 3 ) Recursive max in right subtree ; Utility class to create a new tree node ; Driver Code ; Let us create binary tree shown in above diagram ;...
def maxOfLeftElement ( root ) : NEW_LINE INDENT res = - 999999999999 NEW_LINE if ( root == None ) : NEW_LINE INDENT return res NEW_LINE DEDENT if ( root . left != None ) : NEW_LINE INDENT res = root . left . data NEW_LINE DEDENT return max ( { maxOfLeftElement ( root . left ) , res , maxOfLeftElement ( root . right ) }...
Pizza cut problem ( Or Circle Division by Lines ) | Function for finding maximum pieces with n cuts . ; Driver code
def findMaximumPieces ( n ) : NEW_LINE INDENT return int ( 1 + n * ( n + 1 ) / 2 ) NEW_LINE DEDENT print ( findMaximumPieces ( 3 ) ) NEW_LINE
Optimum location of point to minimize total distance | A Python3 program to find optimum location and total cost ; Class defining a point ; Class defining a line of ax + by + c = 0 form ; Method to get distance of point ( x , y ) from point p ; Utility method to compute total distance all points when choose point on gi...
import math NEW_LINE class Optimum_distance : NEW_LINE INDENT class Point : NEW_LINE INDENT def __init__ ( self , x , y ) : NEW_LINE INDENT self . x = x NEW_LINE self . y = y NEW_LINE DEDENT DEDENT class Line : NEW_LINE INDENT def __init__ ( self , a , b , c ) : NEW_LINE INDENT self . a = a NEW_LINE self . b = b NEW_LI...
Klee 's Algorithm (Length Of Union Of Segments of a line) | Returns sum of lengths covered by union of given segments ; Initialize empty points container ; Create a vector to store starting and ending points ; Sorting all points by point value ; Initialize result as 0 ; To keep track of counts of current open segments ...
def segmentUnionLength ( segments ) : NEW_LINE INDENT n = len ( segments ) NEW_LINE points = [ None ] * ( n * 2 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT points [ i * 2 ] = ( segments [ i ] [ 0 ] , False ) NEW_LINE points [ i * 2 + 1 ] = ( segments [ i ] [ 1 ] , True ) NEW_LINE DEDENT points = sorted ( points ,...
Find all duplicate and missing numbers in given permutation array of 1 to N | Function to find the duplicate and the missing elements over the range [ 1 , N ] ; Stores the missing and duplicate numbers in the array arr [ ] ; Traverse the given array arr [ ] ; Check if the current element is not same as the element at i...
def findElements ( arr , N ) : NEW_LINE INDENT i = 0 ; NEW_LINE missing = [ ] ; NEW_LINE duplicate = set ( ) ; NEW_LINE while ( i != N ) : NEW_LINE INDENT if ( arr [ i ] != arr [ arr [ i ] - 1 ] ) : NEW_LINE INDENT t = arr [ i ] NEW_LINE arr [ i ] = arr [ arr [ i ] - 1 ] NEW_LINE arr [ t - 1 ] = t NEW_LINE DEDENT else ...
Check if elements of given array can be rearranged such that ( arr [ i ] + i * K ) % N = i for all values of i in range [ 0 , N | Function to check if it is possible to generate all numbers in range [ 0 , N - 1 ] using the sum of elements + in the multiset A and B mod N ; If no more pair of elements can be selected ; I...
def isPossible ( A , B , C , N ) : NEW_LINE INDENT if ( len ( A ) == 0 or len ( B ) == 0 ) : NEW_LINE INDENT if ( len ( C ) == N ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT ans = False NEW_LINE for x in A : NEW_LINE INDENT for y in B : NEW_LINE INDENT _A = ...
Height of Factor Tree for a given number | Python 3 program for the above approach ; Function to find the height of the Factor Tree of the integer N ; Stores the height of Factor Tree ; Loop to iterate over values of N ; Stores if there exist a factor of N or not ; Loop to find the smallest factor of N ; If i is a fact...
from math import sqrt NEW_LINE def factorTree ( N ) : NEW_LINE INDENT height = 0 NEW_LINE while ( N > 1 ) : NEW_LINE INDENT flag = False NEW_LINE for i in range ( 2 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT N = N // i NEW_LINE flag = True NEW_LINE break NEW_LINE DEDENT DEDENT ...
Maximize the largest number K such that bitwise and of K till N is 0 | ; Function to find maximum value of k which makes bitwise AND zero . ; Finding the power less than N ; Driver Code
import math NEW_LINE def findMaxK ( N ) : NEW_LINE INDENT p = math . log ( N ) // math . log ( 2 ) ; NEW_LINE return int ( pow ( 2 , p ) ) ; NEW_LINE DEDENT N = 5 ; NEW_LINE print ( findMaxK ( N ) - 1 ) ; NEW_LINE
Count of Ks in the Array for a given range of indices after array updates for Q queries | Python3 program for the above approach ; Function to build the segment tree ; Base case ; Since the count of zero is required set leaf node as 1 ; If the value in array is not zero , store 0 in the leaf node ; Find the mid ; Recur...
a = [ ] NEW_LINE seg_tree = [ ] NEW_LINE query = [ ] NEW_LINE def build_tree ( v , tl , tr ) : NEW_LINE INDENT global a , seg_tree , query NEW_LINE if ( tl != tr ) : NEW_LINE INDENT if ( a [ tl ] == 0 ) : NEW_LINE INDENT seg_tree [ v ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT seg_tree [ v ] = 0 NEW_LINE DEDENT DEDENT...
Find a number in minimum steps | Python program to find a number in minimum steps ; To represent data of a node in tree ; Prints level of node n ; Create a queue and insert root ; Do level order traversal ; Remove a node from queue ; q . pop ( ) To avoid infinite loop ; Check if dequeued number is same as n ; Insert ch...
from collections import deque NEW_LINE InF = 99999 NEW_LINE class number : NEW_LINE INDENT def __init__ ( self , n , l ) : NEW_LINE INDENT self . no = n NEW_LINE self . level = l NEW_LINE DEDENT DEDENT def findnthnumber ( n ) : NEW_LINE INDENT q = deque ( ) NEW_LINE r = number ( 0 , 1 ) NEW_LINE q . append ( r ) NEW_LI...
Check if all 3 Candy bags can be emptied by removing 2 candies from any one bag and 1 from the other two repeatedly | Python code for the above approach ; If total candies are not multiple of 4 then its not possible to be left with 0 candies ; If minimum candies of three bags are less than number of operations required...
def can_empty ( a , b , c ) : NEW_LINE INDENT if ( ( a + b + c ) % 4 != 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT else : NEW_LINE INDENT m = min ( a , min ( b , c ) ) ; NEW_LINE if ( m < ( a + b + c ) // 4 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT a = 4 NEW_LINE ...
Difference between maximum and minimum average of all K | Function to find the difference between averages of the maximum and the minimum subarrays of length k ; Stores min and max sum ; Iterate through starting points ; Sum up next K elements ; Update max and min moving sum ; Return the difference between max and min ...
def Avgdifference ( arr , N , K ) : NEW_LINE INDENT min = 1000000 ; NEW_LINE max = - 1 ; NEW_LINE for i in range ( N - K + 1 ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for j in range ( K ) : NEW_LINE INDENT sum += arr [ i + j ] ; NEW_LINE DEDENT if ( min > sum ) : NEW_LINE INDENT min = sum ; NEW_LINE DEDENT if ( max < sum ...
Find a number in minimum steps | Python3 program to Find a number in minimum steps ; Steps sequence ; Current sum ; Sign of the number ; Basic steps required to get sum >= required value . ; If we have reached ahead to destination . ; If the last step was an odd number , then it has following mechanism for negating a p...
def find ( n ) : NEW_LINE INDENT ans = [ ] NEW_LINE Sum = 0 NEW_LINE i = 0 NEW_LINE sign = 0 NEW_LINE if ( n >= 0 ) : NEW_LINE INDENT sign = 1 NEW_LINE DEDENT else : NEW_LINE INDENT sign = - 1 NEW_LINE DEDENT n = abs ( n ) NEW_LINE i = 1 NEW_LINE while ( Sum < n ) : NEW_LINE INDENT ans . append ( sign * i ) NEW_LINE Su...
Maximum range length such that A [ i ] is maximum in given range for all i from [ 1 , N ] | Python 3 program for the above approach ; Function to find maximum range for each i such that arr [ i ] is max in range ; Vector to store the left and right index for each i such that left [ i ] > arr [ i ] and right [ i ] > arr...
import sys NEW_LINE def MaxRange ( A , n ) : NEW_LINE INDENT left = [ 0 ] * n NEW_LINE right = [ 0 ] * n NEW_LINE s = [ ] NEW_LINE s . append ( ( sys . maxsize , - 1 ) ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( s [ - 1 ] [ 0 ] < A [ i ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT left [ i ] = s [ - 1...
Find Nth smallest number having exactly 4 divisors | Function to find the nth number which has exactly 4 divisors ; The divs [ ] array to store number of divisors of every element ; The vis [ ] array to check if given number is considered or not ; The cnt stores number of elements having exactly 4 divisors ; Iterate wh...
def nthNumber ( n ) : NEW_LINE INDENT divs = [ 0 for i in range ( 1000000 ) ] ; NEW_LINE vis = [ 0 for i in range ( 1000000 ) ] ; NEW_LINE cnt = 0 ; NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( divs [ i ] == 0 ) : NEW_LINE INDENT for j in range ( 2 * i , 1000000 ) : NEW_LINE INDENT if ( vis [ j ] ) : NEW_LI...
Maximum number formed from the digits of given three numbers | Function to find the maximum number formed by taking the maximum digit at the same position from each number ; Stores the result ; Stores the position value of a digit ; Stores the digit at the unit place ; Stores the digit at the unit place ; Stores the di...
def findkey ( A , B , C ) : NEW_LINE INDENT ans = 0 NEW_LINE cur = 1 NEW_LINE while ( A > 0 ) : NEW_LINE INDENT a = A % 10 NEW_LINE b = B % 10 NEW_LINE c = C % 10 NEW_LINE A = A // 10 NEW_LINE B = B // 10 NEW_LINE C = C // 10 NEW_LINE m = max ( a , max ( c , b ) ) NEW_LINE ans += cur * m NEW_LINE cur = cur * 10 NEW_LIN...
Count of distinct GCDs among all the non | Python 3 program for the above approach ; Function to calculate the number of distinct GCDs among all non - empty subsequences of an array ; variables to store the largest element in array and the required count ; Map to store whether a number is present in A ; calculate large...
from math import gcd NEW_LINE def distinctGCDs ( arr , N ) : NEW_LINE INDENT M = - 1 NEW_LINE ans = 0 NEW_LINE Mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT M = max ( M , arr [ i ] ) NEW_LINE Mp [ arr [ i ] ] = 1 NEW_LINE DEDENT for i in range ( 1 , M + 1 , 1 ) : NEW_LINE INDENT currGcd = 0 NEW_LINE for j in...
Compress a Binary Tree into an integer diagonally | Python program for the above approach ; Function to compress the elements in an array into an integer ; Check for each bit position ; Update the count of set and non - set bits ; If number of set bits exceeds the number of non - set bits , then add set bits value to a...
class TreeNode : NEW_LINE INDENT def __init__ ( self , val = ' ' , left = None , right = None ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def findCompressValue ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE getBit = 1 NEW_LINE for i in range ( 32 ) :...
Egg Dropping Puzzle | DP | ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; If there are no floors , then no trials needed . OR if there is one floor , one trial needed . ; We need k trials for one egg and k floors ; Consider all droppings from 1 st floor to kth floor and retu...
import sys NEW_LINE def eggDrop ( n , k ) : NEW_LINE INDENT if ( k == 1 or k == 0 ) : NEW_LINE INDENT return k NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return k NEW_LINE DEDENT min = sys . maxsize NEW_LINE for x in range ( 1 , k + 1 ) : NEW_LINE INDENT res = max ( eggDrop ( n - 1 , x - 1 ) , eggDrop ( n , k - x ...
K | Function to find the kth digit from last in an eger n ; If k is less than equal to 0 ; Divide the number n by 10 upto k - 1 times ; If the number n is equal 0 ; Pr the right most digit ; Driver code ; Given Input ; Function call
def kthDigitFromLast ( n , k ) : NEW_LINE INDENT if ( k <= 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT while ( ( k - 1 ) > 0 and n > 0 ) : NEW_LINE INDENT n = n / 10 NEW_LINE k -= 1 NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print (...