text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Count balanced nodes present in a binary tree | Structure of a Tree Node ; Function to get the sum of left subtree and right subtree ; Base case ; Store the sum of left subtree ; Store the sum of right subtree ; Check if node is balanced or not ; Increase count of balanced nodes ; Return subtree sum ; Insert nodes in t...
class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . data = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def Sum ( root ) : NEW_LINE INDENT global res NEW_LINE if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT leftSubSum = Sum ( root . lef...
Print alternate nodes from all levels of a Binary Tree | Structure of a Node ; Print alternate nodes of a binary tree ; Store nodes of each level ; Store count of nodes of current level ; Print alternate nodes of the current level ; If left child exists ; Store left child ; If right child exists ; Store right child ; D...
class newNode : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . data = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def PrintAlternate ( root ) : NEW_LINE INDENT Q = [ ] NEW_LINE Q . append ( root ) NEW_LINE while ( len ( Q ) ) : NEW_LINE INDENT N = len ( Q ) ...
Count subarrays for every array element in which they are the minimum | Function to required count subarrays ; For storing count of subarrays ; For finding next smaller element left to a element if there is no next smaller element left to it than taking - 1. ; For finding next smaller element right to a element if ther...
def countingSubarray ( arr , n ) : NEW_LINE INDENT a = [ 0 for i in range ( n ) ] NEW_LINE nsml = [ - 1 for i in range ( n ) ] NEW_LINE nsmr = [ n for i in range ( n ) ] NEW_LINE st = [ ] NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT while ( len ( st ) > 0 and arr [ st [ - 1 ] ] >= arr [ i ] ) : NEW_L...
Lexicographically smallest permutation of a string that contains all substrings of another string | Function to reorder the B to contain all the substrings of A ; Find length of strings ; Initialize array to count the frequencies of the character ; Counting frequencies of character in B ; Find remaining character in B ...
def reorderString ( A , B ) : NEW_LINE INDENT size_a = len ( A ) NEW_LINE size_b = len ( B ) NEW_LINE freq = [ 0 ] * 300 NEW_LINE for i in range ( size_b ) : NEW_LINE INDENT freq [ ord ( B [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( size_a ) : NEW_LINE INDENT freq [ ord ( A [ i ] ) ] -= 1 NEW_LINE DEDENT for j in r...
Number from a range [ L , R ] having Kth minimum cost of conversion to 1 by given operations | Function to calculate the cost ; Base case ; Even condition ; Odd condition ; Return cost ; Function to find Kth element ; Array to store the costs ; Sort the array based on cost ; Given range and K ; Function Call
def func ( n ) : NEW_LINE INDENT count = 0 NEW_LINE if n == 2 or n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n % 2 == 0 : NEW_LINE INDENT count = 1 + func ( n // 2 ) NEW_LINE DEDENT if n % 2 != 0 : NEW_LINE INDENT count = 1 + func ( n * 3 + 1 ) NEW_LINE DEDENT return count NEW_LINE DEDENT def findKthElement ( ...
Check if a string represents a hexadecimal number or not | Function to check if the string represents a hexadecimal number ; Iterate over string ; Check if the character is invalid ; Print true if all characters are valid ; Given string ; Function call
def checkHex ( s ) : NEW_LINE INDENT for ch in s : NEW_LINE INDENT if ( ( ch < '0' or ch > '9' ) and ( ch < ' A ' or ch > ' F ' ) ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " Yes " ) NEW_LINE DEDENT s = " BF57C " NEW_LINE checkHex ( s ) NEW_LINE
Longest subsequence forming an Arithmetic Progression ( AP ) | Function that finds the longest arithmetic subsequence having the same absolute difference ; Stores the length of sequences having same difference ; Stores the resultant length ; Iterate over the array ; Update length of subsequence ; Return res ; ; Given ...
def lenghtOfLongestAP ( A , n ) : NEW_LINE INDENT dp = { } NEW_LINE res = 2 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT d = A [ j ] - A [ i ] NEW_LINE if d in dp : NEW_LINE INDENT if i in dp [ d ] : NEW_LINE INDENT dp [ d ] [ j ] = dp [ d ] [ i ] + 1 NEW_LINE DEDENT el...
Length of longest increasing prime subsequence from a given array | Python3 program for the above approach ; Function to find the prime numbers till 10 ^ 5 using Sieve of Eratosthenes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them ...
N = 100005 NEW_LINE def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= p_size : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE for i in range ( p * 2 , p_size + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE p += 1 ...
Check if a given number can be expressed as pair | Python3 program of the above approach ; Function to check if the number is pair - sum of sum of first X natural numbers ; Check if the given number is sum of pair of special numbers ; X is the sum of first i natural numbers ; t = 2 * Y ; Condition to check if Y is a sp...
import math NEW_LINE def checkSumOfNatural ( n ) : NEW_LINE INDENT i = 1 NEW_LINE flag = False NEW_LINE while i * ( i + 1 ) < n * 2 : NEW_LINE INDENT X = i * ( i + 1 ) NEW_LINE t = n * 2 - X NEW_LINE k = int ( math . sqrt ( t ) ) NEW_LINE if k * ( k + 1 ) == t : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDEN...
Count distinct regular bracket sequences which are not N periodic | Function that finds the value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate the value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Return the C ( n , k ) ; Binomial coefficient bas...
def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT res = res * ( n - i ) NEW_LINE res = res // ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def catalan ( n ) : NEW_LINE INDENT c = binomialCoeff ( 2 * ...
Check if two elements of a matrix are on the same diagonal or not | Function to check if two integers are on the same diagonal of the matrix ; Storing Indexes of y in P , Q ; Condition to check if the both the elements are in same diagonal of a matrix ; Driver Code ; Dimensions of Matrix ; Given Matrix ; elements to be...
def checkSameDiag ( x , y ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if li [ i ] [ j ] == x : NEW_LINE INDENT I , J = i , j NEW_LINE DEDENT if li [ i ] [ j ] == y : NEW_LINE INDENT P , Q = i , j NEW_LINE DEDENT DEDENT DEDENT if P - Q == I - J or P + Q == I + J : NE...
Count of decrement operations required to obtain K in N steps | Function to check whether m number of steps of type 1 are valid or not ; If m and n are the count of operations of type 1 and type 2 respectively , then n - m operations are performed ; Find the value of S after step 2 ; If m steps of type 1 is valid ; Fun...
def isValid ( n , m , k ) : NEW_LINE INDENT step2 = n - m NEW_LINE cnt = ( step2 * ( step2 + 1 ) ) // 2 NEW_LINE if ( cnt - m == k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( cnt - m > k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def countOfOperations ( n , k ) : NEW_LINE INDENT start...
Print all Possible Decodings of a given Digit Sequence | Function to check if all the characters are lowercase or not ; Traverse the string ; If any character is not found to be in lowerCase ; Function to print the decodings ; If all characters are not in lowercase ; Function to return the character corresponding to gi...
def nonLower ( s ) : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if not s [ i ] . islower ( ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def printCodes ( output ) : NEW_LINE INDENT for i in range ( len ( output ) ) : NEW_LINE INDENT if ( nonLower ( output [ i ] ...
Count prime numbers that can be expressed as sum of consecutive prime numbers | Function to check if a number is prime or not ; Base Case ; Iterate till [ 5 , sqrt ( N ) ] to detect primality of numbers ; If N is divisible by i or i + 2 ; Return 1 if N is prime ; Function to count the prime numbers which can be express...
def isprm ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : N...
Find a subarray of size K whose sum is a perfect square | Python3 program for the above approach ; Function to check if a given number is a perfect square or not ; Find square root of n ; Check if the square root is an integer or not ; Function to print the subarray whose sum is a perfect square ; Sum of first K elemen...
from math import sqrt , ceil , floor NEW_LINE def isPerfectSquare ( n ) : NEW_LINE INDENT sr = sqrt ( n ) NEW_LINE return ( ( sr - floor ( sr ) ) == 0 ) NEW_LINE DEDENT def SubarrayHavingPerfectSquare ( arr , k ) : NEW_LINE INDENT ans = [ 0 , 0 ] NEW_LINE sum = 0 NEW_LINE i = 0 NEW_LINE while i < k : NEW_LINE INDENT su...
Check if any permutation of a number without any leading zeros is a power of 2 or not | Python3 program for the above approach ; Function to update the frequency array such that freq [ i ] stores the frequency of digit i to n ; While there are digits left to process ; Update the frequency of the current digit ; Remove ...
TEN = 10 NEW_LINE def updateFreq ( n , freq ) : NEW_LINE INDENT while ( n ) : NEW_LINE INDENT digit = n % TEN NEW_LINE freq [ digit ] += 1 NEW_LINE n //= TEN NEW_LINE DEDENT DEDENT def areAnagrams ( a , b ) : NEW_LINE INDENT freqA = [ 0 ] * ( TEN ) NEW_LINE freqB = [ 0 ] * ( TEN ) NEW_LINE updateFreq ( a , freqA ) NEW_...
Count number of triangles possible with length of sides not exceeding N | Function to count total number of right angled triangle ; Initialise count with 0 ; Run three nested loops and check all combinations of sides ; Condition for right angled triangle ; Increment count ; Given N ; Function call
def right_angled ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for z in range ( 1 , n + 1 ) : NEW_LINE INDENT for y in range ( 1 , z + 1 ) : NEW_LINE INDENT for x in range ( 1 , y + 1 ) : NEW_LINE INDENT if ( ( x * x ) + ( y * y ) == ( z * z ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return coun...
Check if the given two matrices are mirror images of one another | Function to check whether the two matrices are mirror of each other ; Initialising row and column of second matrix ; Iterating over the matrices ; Check row of first matrix with reversed row of second matrix ; If the element is not equal ; Increment col...
def mirrorMatrix ( mat1 , mat2 , N ) : NEW_LINE INDENT row = 0 NEW_LINE col = 0 NEW_LINE isMirrorImage = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( mat2 [ row ] [ col ] != mat1 [ i ] [ j ] ) : NEW_LINE INDENT isMirrorImage = False NEW_LINE DEDENT col...
Calculate number of nodes between two vertices in an acyclic Graph by DFS method | Function to return the count of nodes in the path from source to destination ; Mark the node visited ; If dest is reached ; Traverse all adjacent nodes ; If not already visited ; If there is path , then include the current node ; Return ...
def dfs ( src , dest , vis , adj ) : NEW_LINE INDENT vis [ src ] = 1 NEW_LINE if ( src == dest ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for u in adj [ src ] : NEW_LINE INDENT if not vis [ u ] : NEW_LINE INDENT temp = dfs ( u , dest , vis , adj ) NEW_LINE if ( temp != 0 ) : NEW_LINE INDENT return temp + 1 NEW_LINE D...
Check if all array elements are pairwise co | Function to calculate GCD ; Function to calculate LCM ; Function to check if aelements in the array are pairwise coprime ; Initialize variables ; Iterate over the array ; Calculate product of array elements ; Calculate LCM of array elements ; If the product of array element...
def GCD ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return GCD ( b % a , a ) NEW_LINE DEDENT def LCM ( a , b ) : NEW_LINE INDENT return ( a * b ) // GCD ( a , b ) NEW_LINE DEDENT def checkPairwiseCoPrime ( A , n ) : NEW_LINE INDENT prod = 1 NEW_LINE lcm = 1 NEW_LINE for i in ran...
Partition a set into two non | Python3 program for above approach ; Function to return the maximum difference between the subset sums ; Stores the total sum of the array ; Checks for positive and negative elements ; Stores the minimum element from the given array ; Traverse the array ; Calculate total sum ; Mark positi...
import sys NEW_LINE def maxDiffSubsets ( arr ) : NEW_LINE INDENT totalSum = 0 NEW_LINE pos = False NEW_LINE neg = False NEW_LINE min = sys . maxsize NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT totalSum += abs ( arr [ i ] ) NEW_LINE if ( arr [ i ] > 0 ) : NEW_LINE INDENT pos = True NEW_LINE DEDENT if ( arr...
Split array into two subarrays such that difference of their sum is minimum | Python3 program for the above approach ; Function to return minimum difference between two subarray sums ; To store prefix sums ; Generate prefix sum array ; To store suffix sums ; Generate suffix sum array ; Stores the minimum difference ; T...
import sys NEW_LINE def minDiffSubArray ( arr , n ) : NEW_LINE INDENT prefix_sum = [ 0 ] * n NEW_LINE prefix_sum [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix_sum [ i ] = ( prefix_sum [ i - 1 ] + arr [ i ] ) NEW_LINE DEDENT suffix_sum = [ 0 ] * n NEW_LINE suffix_sum [ n - 1 ] = arr [ n - ...
Count of days remaining for the next day with higher temperature | Function to determine how many days required to wait for the next warmer temperature ; To store the answer ; Traverse all the temperatures ; Check if current index is the next warmer temperature of any previous indexes ; Pop the element ; Push the curre...
def dailyTemperatures ( T ) : NEW_LINE INDENT n = len ( T ) NEW_LINE daysOfWait = [ - 1 ] * n NEW_LINE s = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( len ( s ) != 0 and T [ s [ - 1 ] ] < T [ i ] ) : NEW_LINE INDENT daysOfWait [ s [ - 1 ] ] = i - s [ - 1 ] NEW_LINE s . pop ( - 1 ) NEW_LINE DEDENT s . ap...
Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U | To store the time ; Function to perform DFS to store times , distance and parent of each node ; Update the distance of node u ; Update parent of node u ; Increment time timeT ; Discovery time of node u ; Traverse the adjac...
timeT = 0 ; NEW_LINE def dfs ( u , p , dis , vis , distance , parent , preTime , postTime , Adj ) : NEW_LINE INDENT global timeT NEW_LINE distance [ u ] = dis ; NEW_LINE parent [ u ] = p ; NEW_LINE vis [ u ] = 1 ; NEW_LINE timeT += 1 NEW_LINE preTime [ u ] = timeT ; NEW_LINE for i in range ( len ( Adj [ u ] ) ) : NEW_L...
Check if an array contains only one distinct element | Function to find if the array contains only one distinct element ; Create a set ; Compare and print the result ; Driver code ; Function call
def uniqueElement ( arr , n ) : NEW_LINE INDENT s = set ( arr ) NEW_LINE if ( len ( s ) == 1 ) : NEW_LINE INDENT print ( ' YES ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' NO ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 9 , 9 , 9 , 9 , 9 , 9 ] NEW_LINE n = len ( arr )...
Maximum cost of splitting given Binary Tree into two halves | To store the results and sum of all nodes in the array ; To create adjacency list ; Function to add edges into the adjacency list ; Recursive function that calculate the value of the cost of splitting the tree recursively ; Fetch the child of node - r ; Negl...
ans = 0 NEW_LINE allsum = 0 NEW_LINE edges = [ [ ] for i in range ( 100001 ) ] NEW_LINE def addedge ( a , b ) : NEW_LINE INDENT global edges NEW_LINE edges [ a ] . append ( b ) NEW_LINE edges [ b ] . append ( a ) NEW_LINE DEDENT def findCost ( r , p , arr ) : NEW_LINE INDENT global edges NEW_LINE global ans NEW_LINE gl...
Diameters for each node of Tree after connecting it with given disconnected component | Python3 program to implement the above approach ; Keeps track of the farthest end of the diameter ; Keeps track of the length of the diameter ; Stores the nodes which are at ends of the diameter ; Perform DFS on the given tree ; Upd...
from collections import defaultdict NEW_LINE X = 1 NEW_LINE diameter = 0 NEW_LINE mp = defaultdict ( lambda : 0 ) NEW_LINE def dfs ( current_node , prev_node , len , add_to_map , adj ) : NEW_LINE INDENT global diameter , X NEW_LINE if len > diameter : NEW_LINE INDENT diameter = len NEW_LINE X = current_node NEW_LINE DE...
Count of replacements required to make the sum of all Pairs of given type from the Array equal | Python3 program to implement the above approach ; Function to find the minimum replacements required ; Stores the maximum and minimum values for every pair of the form arr [ i ] , arr [ n - i - 1 ] ; Map for storing frequen...
inf = 10 ** 18 NEW_LINE def firstOccurance ( numbers , length , searchnum ) : NEW_LINE INDENT answer = - 1 NEW_LINE start = 0 NEW_LINE end = length - 1 NEW_LINE while start <= end : NEW_LINE INDENT middle = ( start + end ) // 2 NEW_LINE if numbers [ middle ] == searchnum : NEW_LINE INDENT answer = middle NEW_LINE end =...
Print the Forests of a Binary Tree after removal of given Nodes | Stores the nodes to be deleted ; Structure of a Tree node ; Function to create a new node ; Function to check whether the node needs to be deleted or not ; Function to perform tree pruning by performing post order traversal ; If the node needs to be dele...
mp = dict ( ) NEW_LINE 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 newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE return temp NEW_LINE DEDENT def deleteNode ( nodeVal ) : N...
Count of Ways to obtain given Sum from the given Array elements | Function to call dfs to calculate the number of ways ; If target + sum is odd or S exceeds sum ; No sultion exists ; Return the answer ; Driver Code
def knapSack ( nums , S ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( len ( nums ) ) : NEW_LINE INDENT sum += nums [ i ] ; NEW_LINE DEDENT if ( sum < S or - sum > - S or ( S + sum ) % 2 == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT dp = [ 0 ] * ( ( ( S + sum ) // 2 ) + 1 ) ; NEW_LINE dp [ 0 ] = 1 ; NEW_...
Maximum distance between two elements whose absolute difference is K | Function that find maximum distance between two elements whose absolute difference is K ; To store the first index ; Traverse elements and find maximum distance between 2 elements whose absolute difference is K ; If this is first occurrence of eleme...
def maxDistance ( arr , K ) : NEW_LINE INDENT map = { } NEW_LINE maxDist = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if not arr [ i ] in map : NEW_LINE INDENT map [ arr [ i ] ] = i NEW_LINE DEDENT if arr [ i ] + K in map : NEW_LINE INDENT maxDist = max ( maxDist , i - map [ arr [ i ] + K ] ) NEW_LINE ...
Count of Ordered Pairs ( X , Y ) satisfying the Equation 1 / X + 1 / Y = 1 / N | Function to find number of ordered positive integer pairs ( x , y ) such that they satisfy the equation ; Initialize answer variable ; Iterate over all possible values of y ; For valid x and y , ( n * n ) % ( y - n ) has to be 0 ; Incremen...
def solve ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE y = n + 1 NEW_LINE while ( y <= n * n + n ) : NEW_LINE INDENT if ( ( n * n ) % ( y - n ) == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT y += 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT n = 5 NEW_LINE solve ( n ) NEW_LINE
Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K | Initialize the adjacency list and visited array ; Function to find the number of root to leaf paths that contain atmost m consecutive nodes with value k ; Mark the current node as visited ; If value at current node is k ; Increment c...
adj = [ [ ] for i in range ( 100005 ) ] NEW_LINE visited = [ 0 for i in range ( 100005 ) ] NEW_LINE ans = 0 ; NEW_LINE def dfs ( node , count , m , arr , k ) : NEW_LINE INDENT global ans NEW_LINE visited [ node ] = 1 ; NEW_LINE if ( arr [ node - 1 ] == k ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT else : NEW_LINE ...
Count of N | Function to calculate and return the reverse of the number ; Function to calculate the total count of N - digit numbers satisfying the necessary conditions ; Initialize two variables ; Calculate the sum of odd and even positions ; Check for divisibility ; Return the answer ; Driver Code
def reverse ( num ) : NEW_LINE INDENT rev = 0 ; NEW_LINE while ( num > 0 ) : NEW_LINE INDENT r = int ( num % 10 ) ; NEW_LINE rev = rev * 10 + r ; NEW_LINE num = num // 10 ; NEW_LINE DEDENT return rev ; NEW_LINE DEDENT def count ( N , A , B ) : NEW_LINE INDENT l = int ( pow ( 10 , N - 1 ) ) ; NEW_LINE r = int ( pow ( 10...
Distance Traveled by Two Trains together in the same Direction | Function to find the distance traveled together ; Stores distance travelled by A ; Stpres distance travelled by B ; Stores the total distance travelled together ; Sum of distance travelled ; Condition for traveling together ; Driver Code
def calc_distance ( A , B , n ) : NEW_LINE INDENT distance_traveled_A = 0 NEW_LINE distance_traveled_B = 0 NEW_LINE answer = 0 NEW_LINE for i in range ( 5 ) : NEW_LINE INDENT distance_traveled_A += A [ i ] NEW_LINE distance_traveled_B += B [ i ] NEW_LINE if ( ( distance_traveled_A == distance_traveled_B ) and ( A [ i ]...
Sum of Nodes and respective Neighbors on the path from root to a vertex V | Creating Adjacency list ; Function to perform DFS traversal ; Initializing parent of each node to p ; Iterate over the children ; Function to add values of children to respective parent nodes ; Root node ; Function to return sum of values of ea...
def constructTree ( n , edges ) : NEW_LINE INDENT adjl = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT adjl . append ( [ ] ) NEW_LINE DEDENT for i in range ( len ( edges ) ) : NEW_LINE INDENT u = edges [ i ] [ 0 ] NEW_LINE v = edges [ i ] [ 1 ] NEW_LINE adjl [ u ] . append ( v ) NEW_LINE adjl [ v ] . append ( u )...
Find a pair in Array with second largest product | Function to find second largest product pair in arr [ 0. . n - 1 ] ; No pair exits ; Initialize max product pair ; Traverse through every possible pair and keep track of largest product ; If pair is largest ; Second largest ; If pair dose not largest but larger then se...
def maxProduct ( arr , N ) : NEW_LINE INDENT if ( N < 3 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT a = arr [ 0 ] ; b = arr [ 1 ] ; NEW_LINE c = 0 ; d = 0 ; NEW_LINE for i in range ( 0 , N , 1 ) : NEW_LINE INDENT for j in range ( i + 1 , N - 1 , 1 ) : NEW_LINE INDENT if ( arr [ i ] * arr [ j ] > a * b ) : NEW_LINE IND...
Count of substrings consisting of even number of vowels | Utility function to check if a character is a vowel ; Function to calculate and return the count of substrings with even number of vowels ; Stores the count of substrings ; If the current character is a vowel ; Increase count ; If substring contains even number ...
def isVowel ( c ) : NEW_LINE INDENT if ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def countSubstrings ( s , n ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for j in ...
Count of substrings consisting of even number of vowels | Utility function to check if a character is a vowel ; Function to calculate and return the count of substrings with even number of vowels ; Stores the count of substrings with even and odd number of vowels respectively ; Update count of vowels modulo 2 in sum to...
def isVowel ( c ) : NEW_LINE INDENT if ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def countSubstrings ( s , n ) : NEW_LINE INDENT temp = [ 1 , 0 ] ; NEW_LINE result = 0 ; NEW_LINE sum = 0 ; NEW_LINE for i in range...
Find the Level of a Binary Tree with Width K | Python3 program to implement the above approach ; Structure of a Tree node ; Function to create new node ; Function returns required level of width k , if found else - 1 ; To store the node and the label and perform traversal ; Taking the last label of each level of the tr...
from collections import deque NEW_LINE 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 findLevel ( root : Node , k : int , level : int ) -> int : NEW_LINE INDENT qt = deque ( ) NEW_LINE qt . a...
Maximize median after doing K addition operation on the Array | Function to check operation can be perform or not ; Number of operation to perform s . t . mid is median ; If mid is median of the array ; Function to find max median of the array ; Lowest possible median ; Highest possible median ; Checking for mid is pos...
def possible ( arr , N , mid , K ) : NEW_LINE INDENT add = 0 NEW_LINE for i in range ( N // 2 - ( N + 1 ) % 2 , N ) : NEW_LINE INDENT if ( mid - arr [ i ] > 0 ) : NEW_LINE INDENT add += ( mid - arr [ i ] ) NEW_LINE if ( add > K ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT if ( add <= K ) : NEW_LINE IN...
Kth Smallest Element of a Matrix of given dimensions filled with product of indices | Function that returns true if the count of elements is less than mid ; To store count of elements less than mid ; Loop through each row ; Count elements less than mid in the ith row ; Function that returns the Kth smallest element in ...
def countLessThanMid ( mid , N , M , K ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , min ( N , mid ) + 1 ) : NEW_LINE INDENT count = count + min ( mid // i , M ) NEW_LINE DEDENT if ( count >= K ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT def f...
Count of substrings containing only the given character | Function that finds the count of substrings containing only character C in the S ; To store total count of substrings ; To store count of consecutive C 's ; Loop through the string ; Increase the consecutive count of C 's ; Add count of sub - strings from consec...
def countSubString ( S , C ) : NEW_LINE INDENT count = 0 NEW_LINE conCount = 0 NEW_LINE for ch in S : NEW_LINE INDENT if ( ch == C ) : NEW_LINE INDENT conCount += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += ( ( conCount * ( conCount + 1 ) ) // 2 ) NEW_LINE conCount = 0 NEW_LINE DEDENT DEDENT count += ( ( conCount...
Check if both halves of a string are Palindrome or not | Function to check if both halves of a string are palindrome or not ; Length of string ; Initialize both part as true ; If first half is not palindrome ; If second half is not palindrome ; If both halves are palindrome ; Driver code
def checkPalindrome ( S ) : NEW_LINE INDENT n = len ( S ) NEW_LINE first_half = True NEW_LINE second_half = True NEW_LINE cnt = ( n // 2 ) - 1 NEW_LINE for i in range ( 0 , int ( ( n / 2 ) / 2 ) ) : NEW_LINE INDENT if ( S [ i ] != S [ cnt ] ) : NEW_LINE INDENT first_half = False NEW_LINE break NEW_LINE DEDENT if ( S [ ...
Count of pairs of strings whose concatenation forms a palindromic string | Python3 program to find palindromic string ; Stores frequency array and its count ; Total number of pairs ; Initializing array of size 26 to store count of character ; Counting occurrence of each character of current string ; Convert each count ...
from collections import defaultdict NEW_LINE def getCount ( N , s ) : NEW_LINE INDENT mp = defaultdict ( lambda : 0 ) NEW_LINE ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT a = [ 0 ] * 26 NEW_LINE for j in range ( len ( s [ i ] ) ) : NEW_LINE INDENT a [ ord ( s [ i ] [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DE...
Kth Smallest element in a Perfect Binary Search Tree | Python3 program to find K - th smallest element in a perfect BST ; A BST node ; A utility function to create a new BST node ; A utility function to insert a new node with given key in BST ; If the tree is empty ; Recur down the left subtree for smaller values ; Rec...
kth_smallest = 0 NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . key = item NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( node , key ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return newNode ( key ) NEW_LINE DED...
Check if given Binary string follows then given condition or not | Function to check if the string follows rules or not ; Check for the first condition ; Check for the third condition ; Check for the second condition ; Driver code ; Given string ; Function call
def checkrules ( s ) : NEW_LINE INDENT if len ( s ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT if s [ 0 ] != '1' : NEW_LINE INDENT return False NEW_LINE DEDENT if len ( s ) > 2 : NEW_LINE INDENT if s [ 1 ] == '0' and s [ 2 ] == '0' : NEW_LINE INDENT return checkrules ( s [ 3 : ] ) NEW_LINE DEDENT DEDENT return ...
Length of longest subsequence in an Array having all elements as Nude Numbers | Function to check if the number is a Nude number ; Variable initialization ; Integer ' copy ' is converted to a string ; Total digits in the number ; Loop through all digits and check if every digit divides n or not ; flag is used to keep c...
def isNudeNum ( n ) : NEW_LINE INDENT flag = 0 NEW_LINE copy = n NEW_LINE temp = str ( copy ) NEW_LINE length = len ( temp ) NEW_LINE for i in range ( length ) : NEW_LINE INDENT num = ord ( temp [ i ] ) - ord ( '0' ) NEW_LINE if ( ( num == 0 ) or ( n % num != 0 ) ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT if (...
Longest subarray with difference exactly K between any two distinct values | Function to return the length of the longest sub - array ; Initialize set ; Store 1 st element of sub - array into set ; Check absolute difference between two elements ; If the new element is not present in the set ; If the set contains two el...
def longestSubarray ( arr , n , k ) : NEW_LINE INDENT Max = 1 NEW_LINE s = set ( ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( abs ( arr [ i ] - arr [ j ] ) == 0 or abs ( arr [ i ] - arr [ j ] ) == k ) : NEW_LINE INDENT if ( not ...
Longest subarray of non | Function to find the maximum length of a subarray of 1 s after removing at most one 0 ; Stores the count of consecutive 1 's from left ; Stores the count of consecutive 1 's from right ; Traverse left to right ; If cell is non - empty ; Increase count ; If cell is empty ; Store the count of co...
def longestSubarray ( a , n ) : NEW_LINE INDENT l = [ 0 ] * ( n ) NEW_LINE r = [ 0 ] * ( n ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT l [ i ] = count NEW_LINE count = 0 NEW_LINE DEDENT DEDENT count = 0 NEW_...
Find largest factor of N such that N / F is less than K | Function to find the value of X ; Loop to check all the numbers divisible by N that yield minimum N / i value ; Prthe value of packages ; Driver code ; Given N and K ; Function call
def findMaxValue ( N , K ) : NEW_LINE INDENT packages = 0 ; NEW_LINE maxi = 1 ; NEW_LINE for i in range ( 1 , K + 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT maxi = max ( maxi , i ) ; NEW_LINE DEDENT DEDENT packages = N // maxi ; NEW_LINE print ( packages ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ...
Largest square which can be formed using given rectangular blocks | Function to find maximum side length of square ; Sort array in asc order ; Traverse array in desc order ; Driver code ; Given array arr [ ] ; Function Call
def maxSide ( a , n ) : NEW_LINE INDENT sideLength = 0 NEW_LINE a . sort NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] > sideLength ) : NEW_LINE INDENT sideLength += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( sideLength ) NEW_LINE DEDENT N = 6 NEW_LINE a...
Count of subtrees from an N | Function to implement DFS traversal ; Mark node v as visited ; Traverse Adj_List of node v ; If current node is not visited ; DFS call for current node ; Count the total red and blue nodes of children of its subtree ; Count the no . of red and blue nodes in the subtree ; If subtree contain...
def Solution_dfs ( v , color , red , blue , sub_red , sub_blue , vis , adj , ans ) : NEW_LINE INDENT vis [ v ] = 1 ; NEW_LINE for i in range ( len ( adj [ v ] ) ) : NEW_LINE INDENT if ( vis [ adj [ v ] [ i ] ] == 0 ) : NEW_LINE INDENT ans = Solution_dfs ( adj [ v ] [ i ] , color , red , blue , sub_red , sub_blue , vis ...
Minimize difference after changing all odd elements to even | Function to minimize the difference between two elements of array ; Find all the element which are possible by multiplying 2 to odd numbers ; Sort the array ; Find the minimum difference Iterate and find which adjacent elements have the minimum difference ; ...
def minDiff ( a , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 2 == 1 ) : NEW_LINE INDENT a . append ( a [ i ] * 2 ) NEW_LINE DEDENT DEDENT a = sorted ( a ) NEW_LINE mindifference = a [ 1 ] - a [ 0 ] NEW_LINE for i in range ( 1 , len ( a ) ) : NEW_LINE INDENT mindifference = min ( mindiff...
Longest subarray having sum K | Set 2 | To store the prefix sum1 array ; Function for searching the lower bound of the subarray ; Iterate until low less than equal to high ; For each mid finding sum1 of sub array less than or equal to k ; Return the final answer ; Function to find the length of subarray with sum1 K ; I...
v = [ ] NEW_LINE def bin1 ( val , k , n ) : NEW_LINE INDENT global v NEW_LINE lo = 0 NEW_LINE hi = n NEW_LINE mid = 0 NEW_LINE ans = - 1 NEW_LINE while ( lo <= hi ) : NEW_LINE INDENT mid = lo + ( ( hi - lo ) // 2 ) NEW_LINE if ( v [ mid ] - val <= k ) : NEW_LINE INDENT lo = mid + 1 NEW_LINE ans = mid NEW_LINE DEDENT el...
Minimum number of reversals to reach node 0 from every other node | Function to find minimum reversals ; Add all adjacent nodes to the node in the graph ; Insert edges in the graph ; Insert edges in the reversed graph ; Create array visited to mark all the visited nodes ; Stores the number of edges to be reversed ; BFS...
def minRev ( edges , n ) : NEW_LINE INDENT graph = dict ( ) NEW_LINE graph_rev = dict ( ) NEW_LINE for i in range ( len ( edges ) ) : NEW_LINE INDENT x = edges [ i ] [ 0 ] ; NEW_LINE y = edges [ i ] [ 1 ] ; NEW_LINE if x not in graph : NEW_LINE INDENT graph [ x ] = [ ] NEW_LINE DEDENT graph [ x ] . append ( y ) ; NEW_L...
Partition a set into two subsets such that difference between max of one and min of other is minimized | Function to split the array ; Sort the array in increasing order ; Calculating the max difference between consecutive elements ; Return the final minimum difference ; Driver Code ; Given array arr [ ] ; Size of arra...
def splitArray ( arr , N ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE result = 10 ** 9 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT result = min ( result , arr [ i ] - arr [ i - 1 ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 1 , 2 , 6 , 4 ] ...
Find the element at R ' th ▁ row ▁ and ▁ C ' th column in given a 2D pattern | Function to find the R ' th ▁ row ▁ and ▁ C ' th column value in the given pattern ; First element of a given row ; Element in the given column ; Driver Code ; Function call
def findValue ( R , C ) : NEW_LINE INDENT k = ( R * ( R - 1 ) ) // 2 + 1 NEW_LINE diff = R + 1 NEW_LINE for i in range ( 1 , C ) : NEW_LINE INDENT k = ( k + diff ) NEW_LINE diff += 1 NEW_LINE DEDENT return k NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT R = 4 NEW_LINE C = 4 NEW_LINE k = findValue ( ...
Maximize number of groups formed with size not smaller than its largest element | Function that prints the number of maximum groups ; Store the number of occurrence of elements ; Make all groups of similar elements and store the left numbers ; Condition for finding first leftover element ; Condition for current leftove...
def makeGroups ( a , n ) : NEW_LINE INDENT v = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT v [ a [ i ] ] += 1 NEW_LINE DEDENT no_of_groups = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT no_of_groups += v [ i ] // i NEW_LINE v [ i ] = v [ i ] % i NEW_LINE DEDENT i = 1 NEW_LINE total = ...
Leftmost Column with atleast one 1 in a row | Python3 program to calculate leftmost column having at least a 1 ; Function return leftmost column having at least a 1 ; If current element is 1 decrement column by 1 ; If current element is 0 increment row by 1 ; Driver Code
N = 3 NEW_LINE M = 4 NEW_LINE def findColumn ( mat : list ) -> int : NEW_LINE INDENT row = 0 NEW_LINE col = M - 1 NEW_LINE while row < N and col >= 0 : NEW_LINE INDENT if mat [ row ] [ col ] == 1 : NEW_LINE INDENT col -= 1 NEW_LINE flag = 1 NEW_LINE DEDENT else : NEW_LINE INDENT row += 1 NEW_LINE DEDENT DEDENT col += 1...
Find two numbers made up of a given digit such that their difference is divisible by N | Function to implement the above approach ; Hashmap to store remainder - length of the number as key - value pairs ; Iterate till N + 1 length ; Search remainder in the map ; If remainder is not already present insert the length for...
def findNumbers ( N , M ) : NEW_LINE INDENT m = M NEW_LINE remLen = { } NEW_LINE for len1 in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT remainder = M % N NEW_LINE if ( remLen . get ( remainder ) == None ) : NEW_LINE INDENT remLen [ remainder ] = len1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT M = M * 1...
Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements | 2D prefix sum for submatrix sum query for matrix ; Function to find the prefix sum of the matrix from i and j ; Function to count the number of ways to select equal sized subarrays such that they have atleast K com...
prefix_2D = [ [ 0 for x in range ( 2005 ) ] for y in range ( 2005 ) ] NEW_LINE def subMatrixSum ( i , j , length ) : NEW_LINE INDENT return ( prefix_2D [ i ] [ j ] - prefix_2D [ i ] [ j - length ] - prefix_2D [ i - length ] [ j ] + prefix_2D [ i - length ] [ j - length ] ) NEW_LINE DEDENT def numberOfWays ( a , b , n ,...
Find lexicographically smallest string in at most one swaps | Function to return the lexicographically smallest string that can be formed by swapping at most one character . The characters might not necessarily be adjacent . ; Set - 1 as default for every character . ; Character index to fill in the last occurrence arr...
def findSmallest ( s ) : NEW_LINE INDENT length = len ( s ) ; NEW_LINE loccur = [ - 1 ] * 26 ; NEW_LINE for i in range ( length - 1 , - 1 , - 1 ) : NEW_LINE INDENT chI = ord ( s [ i ] ) - ord ( ' a ' ) ; NEW_LINE if ( loccur [ chI ] == - 1 ) : NEW_LINE INDENT loccur [ chI ] = i ; NEW_LINE DEDENT DEDENT sorted_s = s ; N...
Maximum size of square such that all submatrices of that size have sum less than K | Function to preprocess the matrix for computing the sum of every possible matrix of the given size ; Loop to copy the first row of the matrix into the aux matrix ; Computing the sum column - wise ; Computing row wise sum ; Function to ...
def preProcess ( mat , aux ) : NEW_LINE INDENT for i in range ( 5 ) : NEW_LINE INDENT aux [ 0 ] [ i ] = mat [ 0 ] [ i ] NEW_LINE DEDENT for i in range ( 1 , 4 ) : NEW_LINE INDENT for j in range ( 5 ) : NEW_LINE INDENT aux [ i ] [ j ] = ( mat [ i ] [ j ] + aux [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT for i in range ( 4 ...
Length of Longest Subarray with same elements in atmost K increments | Initialize array for segment tree ; Function that builds the segment tree to return the max element in a range ; update the value in segment tree from given array ; find the middle index ; If there are more than one elements , then recur for left an...
segment_tree = [ 0 ] * ( 4 * 1000000 ) ; NEW_LINE def build ( A , start , end , node ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT segment_tree [ node ] = A [ start ] ; NEW_LINE DEDENT else : NEW_LINE INDENT mid = ( start + end ) // 2 ; NEW_LINE segment_tree [ node ] = max ( build ( A , start , mid , 2 * no...
Count of numbers from range [ L , R ] that end with any of the given digits | Function to return the count of the required numbers ; Last digit of the current number ; If the last digit is equal to any of the given digits ; Driver code
def countNums ( l , r ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT lastDigit = ( i % 10 ) ; NEW_LINE if ( ( lastDigit % 10 ) == 2 or ( lastDigit % 10 ) == 3 or ( lastDigit % 10 ) == 9 ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ ...
Minimum K such that sum of array elements after division by K does not exceed S | Function to return the minimum value of k that satisfies the given condition ; Find the maximum element ; Lowest answer can be 1 and the highest answer can be ( maximum + 1 ) ; Binary search ; Get the mid element ; Calculate the sum after...
def findMinimumK ( a , n , s ) : NEW_LINE INDENT maximum = a [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT maximum = max ( maximum , a [ i ] ) NEW_LINE DEDENT low = 1 NEW_LINE high = maximum + 1 NEW_LINE ans = high NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE sum = 0 NEW_L...
Calculate the Sum of GCD over all subarrays | Python3 program to find Sum of GCD over all subarrays ; ; Build Sparse Table ; Building the Sparse Table for GCD [ L , R ] Queries ; Utility Function to calculate GCD in range [ L , R ] ; Calculating where the answer is stored in our Sparse Table ; Utility Function to find...
from math import gcd as __gcd , log , floor NEW_LINE / * int a [ 100001 ] ; * / NEW_LINE SparseTable = [ [ 0 for i in range ( 51 ) ] for i in range ( 100001 ) ] NEW_LINE def buildSparseTable ( a , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT SparseTable [ i ] [ 0 ] = a [ i ] NEW_LINE DEDENT for j in ran...
QuickSelect ( A Simple Iterative Implementation ) | Standard Lomuto partition function ; Implementation of QuickSelect ; Partition a [ left . . right ] around a pivot and find the position of the pivot ; If pivot itself is the k - th smallest element ; If there are more than k - 1 elements on left of pivot , then k - t...
def partition ( arr , low , high ) : NEW_LINE INDENT pivot = arr [ high ] NEW_LINE i = ( low - 1 ) NEW_LINE for j in range ( low , high ) : NEW_LINE INDENT if arr [ j ] <= pivot : NEW_LINE INDENT i += 1 NEW_LINE arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE DEDENT DEDENT arr [ i + 1 ] , arr [ high ] = arr [ hi...
Pair with largest sum which is less than K in the array | Function to find pair with largest sum which is less than K in the array ; To store the break point ; Sort the given array ; Find the break point ; No need to look beyond i 'th index ; Find the required pair ; Print the required answer ; Driver code ; Function c...
def Max_Sum ( arr , n , k ) : NEW_LINE INDENT p = n NEW_LINE arr . sort ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] >= k ) : NEW_LINE INDENT p = i NEW_LINE break NEW_LINE DEDENT DEDENT maxsum = 0 NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE for i in range ( 0 , p ) : NEW_LINE INDENT for j in range ...
Maximum length palindromic substring such that it starts and ends with given char | Function that returns true if str [ i ... j ] is a palindrome ; Function to return the length of the longest palindromic sub - string such that it starts and ends with the character ch ; If current character is a valid starting index ; ...
def isPalindrome ( str , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT if ( str [ i ] != str [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def maxLenPalindrome ( str , n , ch ) : NEW_LINE INDENT maxLen = 0 ; NEW_LINE for i...
Longest sub | Function to find the starting and the ending index of the sub - array with equal number of alphabets and numeric digits ; If its an alphabet ; Else its a number ; Pick a starting poas i ; Consider all sub - arrays starting from i ; If this is a 0 sum sub - array then compare it with maximum size sub - arr...
def findSubArray ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE maxsize = - 1 NEW_LINE startindex = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] . isalpha ( ) ) : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( n - 1 ) : NEW_...
Check if given string can be formed by two other strings or their permutations | Python 3 implementation of the approach ; Function to sort the given string using counting sort ; Array to store the count of each character ; Insert characters in the string in increasing order ; Function that returns true if str can be g...
MAX = 26 NEW_LINE def countingsort ( s ) : NEW_LINE INDENT count = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT count [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT index = 0 NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < count [ i ] ) : NE...
Queries to find the first non | Maximum distinct characters possible ; To store the frequency of the characters ; Function to pre - calculate the frequency array ; Only the first character has frequency 1 till index 0 ; Starting from the second character of the string ; For every possible character ; Current character ...
MAX = 256 NEW_LINE freq = [ [ 0 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE def preCalculate ( string , n ) : NEW_LINE INDENT freq [ ord ( string [ 0 ] ) ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ch = string [ i ] NEW_LINE for j in range ( MAX ) : NEW_LINE INDENT charToUpdate = chr ...
Length of the largest substring which have character with frequency greater than or equal to half of the substring | Python3 implementation of the above approach ; Function to return the length of the longest sub string having frequency of a character greater than half of the length of the sub string ; for each of the ...
import sys NEW_LINE def maxLength ( s , n ) : NEW_LINE INDENT ans = - ( sys . maxsize + 1 ) ; NEW_LINE A , L , R = [ ] , [ ] , [ ] ; NEW_LINE freq = [ 0 ] * ( n + 5 ) ; NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 26 ) : NEW_LINE INDENT count = 0 ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( ord ( s [ j ...
Repeated Character Whose First Appearance is Leftmost | Python3 program to find first repeating character ; The function returns index of the first repeating character in a string . If all characters are repeating then returns - 1 ; Mark all characters as not visited ; Traverse from right and update res as soon as we s...
NO_OF_CHARS = 256 NEW_LINE def firstRepeating ( string ) : NEW_LINE INDENT visited = [ False ] * NO_OF_CHARS ; NEW_LINE for i in range ( NO_OF_CHARS ) : NEW_LINE INDENT visited [ i ] = False ; NEW_LINE DEDENT res = - 1 ; NEW_LINE for i in range ( len ( string ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( visited [ string ...
Find maximum sum taking every Kth element in the array | Function to return the maximum sum for every possible sequence such that a [ i ] + a [ i + k ] + a [ i + 2 k ] + ... + a [ i + qk ] is maximized ; Initialize the maximum with the smallest value ; Initialize the sum array with zero ; Iterate from the right ; Updat...
def maxSum ( arr , n , K ) : NEW_LINE INDENT maximum = - 2 ** 32 ; NEW_LINE sum = [ 0 ] * n NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( i + K < n ) : NEW_LINE INDENT sum [ i ] = sum [ i + K ] + arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT sum [ i ] = arr [ i ] ; NEW_LINE DEDENT maximum = ma...
Count common characters in two strings | Function to return the count of valid indices pairs ; To store the frequencies of characters of string s1 and s2 ; To store the count of valid pairs ; Update the frequencies of the characters of string s1 ; Update the frequencies of the characters of string s2 ; Find the count o...
def countPairs ( s1 , n1 , s2 , n2 ) : NEW_LINE INDENT freq1 = [ 0 ] * 26 ; NEW_LINE freq2 = [ 0 ] * 26 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT freq1 [ ord ( s1 [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( n2 ) : NEW_LINE INDENT freq2 [ ord ( s2 [ i ] ) - ord ( ' a '...
Find a distinct pair ( x , y ) in given range such that x divides y | Python 3 implementation of the approach ; Driver Code
def findpair ( l , r ) : NEW_LINE INDENT c = 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , r + 1 ) : NEW_LINE INDENT if ( j % i == 0 and j != i ) : NEW_LINE INDENT print ( i , " , ▁ " , j ) NEW_LINE c = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( c == 1 ) : NEW_LINE INDENT break NE...
Check if the given array can be reduced to zeros with the given operation performed given number of times | Function that returns true if the array can be reduced to 0 s with the given operation performed given number of times ; Set to store unique elements ; Add every element of the array to the set ; Count of all the...
def check ( arr , N , K ) : NEW_LINE INDENT unique = dict ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT unique [ arr [ i ] ] = 1 NEW_LINE DEDENT if len ( unique ) == K : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT arr = [ 1 , 1 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LIN...
Print all the sum pairs which occur maximum number of times | Function to find the sum pairs that occur the most ; Hash - table ; Keep a count of sum pairs ; Variables to store maximum occurrence ; Iterate in the hash table ; Print all sum pair which occur maximum number of times ; Driver code
def findSumPairs ( a , n ) : NEW_LINE INDENT mpp = { i : 0 for i in range ( 21 ) } NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n , 1 ) : NEW_LINE INDENT mpp [ a [ i ] + a [ j ] ] += 1 NEW_LINE DEDENT DEDENT occur = 0 NEW_LINE for key , value in mpp . items ( ) : NEW_LINE INDENT if ( val...
Minimum index i such that all the elements from index i to given index are equal | Function to return the minimum required index ; Start from arr [ pos - 1 ] ; All elements are equal from arr [ i + 1 ] to arr [ pos ] ; Driver code ; Function Call
def minIndex ( arr , n , pos ) : NEW_LINE INDENT num = arr [ pos ] NEW_LINE i = pos - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( arr [ i ] != num ) : NEW_LINE INDENT break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return i + 1 NEW_LINE DEDENT arr = [ 2 , 1 , 1 , 1 , 5 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE pos = ...
Minimum index i such that all the elements from index i to given index are equal | Function to return the minimum required index ; Short - circuit more comparisions as found the border point ; For cases were high = low + 1 and arr [ high ] will match with arr [ pos ] but not arr [ low ] or arr [ mid ] . In such iterati...
def minIndex ( arr , pos ) : NEW_LINE INDENT low = 0 NEW_LINE high = pos NEW_LINE i = pos NEW_LINE while low < high : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if arr [ mid ] != arr [ pos ] : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE i = mid NEW_LINE if mid > ...
Count of strings that become equal to one of the two strings after one removal | Python3 implementation of the approach ; Function to return the count of the required strings ; Searching index after longest common prefix ends ; Searching index before longest common suffix ends ; ; If only 1 character is different in b...
import math as mt NEW_LINE def findAnswer ( str1 , str2 , n ) : NEW_LINE INDENT l , r = 0 , 0 NEW_LINE ans = 2 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ i ] ) : NEW_LINE INDENT l = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( str1 [ ...
Minimize the maximum minimum difference after one removal from array | Function to return the minimum required difference ; Sort the given array ; When minimum element is removed ; When maximum element is removed ; Return the minimum of diff1 and diff2 ; Driver Code
def findMinDifference ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE diff1 = arr [ n - 1 ] - arr [ 1 ] NEW_LINE diff2 = arr [ n - 2 ] - arr [ 0 ] NEW_LINE return min ( diff1 , diff2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE p...
Minimize the maximum minimum difference after one removal from array | Function to return the minimum required difference ; If current element is greater than max ; max will become secondMax ; Update the max ; If current element is greater than secondMax but smaller than max ; Update the secondMax ; If current element ...
def findMinDifference ( arr , n ) : NEW_LINE INDENT if ( arr [ 0 ] < arr [ 1 ] ) : NEW_LINE INDENT min__ = secondMax = arr [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT min__ = secondMax = arr [ 1 ] NEW_LINE DEDENT if ( arr [ 0 ] < arr [ 1 ] ) : NEW_LINE INDENT max__ = secondMin = arr [ 1 ] NEW_LINE DEDENT else : NEW_LI...
Integers from the range that are composed of a single distinct digit | Boolean function to check distinct digits of a number ; Take last digit ; Check if all other digits are same as last digit ; Remove last digit ; Function to return the count of integers that are composed of a single distinct digit only ; If i has si...
def checkDistinct ( x ) : NEW_LINE INDENT last = x % 10 NEW_LINE while ( x ) : NEW_LINE INDENT if ( x % 10 != last ) : NEW_LINE INDENT return False NEW_LINE DEDENT x = x // 10 NEW_LINE DEDENT return True NEW_LINE DEDENT def findCount ( L , R ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE...
Smallest Pair Sum in an array | Python3 program to print the sum of the minimum pair ; Function to return the sum of the minimum pair from the array ; If found new minimum ; Minimum now becomes second minimum ; Update minimum ; If current element is > min and < secondMin ; Update secondMin ; Return the sum of the minim...
import sys NEW_LINE def smallest_pair ( a , n ) : NEW_LINE INDENT min = sys . maxsize NEW_LINE secondMin = sys . maxsize NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( a [ j ] < min ) : NEW_LINE INDENT secondMin = min NEW_LINE min = a [ j ] NEW_LINE DEDENT elif ( ( a [ j ] < secondMin ) and a [ j ] != min ) : NEW...
Longest subarray with elements divisible by k | function to find longest subarray ; this will contain length of longest subarray found ; Driver code
def longestsubarray ( arr , n , k ) : NEW_LINE INDENT current_count = 0 NEW_LINE max_count = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( arr [ i ] % k == 0 ) : NEW_LINE INDENT current_count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT current_count = 0 NEW_LINE DEDENT max_count = max ( current_count ,...
Remove elements that appear strictly less than k times | Python3 program to remove the elements which appear strictly less than k times from the array . ; Hash map which will store the frequency of the elements of the array . ; Incrementing the frequency of the element by 1. ; Print the element which appear more than o...
def removeElements ( arr , n , k ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] = mp . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] in mp and mp [ arr [ i ] ] >= k ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " )...
Check if a string contains a palindromic sub | function to check if two consecutive same characters are present ; Driver Code
def check ( s ) : NEW_LINE INDENT for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT s = " xzyyz " NEW_LINE if ( check ( s ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ...
Remove elements from the array which appear more than k times | Python 3 program to remove the elements which appear more than k times from the array . ; Hash map which will store the frequency of the elements of the array . ; Incrementing the frequency of the element by 1. ; Print the element which appear less than or...
def RemoveElements ( arr , n , k ) : NEW_LINE INDENT mp = { i : 0 for i in range ( len ( arr ) ) } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( mp [ arr [ i ] ] <= k ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT...
Find the smallest after deleting given elements | Python3 program to find the smallest number from the array after n deletions ; Returns maximum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; Hash Map of the numbers to be deleted ; Increment the count of del [ i ] ; Initializing the S...
import math as mt NEW_LINE def findSmallestAfterDel ( arr , m , dell , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if dell [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ dell [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ dell [ i ] ] = 1 NEW_LINE DEDENT DEDENT SmallestE...
Find the largest after deleting the given elements | Python3 program to find the largest number from the array after n deletions ; Returns maximum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; Hash Map of the numbers to be deleted ; Increment the count of del [ i ] ; Initializing the...
import math as mt NEW_LINE def findlargestAfterDel ( arr , m , dell , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if dell [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ dell [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ dell [ i ] ] = 1 NEW_LINE DEDENT DEDENT largestEle...
Number of anomalies in an array | A simple Python3 solution to count anomalies in an array . ; Driver Code
def countAnomalies ( arr , n , k ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT j = 0 NEW_LINE while j < n : NEW_LINE INDENT if i != j and abs ( arr [ i ] - arr [ j ] ) <= k : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if j == n : NEW_LINE INDENT res += 1 NEW_LINE DEDE...
Count majority element in a matrix | Function to find count of all majority elements in a Matrix ; Store frequency of elements in matrix ; loop to iteratre through map ; check if frequency is greater than or equal to ( N * M ) / 2 ; Driver Code
def majorityInMatrix ( arr ) : NEW_LINE INDENT mp = { i : 0 for i in range ( 7 ) } NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT for j in range ( len ( arr ) ) : NEW_LINE INDENT mp [ arr [ i ] [ j ] ] += 1 NEW_LINE DEDENT DEDENT countMajority = 0 NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT ...
Find pair with maximum difference in any column of a Matrix | Function to find the column with max difference ; Traverse matrix column wise ; Insert elements of column to vector ; calculating difference between maximum and minimum ; Driver Code
def colMaxDiff ( mat ) : NEW_LINE INDENT max_diff = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT max_val = mat [ 0 ] [ i ] NEW_LINE min_val = mat [ 0 ] [ i ] NEW_LINE for j in range ( 1 , N ) : NEW_LINE INDENT max_val = max ( max_val , mat [ j ] [ i ] ) NEW_LINE min_val = min ( min_val , mat [ j ] [ i ] ) NEW_LINE...
Find the Missing Number in a sorted array | A binary search based program to find the only missing number in a sorted in a sorted array of distinct elements within limited range ; Driver Code
def search ( ar , size ) : NEW_LINE INDENT a = 0 NEW_LINE b = size - 1 NEW_LINE mid = 0 NEW_LINE while b > a + 1 : NEW_LINE INDENT mid = ( a + b ) // 2 NEW_LINE if ( ar [ a ] - a ) != ( ar [ mid ] - mid ) : NEW_LINE INDENT b = mid NEW_LINE DEDENT elif ( ar [ b ] - b ) != ( ar [ mid ] - mid ) : NEW_LINE INDENT a = mid N...
Delete array element in given index range [ L | Function to delete L to R element ; Return size of Array after delete element ; Driver Code
def deleteElement ( A , L , R , N ) : NEW_LINE INDENT j = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if i <= L or i >= R : NEW_LINE INDENT A [ j ] = A [ i ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return j NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 5 , 8 , 11 , 15 , 26 , 14 , 19 , 17 ...
Longest subarray having average greater than or equal to x | Function to find index in preSum list of tuples upto which all prefix sum values are less than or equal to val . ; Starting and ending index of search space . ; To store required index value ; If middle value is less than or equal to val then index can lie in...
def findInd ( preSum , n , val ) : NEW_LINE INDENT l = 0 NEW_LINE h = n - 1 NEW_LINE ans = - 1 NEW_LINE while ( l <= h ) : NEW_LINE INDENT mid = ( l + h ) // 2 NEW_LINE if preSum [ mid ] [ 0 ] <= val : NEW_LINE INDENT ans = mid NEW_LINE l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT h = mid - 1 NEW_LINE DEDENT DEDE...