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 tree ; Store the count of balanced nodes
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 . left ) NEW_LINE rightSubSum = Sum ( root . right ) NEW_LINE if ( root . left and root . right and leftSubSum == rightSubSum ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT return ( root . data + leftSubSum + rightSubSum ) NEW_LINE DEDENT root = Node ( 9 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . left . left = Node ( - 1 ) NEW_LINE root . left . right = Node ( 3 ) NEW_LINE root . right = Node ( 4 ) NEW_LINE root . right . right = Node ( 0 ) NEW_LINE global res NEW_LINE res = 0 NEW_LINE Sum ( root ) NEW_LINE print ( res ) NEW_LINE
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 ; Driver Code ; Create a tree
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 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT temp = Q [ 0 ] NEW_LINE Q . remove ( Q [ 0 ] ) NEW_LINE if ( i % 2 == 0 ) : NEW_LINE INDENT print ( temp . data , end = " ▁ " ) NEW_LINE DEDENT if ( temp . left ) : NEW_LINE INDENT Q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT Q . append ( temp . right ) NEW_LINE DEDENT DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 71 ) NEW_LINE root . left = newNode ( 88 ) NEW_LINE root . right = newNode ( 99 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . left . left . left = newNode ( 8 ) NEW_LINE root . left . left . right = newNode ( 9 ) NEW_LINE root . left . right . left = newNode ( 10 ) NEW_LINE root . left . right . right = newNode ( 11 ) NEW_LINE root . right . left . right = newNode ( 13 ) NEW_LINE root . right . right . left = newNode ( 14 ) NEW_LINE PrintAlternate ( root ) NEW_LINE DEDENT
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 there is no next smaller element right to it than taking n . ; Taking exact boundaries in which arr [ i ] is minimum ; Similarly for right side ; Driver code ; Given array arr [ ] ; Function call
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_LINE INDENT del st [ - 1 ] NEW_LINE DEDENT if ( len ( st ) > 0 ) : NEW_LINE INDENT nsmr [ i ] = st [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT nsmr [ i ] = n NEW_LINE DEDENT st . append ( i ) NEW_LINE DEDENT while ( len ( st ) > 0 ) : NEW_LINE INDENT del st [ - 1 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT while ( len ( st ) > 0 and arr [ st [ - 1 ] ] >= arr [ i ] ) : NEW_LINE INDENT del st [ - 1 ] NEW_LINE DEDENT if ( len ( st ) > 0 ) : NEW_LINE INDENT nsml [ i ] = st [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT nsml [ i ] = - 1 NEW_LINE DEDENT st . append ( i ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT nsml [ i ] += 1 NEW_LINE nsmr [ i ] -= 1 NEW_LINE r = nsmr [ i ] - i + 1 ; NEW_LINE l = i - nsml [ i ] + 1 ; NEW_LINE a [ i ] = r * l ; NEW_LINE DEDENT return a ; NEW_LINE DEDENT N = 5 NEW_LINE arr = [ 3 , 2 , 4 , 1 , 5 ] NEW_LINE a = countingSubarray ( arr , N ) NEW_LINE print ( a ) NEW_LINE
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 ; Declare the reordered string ; Loop until freq [ j ] > 0 ; Decrement the value from freq array ; Check if A [ j ] > A [ 0 ] ; Check if A [ j ] < A [ 0 ] ; Append the remaining characters to the end of the result ; Push all the values from frequency array in the answer ; Return the answer ; Driver Code ; Given strings A and B ; Function call
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 range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT if ( freq [ j ] < 0 ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT DEDENT answer = [ ] NEW_LINE for j in range ( ord ( ' a ' ) , ord ( A [ 0 ] ) ) : NEW_LINE INDENT while ( freq [ j ] > 0 ) : NEW_LINE INDENT answer . append ( j ) NEW_LINE freq [ j ] -= 1 NEW_LINE DEDENT DEDENT first = A [ 0 ] NEW_LINE for j in range ( size_a ) : NEW_LINE INDENT if ( A [ j ] > A [ 0 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( A [ j ] < A [ 0 ] ) : NEW_LINE INDENT answer += A NEW_LINE A = " " NEW_LINE break NEW_LINE DEDENT DEDENT while ( freq [ ord ( first ) ] > 0 ) : NEW_LINE INDENT answer . append ( first ) NEW_LINE freq [ ord ( first ) ] -= 1 NEW_LINE DEDENT answer += A NEW_LINE for j in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT while ( freq [ j ] ) : NEW_LINE INDENT answer . append ( chr ( j ) ) NEW_LINE freq [ j ] -= 1 NEW_LINE DEDENT DEDENT return " " . join ( answer ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = " aa " NEW_LINE B = " ababab " NEW_LINE print ( reorderString ( A , B ) ) NEW_LINE DEDENT
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 ( l , r , k ) : NEW_LINE INDENT arr = list ( range ( l , r + 1 ) ) NEW_LINE result = [ ] NEW_LINE for i in arr : NEW_LINE INDENT result . append ( [ i , func ( i ) ] ) NEW_LINE DEDENT result . sort ( ) NEW_LINE print ( result [ k - 1 ] [ 0 ] ) NEW_LINE DEDENT l = 12 NEW_LINE r = 15 NEW_LINE k = 2 NEW_LINE findKthElement ( l , r , k ) NEW_LINE
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 array arr [ ] ; Function Call
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 else : NEW_LINE INDENT dp [ d ] [ j ] = 2 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT dp [ d ] = { } NEW_LINE dp [ d ] [ j ] = 2 NEW_LINE DEDENT if d in dp : NEW_LINE INDENT if j in dp [ d ] : NEW_LINE INDENT res = max ( res , dp [ d ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return res NEW_LINE DEDENT / * Driver Code * / NEW_LINE arr = [ 20 , 1 , 15 , 3 , 10 , 5 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE print ( lenghtOfLongestAP ( arr , N ) ) NEW_LINE
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 to non - prime ; Function which computes the length of the LIS of Prime Numbers ; Create an array of size n ; Create boolean array to mark prime numbers ; Precompute N primes ; Compute optimized LIS having prime numbers in bottom up manner ; check for LIS and prime ; Return maximum value in lis [ ] ; Driver Code ; Given array ; Size of array ; Function Call
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 NEW_LINE DEDENT DEDENT DEDENT def LISPrime ( arr , n ) : NEW_LINE INDENT lisp = [ 0 ] * n NEW_LINE prime = [ True ] * ( N + 1 ) NEW_LINE SieveOfEratosthenes ( prime , N ) NEW_LINE if prime [ arr [ 0 ] ] : NEW_LINE INDENT lisp [ 0 ] = 1 NEW_LINE else : NEW_LINE lisp [ 0 ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( not prime [ arr [ i ] ] ) : NEW_LINE lisp [ i ] = 0 NEW_LINE continue NEW_LINE lisp [ i ] = 1 NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( prime [ arr [ j ] ] and arr [ i ] > arr [ j ] and lisp [ i ] < lisp [ j ] + 1 ) : NEW_LINE lisp [ i ] = lisp [ j ] + 1 NEW_LINE return max ( lisp ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 3 , 2 , 5 , 1 , 7 ] NEW_LINE M = len ( arr ) NEW_LINE print ( LISPrime ( arr , M ) ) NEW_LINE DEDENT
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 special number ; Driver Code ; Function Call
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 DEDENT i += 1 NEW_LINE DEDENT if flag : NEW_LINE INDENT print ( ' YES ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' NO ' ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 25 NEW_LINE checkSumOfNatural ( n ) NEW_LINE DEDENT
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 based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; Return C ( 2 n , n ) / ( n + 1 ) ; Function to find possible ways to put balanced parenthesis in an expression of length n ; If n is odd , not possible to create any valid parentheses ; Otherwise return n / 2 th Catalan Number ; Difference between counting ways of 2 * N and N is the result ; Given value of N ; Function call
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 * n , n ) NEW_LINE return c // ( n + 1 ) NEW_LINE DEDENT def findWays ( n ) : NEW_LINE INDENT if ( ( n & 1 ) == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return catalan ( n // 2 ) NEW_LINE DEDENT def countNonNPeriodic ( N ) : NEW_LINE INDENT print ( findWays ( 2 * N ) - findWays ( N ) ) NEW_LINE DEDENT N = 4 NEW_LINE countNonNPeriodic ( N ) NEW_LINE
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 checked ; Function Call
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 : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m , n = 6 , 5 NEW_LINE li = [ [ 32 , 94 , 99 , 26 , 82 ] , [ 51 , 69 , 52 , 63 , 17 ] , [ 90 , 36 , 88 , 55 , 33 ] , [ 93 , 42 , 73 , 39 , 28 ] , [ 81 , 31 , 83 , 53 , 10 ] , [ 12 , 29 , 85 , 80 , 87 ] ] NEW_LINE x , y = 42 , 80 NEW_LINE checkSameDiag ( x , y ) NEW_LINE DEDENT
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 ; Function to find the number of operations of type 1 required ; Iterate over the range ; Find the value of mid ; Check if m steps of type 1 are valid or not ; If mid is the valid number of steps ; If no valid number of steps exist ; Given and N , K ; Function call
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 = 0 NEW_LINE end = n NEW_LINE ok = 1 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE temp = isValid ( n , mid , k ) NEW_LINE if ( temp == 0 ) : NEW_LINE INDENT ok = 0 NEW_LINE print ( mid ) NEW_LINE break NEW_LINE DEDENT elif ( temp == 1 ) : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT if ( ok ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE K = 4 NEW_LINE countOfOperations ( N , K ) NEW_LINE
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 given integer ; Function to return the decodings ; Base case ; Recursive call ; Stores the characters of two digit numbers ; Extract first digit and first two digits ; Check if it lies in the range of alphabets ; Next recursive call ; Combine both the output in a single readonly output array ; Index of readonly output array ; Store the elements of output1 in readonly output array ; Store the elements of output2 in readonly output array ; Result the result ; Driver Code ; Function call ; Print function call
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 ] ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT print ( output [ i ] ) NEW_LINE DEDENT DEDENT def getChar ( n ) : NEW_LINE INDENT return chr ( n + 96 ) NEW_LINE DEDENT def getCode ( str ) : NEW_LINE INDENT if ( len ( str ) == 0 ) : NEW_LINE INDENT ans = [ " " ] NEW_LINE return ans NEW_LINE DEDENT output1 = getCode ( str [ 1 : ] ) NEW_LINE output2 = [ ] NEW_LINE firstDigit = ( ord ( str [ 0 ] ) - ord ( '0' ) ) NEW_LINE firstTwoDigit = 0 NEW_LINE if ( len ( str ) >= 2 ) : NEW_LINE firstTwoDigit = ( ( ord ( str [ 0 ] ) - ord ( '0' ) ) * 10 + ( ord ( str [ 1 ] ) - ord ( '0' ) ) ) NEW_LINE if ( firstTwoDigit >= 10 and firstTwoDigit <= 26 ) : NEW_LINE INDENT output2 = getCode ( str [ 2 : ] ) NEW_LINE DEDENT output = [ ' ' for i in range ( len ( output1 ) + len ( output2 ) ) ] NEW_LINE k = 0 NEW_LINE for i in range ( len ( output1 ) ) : NEW_LINE INDENT ch = getChar ( firstDigit ) NEW_LINE output [ i ] = ch + output1 [ i ] NEW_LINE k += 1 NEW_LINE DEDENT for i in range ( len ( output2 ) ) : NEW_LINE INDENT ch = getChar ( firstTwoDigit ) NEW_LINE output [ k ] = ch + output2 [ i ] NEW_LINE k += 1 NEW_LINE DEDENT return output NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT input = "101" NEW_LINE output = getCode ( input ) NEW_LINE printCodes ( output ) NEW_LINE DEDENT
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 expressed as sum of consecutive prime numbers ; Initialize count as 0 ; Stores prime numbers ; If i is prime ; Initialize the sum ; Find all required primes upto N ; Add it to the sum ; Return the final count ; Given number N ; Function call
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 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def countprime ( n ) : NEW_LINE INDENT count = 0 NEW_LINE primevector = [ ] NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( isprm ( i ) == 1 ) : NEW_LINE INDENT primevector . append ( i ) NEW_LINE DEDENT DEDENT sum = primevector [ 0 ] NEW_LINE for i in range ( 1 , len ( primevector ) ) : NEW_LINE INDENT sum += primevector [ i ] NEW_LINE if ( sum > n ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( isprm ( sum ) == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT N = 45 NEW_LINE print ( countprime ( N ) ) NEW_LINE
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 elements ; If the first k elements have a sum as perfect square ; Iterate through the array ; If sum is perfect square ; If subarray not found ; Driver Code ; Given array ; Given subarray size K ; Function call
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 sum += arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT found = False NEW_LINE if ( isPerfectSquare ( sum ) ) : NEW_LINE INDENT ans [ 0 ] = 0 NEW_LINE ans [ 1 ] = i - 1 NEW_LINE DEDENT else : NEW_LINE INDENT for j in range ( i , len ( arr ) ) : NEW_LINE INDENT sum = sum + arr [ j ] - arr [ j - k ] NEW_LINE if ( isPerfectSquare ( sum ) ) : NEW_LINE INDENT found = True NEW_LINE ans [ 0 ] = j - k + 1 NEW_LINE ans [ 1 ] = j NEW_LINE DEDENT DEDENT for k in range ( ans [ 0 ] , ans [ 1 ] + 1 ) : NEW_LINE INDENT print ( arr [ k ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if ( found == False ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 20 , 34 , 51 , 10 , 99 , 87 , 23 , 45 ] NEW_LINE K = 3 NEW_LINE SubarrayHavingPerfectSquare ( arr , K ) NEW_LINE DEDENT
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 the last digit ; Function that returns true if a and b are anagrams of each other ; To store the frequencies of the digits in a and b ; Update the frequency of the digits in a ; Update the frequency of the digits in b ; Match the frequencies of the common digits ; If frequency differs for any digit then the numbers are not anagrams of each other ; Function to check if any permutation of a number is a power of 2 or not ; Iterate over all possible perfect power of 2 ; Print that number ; Given number N ; Function call
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_LINE updateFreq ( b , freqB ) NEW_LINE for i in range ( TEN ) : NEW_LINE INDENT if ( freqA [ i ] != freqB [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isPowerOf2 ( N ) : NEW_LINE INDENT for i in range ( 32 ) : NEW_LINE INDENT if ( areAnagrams ( 1 << i , N ) ) : NEW_LINE INDENT print ( 1 << i ) NEW_LINE return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT N = 46 NEW_LINE if ( isPowerOf2 ( N ) == 0 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 count NEW_LINE DEDENT n = 5 NEW_LINE print ( right_angled ( n ) ) NEW_LINE
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 column ; Reset column to 0 for new row ; Increment row ; Driver code ; Given 2 matrices ; Function call
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 += 1 NEW_LINE DEDENT col = 0 NEW_LINE row += 1 NEW_LINE DEDENT if ( isMirrorImage ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE mat1 = [ [ 1 , 2 , 3 , 4 ] , [ 0 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] NEW_LINE mat2 = [ [ 4 , 3 , 2 , 1 ] , [ 8 , 7 , 6 , 0 ] , [ 12 , 11 , 10 , 9 ] , [ 16 , 15 , 14 , 13 ] ] NEW_LINE mirrorMatrix ( mat1 , mat2 , N ) NEW_LINE DEDENT
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 0 if there is no path between src and dest through the current node ; Function to return the count of nodes between two given vertices of the acyclic Graph ; Initialize an adjacency list ; Populate the edges in the list ; Mark all the nodes as not visited ; Count nodes in the path from src to dest ; Return the nodes between src and dest ; Driver Code ; Given number of vertices and edges ; Given source and destination vertices ; Given edges
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 DEDENT DEDENT DEDENT return 0 NEW_LINE DEDENT def countNodes ( V , E , src , dest , edges ) : NEW_LINE INDENT adj = [ [ ] for i in range ( V + 1 ) ] NEW_LINE for i in range ( E ) : NEW_LINE INDENT adj [ edges [ i ] [ 0 ] ] . append ( edges [ i ] [ 1 ] ) NEW_LINE adj [ edges [ i ] [ 1 ] ] . append ( edges [ i ] [ 0 ] ) NEW_LINE DEDENT vis = [ 0 ] * ( V + 1 ) NEW_LINE count = dfs ( src , dest , vis , adj ) NEW_LINE return count - 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = 8 NEW_LINE E = 7 NEW_LINE src = 5 NEW_LINE dest = 2 NEW_LINE edges = [ [ 1 , 4 ] , [ 4 , 5 ] , [ 4 , 2 ] , [ 2 , 6 ] , [ 6 , 3 ] , [ 2 , 7 ] , [ 3 , 8 ] ] NEW_LINE print ( countNodes ( V , E , src , dest , edges ) ) NEW_LINE DEDENT
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 elements is equal to LCM of the array ; Driver Code ; Function call
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 range ( n ) : NEW_LINE INDENT prod *= A [ i ] NEW_LINE lcm = LCM ( A [ i ] , lcm ) NEW_LINE DEDENT if ( prod == lcm ) : 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 = [ 2 , 3 , 5 ] NEW_LINE n = len ( A ) NEW_LINE checkPairwiseCoPrime ( A , n ) NEW_LINE DEDENT
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 positive element present in the set ; Mark negative element present in the set ; Find the minimum element of the set ; If the array contains both positive and negative elements ; Otherwise ; Driver Code ; Given the array ; Length of the array ; Function Call
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 [ i ] < 0 ) : NEW_LINE INDENT neg = True NEW_LINE DEDENT if ( arr [ i ] < min ) : NEW_LINE INDENT min = arr [ i ] NEW_LINE DEDENT DEDENT if ( pos and neg ) : NEW_LINE INDENT return totalSum NEW_LINE DEDENT else : NEW_LINE INDENT return totalSum - 2 * min NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = [ 1 , 2 , 1 ] NEW_LINE N = len ( S ) NEW_LINE if ( N < 2 ) : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( maxDiffSubsets ( S ) ) NEW_LINE DEDENT DEDENT
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 ; Traverse the given array ; Calculate the difference ; Update minDiff ; Return minDiff ; Driver Code ; Given array ; Length of the array
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 - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffix_sum [ i ] = ( suffix_sum [ i + 1 ] + arr [ i ] ) NEW_LINE DEDENT minDiff = sys . maxsize NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT diff = abs ( prefix_sum [ i ] - suffix_sum [ i + 1 ] ) NEW_LINE if ( diff < minDiff ) : NEW_LINE INDENT minDiff = diff NEW_LINE DEDENT DEDENT return minDiff NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 9 , 5 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minDiffSubArray ( arr , n ) ) NEW_LINE DEDENT
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 current index ; Print waiting days ; Given temperatures ; Function call
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 . append ( i ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( daysOfWait [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 73 , 74 , 75 , 71 , 69 , 72 , 76 , 73 ] NEW_LINE dailyTemperatures ( arr ) NEW_LINE
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 adjacency list of current node and recursively call DFS for each vertex ; If current node Adj [ u ] [ i ] is unvisited ; Update the finishing time ; Function to add edges between nodes u and v ; Function to find the node U such that path from root to U contains nodes in V [ ] ; Initialise vis , dis , parent , preTime , and postTime ; Store Adjacency List ; Create adjacency List ; Perform DFS Traversal ; Stores the distance of deepest vertex 'u ; Update the deepest node by traversing the qu [ ] ; Find deepest vertex ; Replace each vertex with it 's corresponding parent except the root vertex ; Checks if the ancestor with respect to deepest vertex u ; Update ans ; Prthe result ; Driver Code ; Total vertices ; Given set of vertices ; Given edges ; Function Call
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_LINE INDENT if ( vis [ Adj [ u ] [ i ] ] == 0 ) : NEW_LINE INDENT dfs ( Adj [ u ] [ i ] , u , dis + 1 , vis , distance , parent , preTime , postTime , Adj ) ; NEW_LINE DEDENT DEDENT timeT += 1 NEW_LINE postTime [ u ] = timeT ; NEW_LINE DEDENT def addEdge ( Adj , u , v ) : NEW_LINE INDENT Adj [ u ] . append ( v ) ; NEW_LINE Adj [ v ] . append ( u ) ; NEW_LINE DEDENT def findNodeU ( N , V , Vertices , Edges ) : NEW_LINE INDENT vis = [ 0 for i in range ( N + 1 ) ] NEW_LINE distance = [ 0 for i in range ( N + 1 ) ] NEW_LINE parent = [ 0 for i in range ( N + 1 ) ] NEW_LINE preTime = [ 0 for i in range ( N + 1 ) ] NEW_LINE postTime = [ 0 for i in range ( N + 1 ) ] NEW_LINE Adj = [ [ ] for i in range ( N + 1 ) ] NEW_LINE u = 0 NEW_LINE v = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT addEdge ( Adj , Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) ; NEW_LINE DEDENT dfs ( 1 , 0 , 0 , vis , distance , parent , preTime , postTime , Adj ) ; NEW_LINE maximumDistance = 0 ; NEW_LINE DEDENT ' NEW_LINE INDENT maximumDistance = 0 ; NEW_LINE for k in range ( V ) : NEW_LINE INDENT if ( maximumDistance < distance [ Vertices [ k ] ] ) : NEW_LINE INDENT maximumDistance = distance [ Vertices [ k ] ] ; NEW_LINE u = Vertices [ k ] ; NEW_LINE DEDENT if ( parent [ Vertices [ k ] ] != 0 ) : NEW_LINE INDENT Vertices [ k ] = parent [ Vertices [ k ] ] ; NEW_LINE DEDENT DEDENT ans = True ; NEW_LINE flag = False NEW_LINE for k in range ( V ) : NEW_LINE INDENT if ( preTime [ Vertices [ k ] ] <= preTime [ u ] and postTime [ Vertices [ k ] ] >= postTime [ u ] ) : NEW_LINE INDENT flag = True ; NEW_LINE DEDENT else : NEW_LINE INDENT flag = False ; NEW_LINE DEDENT ans = ans & flag ; NEW_LINE DEDENT if ( ans ) : NEW_LINE INDENT print ( u ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 ; NEW_LINE V = 5 ; NEW_LINE Vertices = [ 4 , 3 , 8 , 9 , 10 ] ; NEW_LINE Edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 4 ] , [ 2 , 5 ] , [ 2 , 6 ] , [ 3 , 7 ] , [ 7 , 8 ] , [ 7 , 9 ] , [ 9 , 10 ] ] ; NEW_LINE findNodeU ( N , V , Vertices , Edges ) ; NEW_LINE DEDENT
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 ) NEW_LINE uniqueElement ( arr , n ) NEW_LINE DEDENT
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 ; Neglect if cur node is parent ; Add all values of nodes which are decendents of r ; The two trees formed are rooted at ' r ' with its decendents ; Check and replace if current product t1 * t2 is large ; Function to find the maximum cost after splitting the tree in 2 halves ; Find sum of values in all nodes ; Traverse edges to create adjacency list ; Function Call ; Driver Code ; Values in each node ; Given Edges
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 global allsum NEW_LINE i = 0 NEW_LINE for i in range ( len ( edges [ r ] ) ) : NEW_LINE INDENT cur = edges [ r ] [ i ] NEW_LINE if ( cur == p ) : NEW_LINE INDENT continue NEW_LINE DEDENT findCost ( cur , r , arr ) NEW_LINE arr [ r ] += arr [ cur ] NEW_LINE DEDENT t1 = arr [ r ] NEW_LINE t2 = allsum - t1 NEW_LINE if ( t1 * t2 > ans ) : NEW_LINE INDENT ans = t1 * t2 NEW_LINE DEDENT DEDENT def maximumCost ( r , p , N , M , arr , Edges ) : NEW_LINE INDENT global allsum NEW_LINE for i in range ( N ) : NEW_LINE INDENT allsum += arr [ i ] NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT addedge ( Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) NEW_LINE DEDENT findCost ( r , p , arr ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE arr = [ 13 , 8 , 7 , 4 , 5 , 9 ] NEW_LINE M = 5 NEW_LINE Edges = [ [ 0 , 1 ] , [ 1 , 2 ] , [ 1 , 4 ] , [ 3 , 4 ] , [ 4 , 5 ] ] NEW_LINE maximumCost ( 1 , - 1 , N , M , arr , Edges ) NEW_LINE print ( ans ) NEW_LINE DEDENT
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 ; Update diameter and X ; If current node is an end of diameter ; Traverse its neighbors ; Function to call DFS for the required purposes ; DFS from a random node and find the node farthest from it ; DFS from X to calculate diameter ; DFS from farthest_node to find the farthest node ( s ) from it ; DFS from X ( other end of diameter ) and check the farthest node ( s ) from it ; If node i is the end of a diameter ; Increase diameter by 1 ; Otherwise ; Remains unchanged ; constructed tree is 1 / \ 2 3 / | \ 4 5 6 | 7 ; Creating undirected edges
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 DEDENT if add_to_map and len == diameter : NEW_LINE INDENT mp [ current_node ] = 1 NEW_LINE DEDENT for it in adj [ current_node ] : NEW_LINE INDENT if it != prev_node : NEW_LINE INDENT dfs ( it , current_node , len + 1 , add_to_map , adj ) NEW_LINE DEDENT DEDENT DEDENT def dfsUtility ( adj ) : NEW_LINE INDENT dfs ( 1 , - 1 , 0 , 0 , adj ) NEW_LINE farthest_node = X NEW_LINE dfs ( farthest_node , - 1 , 0 , 0 , adj ) NEW_LINE dfs ( farthest_node , - 1 , 0 , 1 , adj ) NEW_LINE dfs ( X , - 1 , 0 , 1 , adj ) NEW_LINE DEDENT def printDiameters ( adj ) : NEW_LINE INDENT global diameter NEW_LINE dfsUtility ( adj ) NEW_LINE for i in range ( 1 , 6 + 1 ) : NEW_LINE INDENT if mp [ i ] == 1 : NEW_LINE INDENT print ( diameter + 1 , end = " , ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( diameter , end = " , ▁ " ) NEW_LINE DEDENT DEDENT DEDENT adj = [ ] NEW_LINE for i in range ( 7 ) : NEW_LINE INDENT adj . append ( [ ] ) NEW_LINE DEDENT adj [ 1 ] . append ( 2 ) NEW_LINE adj [ 2 ] . append ( 1 ) NEW_LINE adj [ 1 ] . append ( 3 ) NEW_LINE adj [ 3 ] . append ( 1 ) NEW_LINE adj [ 2 ] . append ( 4 ) NEW_LINE adj [ 4 ] . append ( 2 ) NEW_LINE adj [ 2 ] . append ( 5 ) NEW_LINE adj [ 5 ] . append ( 2 ) NEW_LINE adj [ 2 ] . append ( 6 ) NEW_LINE adj [ 6 ] . append ( 2 ) NEW_LINE printDiameters ( adj ) NEW_LINE
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 frequencies of every sum formed by pairs ; Minimum element in the pair ; Maximum element in the pair ; Incrementing the frequency of sum encountered ; Insert minimum and maximum values ; Sorting the vectors ; Iterate over all possible values of x ; Count of pairs for which x > x + k ; Count of pairs for which x < mn + 1 ; Count of pairs requiring 2 replacements ; Count of pairs requiring no replacements ; Count of pairs requiring 1 replacement ; Update the answer ; Return the answer ; Driver Code
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 = middle - 1 NEW_LINE DEDENT elif numbers [ middle ] > searchnum : NEW_LINE INDENT end = middle - 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = middle + 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT def minimumReplacement ( arr , N , K ) : NEW_LINE INDENT ans = inf NEW_LINE max_values = [ ] NEW_LINE min_values = [ ] NEW_LINE sum_equal_to_x = dict ( ) NEW_LINE for i in range ( N // 2 ) : NEW_LINE INDENT mn = min ( arr [ i ] , arr [ N - i - 1 ] ) NEW_LINE mx = max ( arr [ i ] , arr [ N - i - 1 ] ) NEW_LINE if ( arr [ i ] + arr [ N - i - 1 ] not in sum_equal_to_x ) : NEW_LINE INDENT sum_equal_to_x [ arr [ i ] + arr [ N - i - 1 ] ] = 0 NEW_LINE DEDENT sum_equal_to_x [ arr [ i ] + arr [ N - i - 1 ] ] += 1 NEW_LINE min_values . append ( mn ) NEW_LINE max_values . append ( mx ) NEW_LINE DEDENT max_values . sort ( ) NEW_LINE min_values . sort ( ) NEW_LINE for x in range ( 2 , 2 * K + 1 ) : NEW_LINE INDENT mp1 = firstOccurance ( max_values , len ( max_values ) , x - K ) NEW_LINE mp2 = firstOccurance ( min_values , len ( min_values ) , x ) NEW_LINE rep2 = mp1 + ( N // 2 - mp2 ) NEW_LINE if x in sum_equal_to_x : NEW_LINE INDENT rep0 = sum_equal_to_x [ x ] NEW_LINE DEDENT else : NEW_LINE INDENT rep0 = 0 NEW_LINE DEDENT rep1 = ( N // 2 - rep2 - rep0 ) NEW_LINE ans = min ( ans , rep2 * 2 + rep1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE K = 3 NEW_LINE arr = [ 1 , 2 , 2 , 1 ] NEW_LINE print ( minimumReplacement ( arr , N , K ) ) NEW_LINE DEDENT
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 deleted ; Store the its subtree ; Perform Inorder Traversal ; Function to print the forests ; Stores the remaining nodes ; Print the inorder traversal of Forests ; Driver Code
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 ) : NEW_LINE INDENT if nodeVal in mp : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def treePruning ( root , result ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None ; NEW_LINE DEDENT root . left = treePruning ( root . left , result ) ; NEW_LINE root . right = treePruning ( root . right , result ) ; NEW_LINE if ( deleteNode ( root . key ) ) : NEW_LINE INDENT if ( root . left ) : NEW_LINE INDENT result . append ( root . left ) ; NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT result . append ( root . right ) ; NEW_LINE DEDENT return None ; NEW_LINE DEDENT return root ; NEW_LINE DEDENT def printInorderTree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return ; NEW_LINE DEDENT printInorderTree ( root . left ) ; NEW_LINE print ( root . key , end = ' ▁ ' ) NEW_LINE printInorderTree ( root . right ) ; NEW_LINE DEDENT def printForests ( root , arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] = True ; NEW_LINE DEDENT result = [ ] NEW_LINE if ( treePruning ( root , result ) ) : NEW_LINE INDENT result . append ( root ) ; NEW_LINE DEDENT for i in range ( len ( result ) ) : NEW_LINE INDENT printInorderTree ( result [ i ] ) ; NEW_LINE print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) ; NEW_LINE root . left = newNode ( 12 ) ; NEW_LINE root . right = newNode ( 13 ) ; NEW_LINE root . right . left = newNode ( 14 ) ; NEW_LINE root . right . right = newNode ( 15 ) ; NEW_LINE root . right . left . left = newNode ( 21 ) ; NEW_LINE root . right . left . right = newNode ( 22 ) ; NEW_LINE root . right . right . left = newNode ( 23 ) ; NEW_LINE root . right . right . right = newNode ( 24 ) ; NEW_LINE arr = [ 14 , 23 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE printForests ( root , arr , n ) ; NEW_LINE DEDENT
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_LINE for j in range ( len ( nums ) ) : NEW_LINE INDENT for i in range ( len ( dp ) - 1 , nums [ j ] - 1 , - 1 ) : NEW_LINE INDENT dp [ i ] += dp [ i - nums [ j ] ] ; NEW_LINE DEDENT DEDENT return dp [ len ( dp ) - 1 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = 3 ; NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE answer = knapSack ( arr , S ) ; NEW_LINE print ( answer ) ; NEW_LINE DEDENT
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 element then insert its index in map ; If next element present in map then update max distance ; If previous element present in map then update max distance ; Return the answer ; Given array arr [ ] ; Given difference K ; Function call
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 DEDENT if arr [ i ] - K in map : NEW_LINE INDENT maxDist = max ( maxDist , i - map [ arr [ i ] - K ] ) NEW_LINE DEDENT DEDENT if maxDist == 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return maxDist NEW_LINE DEDENT DEDENT arr = [ 11 , 2 , 3 , 8 , 5 , 2 ] NEW_LINE K = 2 NEW_LINE print ( maxDistance ( arr , 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 ; Increment count of ordered pairs ; Print the answer ; Driver Code ; Function call
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 counter ; If count is greater than m return from that path ; Path is allowed if size of present node becomes 0 i . e it has no child root and no more than m consecutive 1 's ; Driver code ; Desigining the tree ; Counter counts no . of consecutive nodes
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 INDENT count = 0 ; NEW_LINE DEDENT if ( count > m ) : NEW_LINE INDENT return ; NEW_LINE DEDENT if ( len ( adj [ node ] ) == 1 and node != 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT for x in adj [ node ] : NEW_LINE INDENT if ( not visited [ x ] ) : NEW_LINE INDENT dfs ( x , count , m , arr , k ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 1 , 3 , 2 , 1 , 2 , 1 ] NEW_LINE N = 7 NEW_LINE K = 2 NEW_LINE M = 2 NEW_LINE adj [ 1 ] . append ( 2 ) ; NEW_LINE adj [ 2 ] . append ( 1 ) ; NEW_LINE adj [ 1 ] . append ( 3 ) ; NEW_LINE adj [ 3 ] . append ( 1 ) ; NEW_LINE adj [ 2 ] . append ( 4 ) ; NEW_LINE adj [ 4 ] . append ( 2 ) ; NEW_LINE adj [ 2 ] . append ( 5 ) ; NEW_LINE adj [ 5 ] . append ( 2 ) ; NEW_LINE adj [ 3 ] . append ( 6 ) ; NEW_LINE adj [ 6 ] . append ( 3 ) ; NEW_LINE adj [ 3 ] . append ( 7 ) ; NEW_LINE adj [ 7 ] . append ( 3 ) ; NEW_LINE counter = 0 ; NEW_LINE dfs ( 1 , counter , M , arr , K ) ; NEW_LINE print ( ans ) NEW_LINE DEDENT
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 , N ) - 1 ) ; NEW_LINE if ( l == 1 ) : NEW_LINE INDENT l = 0 ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT even_sum = 0 ; NEW_LINE odd_sum = 0 ; NEW_LINE itr = 0 ; NEW_LINE num = reverse ( i ) ; NEW_LINE while ( num > 0 ) : NEW_LINE INDENT if ( itr % 2 == 0 ) : NEW_LINE INDENT odd_sum += num % 10 ; NEW_LINE DEDENT else : NEW_LINE INDENT even_sum += num % 10 ; NEW_LINE DEDENT num = num // 10 ; NEW_LINE itr += 1 ; NEW_LINE DEDENT if ( even_sum % A == 0 and odd_sum % B == 0 ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 ; NEW_LINE A = 5 ; NEW_LINE B = 3 ; NEW_LINE print ( count ( N , A , B ) ) ; NEW_LINE DEDENT
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 ] == B [ i ] ) ) : NEW_LINE INDENT answer += A [ i ] NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT A = [ 1 , 2 , 3 , 2 , 4 ] NEW_LINE B = [ 2 , 1 , 3 , 1 , 4 ] NEW_LINE N = len ( A ) NEW_LINE print ( calc_distance ( A , B , N ) ) NEW_LINE
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 each node in path from V to the root ; Path from node V to root node ; Driver Code ; Insert edges into the graph ; Values assigned to each vertex ; Constructing the tree using adjacency list ; Parent array ; store values in the parent array ; Add values of children to the parent ; Find sum of nodes lying in the path ; Add root node since its value is not included yet
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 ) NEW_LINE DEDENT return adjl NEW_LINE DEDENT def DFS ( adjl , parent , u , p ) : NEW_LINE INDENT parent [ u ] = p NEW_LINE for v in adjl [ u ] : NEW_LINE INDENT if ( v != p ) : NEW_LINE INDENT DFS ( adjl , parent , v , u ) NEW_LINE DEDENT DEDENT DEDENT def valuesFromChildren ( parent , values ) : NEW_LINE INDENT valuesChildren = [ 0 ] * ( len ( parent ) ) NEW_LINE for i in range ( len ( parent ) ) : NEW_LINE INDENT if ( parent [ i ] == - 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT p = parent [ i ] NEW_LINE valuesChildren [ p ] += values [ i ] NEW_LINE DEDENT DEDENT return valuesChildren NEW_LINE DEDENT def findSumOfValues ( v , parent , valuesChildren ) : NEW_LINE INDENT cur_node = v NEW_LINE Sum = 0 NEW_LINE while ( cur_node != - 1 ) : NEW_LINE INDENT Sum += valuesChildren [ cur_node ] NEW_LINE cur_node = parent [ cur_node ] NEW_LINE DEDENT return Sum NEW_LINE DEDENT n = 8 NEW_LINE edges = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 0 , 3 ] , [ 1 , 4 ] , [ 1 , 5 ] , [ 4 , 7 ] , [ 3 , 6 ] ] NEW_LINE v = 7 NEW_LINE values = [ 1 , 2 , 3 , 0 , 0 , 4 , 3 , 6 ] NEW_LINE adjl = constructTree ( n , edges ) NEW_LINE parent = [ 0 ] * ( n ) NEW_LINE DFS ( adjl , parent , 0 , - 1 ) NEW_LINE valuesChildren = valuesFromChildren ( parent , values ) NEW_LINE Sum = findSumOfValues ( v , parent , valuesChildren ) NEW_LINE Sum += values [ 0 ] NEW_LINE print ( Sum ) NEW_LINE
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 second largest ; Print the pairs ; Driver Code ; Given array ; Function call
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 INDENT c = a ; NEW_LINE d = b ; NEW_LINE a = arr [ i ] ; NEW_LINE b = arr [ j ] ; NEW_LINE DEDENT if ( arr [ i ] * arr [ j ] < a * b and arr [ i ] * arr [ j ] > c * d ) : NEW_LINE INDENT c = arr [ i ] ; NEW_LINE DEDENT d = arr [ j ] ; NEW_LINE DEDENT DEDENT print ( c , " ▁ " , d ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 2 , 67 , 45 , 160 , 78 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE maxProduct ( arr , N ) ; NEW_LINE DEDENT
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 of vowels ; Increase the answer ; Prthe final answer ; Driver Code
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 range ( i , n ) : NEW_LINE INDENT if ( isVowel ( s [ j ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( count % 2 == 0 ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT DEDENT print ( result ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE s = " abcde " NEW_LINE countSubstrings ( s , n ) NEW_LINE DEDENT
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 obtain even or odd ; Increment even / odd count ; Count substrings with even number of vowels using Handshaking Lemma ; Driver Code
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 ( 0 , n ) : NEW_LINE INDENT sum += ( 1 if isVowel ( s [ i ] ) else 0 ) ; NEW_LINE sum %= 2 ; NEW_LINE temp [ sum ] += 1 ; NEW_LINE DEDENT result += ( ( temp [ 0 ] * ( temp [ 0 ] - 1 ) ) // 2 ) ; NEW_LINE result += ( ( temp [ 1 ] * ( temp [ 1 ] - 1 ) ) // 2 ) ; NEW_LINE print ( result ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; NEW_LINE s = " abcde " ; NEW_LINE countSubstrings ( s , n ) ; NEW_LINE DEDENT
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 tree ; Check width of current level ; If the width is equal to k then return that level ; Taking the first label of each level of the tree ; If any level does not has width equal to k , return - 1 ; Driver Code
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 . append ( [ root , 0 ] ) NEW_LINE count = 1 NEW_LINE b = 0 NEW_LINE a = 0 NEW_LINE while qt : NEW_LINE INDENT temp = qt . popleft ( ) NEW_LINE if ( count == 1 ) : NEW_LINE INDENT b = temp [ 1 ] NEW_LINE DEDENT if ( temp [ 0 ] . left ) : NEW_LINE INDENT qt . append ( [ temp [ 0 ] . left , 2 * temp [ 1 ] ] ) NEW_LINE DEDENT if ( temp [ 0 ] . right ) : NEW_LINE INDENT qt . append ( [ temp [ 0 ] . right , 2 * temp [ 1 ] + 1 ] ) NEW_LINE DEDENT count -= 1 NEW_LINE if ( count == 0 ) : NEW_LINE INDENT if ( b - a + 1 == k ) : NEW_LINE INDENT return level NEW_LINE DEDENT secondLabel = qt [ 0 ] NEW_LINE a = secondLabel [ 1 ] NEW_LINE level += 1 NEW_LINE count = len ( qt ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 5 ) NEW_LINE root . left = Node ( 6 ) NEW_LINE root . right = Node ( 2 ) NEW_LINE root . right . right = Node ( 8 ) NEW_LINE root . left . left = Node ( 7 ) NEW_LINE root . left . left . left = Node ( 5 ) NEW_LINE root . left . right = Node ( 3 ) NEW_LINE root . left . right . right = Node ( 4 ) NEW_LINE k = 4 NEW_LINE print ( findLevel ( root , k , 1 ) ) NEW_LINE DEDENT
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 possible for the median of array after doing at most k operation ; Return the max possible ans ; Driver Code ; Given array ; Given number of operation ; Size of array ; Sort the array ; Function call
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 INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def findMaxMedian ( arr , N , K ) : NEW_LINE INDENT low = 1 NEW_LINE mx = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT mx = max ( mx , arr [ i ] ) NEW_LINE DEDENT high = K + mx NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( high + low ) // 2 NEW_LINE if ( possible ( arr , N , mid , K ) ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT if ( N % 2 == 0 ) : NEW_LINE INDENT if ( low - 1 < arr [ N // 2 ] ) : NEW_LINE INDENT return ( arr [ N // 2 ] + low - 1 ) // 2 NEW_LINE DEDENT DEDENT return low - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 6 ] NEW_LINE K = 10 NEW_LINE N = len ( arr ) NEW_LINE arr = sorted ( arr ) NEW_LINE print ( findMaxMedian ( arr , N , K ) ) NEW_LINE DEDENT
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 the NxM Matrix after sorting in an array ; Initialize low and high ; Perform binary search ; Find the mid ; Check if the count of elements is less than mid ; Return Kth smallest element of the matrix ; Driver Code
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 findKthElement ( N , M , K ) : NEW_LINE INDENT low = 1 NEW_LINE high = N * M NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( countLessThanMid ( mid , N , M , K ) ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return high + 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE M = 3 NEW_LINE K = 5 NEW_LINE print ( findKthElement ( N , M , K ) ) NEW_LINE DEDENT
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 consecutive strings ; Reset the consecutive count of C 's ; Add count of sub - strings from consecutive strings ; Print the count of sub - strings containing only C ; Driver Code
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 * ( conCount + 1 ) ) // 2 ) NEW_LINE print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " geeksforgeeks " NEW_LINE C = ' e ' NEW_LINE countSubString ( S , C ) NEW_LINE DEDENT
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 [ n // 2 + i ] != S [ n // 2 + cnt ] ) : NEW_LINE INDENT second_half = False NEW_LINE break NEW_LINE DEDENT cnt -= 1 NEW_LINE DEDENT if ( first_half and second_half ) : NEW_LINE INDENT print ( ' Yes ' , end = ' ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' , end = ' ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = ' momdad ' NEW_LINE checkPalindrome ( S ) NEW_LINE DEDENT
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 to parity ( 0 or 1 ) on the basis of its frequency ; Adding to answer ; Frequency of single character can be possibly changed , so change its parity ; Driver code
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 DEDENT for j in range ( 26 ) : NEW_LINE INDENT a [ j ] = a [ j ] % 2 NEW_LINE DEDENT ans += mp [ tuple ( a ) ] NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT changedCount = a [ : ] NEW_LINE if ( a [ j ] == 0 ) : NEW_LINE INDENT changedCount [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT changedCount [ j ] = 0 NEW_LINE DEDENT ans += mp [ tuple ( changedCount ) ] NEW_LINE DEDENT mp [ tuple ( a ) ] += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE A = [ " aab " , " abcac " , " dffe " , " ed " , " aa " , " aade " ] NEW_LINE print ( getCount ( N , A ) ) NEW_LINE DEDENT
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 ; Recur down the right subtree for smaller values ; Return the ( unchanged ) node pointer ; FUnction to find Kth Smallest element in a perfect BST ; Find the median ( division operation is floored ) ; If the element is at the median ; Calculate the number of nodes in the right and left sub - trees ( division operation is floored ) ; If median is located higher ; If median is located lower ; Driver Code ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 / \ / \ / \ / \ 14 25 35 45 55 65 75 85 ; Function call
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 DEDENT if ( key < node . key ) : NEW_LINE INDENT node . left = insert ( node . left , key ) NEW_LINE DEDENT elif ( key > node . key ) : NEW_LINE INDENT node . right = insert ( node . right , key ) NEW_LINE DEDENT return node NEW_LINE DEDENT def KSmallestPerfectBST ( root , k , treeSize ) : NEW_LINE INDENT global kth_smallest NEW_LINE if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT median_loc = ( treeSize // 2 ) + 1 NEW_LINE if ( k == median_loc ) : NEW_LINE INDENT kth_smallest = root . key NEW_LINE return True NEW_LINE DEDENT newTreeSize = treeSize // 2 NEW_LINE if ( k < median_loc ) : NEW_LINE INDENT return KSmallestPerfectBST ( root . left , k , newTreeSize ) NEW_LINE DEDENT newK = k - median_loc NEW_LINE return KSmallestPerfectBST ( root . right , newK , newTreeSize ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 50 ) NEW_LINE insert ( root , 30 ) NEW_LINE insert ( root , 20 ) NEW_LINE insert ( root , 40 ) NEW_LINE insert ( root , 70 ) NEW_LINE insert ( root , 60 ) NEW_LINE insert ( root , 80 ) NEW_LINE insert ( root , 14 ) NEW_LINE insert ( root , 25 ) NEW_LINE insert ( root , 35 ) NEW_LINE insert ( root , 45 ) NEW_LINE insert ( root , 55 ) NEW_LINE insert ( root , 65 ) NEW_LINE insert ( root , 75 ) NEW_LINE insert ( root , 85 ) NEW_LINE n = 15 NEW_LINE k = 5 NEW_LINE if ( KSmallestPerfectBST ( root , k , n ) ) : NEW_LINE INDENT print ( kth_smallest , end = " ▁ " ) NEW_LINE DEDENT DEDENT
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 checkrules ( s [ 1 : ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = '1111' NEW_LINE if checkrules ( s ) : NEW_LINE INDENT print ( ' valid ▁ string ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' invalid ▁ string ' ) NEW_LINE DEDENT DEDENT
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 check ; Return true or false as per the condition ; Function to find the longest subsequence which contain all Nude numbers ; Find the length of longest Nude number subsequence ; Given array arr [ ] ; Function call
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 ( flag == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT def longestNudeSubseq ( arr , n ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( isNudeNum ( arr [ i ] ) ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT arr = [ 34 , 34 , 2 , 2 , 3 , 333 , 221 , 32 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestNudeSubseq ( arr , n ) ) NEW_LINE
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 elements ; Otherwise ; Update the maximum length ; Remove the set elements ; Driver Code
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 arr [ j ] in s ) : NEW_LINE INDENT if ( len ( s ) == 2 ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT s . add ( arr [ j ] ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( len ( s ) == 2 ) : NEW_LINE INDENT Max = max ( Max , j - i ) NEW_LINE s . clear ( ) NEW_LINE DEDENT else : NEW_LINE INDENT s . clear ( ) NEW_LINE DEDENT DEDENT return Max NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 2 , 2 , 5 , 5 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE K = 1 NEW_LINE length = longestSubarray ( arr , N , K ) NEW_LINE if ( length == 1 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( length ) NEW_LINE DEDENT DEDENT
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 consecutive 1 's till (i - 1)-th index ; Traverse from right to left ; Store the count of consecutive 1 s till ( i + 1 ) - th index ; Stores the length of longest subarray ; Store the maximum ; If array a contains only 1 s return n else return ans ; Driver code
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_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT r [ i ] = count NEW_LINE count = 0 NEW_LINE DEDENT DEDENT ans = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT ans = max ( ans , l [ i ] + r [ i ] ) NEW_LINE DEDENT DEDENT return ans < 0 and n or ans NEW_LINE DEDENT arr = [ 0 , 1 , 1 , 1 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestSubarray ( arr , n ) ) NEW_LINE
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 _ _ ' : NEW_LINE INDENT N = 8 ; NEW_LINE K = 7 ; NEW_LINE findMaxValue ( N , K ) ; NEW_LINE DEDENT
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 arr = [ 3 , 2 , 1 , 5 , 2 , 4 ] NEW_LINE maxSide ( arr , N ) NEW_LINE
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 contains all red node & no blue node ; If subtree contains all blue node & no red node ; Function to count the number of nodes with red color ; Function to count the number of nodes with blue color ; Function to create a Tree with given vertices ; Traverse the edge [ ] array ; Create adjacency list ; Function to count the number of subtree with the given condition ; For creating adjacency list ; To store the count of subtree with only blue and red color ; visited array for DFS Traversal ; Count the number of red node in the tree ; Count the number of blue node in the tree ; Function Call to build tree ; DFS Traversal ; Print the final count ; Driver Code
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 , adj , ans ) ; NEW_LINE sub_red [ v ] += sub_red [ adj [ v ] [ i ] ] ; NEW_LINE sub_blue [ v ] += sub_blue [ adj [ v ] [ i ] ] ; NEW_LINE DEDENT DEDENT if ( color [ v ] == 1 ) : NEW_LINE INDENT sub_red [ v ] += 1 ; NEW_LINE DEDENT if ( color [ v ] == 2 ) : NEW_LINE INDENT sub_blue [ v ] += 1 ; NEW_LINE DEDENT if ( sub_red [ v ] == red and sub_blue [ v ] == 0 ) : NEW_LINE INDENT ( ans ) += 1 ; NEW_LINE DEDENT if ( sub_red [ v ] == 0 and sub_blue [ v ] == blue ) : NEW_LINE INDENT ( ans ) += 1 ; NEW_LINE DEDENT return ans NEW_LINE DEDENT def countRed ( color , n ) : NEW_LINE INDENT red = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( color [ i ] == 1 ) : NEW_LINE INDENT red += 1 ; NEW_LINE DEDENT DEDENT return red ; NEW_LINE DEDENT def countBlue ( color , n ) : NEW_LINE INDENT blue = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( color [ i ] == 2 ) : NEW_LINE INDENT blue += 1 NEW_LINE DEDENT DEDENT return blue ; NEW_LINE DEDENT def buildTree ( edge , m , n ) : NEW_LINE INDENT u , v , i = 0 , 0 , 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT u = edge [ i ] [ 0 ] - 1 ; NEW_LINE v = edge [ i ] [ 1 ] - 1 ; NEW_LINE if u not in m : NEW_LINE INDENT m [ u ] = [ ] NEW_LINE DEDENT if v not in m : NEW_LINE INDENT m [ v ] = [ ] NEW_LINE DEDENT m [ u ] . append ( v ) NEW_LINE m [ v ] . append ( u ) ; NEW_LINE DEDENT DEDENT def countSubtree ( color , n , edge ) : NEW_LINE INDENT adj = dict ( ) NEW_LINE ans = 0 ; NEW_LINE sub_red = [ 0 for i in range ( n + 3 ) ] NEW_LINE sub_blue = [ 0 for i in range ( n + 3 ) ] NEW_LINE vis = [ 0 for i in range ( n + 3 ) ] NEW_LINE red = countRed ( color , n ) ; NEW_LINE blue = countBlue ( color , n ) ; NEW_LINE buildTree ( edge , adj , n ) ; NEW_LINE ans = Solution_dfs ( 0 , color , red , blue , sub_red , sub_blue , vis , adj , ans ) ; NEW_LINE print ( ans , end = ' ' ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE color = [ 1 , 0 , 0 , 0 , 2 ] NEW_LINE edge = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 4 ] , [ 4 , 5 ] ] ; NEW_LINE countSubtree ( color , N , edge ) ; NEW_LINE DEDENT
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 ; Print the minimum difference ; Driver Code ; Given array ; Function Call
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 ( mindifference , a [ i ] - a [ i - 1 ] ) NEW_LINE DEDENT print ( mindifference ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 8 , 13 , 30 , 50 ] NEW_LINE n = len ( arr ) NEW_LINE minDiff ( arr , n ) NEW_LINE DEDENT
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 ; Initialize sum1 to 0 ; Push the prefix sum1 of the array arr [ ] in prefix [ ] ; Search r for each i ; Update ans ; Print the length of subarray found in the array ; Driver Code ; Given array arr [ ] ; Given sum1 K ; Function Call
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 else : NEW_LINE INDENT hi = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def findSubarraysum1K ( arr , N , K ) : NEW_LINE INDENT global v NEW_LINE sum1 = 0 NEW_LINE v . append ( 0 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum1 += arr [ i ] NEW_LINE v . append ( sum1 ) NEW_LINE DEDENT l = 0 NEW_LINE ans = 0 NEW_LINE r = 0 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT r = bin1 ( v [ i ] , K , N ) NEW_LINE ans = max ( ans , r - i ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 6 , 8 , 14 , 9 , 4 , 11 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE K = 13 NEW_LINE findSubarraysum1K ( arr , N , K ) NEW_LINE DEDENT
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 Traversal ; Pop the current node from the queue ; mark the current node visited ; Intitialize count of edges need to be reversed to 0 ; Push adjacent nodes in the reversed graph to the queue , if not visited ; Push adjacent nodes in graph to the queue , if not visited count the number of nodes added to the queue ; Update the reverse edge to the final count ; Return the result ; Driver Code ; Given edges to the graph ; Number of nodes ; Function Call
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_LINE if y not in graph_rev : NEW_LINE INDENT graph_rev [ y ] = [ ] NEW_LINE DEDENT graph_rev [ y ] . append ( x ) ; NEW_LINE DEDENT q = [ ] NEW_LINE visited = [ 0 for i in range ( n ) ] NEW_LINE q . append ( 0 ) ; NEW_LINE ans = 0 ; NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT curr = q [ 0 ] NEW_LINE visited [ curr ] = 1 ; NEW_LINE count = 0 ; NEW_LINE q . pop ( 0 ) ; NEW_LINE if curr in graph_rev : NEW_LINE INDENT for i in range ( len ( graph_rev [ curr ] ) ) : NEW_LINE INDENT if ( not visited [ graph_rev [ curr ] [ i ] ] ) : NEW_LINE INDENT q . append ( graph_rev [ curr ] [ i ] ) ; NEW_LINE DEDENT DEDENT DEDENT if curr in graph : NEW_LINE INDENT for i in range ( len ( graph [ curr ] ) ) : NEW_LINE INDENT if ( not visited [ graph [ curr ] [ i ] ] ) : NEW_LINE INDENT q . append ( graph [ curr ] [ i ] ) ; NEW_LINE count += 1 NEW_LINE DEDENT DEDENT DEDENT ans += count ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT edges = [ ] NEW_LINE edges = [ [ 0 , 1 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 4 , 0 ] , [ 4 , 5 ] ] ; NEW_LINE n = 6 ; NEW_LINE print ( minRev ( edges , n ) ) NEW_LINE DEDENT
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 array ; Function Call
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 ] NEW_LINE N = len ( arr ) NEW_LINE print ( splitArray ( arr , N ) ) NEW_LINE DEDENT
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 ( R , C ) NEW_LINE print ( k ) NEW_LINE DEDENT
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 leftover element ; Condition if group size is equal to or more than current element ; Printing maximum number of groups ; Driver Code
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 = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( v [ i ] != 0 ) : NEW_LINE INDENT total = v [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT i += 1 NEW_LINE while ( i <= n ) : NEW_LINE INDENT if ( v [ i ] != 0 ) : NEW_LINE INDENT total += v [ i ] NEW_LINE if ( total >= i ) : NEW_LINE INDENT rem = total - i NEW_LINE no_of_groups += 1 NEW_LINE total = rem NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT print ( no_of_groups ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 1 , 2 , 2 ] NEW_LINE size = len ( arr ) NEW_LINE makeGroups ( arr , size ) NEW_LINE DEDENT
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 NEW_LINE if flag : NEW_LINE INDENT return col + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 0 , 0 , 0 , 1 ] , [ 0 , 1 , 1 , 1 ] , [ 0 , 0 , 1 , 1 ] ] NEW_LINE print ( findColumn ( mat ) ) NEW_LINE DEDENT
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 the corresponding remainder ; Keep increasing M ; To keep M in range of integer ; Length of one number is the current Length ; Length of the other number is the length paired with current remainder in map ; Driver code
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 * 10 + m NEW_LINE M = M % N NEW_LINE DEDENT LenA = len1 NEW_LINE LenB = remLen [ remainder ] NEW_LINE for i in range ( LenB ) : NEW_LINE INDENT print ( m , end = " " ) NEW_LINE DEDENT print ( " ▁ " , end = " " ) NEW_LINE for i in range ( LenA ) : NEW_LINE INDENT print ( m , end = " " ) NEW_LINE DEDENT return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE M = 2 NEW_LINE findNumbers ( N , M ) NEW_LINE DEDENT
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 common elements ; Combining the two arrays ; Calculating the 2D prefix sum ; iterating through all the elements of matrix and considering them to be the bottom right ; applying binary search over side length ; if sum of this submatrix >= k then new search space will be [ low , mid ] ; else new search space will be [ mid + 1 , high ] ; Adding the total submatrices ; Driver Code
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 , m , k ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( a [ i - 1 ] == b [ j - 1 ] ) : NEW_LINE INDENT prefix_2D [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT prefix_2D [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT prefix_2D [ i ] [ j ] += prefix_2D [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT prefix_2D [ i ] [ j ] += prefix_2D [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT answer = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT low = 1 NEW_LINE high = min ( i , j ) NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = ( low + high ) >> 1 NEW_LINE if ( subMatrixSum ( i , j , mid ) >= k ) : NEW_LINE INDENT high = mid NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT if ( subMatrixSum ( i , j , low ) >= k ) : NEW_LINE INDENT answer += ( min ( i , j ) - low + 1 ) NEW_LINE DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE M = 3 NEW_LINE A = [ 1 , 2 ] NEW_LINE B = [ 1 , 2 , 3 ] NEW_LINE K = 1 NEW_LINE print ( numberOfWays ( A , B , N , M , K ) ) NEW_LINE DEDENT
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 array ; If this is true then this character is being visited for the first time from the last Thus last occurrence of this character is stored in this index ; Character to replace ; Find the last occurrence of this character . ; Swap this with the last occurrence swap ( s [ i ] , s [ last_occ ] ) ; ; Driver code
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 ; NEW_LINE sorted_s . sort ( ) ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( s [ i ] != sorted_s [ i ] ) : NEW_LINE INDENT chI = ord ( sorted_s [ i ] ) - ord ( ' a ' ) ; NEW_LINE last_occ = loccur [ chI ] ; NEW_LINE s [ i ] , s [ last_occ ] = s [ last_occ ] , s [ i ] NEW_LINE break ; NEW_LINE DEDENT DEDENT return " " . join ( s ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeks " ; NEW_LINE print ( findSmallest ( list ( s ) ) ) ; NEW_LINE DEDENT
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 find the sum of a submatrix with the given indices ; Overall sum from the top to right corner of matrix ; Removing the sum from the top corer of the matrix ; Remove the overlapping sum ; Add the sum of top corner which is subtracted twice ; Function to check whether square sub matrices of size mid satisfy the condition or not ; Iterating throught all possible submatrices of given size ; Function to find the maximum square size possible with the such that every submatrix have sum less than the given sum ; Search space ; Binary search for size ; Check if the mid satisfies the given condition ; Driver Code
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 ) : NEW_LINE INDENT for j in range ( 1 , 5 ) : NEW_LINE INDENT aux [ i ] [ j ] += aux [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT return aux NEW_LINE DEDENT def sumQuery ( aux , tli , tlj , rbi , rbj ) : NEW_LINE INDENT res = aux [ rbi ] [ rbj ] NEW_LINE if ( tli > 0 ) : NEW_LINE INDENT res = res - aux [ tli - 1 ] [ rbj ] NEW_LINE DEDENT if ( tlj > 0 ) : NEW_LINE INDENT res = res - aux [ rbi ] [ tlj - 1 ] NEW_LINE DEDENT if ( tli > 0 and tlj > 0 ) : NEW_LINE INDENT res = res + aux [ tli - 1 ] [ tlj - 1 ] NEW_LINE DEDENT return res NEW_LINE DEDENT def check ( mid , aux , K ) : NEW_LINE INDENT satisfies = True NEW_LINE for x in range ( 4 ) : NEW_LINE INDENT for y in range ( 5 ) : NEW_LINE INDENT if ( x + mid - 1 <= 4 - 1 and y + mid - 1 <= 5 - 1 ) : NEW_LINE INDENT if ( sumQuery ( aux , x , y , x + mid - 1 , y + mid - 1 ) > K ) : NEW_LINE INDENT satisfies = False NEW_LINE DEDENT DEDENT DEDENT DEDENT return True if satisfies == True else False NEW_LINE DEDENT def maximumSquareSize ( mat , K ) : NEW_LINE INDENT aux = [ [ 0 for i in range ( 5 ) ] for i in range ( 4 ) ] NEW_LINE aux = preProcess ( mat , aux ) NEW_LINE low , high = 1 , min ( 4 , 5 ) NEW_LINE mid = 0 NEW_LINE while ( high - low > 1 ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( check ( mid , aux , K ) ) : NEW_LINE INDENT low = mid NEW_LINE DEDENT else : NEW_LINE INDENT high = mid NEW_LINE DEDENT DEDENT if ( check ( high , aux , K ) ) : NEW_LINE INDENT return high NEW_LINE DEDENT return low NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 30 NEW_LINE mat = [ [ 1 , 2 , 3 , 4 , 6 ] , [ 5 , 3 , 8 , 1 , 2 ] , [ 4 , 6 , 7 , 5 , 5 ] , [ 2 , 4 , 8 , 9 , 4 ] ] NEW_LINE print ( maximumSquareSize ( mat , K ) ) NEW_LINE DEDENT
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 and right subtrees and store the max of values in this node ; Function to return the max element in the given range ; If the range is out of bounds , return - 1 ; Function that returns length of longest subarray with same elements in atmost K increments . ; Initialize the result variable Even though the K is 0 , the required longest subarray , in that case , will also be of length 1 ; Initialize the prefix sum array ; Build the prefix sum array ; Build the segment tree for range max query ; Loop through the array with a starting point as i for the required subarray till the longest subarray is found ; Performing the binary search to find the endpoint for the selected range ; Find the mid for binary search ; Find the max element in the range [ i , mid ] using Segment Tree ; Total sum of subarray after increments ; Actual sum of elements before increments ; Check if such increment is possible If true , then current i is the actual starting point of the required longest subarray ; Now for finding the endpoint for this range Perform the Binary search again with the updated start ; Store max end point for the range to give longest subarray ; If false , it means that the selected range is invalid ; Perform the Binary Search again with the updated end ; Store the length of longest subarray ; Return result ; Driver code
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 * node + 1 ) , build ( A , mid + 1 , end , 2 * node + 2 ) ) ; NEW_LINE DEDENT return segment_tree [ node ] ; NEW_LINE DEDENT def query ( start , end , l , r , node ) : NEW_LINE INDENT if ( start > r or end < l ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( start >= l and end <= r ) : NEW_LINE INDENT return segment_tree [ node ] ; NEW_LINE DEDENT mid = ( start + end ) // 2 ; NEW_LINE return max ( query ( start , mid , l , r , 2 * node + 1 ) , query ( mid + 1 , end , l , r , 2 * node + 2 ) ) ; NEW_LINE DEDENT def longestSubArray ( A , N , K ) : NEW_LINE INDENT res = 1 ; NEW_LINE preSum = [ 0 ] * ( N + 1 ) ; NEW_LINE preSum [ 0 ] = A [ 0 ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT preSum [ i + 1 ] = preSum [ i ] + A [ i ] ; NEW_LINE DEDENT build ( A , 0 , N - 1 , 0 ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT start = i ; NEW_LINE end = N - 1 ; NEW_LINE max_index = i ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 ; NEW_LINE max_element = query ( 0 , N - 1 , i , mid , 0 ) ; NEW_LINE expected_sum = ( mid - i + 1 ) * max_element ; NEW_LINE actual_sum = preSum [ mid + 1 ] - preSum [ i ] ; NEW_LINE if ( expected_sum - actual_sum <= K ) : NEW_LINE INDENT start = mid + 1 ; NEW_LINE max_index = max ( max_index , mid ) ; NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 ; NEW_LINE DEDENT DEDENT res = max ( res , max_index - i + 1 ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 0 , 4 , 6 , 7 ] ; K = 6 ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( longestSubArray ( arr , N , K ) ) ; NEW_LINE DEDENT
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__ == " _ _ main _ _ " : NEW_LINE INDENT l = 11 ; r = 33 ; NEW_LINE print ( countNums ( l , r ) ) ; NEW_LINE DEDENT
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 dividing the array by new K which is mid ; Search in the second half ; First half ; Driver code
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_LINE for i in range ( n ) : NEW_LINE INDENT sum += ( a [ i ] // mid ) NEW_LINE DEDENT if ( sum > s ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans = min ( ans , mid ) NEW_LINE high = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT a = [ 10 , 7 , 8 , 10 , 12 , 19 ] NEW_LINE n = len ( a ) NEW_LINE s = 27 NEW_LINE print ( findMinimumK ( a , n , s ) ) NEW_LINE
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 next - farther position where gcd is same ; BinarySearch for Next Position for EndPointer ; Utility function to calculate sum of gcd ; Initializing all the values ; Finding the next position for endPointer ; Adding the suitable sum to our answer ; Changing prevEndPointer ; Recalculating tempGCD ; Driver code
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 range ( 1 , 20 ) : NEW_LINE INDENT for i in range ( n - ( 1 << j ) + 1 ) : NEW_LINE INDENT SparseTable [ i ] [ j ] = __gcd ( SparseTable [ i ] [ j - 1 ] , SparseTable [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT def queryForGCD ( L , R ) : NEW_LINE INDENT j = floor ( log ( R - L + 1 , 2 ) ) NEW_LINE returnValue = __gcd ( SparseTable [ L ] [ j ] , SparseTable [ R - ( 1 << j ) + 1 ] [ j ] ) NEW_LINE return returnValue NEW_LINE DEDENT def nextPosition ( tempGCD , startPointer , prevEndPointer , n ) : NEW_LINE INDENT high = n - 1 NEW_LINE low = prevEndPointer NEW_LINE mid = prevEndPointer NEW_LINE nextPos = prevEndPointer NEW_LINE while ( high >= low ) : NEW_LINE INDENT mid = ( ( high + low ) >> 1 ) NEW_LINE if ( queryForGCD ( startPointer , mid ) == tempGCD ) : NEW_LINE INDENT nextPos = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return nextPos + 1 NEW_LINE DEDENT def calculateSum ( a , n ) : NEW_LINE INDENT buildSparseTable ( a , n ) NEW_LINE tempAns = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT endPointer = i NEW_LINE startPointer = i NEW_LINE prevEndPointer = i NEW_LINE tempGCD = a [ i ] NEW_LINE while ( endPointer < n ) : NEW_LINE INDENT endPointer = nextPosition ( tempGCD , startPointer , prevEndPointer , n ) NEW_LINE tempAns += ( ( endPointer - prevEndPointer ) * tempGCD ) NEW_LINE prevEndPointer = endPointer NEW_LINE if ( endPointer < n ) : NEW_LINE INDENT tempGCD = __gcd ( tempGCD , a [ endPointer ] ) NEW_LINE DEDENT DEDENT DEDENT return tempAns NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE a = [ 2 , 2 , 2 , 3 , 5 , 5 ] NEW_LINE print ( calculateSum ( a , n ) ) NEW_LINE DEDENT
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 - th smallest must be on left side . ; Else k - th smallest is on right side . ; Driver Code
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 [ high ] , arr [ i + 1 ] NEW_LINE return ( i + 1 ) NEW_LINE DEDENT def kthSmallest ( a , left , right , k ) : NEW_LINE INDENT while left <= right : NEW_LINE INDENT pivotIndex = partition ( a , left , right ) NEW_LINE if pivotIndex == k - 1 : NEW_LINE INDENT return a [ pivotIndex ] NEW_LINE DEDENT elif pivotIndex > k - 1 : NEW_LINE INDENT right = pivotIndex - 1 NEW_LINE DEDENT else : NEW_LINE INDENT left = pivotIndex + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 10 , 4 , 5 , 8 , 11 , 6 , 26 ] NEW_LINE n = len ( arr ) NEW_LINE k = 5 NEW_LINE print ( " K - th ▁ smallest ▁ element ▁ is " , kthSmallest ( arr , 0 , n - 1 , k ) ) NEW_LINE
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 call
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 ( i + 1 , p ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] < k and arr [ i ] + arr [ j ] > maxsum ) : NEW_LINE INDENT maxsum = arr [ i ] + arr [ j ] NEW_LINE a = arr [ i ] NEW_LINE b = arr [ j ] NEW_LINE DEDENT DEDENT DEDENT print ( a , b ) NEW_LINE DEDENT arr = [ 5 , 20 , 110 , 100 , 10 ] NEW_LINE k = 85 NEW_LINE n = len ( arr ) NEW_LINE Max_Sum ( arr , n , k ) NEW_LINE
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 ; Instead of finding the ending index from the beginning , find the index from the end This is because if the current sub - string is a palindrome then there is no need to check the sub - strings of smaller length and we can skip to the next iteration of the outer loop ; If current character is a valid ending index ; If str [ i ... j ] is a palindrome then update the length of the maximum palindrome so far ; Driver code
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 in range ( n ) : NEW_LINE INDENT if ( str [ i ] == ch ) : NEW_LINE INDENT for j in range ( n - 1 , i + 1 , - 1 ) : NEW_LINE INDENT if ( str [ j ] == ch ) : NEW_LINE INDENT if ( isPalindrome ( str , i , j ) ) : NEW_LINE INDENT maxLen = max ( maxLen , j - i + 1 ) ; NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return maxLen ; NEW_LINE DEDENT str = " lapqooqpqpl " ; NEW_LINE n = len ( str ) ; NEW_LINE ch = ' p ' ; NEW_LINE print ( maxLenPalindrome ( str , n , ch ) ) ; NEW_LINE
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 - array calculated so far ; If no valid sub - array found ; Driver code
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_LINE INDENT if arr [ i ] == '1' : NEW_LINE INDENT sum = 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum = - 1 NEW_LINE DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if arr [ j ] == 0 : NEW_LINE INDENT sum -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum += 1 NEW_LINE DEDENT if ( sum == 0 and maxsize < j - i + 1 ) : NEW_LINE INDENT maxsize = j - i + 1 NEW_LINE startindex = i NEW_LINE DEDENT DEDENT DEDENT if ( maxsize == - 1 ) : NEW_LINE INDENT print ( maxsize , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( startindex , ( startindex + maxsize - 1 ) ) NEW_LINE DEDENT DEDENT arr = [ ' A ' , ' B ' , ' X ' , '4' , '6' , ' X ' , ' a ' ] NEW_LINE size = len ( arr ) NEW_LINE findSubArray ( arr , size ) NEW_LINE
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 generated from any permutation of the two strings selected from the given vector ; Sort the given string ; Select two strings at a time from given vector ; Get the concatenated string ; Sort the resultant string ; If the resultant string is equal to the given string str ; No valid pair found ; Driver code
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 ] ) : NEW_LINE INDENT s = s . replace ( s [ index ] , chr ( 97 + i ) ) NEW_LINE index += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT def isPossible ( v , str1 ) : NEW_LINE INDENT countingsort ( str1 ) ; NEW_LINE for i in range ( len ( v ) - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , len ( v ) , 1 ) : NEW_LINE INDENT temp = v [ i ] + v [ j ] NEW_LINE countingsort ( temp ) NEW_LINE if ( temp == str1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " amazon " NEW_LINE v = [ " fds " , " oxq " , " zoa " , " epw " , " amn " ] NEW_LINE if ( isPossible ( v , str1 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 under consideration ; If it is equal to the character at the current index ; Function to return the frequency of the given character in the sub - string str [ l ... r ] ; Function to return the first non - repeating character in range [ l . . r ] ; Starting from the first character ; Current character ; If frequency of the current character is 1 then return the character ; All the characters of the sub - string are repeating ; Driver Code ; Pre - calculate the frequency array
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 ( j ) NEW_LINE if charToUpdate == ch : NEW_LINE INDENT freq [ j ] [ i ] = freq [ j ] [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ j ] [ i ] = freq [ j ] [ i - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def getFrequency ( ch , l , r ) : NEW_LINE INDENT if l == 0 : NEW_LINE INDENT return freq [ ord ( ch ) ] [ r ] NEW_LINE DEDENT else : NEW_LINE INDENT return ( freq [ ord ( ch ) ] [ r ] - freq [ ord ( ch ) ] [ l - 1 ] ) NEW_LINE DEDENT DEDENT def firstNonRepeating ( string , n , l , r ) : NEW_LINE INDENT t = [ " " ] * 2 NEW_LINE for i in range ( l , r ) : NEW_LINE INDENT ch = string [ i ] NEW_LINE if getFrequency ( ch , l , r ) == 1 : NEW_LINE INDENT t [ 0 ] = ch NEW_LINE return t [ 0 ] NEW_LINE DEDENT DEDENT return " - 1" NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GeeksForGeeks " NEW_LINE n = len ( string ) NEW_LINE queries = [ ( 0 , 3 ) , ( 2 , 3 ) , ( 5 , 12 ) ] NEW_LINE q = len ( queries ) NEW_LINE preCalculate ( string , n ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( firstNonRepeating ( string , n , queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) NEW_LINE DEDENT DEDENT
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 character ' a ' to 'z ; finding frequency prefix array of the character ; Finding the r [ ] and l [ ] arrays . ; for each j from 0 to n ; Finding the lower bound of i . ; storing the maximum value of i - j + 1 ; clearing all the vector so that it can be used for other characters . ; Driver Code
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 ] ) - ord ( ' a ' ) == i ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT freq [ j ] = count ; NEW_LINE DEDENT for j in range ( n ) : NEW_LINE INDENT L . append ( ( 2 * freq [ j - 1 ] ) - j ) ; NEW_LINE R . append ( ( 2 * freq [ j ] ) - j ) ; NEW_LINE DEDENT max_len = - ( sys . maxsize + 1 ) ; NEW_LINE min_val = sys . maxsize ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT min_val = min ( min_val , L [ j ] ) ; NEW_LINE A . append ( min_val ) ; NEW_LINE l = 0 ; r = j ; NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = ( l + r ) >> 1 ; NEW_LINE if ( A [ mid ] <= R [ j ] ) : NEW_LINE INDENT max_len = max ( max_len , j - mid + 1 ) ; NEW_LINE r = mid - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT l = mid + 1 ; NEW_LINE DEDENT DEDENT DEDENT ans = max ( ans , max_len ) ; NEW_LINE A . clear ( ) ; NEW_LINE R . clear ( ) ; NEW_LINE L . clear ( ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " ababbbacbcbcca " ; NEW_LINE n = len ( s ) ; NEW_LINE print ( maxLength ( s , n ) ) ; NEW_LINE DEDENT
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 see a visited character . ; Driver program to test above function
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 . index ( string [ i ] ) ] == False ) : NEW_LINE INDENT visited [ string . index ( string [ i ] ) ] = True ; NEW_LINE DEDENT else : NEW_LINE INDENT res = i ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE index = firstRepeating ( string ) ; NEW_LINE if ( index == - 1 ) : NEW_LINE INDENT print ( " Either ▁ all ▁ characters ▁ are " , " distinct ▁ or ▁ string ▁ is ▁ empty " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " First ▁ Repeating ▁ character ▁ is : " , string [ index ] ) ; NEW_LINE DEDENT DEDENT
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 ; Update the sum starting at the current element ; Update the maximum so far ; Driver code
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 = max ( maximum , sum [ i ] ) NEW_LINE DEDENT return maximum ; NEW_LINE DEDENT arr = [ 3 , 6 , 4 , 7 , 2 ] NEW_LINE n = len ( arr ) ; NEW_LINE K = 2 NEW_LINE print ( maxSum ( arr , n , K ) ) NEW_LINE
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 of valid pairs ; Driver code
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 ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT count += min ( freq1 [ i ] , freq2 [ i ] ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " geeksforgeeks " ; NEW_LINE s2 = " platformforgeeks " ; NEW_LINE n1 = len ( s1 ) ; NEW_LINE n2 = len ( s2 ) ; NEW_LINE print ( countPairs ( s1 , n1 , s2 , n2 ) ) ; NEW_LINE DEDENT
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 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 1 NEW_LINE r = 10 NEW_LINE findpair ( l , r ) NEW_LINE DEDENT
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 unique elements in the array ; Driver code
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_LINE if ( check ( arr , N , K ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 ( value > occur ) : NEW_LINE INDENT occur = value NEW_LINE DEDENT DEDENT for key , value in mpp . items ( ) : NEW_LINE INDENT if ( value == occur ) : NEW_LINE INDENT print ( key ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 8 , 3 , 11 , 4 , 9 , 2 , 7 ] NEW_LINE n = len ( a ) NEW_LINE findSumPairs ( a , n ) NEW_LINE DEDENT
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 = 4 NEW_LINE print ( minIndex ( arr , n , pos ) ) NEW_LINE
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 iteration the if condition will satisfy and loop will break post that low will be updated . Hence i will not point to the correct index . ; Driver code
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 > 0 and arr [ mid - 1 ] != arr [ pos ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return low if arr [ low ] == arr [ pos ] else i NEW_LINE DEDENT arr = [ 2 , 1 , 1 , 1 , 5 , 2 ] NEW_LINE
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 both the strings ; Checking remaining part of string for equality ; Searching in right of string h ( g to h ) ; Driver code
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 [ i ] != str2 [ i ] ) : NEW_LINE INDENT r = i NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT / * If str1 = str2 * / NEW_LINE INDENT if ( r < l ) : NEW_LINE INDENT return 26 * ( n + 1 ) NEW_LINE DEDENT elif ( l == r ) : NEW_LINE INDENT return ans NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( l + 1 , r + 1 ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ i - 1 ] ) : NEW_LINE INDENT ans -= 1 NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( l + 1 , r + 1 ) : NEW_LINE INDENT if ( str1 [ i - 1 ] != str2 [ i ] ) : NEW_LINE INDENT ans -= 1 NEW_LINE break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT DEDENT str1 = " toy " NEW_LINE str2 = " try " NEW_LINE n = len ( str1 ) NEW_LINE print ( findAnswer ( str1 , str2 , n ) ) NEW_LINE
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 print ( findMinDifference ( arr , n ) ) NEW_LINE DEDENT
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 is smaller than min ; min will become secondMin ; Update the min ; If current element is smaller than secondMin but greater than min ; Update the secondMin ; Minimum of the two possible differences ; Driver code
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_LINE INDENT max__ = secondMin = arr [ 0 ] NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT if ( arr [ i ] > max__ ) : NEW_LINE INDENT secondMax = max__ NEW_LINE max__ = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > secondMax ) : NEW_LINE INDENT secondMax = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < min__ ) : NEW_LINE INDENT secondMin = min__ NEW_LINE min__ = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < secondMin ) : NEW_LINE INDENT secondMin = arr [ i ] NEW_LINE DEDENT DEDENT diff = min ( max__ - secondMin , secondMax - min__ ) NEW_LINE return diff NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMinDifference ( arr , n ) ) NEW_LINE DEDENT
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 single distinct digit ; Driver code
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 INDENT if ( checkDistinct ( i ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT L = 10 NEW_LINE R = 50 NEW_LINE print ( findCount ( L , R ) ) 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 minimum pair ; Driver code
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_LINE INDENT secondMin = a [ j ] NEW_LINE DEDENT DEDENT return ( secondMin + min ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( smallest_pair ( arr , n ) ) NEW_LINE DEDENT
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 , max_count ) NEW_LINE DEDENT return max_count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 5 , 11 , 32 , 64 , 88 ] NEW_LINE n = len ( arr ) NEW_LINE k = 8 NEW_LINE print ( longestsubarray ( arr , n , k ) ) NEW_LINE DEDENT
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 or equal to k times . ; Driver Code
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 = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 2 , 2 , 3 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE removeElements ( arr , n , k ) NEW_LINE
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 ( " NO " ) NEW_LINE DEDENT
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 equal to k times . ; Driver Code
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 DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 3 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE RemoveElements ( arr , n , k ) 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 SmallestElement ; Search if the element is present ; Decrement its frequency ; If the frequency becomes 0 , erase it from the map ; Else compare it SmallestElement ; Driver code
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 SmallestElement = 10 ** 9 NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( arr [ i ] in mp . keys ( ) ) : NEW_LINE INDENT mp [ arr [ i ] ] -= 1 NEW_LINE if ( mp [ arr [ i ] ] == 0 ) : NEW_LINE INDENT mp . pop ( arr [ i ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT SmallestElement = min ( SmallestElement , arr [ i ] ) NEW_LINE DEDENT DEDENT return SmallestElement NEW_LINE DEDENT array = [ 5 , 12 , 33 , 4 , 56 , 12 , 20 ] NEW_LINE m = len ( array ) NEW_LINE dell = [ 12 , 4 , 56 , 5 ] NEW_LINE n = len ( dell ) NEW_LINE print ( findSmallestAfterDel ( array , m , dell , n ) ) NEW_LINE
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 largestElement ; Search if the element is present ; Decrement its frequency ; If the frequency becomes 0 , erase it from the map ; Else compare it largestElement ; Driver code
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 largestElement = - 10 ** 9 NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( arr [ i ] in mp . keys ( ) ) : NEW_LINE INDENT mp [ arr [ i ] ] -= 1 NEW_LINE if ( mp [ arr [ i ] ] == 0 ) : NEW_LINE INDENT mp . pop ( arr [ i ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT largestElement = max ( largestElement , arr [ i ] ) NEW_LINE DEDENT DEDENT return largestElement NEW_LINE DEDENT array = [ 5 , 12 , 33 , 4 , 56 , 12 , 20 ] NEW_LINE m = len ( array ) NEW_LINE dell = [ 12 , 33 , 56 , 5 ] NEW_LINE n = len ( dell ) NEW_LINE print ( findlargestAfterDel ( array , m , dell , n ) ) NEW_LINE
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 DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 1 , 8 ] NEW_LINE k = 5 NEW_LINE n = len ( arr ) NEW_LINE print ( countAnomalies ( arr , n , k ) ) NEW_LINE DEDENT
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 if ( value >= ( int ( ( N * M ) / 2 ) ) ) : NEW_LINE INDENT countMajority += 1 NEW_LINE DEDENT DEDENT return countMajority NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 2 , 2 ] , [ 1 , 3 , 2 ] , [ 1 , 2 , 6 ] ] NEW_LINE print ( majorityInMatrix ( mat ) ) NEW_LINE DEDENT
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 DEDENT max_diff = max ( max_diff , max_val - min_val ) NEW_LINE DEDENT return max_diff NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 5 , 3 , 5 , 4 , 0 ] , [ 5 , 6 , 7 , 8 , 9 ] , [ 0 , 6 , 3 , 4 , 12 ] , [ 9 , 7 , 12 , 4 , 3 ] ] NEW_LINE print ( " Max ▁ difference ▁ : " , colMaxDiff ( mat ) ) NEW_LINE DEDENT
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 NEW_LINE DEDENT DEDENT return ar [ a ] + 1 NEW_LINE DEDENT a = [ 1 , 2 , 3 , 4 , 5 , 6 , 8 ] NEW_LINE n = len ( a ) NEW_LINE print ( " Missing ▁ number : " , search ( a , n ) ) NEW_LINE
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 , 10 , 14 ] NEW_LINE L , R = 2 , 7 NEW_LINE n = len ( A ) NEW_LINE res_size = deleteElement ( A , L , R , n ) NEW_LINE for i in range ( res_size ) : NEW_LINE INDENT print ( A [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT
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 mid + 1. . n else it lies in 0. . mid - 1 ; Function to find Longest subarray having average greater than or equal to x . ; Update array by subtracting x from each element ; Length of Longest subarray . ; list to store pair of prefix sum and corresponding ending index value . ; To store current value of prefix sum . ; To store minimum index value in range 0. . i of preSum vector . ; Insert values in preSum vector ; Update minInd array . ; If sum is greater than or equal to 0 , then answer is i + 1 ; If sum is less than 0 , then find if there is a prefix array having sum that needs to be added to current sum to make its value greater than or equal to 0. If yes , then compare length of updated subarray with maximum length found so far ; Driver Code
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 DEDENT return ans NEW_LINE DEDENT def LongestSub ( arr , n , x ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] -= x NEW_LINE DEDENT maxlen = 0 NEW_LINE preSum = [ ] NEW_LINE total = 0 NEW_LINE minInd = [ None ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT total += arr [ i ] NEW_LINE preSum . append ( ( total , i ) ) NEW_LINE DEDENT preSum = sorted ( preSum ) NEW_LINE minInd [ 0 ] = preSum [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT minInd [ i ] = min ( minInd [ i - 1 ] , preSum [ i ] [ 1 ] ) NEW_LINE DEDENT total = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT total += arr [ i ] NEW_LINE if total >= 0 : NEW_LINE INDENT maxlen = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ind = findInd ( preSum , n , total ) NEW_LINE if ( ind != - 1 ) & ( minInd [ ind ] < i ) : NEW_LINE INDENT maxlen = max ( maxlen , i - minInd [ ind ] ) NEW_LINE DEDENT DEDENT DEDENT return maxlen NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 2 , 1 , 6 , - 3 ] NEW_LINE n = len ( arr ) NEW_LINE x = 3 NEW_LINE print ( LongestSub ( arr , n , x ) ) NEW_LINE DEDENT