text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Count of pairs satisfying the given condition | Function to return the number of pairs satisfying the equation ; Converting integer b to string by using to_function ; Loop to check if all the digits of b are 9 or not ; If '9' doesn 't appear then break the loop ; If all the digits of b contain 9 then multiply a with length else multiply a with length - 1 ; Return the number of pairs ; Driver code
def countPair ( a , b ) : NEW_LINE INDENT s = str ( b ) NEW_LINE i = 0 NEW_LINE while i < ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] != '9' ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT result = 0 NEW_LINE if ( i == len ( s ) ) : NEW_LINE INDENT result = a * len ( s ) NEW_LINE DEDENT else : NEW_LINE INDENT result = a * ( len ( s ) - 1 ) NEW_LINE DEDENT return result NEW_LINE DEDENT a = 5 NEW_LINE b = 101 NEW_LINE print ( countPair ( a , b ) ) NEW_LINE
Partition the digits of an integer such that it satisfies a given condition | Function to generate sequence from the given string ; Initialize vector to store sequence ; First add all the digits of group A from left to right ; Then add all the digits of group B from left to right ; Return the sequence ; Function that returns true if the sequence is non - decreasing ; Initialize result ; Function to partition the digits of an integer such that it satisfies the given conditions ; Convert the integer to string ; Length of the string ; Array to store the digits ; Storing the digits of X in array ; Initialize the result ; Loop through the digits ; Put into group A if digit less than D ; Put into group B if digit greater than D ; Put into group C if digit equal to D ; Loop through the digits to decide for group C digits ; Set flag equal to true if group B digit present ; If flag is true put in group A or else put in B ; Generate the sequence from partition ; Check if the sequence is non decreasing ; Return - 1 if no such partition is possible ; Driver code
def makeSeq ( s , a ) : NEW_LINE INDENT seq = [ ] ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' A ' ) : NEW_LINE INDENT seq . append ( a [ i ] ) ; NEW_LINE DEDENT DEDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' B ' ) : NEW_LINE INDENT seq . append ( a [ i ] ) ; NEW_LINE DEDENT DEDENT return seq ; NEW_LINE DEDENT def checkSeq ( v ) : NEW_LINE INDENT check = True ; NEW_LINE for i in range ( 1 , len ( v ) ) : NEW_LINE INDENT if ( v [ i ] < v [ i - 1 ] ) : NEW_LINE INDENT check = False ; NEW_LINE DEDENT DEDENT return check ; NEW_LINE DEDENT def digitPartition ( X ) : NEW_LINE INDENT num = str ( X ) ; NEW_LINE l = len ( num ) ; NEW_LINE a = [ 0 ] * l ; NEW_LINE for i in range ( l ) : NEW_LINE INDENT a [ i ] = ( ord ( num [ i ] ) - ord ( '0' ) ) ; NEW_LINE DEDENT for D in range ( 10 ) : NEW_LINE INDENT res = " " ; NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( a [ i ] < D ) : NEW_LINE INDENT res += ' A ' ; NEW_LINE DEDENT elif ( a [ i ] > D ) : NEW_LINE INDENT res += ' B ' ; NEW_LINE DEDENT else : NEW_LINE INDENT res += ' C ' ; NEW_LINE DEDENT DEDENT flag = False ; NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( res [ i ] == ' B ' ) : NEW_LINE INDENT flag = True ; NEW_LINE DEDENT res = list ( res ) ; NEW_LINE if ( res [ i ] == ' C ' ) : NEW_LINE INDENT res [ i ] = ' A ' if flag else ' B ' ; NEW_LINE DEDENT DEDENT seq = makeSeq ( res , a ) ; NEW_LINE if ( checkSeq ( seq ) ) : NEW_LINE INDENT return " " . join ( res ) ; NEW_LINE DEDENT DEDENT return " - 1" ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 777147777 ; NEW_LINE print ( digitPartition ( X ) ) ; NEW_LINE DEDENT
Area of the circle that has a square and a circle inscribed in it | Python3 implementation of the approach ; Function to return the required area ; Calculate the area ; Driver code
import math NEW_LINE def getArea ( a ) : NEW_LINE INDENT area = ( math . pi * a * a ) / 4 NEW_LINE return area NEW_LINE DEDENT a = 3 NEW_LINE print ( ' { 0 : . 6f } ' . format ( getArea ( a ) ) ) NEW_LINE
Check if all the elements can be made of same parity by inverting adjacent elements | Function to check if parity can be made same or not ; Iterate and count the parity ; Odd ; Even ; Condition check ; Driver Code
def flipsPossible ( a , n ) : NEW_LINE INDENT count_odd = 0 ; count_even = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] & 1 ) : NEW_LINE INDENT count_odd += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT count_even += 1 ; NEW_LINE DEDENT DEDENT if ( count_odd % 2 and count_even % 2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT else : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 0 , 1 , 1 , 0 , 1 ] ; NEW_LINE n = len ( a ) ; NEW_LINE if ( flipsPossible ( a , n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Queries On Array with disappearing and reappearing elements | Function to perform the queries ; Size of the array with 1 - based indexing ; Number of queries ; Iterating through the queries ; If m is more than the size of the array ; Count of turns ; Find the remainder ; If the remainder is 0 and turn is odd then the array is empty ; If the remainder is 0 and turn is even then array is full and is in its initial state ; If the remainder is not 0 and the turn is even ; Current size of the array ; Current size of the array ; Print the result ; Driver code ; The initial array , - 1 is for 1 base indexing ; Queries in the form of the pairs of ( t , M )
def PerformQueries ( a , vec ) : NEW_LINE INDENT ans = [ ] ; NEW_LINE n = len ( a ) - 1 ; NEW_LINE q = len ( vec ) ; NEW_LINE for i in range ( q ) : NEW_LINE INDENT t = vec [ i ] [ 0 ] ; NEW_LINE m = vec [ i ] [ 1 ] ; NEW_LINE if ( m > n ) : NEW_LINE INDENT ans . append ( - 1 ) ; NEW_LINE continue ; NEW_LINE DEDENT turn = t // n ; NEW_LINE rem = t % n ; NEW_LINE if ( rem == 0 and turn % 2 == 1 ) : NEW_LINE INDENT ans . append ( - 1 ) ; NEW_LINE continue ; NEW_LINE DEDENT if ( rem == 0 and turn % 2 == 0 ) : NEW_LINE INDENT ans . append ( a [ m ] ) ; NEW_LINE continue ; NEW_LINE DEDENT if ( turn % 2 == 0 ) : NEW_LINE INDENT cursize = n - rem ; NEW_LINE if ( cursize < m ) : NEW_LINE INDENT ans . append ( - 1 ) ; NEW_LINE continue ; NEW_LINE DEDENT ans . append ( a [ m + rem ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT cursize = rem ; NEW_LINE if ( cursize < m ) : NEW_LINE INDENT ans . append ( - 1 ) ; NEW_LINE continue ; NEW_LINE DEDENT ans . append ( a [ m ] ) ; NEW_LINE DEDENT DEDENT for i in ans : NEW_LINE INDENT print ( i ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ - 1 , 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE vec = [ [ 1 , 4 ] , [ 6 , 1 ] , [ 3 , 5 ] ] ; NEW_LINE PerformQueries ( a , vec ) ; NEW_LINE DEDENT
Number of pairs in an array having sum equal to product | Function to return the count of the required pairs ; Find the count of 0 s and 2 s in the array ; Find the count of required pairs ; Return the count ; Driver code
def sumEqualProduct ( a , n ) : NEW_LINE INDENT zero = 0 NEW_LINE two = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] == 0 : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT if a [ i ] == 2 : NEW_LINE INDENT two += 1 NEW_LINE DEDENT DEDENT cnt = ( zero * ( zero - 1 ) ) // 2 + ( two * ( two - 1 ) ) // 2 NEW_LINE return cnt NEW_LINE DEDENT a = [ 2 , 2 , 3 , 4 , 2 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( sumEqualProduct ( a , n ) ) NEW_LINE
Minimize the sum of digits of A and B such that A + B = N | Function to return the minimum possible sum of digits of A and B such that A + B = n ; Find the sum of digits of n ; If num is a power of 10 ; Driver code
def minSum ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT sum += ( n % 10 ) ; NEW_LINE n //= 10 ; NEW_LINE DEDENT if ( sum == 1 ) : NEW_LINE INDENT return 10 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 1884 ; NEW_LINE print ( minSum ( n ) ) ; NEW_LINE DEDENT
Multiplication on Array : Range update query in O ( 1 ) | Creates a mul [ ] array for A [ ] and returns it after filling initial values . ; Does range update ; Prints updated Array ; Driver code ; ; Array to be updated ; Create and fill mul and div Array
def initialize ( mul , div , size ) : NEW_LINE INDENT for i in range ( 1 , size ) : NEW_LINE INDENT mul [ i ] = ( mul [ i ] * mul [ i - 1 ] ) / div [ i ] ; NEW_LINE DEDENT DEDENT def update ( l , r , x , mul , div ) : NEW_LINE INDENT mul [ l ] *= x ; NEW_LINE div [ r + 1 ] *= x ; NEW_LINE DEDENT def printArray ( ar , mul , div , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT ar [ i ] = ar [ i ] * mul [ i ] ; NEW_LINE print ( int ( ar [ i ] ) , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ar = [ 10 , 5 , 20 , 40 ] ; NEW_LINE n = len ( ar ) ; NEW_LINE mul = [ 0 ] * ( n + 1 ) ; NEW_LINE div = [ 0 ] * ( n + 1 ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT mul [ i ] = div [ i ] = 1 ; NEW_LINE DEDENT update ( 0 , 1 , 10 , mul , div ) ; NEW_LINE update ( 1 , 3 , 20 , mul , div ) ; NEW_LINE update ( 2 , 2 , 2 , mul , div ) ; NEW_LINE initialize ( mul , div , n + 1 ) ; NEW_LINE printArray ( ar , mul , div , n ) ; NEW_LINE DEDENT
Optimal Strategy for a Game | Special Gold Coin | Function to return the winner of the game ; To store the count of silver coins ; Update the position of the gold coin ; First player will win the game ; Driver code
def getWinner ( string , length ) : NEW_LINE INDENT total = 0 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( string [ i ] == ' S ' ) : NEW_LINE INDENT total += 1 ; NEW_LINE DEDENT DEDENT if ( ( total % 2 ) == 1 ) : NEW_LINE INDENT return " First " ; NEW_LINE DEDENT return " Second " ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GSSS " ; NEW_LINE length = len ( string ) ; NEW_LINE print ( getWinner ( string , length ) ) ; NEW_LINE DEDENT
Find the coordinates of a triangle whose Area = ( S / 2 ) | Python3 implementation of the approach ; Function to find the triangle with area = ( S / 2 ) ; Fix the two pairs of coordinates ; Find ( X3 , Y3 ) with integer coordinates ; Driver code
MAX = 1000000000 ; NEW_LINE def findTriangle ( S ) : NEW_LINE INDENT X1 = 0 ; Y1 = 0 ; NEW_LINE X2 = MAX ; Y2 = 1 ; NEW_LINE X3 = ( MAX - S % MAX ) % MAX ; NEW_LINE Y3 = ( S + X3 ) / MAX ; NEW_LINE print ( " ( " , X1 , " , " , Y1 , " ) " ) ; NEW_LINE print ( " ( " , X2 , " , " , Y2 , " ) " ) ; NEW_LINE print ( " ( " , X3 , " , " , Y3 , " ) " ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = 4 ; NEW_LINE findTriangle ( S ) ; NEW_LINE DEDENT
Rearrange array elements such that Bitwise AND of first N | Utility function to print the elements of an array ; Function to find the required arrangement ; There has to be atleast 2 elements ; Minimum element from the array ; Swap any occurrence of the minimum element with the last element ; Find the bitwise AND of the first ( n - 1 ) elements ; If the bitwise AND is equal to the last element then print the arrangement ; Driver code
def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT def findArrangement ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT print ( " - 1" , end = " " ) ; NEW_LINE return ; NEW_LINE DEDENT minVal = min ( arr ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == minVal ) : NEW_LINE INDENT arr [ i ] , arr [ n - 1 ] = arr [ n - 1 ] , arr [ i ] ; NEW_LINE break ; NEW_LINE DEDENT DEDENT andVal = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT andVal &= arr [ i ] ; NEW_LINE DEDENT if ( andVal == arr [ n - 1 ] ) : NEW_LINE INDENT printArr ( arr , n ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 5 , 3 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findArrangement ( arr , n ) ; NEW_LINE DEDENT
Maximum prime moves to convert X to Y | Function to return the maximum operations required to convert X to Y ; X cannot be converted to Y ; If the difference is 1 ; If the difference is even ; Add 3 to X and the new difference will be even ; Driver code
def maxOperations ( X , Y ) : NEW_LINE INDENT if ( X > Y ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT diff = Y - X ; NEW_LINE if ( diff == 1 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( diff % 2 == 0 ) : NEW_LINE INDENT return ( diff // 2 ) ; NEW_LINE DEDENT return ( 1 + ( ( diff - 3 ) // 2 ) ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 5 ; Y = 16 ; NEW_LINE print ( maxOperations ( X , Y ) ) ; NEW_LINE DEDENT
Sum of Digits of the Good Strings | Python3 implementation of the approach ; To store the states of the dp ; Function to fill the dp table ; Sum of digits of the string of length 1 is i as i is only number in that string and count of good strings of length 1 that end with i is also 1 ; Adjacent digits are different ; Increment the count as digit at ( i - 1 ) 'th index is k and count of good strings is equal to this because at the end of the strings of length (i - 1) we are just putting digit j as the last digit ; Driver code
DIGITS = 10 ; NEW_LINE MAX = 10000 ; NEW_LINE MOD = 1000000007 ; NEW_LINE dp = [ [ 0 for i in range ( DIGITS ) ] for i in range ( MAX ) ] ; NEW_LINE cnt = [ [ 0 for i in range ( DIGITS ) ] for i in range ( MAX ) ] ; NEW_LINE def precompute ( ) : NEW_LINE INDENT for i in range ( DIGITS ) : NEW_LINE INDENT dp [ 1 ] [ i ] = i ; NEW_LINE cnt [ 1 ] [ i ] = 1 ; NEW_LINE DEDENT for i in range ( 2 , MAX ) : NEW_LINE INDENT for j in range ( DIGITS ) : NEW_LINE INDENT for k in range ( DIGITS ) : NEW_LINE INDENT if ( j != k ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i ] [ j ] + ( dp [ i - 1 ] [ k ] + ( cnt [ i - 1 ] [ k ] * j ) % MOD ) % MOD ; NEW_LINE dp [ i ] [ j ] %= MOD ; NEW_LINE cnt [ i ] [ j ] += cnt [ i - 1 ] [ k ] ; NEW_LINE cnt [ i ] [ j ] %= MOD ; NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT x = 6 ; y = 4 ; NEW_LINE precompute ( ) ; NEW_LINE print ( dp [ x ] [ y ] ) ; NEW_LINE
Count non | Python implementation of the approach ; Function to pre - compute the sequence ; For N = 1 the answer will be 2 ; Starting two terms of the sequence ; Compute the rest of the sequence with the relation F [ i ] = F [ i - 1 ] + F [ i - 2 ] ; Driver code ; Pre - compute the sequence
N = 10000 ; NEW_LINE MOD = 1000000007 ; NEW_LINE F = [ 0 ] * N ; NEW_LINE def precompute ( ) : NEW_LINE INDENT F [ 1 ] = 2 ; NEW_LINE F [ 2 ] = 3 ; NEW_LINE F [ 3 ] = 4 ; NEW_LINE for i in range ( 4 , N ) : NEW_LINE INDENT F [ i ] = ( F [ i - 1 ] + F [ i - 2 ] ) % MOD ; NEW_LINE DEDENT DEDENT n = 8 ; NEW_LINE precompute ( ) ; NEW_LINE print ( F [ n ] ) ; NEW_LINE
Minimize sum by dividing all elements of a subarray by K | Python3 implementation of the approach ; Function to return the maximum subarray sum ; Function to return the minimized sum of the array elements after performing the given operation ; Find maximum subarray sum ; Find total sum of the array ; Maximum subarray sum is already negative ; Choose the subarray whose sum is maximum and divide all elements by K ; Driver code
import sys NEW_LINE def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - ( sys . maxsize - 1 ) ; NEW_LINE max_ending_here = 0 ; NEW_LINE for i in range ( size ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] ; NEW_LINE if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_here ; NEW_LINE DEDENT if ( max_ending_here < 0 ) : NEW_LINE INDENT max_ending_here = 0 ; NEW_LINE DEDENT DEDENT return max_so_far ; NEW_LINE DEDENT def minimizedSum ( a , n , K ) : NEW_LINE INDENT sum = maxSubArraySum ( a , n ) ; NEW_LINE totalSum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT totalSum += a [ i ] ; NEW_LINE DEDENT if ( sum < 0 ) : NEW_LINE INDENT return totalSum ; NEW_LINE DEDENT totalSum = totalSum - sum + sum / K ; NEW_LINE return totalSum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , - 2 , 3 ] ; NEW_LINE n = len ( a ) ; NEW_LINE K = 2 ; NEW_LINE print ( minimizedSum ( a , n , K ) ) ; NEW_LINE DEDENT
Minimum numbers with one 's place as 9 to be added to get N | Function to find minimum count of numbers ( with one 's digit 9) that sum up to N ; Fetch one 's digit ; Apply Cases mentioned in approach ; If no possible answer exists ; Driver Code
def findMin ( N : int ) : NEW_LINE INDENT digit = N % 10 NEW_LINE if digit == 0 and N >= 90 : NEW_LINE INDENT return 10 NEW_LINE DEDENT elif digit == 1 and N >= 81 : NEW_LINE INDENT return 9 NEW_LINE DEDENT elif digit == 2 and N >= 72 : NEW_LINE INDENT return 8 NEW_LINE DEDENT elif digit == 3 and N >= 63 : NEW_LINE INDENT return 7 NEW_LINE DEDENT elif digit == 4 and N >= 54 : NEW_LINE INDENT return 6 NEW_LINE DEDENT elif digit == 5 and N >= 45 : NEW_LINE INDENT return 5 NEW_LINE DEDENT elif digit == 6 and N >= 36 : NEW_LINE INDENT return 4 NEW_LINE DEDENT elif digit == 7 and N >= 27 : NEW_LINE INDENT return 3 NEW_LINE DEDENT elif digit == 8 and N >= 18 : NEW_LINE INDENT return 2 NEW_LINE DEDENT elif digit == 9 and N >= 9 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 27 NEW_LINE print ( findMin ( N ) ) NEW_LINE DEDENT
Random list of M non | Python3 implementation of the approach ; Utility function to print the elements of an array ; Function to generate a list of m random non - negative integers whose sum is n ; Create an array of size m where every element is initialized to 0 ; To make the sum of the final list as n ; Increment any random element from the array by 1 ; Print the generated list ; Driver code
from random import randint NEW_LINE def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT def randomList ( m , n ) : NEW_LINE INDENT arr = [ 0 ] * m ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ randint ( 0 , n ) % m ] += 1 ; NEW_LINE DEDENT printArr ( arr , m ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m = 4 ; n = 8 ; NEW_LINE randomList ( m , n ) ; NEW_LINE DEDENT
Maximum String Partition | Return the count of string ; P will store the answer ; Current will store current string Previous will store the previous that has been taken already ; Add a character to current string ; Here we will create a partition and update the previous with current string ; Now we will clear the current string ; Increment the count of partition . ; Driver code
def maxPartition ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE P = 0 NEW_LINE current = " " NEW_LINE previous = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT current += s [ i ] NEW_LINE if ( current != previous ) : NEW_LINE INDENT previous = current NEW_LINE current = " " NEW_LINE P += 1 NEW_LINE DEDENT DEDENT return P NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE ans = maxPartition ( s ) NEW_LINE print ( ans ) NEW_LINE
How to learn Pattern printing easily ? |
N = 4 ; NEW_LINE print ( " Value ▁ of ▁ N : ▁ " , N ) ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT min = i if i < j else j ; NEW_LINE print ( N - min + 1 , end = " " ) ; NEW_LINE DEDENT for j in range ( N - 1 , 0 , - 1 ) : NEW_LINE INDENT min = i if i < j else j ; NEW_LINE print ( N - min + 1 , end = " " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT
Find the smallest positive number missing from an unsorted array | Set 3 | Function to find the smallest positive missing number ; Default smallest Positive Integer ; Store values in set which are greater than variable m ; Store value when m is less than current index of given array ; Increment m when it is equal to current element ; Increment m when it is one of the element of the set ; Return the required answer ; Driver code ; Function call
def findMissingPositive ( arr , n ) : NEW_LINE INDENT m = 1 NEW_LINE x = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( m < arr [ i ] ) : NEW_LINE INDENT x . append ( arr [ i ] ) NEW_LINE DEDENT elif ( m == arr [ i ] ) : NEW_LINE INDENT m = m + 1 NEW_LINE while ( x . count ( m ) ) : NEW_LINE INDENT x . remove ( m ) NEW_LINE m = m + 1 NEW_LINE DEDENT DEDENT DEDENT return m NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , - 7 , 6 , 8 , 1 , - 10 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMissingPositive ( arr , n ) ) NEW_LINE DEDENT
Sum of all second largest divisors after splitting a number into one or more parts | Python 3 program to find sum of all second largest divisor after splitting a number into one or more parts ; Function to find a number is prime or not ; If there is any divisor ; Function to find the sum of all second largest divisor after splitting a number into one or more parts ; If number is prime ; If n is even ; If the number is odd ; If N - 2 is prime ; There exists 3 primes x1 , x2 , x3 such that x1 + x2 + x3 = n ; Driver code ; Function call
from math import sqrt NEW_LINE def prime ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def Min_Sum ( n ) : NEW_LINE INDENT if ( prime ( n ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT else : NEW_LINE INDENT if ( prime ( n - 2 ) ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT else : NEW_LINE INDENT return 3 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 27 NEW_LINE print ( Min_Sum ( n ) ) NEW_LINE DEDENT
Count pairs of strings that satisfy the given conditions | Function that returns true if c is vowel ; Function to return the count of required pairs ; For every of the array ; Vector to store the vowels of the current string ; If current character is a vowel ; If current contains vowels ; Create tuple ( first vowel , last vowel , total vowels ) ; v stores the indices for which the given condition satisfies Total valid pairs will be half the size ; Driver code
def is_vowel ( c ) : NEW_LINE INDENT return ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) NEW_LINE DEDENT def count ( s , n ) : NEW_LINE INDENT map = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT vowel = [ ] NEW_LINE for j in range ( len ( s [ i ] ) ) : NEW_LINE INDENT if ( is_vowel ( s [ i ] [ j ] ) ) : NEW_LINE INDENT vowel . append ( s [ i ] [ j ] ) NEW_LINE DEDENT DEDENT if ( len ( vowel ) > 0 ) : NEW_LINE INDENT Len = len ( vowel ) NEW_LINE if ( vowel [ 0 ] , vowel [ Len - 1 ] , Len ) in map . keys ( ) : NEW_LINE INDENT map [ ( vowel [ 0 ] , vowel [ Len - 1 ] , Len ) ] . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT map [ ( vowel [ 0 ] , vowel [ Len - 1 ] , Len ) ] = [ i , ] NEW_LINE DEDENT DEDENT DEDENT count = 0 NEW_LINE for i in map : NEW_LINE INDENT v = map [ i ] NEW_LINE count += len ( v ) // 2 NEW_LINE DEDENT return count NEW_LINE DEDENT s = [ " geeks " , " for " , " geeks " ] NEW_LINE n = len ( s ) NEW_LINE print ( count ( s , n ) ) NEW_LINE
Find maximum value of the last element after reducing the array with given operations | Function to return the maximized value ; Overall minimum absolute value of some element from the array ; Add all absolute values ; Count positive and negative elements ; Both positive and negative values are present ; Only positive or negative values are present ; Driver code
def find_maximum_value ( a , n ) : NEW_LINE INDENT sum = 0 NEW_LINE minimum = 10 ** 9 NEW_LINE pos = 0 NEW_LINE neg = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT minimum = min ( minimum , abs ( a [ i ] ) ) NEW_LINE sum += abs ( a [ i ] ) NEW_LINE if ( a [ i ] >= 0 ) : NEW_LINE INDENT pos += 1 NEW_LINE DEDENT else : NEW_LINE INDENT neg += 1 NEW_LINE DEDENT DEDENT if ( pos > 0 and neg > 0 ) : NEW_LINE INDENT return sum NEW_LINE DEDENT return ( sum - 2 * minimum ) NEW_LINE DEDENT a = [ 5 , 4 , 6 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( find_maximum_value ( a , n ) ) NEW_LINE
Find Nth smallest number that is divisible by 100 exactly K times | Function to find the Nth smallest number ; If N is divisible by 100 then we multiply N + 1 otherwise , it will be divisible by 100 more than K times ; convert integer to string ; if N is not divisible by 100 ; convert integer to string ; add 2 * K 0 's at the end to be divisible by 100 exactly K times ; Driver Code
def find_number ( N , K ) : NEW_LINE INDENT r = " " NEW_LINE if ( N % 100 == 0 ) : NEW_LINE INDENT N += 1 ; NEW_LINE r = str ( N ) NEW_LINE DEDENT else : NEW_LINE INDENT r = str ( N ) NEW_LINE DEDENT for i in range ( 1 , K + 1 ) : NEW_LINE INDENT r += "00" NEW_LINE DEDENT return r NEW_LINE DEDENT N = 1000 NEW_LINE K = 2 ; NEW_LINE ans = find_number ( N , K ) NEW_LINE print ( ans ) NEW_LINE
Count of adjacent Vowel Consonant Pairs | Function to count the adjacent pairs of consonant and vowels in the string ; Using a set to store the vowels so that checking each character becomes easier ; Variable to store number of consonant - vowel pairs ; If the ith character is not found in the set , means it is a consonant And if the ( i + 1 ) th character is found in the set , means it is a vowel We increment the count of such pairs ; Driver Code
def countPairs ( s ) : NEW_LINE INDENT st = set ( ) ; NEW_LINE st . add ( ' a ' ) ; NEW_LINE st . add ( ' e ' ) ; NEW_LINE st . add ( ' i ' ) ; NEW_LINE st . add ( ' o ' ) ; NEW_LINE st . add ( ' u ' ) ; NEW_LINE count = 0 ; NEW_LINE n = len ( s ) ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( s [ i ] not in st and s [ i + 1 ] in st ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeksforgeeks " ; NEW_LINE print ( countPairs ( s ) ) ; NEW_LINE DEDENT
Find the largest interval that contains exactly one of the given N integers . | Function to return the maximum size of the required interval ; Insert the borders for array ; Sort the elements in ascending order ; To store the maximum size ; To store the range [ L , R ] such that only v [ i ] lies within the range ; Total integers in the range ; Driver code
def maxSize ( v , n ) : NEW_LINE INDENT v . append ( 0 ) NEW_LINE v . append ( 100001 ) NEW_LINE n += 2 NEW_LINE v = sorted ( v ) NEW_LINE mx = 0 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT L = v [ i - 1 ] + 1 NEW_LINE R = v [ i + 1 ] - 1 NEW_LINE cnt = R - L + 1 NEW_LINE mx = max ( mx , cnt ) NEW_LINE DEDENT return mx NEW_LINE DEDENT v = [ 200 , 10 , 5 ] NEW_LINE n = len ( v ) NEW_LINE print ( maxSize ( v , n ) ) NEW_LINE
Maximum length of subarray such that sum of the subarray is even | Function to find Length of the longest subarray such that Sum of the subarray is even ; Check if Sum of complete array is even ; if ( Sum % 2 == 0 ) : total Sum is already even ; Find an index i such the a [ i ] is odd and compare Length of both halfs excluding a [ i ] to find max Length subarray ; Driver Code
def maxLength ( a , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE Len = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum += a [ i ] NEW_LINE return n NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 2 == 1 ) : NEW_LINE INDENT Len = max ( Len , max ( n - i - 1 , i ) ) NEW_LINE DEDENT DEDENT return Len NEW_LINE DEDENT a = [ 1 , 2 , 3 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( maxLength ( a , n ) ) NEW_LINE
Find a Symmetric matrix of order N that contain integers from 0 to N | Function to generate the required matrix ; Form cyclic array of elements 1 to n - 1 ; Store initial array into final array ; Fill the last row and column with 0 's ; Swap 0 and the number present at the current indexed row ; Also make changes in the last row with the number we swapped ; Print the final array ; Driver code
def solve ( n ) : NEW_LINE INDENT initial_array = [ [ 0 for i in range ( n - 1 ) ] for j in range ( n - 1 ) ] NEW_LINE final_array = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT initial_array [ 0 ] [ i ] = i + 1 NEW_LINE DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT for j in range ( n - 1 ) : NEW_LINE INDENT initial_array [ i ] [ j ] = initial_array [ i - 1 ] [ ( j + 1 ) % ( n - 1 ) ] NEW_LINE DEDENT DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( n - 1 ) : NEW_LINE INDENT final_array [ i ] [ j ] = initial_array [ i ] [ j ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT final_array [ i ] [ n - 1 ] = final_array [ n - 1 ] [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT t0 = final_array [ i ] [ i ] NEW_LINE t1 = final_array [ i ] [ n - 1 ] NEW_LINE temp = final_array [ i ] [ i ] NEW_LINE final_array [ i ] [ i ] = final_array [ i ] [ n - 1 ] NEW_LINE final_array [ i ] [ n - 1 ] = temp NEW_LINE final_array [ n - 1 ] [ i ] = t0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( final_array [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " , end ▁ = ▁ " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE solve ( n ) NEW_LINE DEDENT
Generate original array from difference between every two consecutive elements | Function to print the required permutation ; Take x = 0 for simplicity ; Calculate athe differences and store it in a vector ; Preserve the original array ; Check if athe consecutive elements have difference = 1 ; If consecutive elements don 't have difference 1 at any position then the answer is impossible ; Else store the indices and values at those indices in a map and finainty print them ; Driver code
def findPerm ( n , differences ) : NEW_LINE INDENT ans = [ ] NEW_LINE ans . append ( 0 ) NEW_LINE x = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT diff = differences [ i ] NEW_LINE x = x + diff NEW_LINE ans . append ( x ) NEW_LINE DEDENT anss = ans NEW_LINE ans = sorted ( ans ) NEW_LINE flag = - 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT res = ans [ i ] - ans [ i - 1 ] NEW_LINE if ( res != 1 ) : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT mpp = dict ( ) NEW_LINE j = 1 NEW_LINE value_at_index = [ ] NEW_LINE for x in ans : NEW_LINE INDENT mpp [ x ] = j NEW_LINE j += 1 NEW_LINE DEDENT for x in anss : NEW_LINE INDENT value_at_index . append ( mpp [ x ] ) NEW_LINE DEDENT for x in value_at_index : NEW_LINE INDENT print ( x , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT differences = [ ] NEW_LINE differences . append ( 2 ) NEW_LINE differences . append ( - 3 ) NEW_LINE differences . append ( 2 ) NEW_LINE n = len ( differences ) + 1 NEW_LINE findPerm ( n , differences ) NEW_LINE
Find smallest number K such that K % p = 0 and q % K = 0 | Function to return the minimum value K such that K % p = 0 and q % k = 0 ; If K is possible ; No such K is possible ; Driver code
def getMinVal ( p , q ) : NEW_LINE INDENT if q % p == 0 : NEW_LINE INDENT return p NEW_LINE DEDENT return - 1 NEW_LINE DEDENT p = 24 ; q = 48 NEW_LINE print ( getMinVal ( p , q ) ) NEW_LINE
Sort the numbers according to their sum of digits | Function to return the sum of the digits of n ; Function to sort the array according to the sum of the digits of elements ; Vector to store digit sum with respective element ; Inserting digit sum with element in the vector pair ; Quick sort the vector , this will sort the pair according to sum of the digits of elements ; Print the sorted vector content ; Driver code
def sumOfDigit ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT sum += n % 10 ; NEW_LINE n = n // 10 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT vp = [ ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT vp . append ( [ sumOfDigit ( arr [ i ] ) , arr [ i ] ] ) ; NEW_LINE DEDENT vp . sort ( ) NEW_LINE for i in range ( len ( vp ) ) : NEW_LINE INDENT print ( vp [ i ] [ 1 ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 14 , 1101 , 10 , 35 , 0 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE sortArr ( arr , n ) ; NEW_LINE DEDENT
Count all Prime Length Palindromic Substrings | Python3 implementation of the approach ; Function that returns True if sub - str1ing starting at i and ending at j in str1 is a palindrome ; Function to count all palindromic substr1ing whose lwngth is a prime number ; 0 and 1 are non - primes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; To store the required number of sub - str1ings ; Starting from the smallest prime till the largest Length of the sub - str1ing possible ; If j is prime ; Check all the sub - str1ings of Length j ; If current sub - str1ing is a palindrome ; Driver Code
import math as mt NEW_LINE def isPalindrome ( str1 , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT if ( str1 [ i ] != str1 [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def countPrimePalindrome ( str1 , Len ) : NEW_LINE INDENT prime = [ True for i in range ( Len + 1 ) ] NEW_LINE prime [ 0 ] , prime [ 1 ] = False , False NEW_LINE for p in range ( 2 , mt . ceil ( mt . sqrt ( Len + 1 ) ) ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( 2 * p , Len + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT count = 0 NEW_LINE for j in range ( 2 , Len + 1 ) : NEW_LINE INDENT if ( prime [ j ] ) : NEW_LINE INDENT for i in range ( Len + 1 - j ) : NEW_LINE INDENT if ( isPalindrome ( str1 , i , i + j - 1 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return count NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE Len = len ( s ) NEW_LINE print ( countPrimePalindrome ( s , Len ) ) NEW_LINE
Minimum operations of the given type required to make a complete graph | Python 3 implementation of the approach ; Function to return the minimum number of steps required ; Driver Code
from math import log2 , ceil NEW_LINE def minOperations ( N ) : NEW_LINE INDENT x = log2 ( N ) NEW_LINE ans = ceil ( x ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE print ( minOperations ( N ) ) NEW_LINE DEDENT
Greatest divisor which divides all natural number in range [ L , R ] | Function to return the greatest divisor that divides all the natural numbers in the range [ l , r ] ; Driver Code
def find_greatest_divisor ( l , r ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT return l ; NEW_LINE DEDENT return 1 ; NEW_LINE DEDENT l = 2 ; NEW_LINE r = 12 ; NEW_LINE print ( find_greatest_divisor ( l , r ) ) ; NEW_LINE
Probability of getting two consecutive heads after choosing a random coin among two different types of coins | Function to return the probability of getting two consecutive heads ; Formula derived from Bayes 's theorem ; Driver code ; given the probability of getting a head for both the coins
def getProbability ( p , q ) : NEW_LINE INDENT p /= 100 NEW_LINE q /= 100 NEW_LINE probability = ( p * p + q * q ) / ( p + q ) NEW_LINE return probability NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p = 80 NEW_LINE q = 40 NEW_LINE print ( getProbability ( p , q ) ) NEW_LINE DEDENT
Check whether bitwise OR of N numbers is Even or Odd | Function to check if bitwise OR of n numbers is even or odd ; if at least one odd number is found , then the bitwise OR of all numbers will be odd ; Bitwise OR is an odd number ; Driver code
def check ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] & 1 : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 9 , 12 , 13 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE if check ( arr , n ) : NEW_LINE INDENT print ( " Odd ▁ Bit - wise ▁ OR " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Even ▁ Bit - wise ▁ OR " ) NEW_LINE DEDENT DEDENT
Time taken by Loop unrolling vs Normal loop | Python program to compare normal loops and loops with unrolling technique ; n is 8 lakhs ; t to note start time ; to store the sum ; Normal loop ; to mark end time ; to mark start time of unrolling ; Unrolling technique ( assuming that n is a multiple of 8 ) . ; to mark the end of loop
from timeit import default_timer as clock NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 800000 ; NEW_LINE t = clock ( ) NEW_LINE sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT t = clock ( ) - t NEW_LINE print ( " sum ▁ is : ▁ " + str ( sum ) ) NEW_LINE print ( " time ▁ taken ▁ by ▁ normal ▁ " + " loops : " + str ( t ) ) NEW_LINE t = clock ( ) NEW_LINE sum = 0 NEW_LINE for i in range ( 1 , n + 1 , 8 ) : NEW_LINE INDENT sum += i NEW_LINE sum += ( i + 1 ) NEW_LINE sum += ( i + 2 ) NEW_LINE sum += ( i + 3 ) NEW_LINE sum += ( i + 4 ) NEW_LINE sum += ( i + 5 ) NEW_LINE sum += ( i + 6 ) NEW_LINE sum += ( i + 7 ) NEW_LINE DEDENT t = clock ( ) - t NEW_LINE print ( " Sum ▁ is : ▁ " + str ( sum ) ) NEW_LINE print ( " Time ▁ taken ▁ by ▁ unrolling : ▁ " + str ( t ) ) NEW_LINE DEDENT
Iterated Logarithm log * ( n ) | Recursive Python3 program to find value of Iterated Logarithm ; Driver code
import math NEW_LINE def _log ( x , base ) : NEW_LINE INDENT return ( int ) ( math . log ( x ) / math . log ( base ) ) NEW_LINE DEDENT def recursiveLogStar ( n , b ) : NEW_LINE INDENT if ( n > 1.0 ) : NEW_LINE INDENT return 1.0 + recursiveLogStar ( _log ( n , b ) , b ) NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 100 NEW_LINE base = 5 NEW_LINE print ( " Log * ( " , n , " ) ▁ = ▁ " , recursiveLogStar ( n , base ) ) NEW_LINE DEDENT
Iterated Logarithm log * ( n ) | Iterative Python function to find value of Iterated Logarithm
def iterativeLogStar ( n , b ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n >= 1 ) : NEW_LINE INDENT n = _log ( n , b ) NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT
Tail Recursion | An example of tail recursive function ; The last executed statement is recursive call
def prints ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( str ( n ) , end = ' ▁ ' ) NEW_LINE prints ( n - 1 ) NEW_LINE DEDENT
Find the maximum among the count of positive or negative integers in the array | Function to find the maximum of the count of positive or negative elements ; Initialize the pointers ; Find the value of mid ; If element is negative then ignore the left half ; If element is positive then ignore the right half ; Return maximum among the count of positive & negative element ; Driver Code
def findMaximum ( arr , size ) : NEW_LINE INDENT i = 0 NEW_LINE j = size - 1 NEW_LINE while ( i <= j ) : NEW_LINE INDENT mid = i + ( j - i ) // 2 NEW_LINE if ( arr [ mid ] < 0 ) : NEW_LINE INDENT i = mid + 1 NEW_LINE DEDENT elif ( arr [ mid ] > 0 ) : NEW_LINE INDENT j = mid - 1 NEW_LINE DEDENT DEDENT return max ( i , size - i ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 9 , - 7 , - 4 , 1 , 5 , 8 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findMaximum ( arr , N ) ) NEW_LINE DEDENT
Perform given queries on Queue according to the given rules | Function to perform all the queries operations on the given queue ; Stores the count query of type 1 ; Event E1 : increase countE1 ; Event E2 : add the X in set ; Event E3 : Find position of X ; Initial position is ( position - countE1 ) ; If X is already removed or popped out ; Finding the position of X in queue ; Traverse set to decrease position of X for all the number removed in front ; Print the position of X ; Driver Code
def solve ( n , m , queries ) : NEW_LINE INDENT countE1 = 0 NEW_LINE removed = set ( ) NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT if ( queries [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT countE1 += 1 NEW_LINE DEDENT elif ( queries [ i ] [ 0 ] == 2 ) : NEW_LINE INDENT removed . add ( queries [ i ] [ 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT position = queries [ i ] [ 1 ] - countE1 NEW_LINE if ( queries [ i ] [ 1 ] in removed or position <= 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT for it in removed : NEW_LINE INDENT if ( it > queries [ i ] [ 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT position -= 1 NEW_LINE DEDENT print ( position ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE Q = 3 NEW_LINE queries = [ [ 0 for _ in range ( 2 ) ] for _ in range ( Q ) ] NEW_LINE queries [ 0 ] [ 0 ] = 1 NEW_LINE queries [ 0 ] [ 1 ] = 0 NEW_LINE queries [ 1 ] [ 0 ] = 3 NEW_LINE queries [ 1 ] [ 1 ] = 3 NEW_LINE queries [ 2 ] [ 0 ] = 2 NEW_LINE queries [ 2 ] [ 1 ] = 2 NEW_LINE solve ( N , Q , queries ) NEW_LINE DEDENT
Maximum index a pointer can reach in N steps by avoiding a given index B | Python 3 program for the above approach ; Function to find the maximum index reachable ; Store the answer ; Store the maximum index possible i . e , N * ( N - 1 ) ; Add bthe previous elements ; Run a loop ; Binary Search ; Driver Code
from bisect import bisect_left NEW_LINE def maxIndex ( N , B ) : NEW_LINE INDENT maximumIndexReached = 0 NEW_LINE Ans = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT maximumIndexReached += i NEW_LINE Ans . append ( i ) NEW_LINE DEDENT Ans . reverse ( ) NEW_LINE for i in range ( len ( Ans ) ) : NEW_LINE INDENT Ans [ i ] += Ans [ i - 1 ] NEW_LINE DEDENT while ( maximumIndexReached ) : NEW_LINE INDENT it = bisect_left ( Ans , maximumIndexReached - B ) NEW_LINE if ( it not in Ans ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( it == maximumIndexReached - B ) : NEW_LINE INDENT maximumIndexReached -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return maximumIndexReached NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE B = 2 NEW_LINE print ( maxIndex ( N , B ) ) NEW_LINE DEDENT
Maximize Kth largest element after splitting the given Array at most C times | Function to find the K - th maximum element after upto C operations ; Check for the base case ; Stores the count iterations of BS ; Create the left and right bounds of binary search ; Perform binary search ; Find the value of mid ; Traverse the array ; Update the ranges ; Return the maximum value obtained ; Driver Code
def maxKth ( arr , N , C , K ) : NEW_LINE INDENT if ( N + C < K ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT iter = 300 NEW_LINE l = 0 NEW_LINE r = 1000000000.0 NEW_LINE while ( iter ) : NEW_LINE INDENT iter = iter - 1 NEW_LINE mid = ( l + r ) * 0.5 NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT a += arr [ i ] // mid NEW_LINE if ( arr [ i ] >= mid ) : NEW_LINE INDENT b += 1 NEW_LINE DEDENT DEDENT if ( a >= K and b + C >= K ) : NEW_LINE INDENT l = mid NEW_LINE DEDENT else : NEW_LINE INDENT r = mid NEW_LINE DEDENT DEDENT return int ( l ) NEW_LINE DEDENT arr = [ 5 , 8 ] NEW_LINE K = 1 NEW_LINE C = 1 NEW_LINE N = len ( arr ) NEW_LINE print ( maxKth ( arr , N , C , K ) ) NEW_LINE
Maximize the minimum difference between any element pair by selecting K elements from given Array | To check if selection of K elements is possible such that difference between them is greater than dif ; Selecting first element in the sorted array ; prev is the previously selected element initially at index 0 as first element is already selected ; Check if selection of K - 1 elements from array with a minimum difference of dif is possible ; If the current element is atleast dif difference apart from the previously selected element then select the current element and increase the count ; If selection of K elements with a min difference of dif is possible then return true ; Prev will become current element for the next iteration ; If selection of K elements with minimum difference of dif is not possible then return false ; Minimum largest difference possible is 1 ; Check if selection of K elements is possible with a minimum difference of dif ; If dif is greater than previous ans we update ans ; Continue to search for better answer . Try finding greater dif ; K elements cannot be selected ; Driver code ; arr should be in a sorted order
def isPossibleToSelect ( arr , N , dif , K ) : NEW_LINE INDENT count = 1 NEW_LINE prev = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] >= ( prev + dif ) ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count == K ) : NEW_LINE INDENT return True NEW_LINE DEDENT prev = arr [ i ] NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def binarySearch ( arr , left , right , K , N ) : NEW_LINE INDENT ans = 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT dif = left + ( right - left ) // 2 NEW_LINE if ( isPossibleToSelect ( arr , N , dif , K ) ) : NEW_LINE INDENT ans = max ( ans , dif ) NEW_LINE left = dif + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = dif - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 NEW_LINE K = 4 NEW_LINE arr = [ 1 , 4 , 9 , 0 , 2 , 13 , 3 ] NEW_LINE arr . sort ( ) NEW_LINE print ( binarySearch ( arr , 0 , arr [ N - 1 ] , K , N ) ) NEW_LINE DEDENT
Find maximum height to cut all chocolates horizontally such that at least K amount remains | Function to find the sum of remaining chocolate after making the horizontal cut at height mid ; Stores the sum of chocolates ; Traverse the array arr [ ] ; If the height is at least mid ; Return the possible sum ; Function to find the maximum horizontal cut made to all the chocolates such that the sum of the remaining element is at least K ; Ranges of Binary Search ; Perform the Binary Search ; Find the sum of removed after making cut at height mid ; If the chocolate removed is same as the chocolate needed then return the height ; If the chocolate removed is less than chocolate needed then shift to the left range ; Otherwise , shift to the right range ; Return the possible cut ; Driver Code
def cal ( arr , mid ) : NEW_LINE INDENT chocolate = 0 NEW_LINE for i in arr : NEW_LINE INDENT if i >= mid : NEW_LINE INDENT chocolate += i - mid NEW_LINE DEDENT DEDENT return chocolate NEW_LINE DEDENT def maximumCut ( arr , K ) : NEW_LINE INDENT low = 0 NEW_LINE high = max ( arr ) NEW_LINE while low <= high : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE chocolate = cal ( arr , mid ) NEW_LINE if chocolate == K : NEW_LINE INDENT return mid NEW_LINE DEDENT elif chocolate < K : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE if mid > high : NEW_LINE INDENT high = mid NEW_LINE DEDENT DEDENT DEDENT return high NEW_LINE DEDENT N , K = 4 , 7 NEW_LINE arr = [ 15 , 20 , 8 , 17 ] NEW_LINE print ( maximumCut ( arr , K ) ) NEW_LINE
Koko Eating Bananas | Python implementation for the above approach ; to get the ceil value ; in case of odd number ; in case of even number ; check if time is less than or equals to given hour ; as minimum speed of eating must be 1 ; Maximum speed of eating is the maximum bananas in given piles ; Check if the mid ( hours ) is valid ; If valid continue to search lower speed ; If cant finish bananas in given hours , then increase the speed ; Driver code
def check ( bananas , mid_val , H ) : NEW_LINE INDENT time = 0 ; NEW_LINE for i in range ( len ( bananas ) ) : NEW_LINE INDENT if ( bananas [ i ] % mid_val != 0 ) : NEW_LINE time += bananas [ i ] // mid_val + 1 ; NEW_LINE else : NEW_LINE time += bananas [ i ] // mid_val NEW_LINE DEDENT if ( time <= H ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT def minEatingSpeed ( piles , H ) : NEW_LINE INDENT start = 1 ; NEW_LINE end = sorted ( piles . copy ( ) , reverse = True ) [ 0 ] NEW_LINE while ( start < end ) : NEW_LINE INDENT mid = start + ( end - start ) // 2 ; NEW_LINE if ( check ( piles , mid , H ) == True ) : NEW_LINE end = mid ; NEW_LINE else : NEW_LINE start = mid + 1 ; NEW_LINE DEDENT return end ; NEW_LINE DEDENT piles = [ 30 , 11 , 23 , 4 , 20 ] ; NEW_LINE H = 6 ; NEW_LINE print ( minEatingSpeed ( piles , H ) ) ; NEW_LINE
Minimize the sum of pair which upon removing divides the Array into 3 subarrays | Python 3 implementation of the above approach ; Function to find minimum possible sum of pair which breaks the array into 3 non - empty subarrays ; prefixMin [ i ] contains minimum element till i ; Driver Code ; Given array
import sys NEW_LINE def minSumPair ( arr , N ) : NEW_LINE INDENT if ( N < 5 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT prefixMin = [ 0 for i in range ( N ) ] NEW_LINE prefixMin [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , N - 1 , 1 ) : NEW_LINE INDENT prefixMin [ i ] = min ( arr [ i ] , prefixMin [ i - 1 ] ) NEW_LINE DEDENT ans = sys . maxsize NEW_LINE for i in range ( 3 , N - 1 , 1 ) : NEW_LINE INDENT ans = min ( ans , arr [ i ] + prefixMin [ i - 2 ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 2 , 4 , 6 , 3 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minSumPair ( arr , N ) ) NEW_LINE DEDENT
Minimum time remaining for safety alarm to start | Function to check if the value of mid as the minimum number of hours satisfies the condition ; Stores the sum of speed ; Iterate over the range [ 0 , N ] ; Find the value of speed ; If the bike is considered to be fast add it in sum ; Return the resultant sum ; Function to find the minimum number of time required ; Stores the range of Binary Search ; Stores the minimum number of time required ; Find the value of mid ; If the mid is the resultant speed required ; Update the ans and high ; Otherwise ; Return the minimum number of hours ; Driver Code
def check ( H , A , mid , N , M , L ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT speed = mid * A [ i ] + H [ i ] NEW_LINE if ( speed >= L ) : NEW_LINE INDENT sum += speed NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT def buzzTime ( N , M , L , H , A ) : NEW_LINE INDENT low = 0 NEW_LINE high = 1e10 NEW_LINE ans = 0 NEW_LINE while ( high >= low ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( check ( H , A , mid , N , M , L ) >= M ) : NEW_LINE INDENT ans = mid NEW_LINE high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return int ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = 400 NEW_LINE L = 120 NEW_LINE H = [ 20 , 50 , 20 ] NEW_LINE A = [ 20 , 70 , 90 ] NEW_LINE N = len ( A ) NEW_LINE print ( buzzTime ( N , M , L , H , A ) ) NEW_LINE DEDENT
Count of different numbers divisible by 3 that can be obtained by changing at most one digit | Function to count the number of possible numbers divisible by 3 ; Calculate the sum ; Store the answer ; Iterate over the range ; Decreasing the sum ; Iterate over the range ; Checking if the new sum is divisible by 3 or not ; If yes increment the value of the count ; Given number
def findCount ( number ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len ( number ) ) : NEW_LINE INDENT sum += int ( number [ i ] ) - 48 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( len ( number ) ) : NEW_LINE INDENT remaining_sum = sum - ( int ( number [ i ] ) - 48 ) NEW_LINE for j in range ( 10 ) : NEW_LINE INDENT if ( ( remaining_sum + j ) % 3 == 0 and j != int ( number [ i ] ) - 48 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT number = "235" NEW_LINE findCount ( number ) NEW_LINE
Maximum number of teams of size K possible with each player from different country | Function to find if T number of teams can be formed or not ; Store the sum of array elements ; Traverse the array teams [ ] ; Required Condition ; Function to find the maximum number of teams possible ; Lower and Upper part of the range ; Perform the Binary Search ; Find the value of mid ; Perform the Binary Search ; Otherwise , update the search range ; Otherwise , update the search range ; Driver Code
def is_possible ( teams , T , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len ( teams ) ) : NEW_LINE INDENT sum += min ( T , teams [ i ] ) NEW_LINE DEDENT return ( sum >= ( T * k ) ) NEW_LINE DEDENT def countOfTeams ( teams_list , N , K ) : NEW_LINE INDENT lb = 0 NEW_LINE ub = 1000000000 NEW_LINE while ( lb <= ub ) : NEW_LINE INDENT mid = lb + ( ub - lb ) // 2 NEW_LINE if ( is_possible ( teams_list , mid , K ) ) : NEW_LINE INDENT if ( is_possible ( teams_list , mid + 1 , K ) == False ) : NEW_LINE INDENT return mid NEW_LINE DEDENT else : NEW_LINE INDENT lb = mid + 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT ub = mid - 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( countOfTeams ( arr , N , K ) ) NEW_LINE DEDENT
Minimum number of decrements by 1 required to reduce all elements of a circular array to 0 | Function to find minimum operation require to make all elements 0 ; Stores the maximum element and its position in the array ; Traverse the array ; Update the maximum element and its index ; Print the minimum number of operations required ; Driver Code
def minimumOperations ( arr , N ) : NEW_LINE INDENT mx = 0 NEW_LINE pos = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] >= mx ) : NEW_LINE INDENT mx = arr [ i ] NEW_LINE pos = i NEW_LINE DEDENT DEDENT print ( ( mx - 1 ) * N + pos + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 0 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE minimumOperations ( arr , N ) NEW_LINE DEDENT
Maximize the smallest array element by incrementing all elements in a K | Python 3 program for above approach ; Function to check if the smallest value of v is achievable or not ; Create array to store previous moves ; Remove previous moves ; Add balance to ans ; Update contiguous subarray of length k ; Number of moves should not exceed m ; Function to find the maximum value of the smallest array element that can be obtained ; Perform Binary search ; Driver Code ; Given Input ; Function Call
n = 0 NEW_LINE m = 0 NEW_LINE k = 0 NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE i = 0 NEW_LINE from math import pow NEW_LINE def check ( v , a ) : NEW_LINE INDENT tec = 0 NEW_LINE ans = 0 NEW_LINE b = [ 0 for i in range ( n + k + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT tec -= b [ i ] NEW_LINE if ( a [ i ] + tec < v ) : NEW_LINE INDENT mov = v - a [ i ] - tec NEW_LINE ans = ans + mov NEW_LINE tec += mov NEW_LINE b [ i + k ] = mov NEW_LINE DEDENT DEDENT return ( ans <= m ) NEW_LINE DEDENT def FindLargest ( a ) : NEW_LINE INDENT l = 1 NEW_LINE r = pow ( 10 , 10 ) NEW_LINE while ( r - l > 0 ) : NEW_LINE INDENT tm = ( l + r + 1 ) // 2 NEW_LINE if ( check ( tm , a ) ) : NEW_LINE INDENT l = tm NEW_LINE DEDENT else : NEW_LINE INDENT r = tm - 1 NEW_LINE DEDENT DEDENT return l NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 2 , 2 , 2 , 2 , 1 , 1 ] NEW_LINE m = 2 NEW_LINE k = 3 NEW_LINE n = len ( a ) NEW_LINE print ( int ( FindLargest ( a ) ) ) NEW_LINE DEDENT
Altitude of largest Triangle that can be inscribed in a Rectangle | Function to find the greatest altitude of the largest triangle triangle that can be inscribed in the rectangle ; If L is greater than B ; Variables to perform binary search ; Stores the maximum altitude possible ; Iterate until low is less than high ; Stores the mid value ; If mide is less than or equal to the B / 2 ; Update res ; Update low ; Update high ; Print the result ; Driver Code ; Given Input ; Function call
def largestAltitude ( L , B ) : NEW_LINE INDENT if ( L > B ) : NEW_LINE INDENT temp = B NEW_LINE B = L NEW_LINE L = temp NEW_LINE DEDENT low = 0 NEW_LINE high = L NEW_LINE res = 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( mid <= ( B / 2 ) ) : NEW_LINE INDENT res = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 3 NEW_LINE B = 4 NEW_LINE print ( largestAltitude ( L , B ) ) NEW_LINE DEDENT
Find the frequency of each element in a sorted array | Function to print the frequency of each element of the sorted array ; Stores the frequency of an element ; Traverse the array arr [ ] ; If the current element is equal to the previous element ; Increment the freq by 1 ; Otherwise , ; Update freq ; Print the frequency of the last element ; Driver Code ; Given Input ; Function Call
def printFreq ( arr , N ) : NEW_LINE INDENT freq = 1 NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT freq += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Frequency ▁ of " , arr [ i - 1 ] , " is : " , freq ) NEW_LINE freq = 1 NEW_LINE DEDENT DEDENT print ( " Frequency ▁ of " , arr [ N - 1 ] , " is : " , freq ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 , 8 , 8 , 8 , 9 , 9 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE printFreq ( arr , N ) NEW_LINE DEDENT
Count pairs from a given array whose sum lies from a given range | Python3 program for the above approach ; Function to count pairs whose sum lies over the range [ L , R ] ; Sort the given array ; Iterate until right > 0 ; Starting index of element whose sum with arr [ right ] >= L ; Ending index of element whose sum with arr [ right ] <= R ; Update the value of end ; Add the count of elements to the variable count ; Return the value of count ; Driver Code
from bisect import bisect_left , bisect_right NEW_LINE def countPairSum ( arr , L , R , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE right = N - 1 NEW_LINE count = 0 NEW_LINE while ( right > 0 ) : NEW_LINE INDENT it1 = bisect_left ( arr , L - arr [ right ] ) NEW_LINE start = it1 NEW_LINE it2 = bisect_right ( arr , R - arr [ right ] ) NEW_LINE it2 -= 1 NEW_LINE end = it2 NEW_LINE end = min ( end , right - 1 ) NEW_LINE if ( end - start >= 0 ) : NEW_LINE INDENT count += ( end - start + 1 ) NEW_LINE DEDENT right -= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 1 , 2 , 4 , 3 ] NEW_LINE L = 5 NEW_LINE R = 8 NEW_LINE N = len ( arr ) NEW_LINE print ( countPairSum ( arr , L , R , N ) ) NEW_LINE DEDENT
Maximize median of a KxK sub | Function to determine if a given value can be median ; Stores the prefix sum array ; Traverse the matrix arr [ ] [ ] ; Update Pre [ i + 1 ] [ j + 1 ] ; If arr [ i ] [ j ] is less than or equal to mid ; Stores the count of elements should be less than mid ; Stores if the median mid can be possible or not ; Iterate over the range [ K , N ] ; Iterate over the range [ K , N ] ; Stores count of elements less than or equal to the value mid in submatrix with bottom right vertices at ( i , j ) ; If X is less than or equal to required ; Return flag ; Function to find the maximum median of a subsquare of the given size ; Stores the range of the search space ; Iterate until low is less than high ; Stores the mid value of the range [ low , high ] ; If the current median can be possible ; Update the value of low ; Update the value of high ; Return value stored in low as answer ; Driver Code
def isMaximumMedian ( arr , N , K , mid ) : NEW_LINE INDENT Pre = [ [ 0 for x in range ( N + 5 ) ] for y in range ( N + 5 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT Pre [ i + 1 ] [ j + 1 ] = ( Pre [ i + 1 ] [ j ] + Pre [ i ] [ j + 1 ] - Pre [ i ] [ j ] ) NEW_LINE if ( arr [ i ] [ j ] <= mid ) : NEW_LINE INDENT Pre [ i + 1 ] [ j + 1 ] += 1 NEW_LINE DEDENT DEDENT DEDENT required = ( K * K + 1 ) // 2 NEW_LINE flag = 0 NEW_LINE for i in range ( K , N + 1 ) : NEW_LINE INDENT for j in range ( K , N + 1 ) : NEW_LINE INDENT X = ( Pre [ i ] [ j ] - Pre [ i - K ] [ j ] - Pre [ i ] [ j - K ] + Pre [ i - K ] [ j - K ] ) NEW_LINE if ( X < required ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT DEDENT return flag NEW_LINE DEDENT def maximumMedian ( arr , N , K ) : NEW_LINE INDENT low = 0 NEW_LINE high = 1000000009 NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( isMaximumMedian ( arr , N , K , mid ) ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 5 , 12 ] , [ 6 , 7 , 11 ] , [ 8 , 9 , 10 ] ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( maximumMedian ( arr , N , K ) ) NEW_LINE DEDENT
Minimum days to make Array elements with value at least K sum at least X | Function to find the minimum number of days such that the sum of array elements >= K is at least X ; Initialize the boundaries of search space ; Perform the binary search ; Find the value of mid ; Traverse the array , arr [ ] ; Find the value of arr [ i ] after mid number of days ; Check if temp is not less than K ; Update the value of sum ; Check if the value of sum is greater than X ; Update value of high ; Update the value of low ; Print the minimum number of days ; Driver Code
def findMinDays ( arr , R , N , X , K ) : NEW_LINE INDENT low = 0 NEW_LINE high = X NEW_LINE minDays = 0 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 temp = arr [ i ] + R [ i ] * mid NEW_LINE if ( temp >= K ) : NEW_LINE INDENT sum += temp NEW_LINE DEDENT DEDENT if ( sum >= X ) : NEW_LINE INDENT minDays = mid NEW_LINE high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT print ( minDays ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 100 NEW_LINE K = 45 NEW_LINE arr = [ 2 , 5 , 2 , 6 ] NEW_LINE R = [ 10 , 13 , 15 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE findMinDays ( arr , R , N , X , K ) NEW_LINE DEDENT
Count of indices pairs such that product of elements at these indices is equal to absolute difference of indices | Function to count the number of pairs ( i , j ) such that arr [ i ] * arr [ j ] is equal to abs ( i - j ) ; Stores the resultant number of pairs ; Generate all possible pairs from the array arr [ ] ; If the given condition satisfy then increment the value of count ; Return the resultant count ; Driver Code
def getPairsCount ( a , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( ( a [ i ] * a [ j ] ) == abs ( i - j ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( getPairsCount ( arr , N ) ) NEW_LINE DEDENT
Lexicographically smallest string formed repeatedly deleting character from substring 10 | Function to find smallest lexicogra - phically smallest string ; Stores the index of last occuring 0 ; Stores the lexicographically smallest string ; Traverse the S ; If str [ i ] is 0 ; Assign i to lastZe ; Traverse the str ; If i is less than or equal to lastZe and str [ i ] is 0 ; If i is greater than lastZe ; Return ans ; Driver Code ; Input ; Function Call
def lexicographicallySmallestString ( S , N ) : NEW_LINE INDENT LastZe = - 1 NEW_LINE ans = " " NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT LastZe = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( i <= LastZe and S [ i ] == '0' ) : NEW_LINE INDENT ans += S [ i ] NEW_LINE DEDENT elif ( i > LastZe ) : NEW_LINE INDENT ans += S [ i ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "11001101" NEW_LINE N = len ( S ) NEW_LINE print ( lexicographicallySmallestString ( S , N ) ) NEW_LINE DEDENT
Count of Nodes at distance K from S in its subtree for Q queries | Python3 program for the above approach ; Function to add edges ; Function to perform Depth First Search ; Stores the entry time of a node ; Stores the entering time of a node at depth d ; Iterate over the children of node ; Stores the Exit time of a node ; Function to find number of nodes at distance K from node S in the subtree of S ; Distance from root node ; Index of node with greater tin value then tin [ S ] ; Index of node with greater tout value then tout [ S ] ; Answer to the Query ; Function for performing DFS and answer to queries ; DFS function call ; Traverse the array Q [ ] ; Driver Code ; Input ; Function call
from bisect import bisect_left , bisect_right NEW_LINE tin = [ 0 ] * 100 NEW_LINE tout = [ 0 ] * 100 NEW_LINE depth = [ 0 ] * 100 NEW_LINE t = 0 NEW_LINE def Add_edge ( parent , child , adj ) : NEW_LINE INDENT adj [ parent ] . append ( child ) NEW_LINE adj [ child ] . append ( parent ) NEW_LINE return adj NEW_LINE DEDENT def dfs ( node , parent , d ) : NEW_LINE INDENT global tin , tout , depth , adj , levels , t NEW_LINE tin [ node ] = t NEW_LINE t += 1 NEW_LINE levels [ d ] . append ( tin [ node ] ) NEW_LINE depth [ node ] = d NEW_LINE for x in adj [ node ] : NEW_LINE INDENT if ( x != parent ) : NEW_LINE INDENT dfs ( x , node , d + 1 ) NEW_LINE DEDENT DEDENT tout [ node ] = t NEW_LINE t += 1 NEW_LINE DEDENT def numberOfNodes ( node , dist ) : NEW_LINE INDENT global levels , tin , tout NEW_LINE dist += depth [ node ] NEW_LINE start = bisect_left ( levels [ dist ] , tin [ node ] ) NEW_LINE ed = bisect_left ( levels [ dist ] , tout [ node ] ) NEW_LINE print ( ed - start ) NEW_LINE DEDENT def numberOfNodesUtil ( Q , M , N ) : NEW_LINE INDENT global t , adj NEW_LINE adj = Add_edge ( 1 , 2 , adj ) NEW_LINE adj = Add_edge ( 1 , 3 , adj ) NEW_LINE adj = Add_edge ( 2 , 4 , adj ) NEW_LINE adj = Add_edge ( 2 , 5 , adj ) NEW_LINE adj = Add_edge ( 2 , 6 , adj ) NEW_LINE t = 1 NEW_LINE dfs ( 1 , 1 , 0 ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT numberOfNodes ( Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE Q = [ [ 2 , 1 ] , [ 1 , 1 ] ] NEW_LINE M = len ( Q ) NEW_LINE adj = [ [ ] for i in range ( N + 5 ) ] NEW_LINE levels = [ [ ] for i in range ( N + 5 ) ] NEW_LINE numberOfNodesUtil ( Q , M , N ) NEW_LINE DEDENT
Maximize boxes required to keep at least one black and one white shirt | Function to find the maximum number of boxes such that each box contains three shirts comprising of at least one white and black shirt ; Stores the low and high pointers for binary search ; Store the required answer ; Loop while low <= high ; Store the mid value ; Check if the mid number of boxes can be used ; Update answer and recur for the right half ; Else , recur for the left half ; Print result ; Driver Code
def numberofBoxes ( W , B , O ) : NEW_LINE INDENT low = 0 NEW_LINE high = min ( W , B ) NEW_LINE ans = 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( ( ( W >= mid ) and ( B >= mid ) ) and ( ( W - mid ) + ( B - mid ) + O ) >= mid ) : NEW_LINE INDENT ans = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT W = 3 NEW_LINE B = 3 NEW_LINE O = 1 NEW_LINE numberofBoxes ( W , B , O ) NEW_LINE DEDENT
Minimum swaps needed to convert given Binary Matrix A to Binary Matrix B | Function to count the minimum number of swaps required to convert matrix A to matrix B ; Stores number of cells such that matrix A contains 0 and matrix B contains 1 ; Stores number of cells such that matrix A contains 1 and matrix B contains 0 ; Iterate over the range [ 0 , N - 1 ] ; Iterate over the range [ 0 , M - 1 ] ; If A [ i ] [ j ] = 1 and B [ i ] [ j ] = 0 ; If A [ i ] [ j ] = 0 and B [ i ] [ j ] = 1 ; If count01 is equal to count10 ; Otherwise , ; Driver Code
def minSwaps ( N , M , A , B ) : NEW_LINE INDENT count01 = 0 NEW_LINE count10 = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , M ) : NEW_LINE INDENT if ( A [ i ] [ j ] != B [ i ] [ j ] ) : NEW_LINE INDENT if ( A [ i ] [ j ] == 1 ) : NEW_LINE INDENT count10 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count01 += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( count01 == count10 ) : NEW_LINE INDENT return count01 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT A = [ [ 1 , 1 , 0 ] , [ 0 , 0 , 1 ] , [ 0 , 1 , 0 ] ] NEW_LINE B = [ [ 0 , 0 , 1 ] , [ 0 , 1 , 0 ] , [ 1 , 1 , 0 ] ] NEW_LINE N = len ( A ) NEW_LINE M = len ( B [ 0 ] ) NEW_LINE print ( minSwaps ( N , M , A , B ) ) NEW_LINE
Maximize X such that sum of numbers in range [ 1 , X ] is at most K | Function to count the elements with sum of the first that many natural numbers less than or equal to K ; If K equals to 0 ; Stores sum of first i natural numbers ; Stores the result ; Iterate over the range [ 1 , N ] ; Increment sum by i ; Is sum is less than or equal to K ; Otherwise , ; Return res ; Driver Code ; Input ; Function call
def Count ( N , K ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT sum = 0 NEW_LINE res = 0 NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT sum += i NEW_LINE if ( sum <= K ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE K = 14 NEW_LINE print ( Count ( N , K ) ) NEW_LINE DEDENT
Remove last occurrence of a word from a given sentence string | Function to remove last occurrence of W from S ; If M is greater than N ; Iterate while i is greater than or equal to 0 ; of W has been found or not ; Iterate over the range [ 0 , M ] ; If S [ j + 1 ] is not equal to W [ j ] ; Mark flag true and break ; If occurrence has been found ; Delete the subover the range [ i , i + M ] ; Resize the S ; Return S ; Driver Code ; Input ; Function call
def removeLastOccurrence ( S , W , N , M ) : NEW_LINE INDENT S = [ i for i in S ] NEW_LINE W = [ i for i in W ] NEW_LINE if ( M > N ) : NEW_LINE INDENT return S NEW_LINE DEDENT for i in range ( N - M , - 1 , - 1 ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( M ) : NEW_LINE INDENT if ( S [ j + i ] != W [ j ] ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT for j in range ( i , N - M ) : NEW_LINE INDENT S [ j ] = S [ j + M ] NEW_LINE DEDENT S = S [ : N - M ] NEW_LINE break NEW_LINE DEDENT DEDENT return " " . join ( S ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " This ▁ is ▁ GeeksForGeeks " NEW_LINE W = " Geeks " NEW_LINE N = len ( S ) NEW_LINE M = len ( W ) NEW_LINE print ( removeLastOccurrence ( S , W , N , M ) ) NEW_LINE DEDENT
Rearrange the Array to maximize the elements which is smaller than both its adjacent elements | Function to rearrange array such that count of element that are smaller than their adjacent elements is maximum ; Stores the rearranged array ; Stores the maximum count of elements ; Sort the given array ; Place the smallest ( N - 1 ) / 2 elements at odd indices ; Placing the rest of the elements at remaining indices ; If no element of the array has been placed here ; Print the resultant array ; Input ; Function call
def maximumIndices ( arr , N ) : NEW_LINE INDENT temp = [ 0 ] * N NEW_LINE maxIndices = ( N - 1 ) // 2 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( maxIndices ) : NEW_LINE INDENT temp [ 2 * i + 1 ] = arr [ i ] NEW_LINE DEDENT j = 0 NEW_LINE i = maxIndices NEW_LINE while ( i < N ) : NEW_LINE INDENT if ( temp [ j ] == 0 ) : NEW_LINE INDENT temp [ j ] = arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT j += 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( temp [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE maximumIndices ( arr , N ) NEW_LINE
Check if given Strings can be made equal by inserting at most 1 String | Python3 program for the above approach ; Function to check whether two sentences can be made equal by inserting at most one sentence in one of them ; Size of sentence S1 ; Size of sentence S2 ; Check if S1 and S2 are of equal sizes ; If both sentences are the same , return True ; Otherwise , return false ; Declare 2 deques X and Y ; Insert ' ▁ ' at the end of both sentences so that the last word can be identified ; Traverse the sentence S1 ; Push temp in deque when a space comes in sentence i . e a word has been formed ; temp stores words of the sentence ; Traverse the sentence S1 ; Push temp in deque when a space comes in sentence i . e a word has been formed ; temp stores words of the sentence ; Check for prefixes of both sentences ; Pop the prefix from both deques till they are equal ; Check for suffixes of both sentences ; Pop the suffix from both deques till they are equal ; If any of the deques is empty return True ; If both the deques are not empty return false ; Driver code ; Input ; Function call
from collections import deque NEW_LINE def areSimilar ( S1 , S2 ) : NEW_LINE INDENT S1 = [ i for i in S1 ] NEW_LINE S2 = [ i for i in S2 ] NEW_LINE N = len ( S1 ) NEW_LINE M = len ( S2 ) NEW_LINE if ( N == M ) : NEW_LINE INDENT if ( S1 == S2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT X , Y = deque ( ) , deque ( ) NEW_LINE S1 . append ( ' ▁ ' ) NEW_LINE S2 . append ( ' ▁ ' ) NEW_LINE temp = " " NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT if ( S1 [ i ] == ' ▁ ' ) : NEW_LINE INDENT X . append ( temp ) NEW_LINE temp = " " NEW_LINE DEDENT else : NEW_LINE INDENT temp += S1 [ i ] NEW_LINE DEDENT DEDENT for i in range ( M + 1 ) : NEW_LINE INDENT if ( S2 [ i ] == ' ▁ ' ) : NEW_LINE INDENT Y . append ( temp ) NEW_LINE temp = " " NEW_LINE DEDENT else : NEW_LINE INDENT temp += S2 [ i ] NEW_LINE DEDENT DEDENT while ( len ( X ) > 0 and len ( Y ) > 0 and X [ 0 ] == Y [ 0 ] ) : NEW_LINE INDENT X . popleft ( ) NEW_LINE Y . popleft ( ) NEW_LINE DEDENT while ( len ( X ) > 0 and len ( Y ) > 0 and X [ - 1 ] == Y [ - 1 ] ) : NEW_LINE INDENT X . pop ( ) NEW_LINE Y . pop ( ) NEW_LINE DEDENT if ( len ( X ) == 0 or len ( Y ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S1 = " Start ▁ practicing ▁ on ▁ GeeksforGeeks " NEW_LINE S2 = " Start ▁ GeeksforGeeks " NEW_LINE if ( areSimilar ( S1 , S2 ) ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT DEDENT
Find the repeating element in an Array of size N consisting of first M natural numbers | Function to calculate the repeating character in a given permutation ; variables to store maximum element and sum of the array respectively . ; calculate sum of array ; calculate maximum element in the array ; calculating sum of permutation ; calculate required answer ; Driver code ; Input ; Function call
def repeatingElement ( arr , N ) : NEW_LINE INDENT M = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE M = max ( M , arr [ i ] ) NEW_LINE DEDENT sum1 = M * ( M + 1 ) // 2 NEW_LINE ans = ( sum - sum1 ) // ( N - M ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 6 , 4 , 3 , 1 , 5 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( repeatingElement ( arr , N ) ) NEW_LINE DEDENT
Maximize value at Kth index to create N size array with adjacent difference 1 and sum less than M | Function to calculate maximum value that can be placed at the Kth index in a distribution in which difference of adjacent elements is less than 1 and total sum of distribution is M . ; Variable to store final answer ; Variables for binary search ; Binary search ; Variable for binary search ; Variable to store total sum of array ; Number of indices on the left excluding the Kth index ; Number of indices on the left excluding the Kth index ; Add mid to final sum ; Distribution on left side is possible ; Sum of distribution on the left side ; Sum of distribution on the left side with ( L - mid ) 1 s ; Distribution on right side is possible ; Sum of distribution on the right side ; Sum of distribution on the left side with ( R - mid ) 1 s ; Distribution is valid ; Return answer ; Input ; Function call
def calculateMax ( N , M , K ) : NEW_LINE INDENT ans = - 1 NEW_LINE low = 0 NEW_LINE high = M NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) / 2 NEW_LINE val = 0 NEW_LINE L = K - 1 NEW_LINE R = N - K NEW_LINE val += mid NEW_LINE if ( mid >= L ) : NEW_LINE INDENT val += ( L ) * ( 2 * mid - L - 1 ) / 2 NEW_LINE DEDENT else : NEW_LINE INDENT val += mid * ( mid - 1 ) / 2 + ( L - mid ) NEW_LINE DEDENT if ( mid >= R ) : NEW_LINE INDENT val += ( R ) * ( 2 * mid - R - 1 ) / 2 NEW_LINE DEDENT else : NEW_LINE INDENT val += mid * ( mid - 1 ) / 2 + ( R - mid ) NEW_LINE DEDENT if ( val <= M ) : NEW_LINE INDENT ans = max ( ans , mid ) NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return int ( ans ) NEW_LINE DEDENT N = 7 NEW_LINE M = 100 NEW_LINE K = 6 NEW_LINE print ( calculateMax ( N , M , K ) ) ; NEW_LINE
Minimum time required to color all edges of a Tree | Stores the required answer ; Stores the graph ; Function to add edges ; Function to calculate the minimum time required to color all the edges of a tree ; Starting from time = 0 , for all the child edges ; If the edge is not visited yet . ; Time of coloring of the current edge ; If the parent edge has been colored at the same time ; Update the maximum time ; Recursively call the function to its child node ; Driver Code ; Function call ; Finally , print the answer
ans = 0 NEW_LINE edges = [ [ ] for i in range ( 100000 ) ] NEW_LINE def Add_edge ( u , v ) : NEW_LINE INDENT global edges NEW_LINE edges [ u ] . append ( v ) NEW_LINE edges [ v ] . append ( u ) NEW_LINE DEDENT def minTimeToColor ( node , parent , arrival_time ) : NEW_LINE INDENT global ans NEW_LINE current_time = 0 NEW_LINE for x in edges [ node ] : NEW_LINE INDENT if ( x != parent ) : NEW_LINE INDENT current_time += 1 NEW_LINE if ( current_time == arrival_time ) : NEW_LINE INDENT current_time += 1 NEW_LINE DEDENT ans = max ( ans , current_time ) NEW_LINE minTimeToColor ( x , node , current_time ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 4 ] ] NEW_LINE for i in A : NEW_LINE INDENT Add_edge ( i [ 0 ] , i [ 1 ] ) NEW_LINE DEDENT minTimeToColor ( 1 , - 1 , 0 ) NEW_LINE print ( ans ) NEW_LINE DEDENT
Largest number having both positive and negative values present in the array | Function to find the largest number k such that both k and - k are present in the array ; Stores the resultant value of K ; Sort the array arr [ ] ; Initialize two variables to use two pointers technique ; Iterate until the value of l is less than r ; Find the value of the sum ; If the sum is 0 , then the resultant element is found ; If the sum is negative ; Otherwise , decrement r ; Driver Code
def largestNum ( arr ) : NEW_LINE INDENT res = 0 NEW_LINE arr = sorted ( arr ) NEW_LINE l = 0 NEW_LINE r = len ( arr ) - 1 NEW_LINE while ( l < r ) : NEW_LINE INDENT sum = arr [ l ] + arr [ r ] NEW_LINE if ( sum == 0 ) : NEW_LINE INDENT res = max ( res , max ( arr [ l ] , arr [ r ] ) ) NEW_LINE return res NEW_LINE DEDENT elif ( sum < 0 ) : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT r -= 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , - 2 , 5 , - 3 ] NEW_LINE print ( largestNum ( arr ) ) NEW_LINE DEDENT
Find elements larger than half of the elements in an array | Set 2 | Function to find the element that are larger than half of elements of the array ; Find the value of mid ; Stores the maximum element ; Stores the frequency of each array element ; Traverse the array in the reverse order ; Decrement the value of count [ i ] and mid ; Prthe current element ; Check if the value of mid is equal to 0 ; Driver Code
def findLarger ( arr , n ) : NEW_LINE INDENT mid = ( n + 1 ) // 2 NEW_LINE mx = max ( arr ) NEW_LINE count = [ 0 ] * ( mx + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( mx , - 1 , - 1 ) : NEW_LINE INDENT while ( count [ i ] > 0 ) : NEW_LINE INDENT count [ i ] -= 1 NEW_LINE mid -= 1 NEW_LINE print ( i , end = " ▁ " ) NEW_LINE if ( mid == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( mid == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 4 , 2 , 8 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE findLarger ( arr , N ) NEW_LINE DEDENT
Probability of obtaining pairs from two arrays such that element from the first array is smaller than that of the second array | Function to find probability such that x < y and X belongs to arr1 [ ] and Y belongs to arr2 [ ] ; Stores the length of arr1 ; Stores the length of arr2 ; Stores the result ; Traverse the arr1 [ ] ; Stores the count of elements in arr2 that are greater than arr [ i ] ; Traverse the arr2 [ ] ; If arr2 [ j ] is greater than arr1 [ i ] ; Increment res by y ; Update the value of res ; Return resultant probability ; Driver Code
def probability ( arr1 , arr2 ) : NEW_LINE INDENT N = len ( arr1 ) NEW_LINE M = len ( arr2 ) NEW_LINE res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT y = 0 NEW_LINE for j in range ( M ) : NEW_LINE INDENT if ( arr2 [ j ] > arr1 [ i ] ) : NEW_LINE INDENT y += 1 NEW_LINE DEDENT DEDENT res += y NEW_LINE DEDENT res = res / ( N * M ) NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr1 = [ 5 , 2 , 6 , 1 ] NEW_LINE arr2 = [ 1 , 6 , 10 , 1 ] NEW_LINE print ( probability ( arr1 , arr2 ) ) NEW_LINE DEDENT
Probability of obtaining pairs from two arrays such that element from the first array is smaller than that of the second array | Function to find probability such that x < y and X belongs to arr1 [ ] & Y belongs to arr2 [ ] ; Stores the length of arr1 ; Stores the length of arr2 ; Stores the result ; Sort the arr2 [ ] in the ascending order ; Traverse the arr1 [ ] ; Stores the count of elements in arr2 that are greater than arr [ i ] ; Increment res by y ; Update the resultant probability ; Return the result ; Function to return the count of elements from the array which are greater than k ; Stores the index of the leftmost element from the array which is at least k ; Finds number of elements greater than k ; If mid element is at least K , then update the value of leftGreater and r ; Update leftGreater ; Update r ; If mid element is at most K , then update the value of l ; Return the count of elements greater than k ; Driver code
def probability ( arr1 , arr2 ) : NEW_LINE INDENT n = len ( arr1 ) NEW_LINE m = len ( arr2 ) NEW_LINE res = 0 NEW_LINE arr2 . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT y = countGreater ( arr2 , arr1 [ i ] ) NEW_LINE res += y NEW_LINE DEDENT res /= ( n * m ) NEW_LINE return res NEW_LINE DEDENT def countGreater ( arr , k ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE l = 0 NEW_LINE r = n - 1 NEW_LINE leftGreater = n NEW_LINE while l <= r : NEW_LINE INDENT m = ( l + r ) // 2 NEW_LINE if ( arr [ m ] > k ) : NEW_LINE INDENT leftGreater = m NEW_LINE r = m - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT DEDENT return n - leftGreater NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 5 , 2 , 6 , 1 ] NEW_LINE arr2 = [ 1 , 6 , 10 , 1 ] NEW_LINE print ( probability ( arr1 , arr2 ) ) NEW_LINE DEDENT
Minimize cost to cover floor using tiles of dimensions 1 * 1 and 1 * 2 | Function to find the minimum cost of flooring with the given tiles ; Store the size of the 2d array ; Stores the minimum cost of flooring ; Traverse the 2d array row - wise ; If the current character is ' * ' , then skip it ; Choose the 1 * 1 tile if j is m - 1 ; If consecutive ' . ' are present , the greedily choose tile with the minimum cost ; Otherwise choose the 1 * 1 tile ; Print the minimum cost ; Driver Code
def minCost ( arr , A , B ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE m = len ( arr [ 0 ] ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = 0 NEW_LINE while j < m : NEW_LINE INDENT if ( arr [ i ] [ j ] == ' * ' ) : NEW_LINE INDENT j += 1 NEW_LINE continue NEW_LINE DEDENT if ( j == m - 1 ) : NEW_LINE INDENT ans += A NEW_LINE DEDENT else : NEW_LINE INDENT if ( arr [ i ] [ j + 1 ] == ' . ' ) : NEW_LINE INDENT ans += min ( 2 * A , B ) NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += A NEW_LINE DEDENT DEDENT j += 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ ' . ' , ' . ' , ' * ' ] , [ ' . ' , ' * ' , ' * ' ] ] NEW_LINE A , B = 2 , 10 NEW_LINE minCost ( arr , A , B ) NEW_LINE DEDENT
Count inversions in a permutation of first N natural numbers | Python3 program for the above approach ; Function to count number of inversions in a permutation of first N natural numbers ; Store array elements in sorted order ; Store the count of inversions ; Traverse the array ; Store the index of first occurrence of arr [ i ] in vector V ; Add count of smaller elements than current element ; Erase current element from vector and go to next index ; Print the result ; Driver Code ; Given Input ; Function Call
from bisect import bisect_left NEW_LINE def countInversions ( arr , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT itr = bisect_left ( v , arr [ i ] ) NEW_LINE ans += itr NEW_LINE v = v [ : itr ] + v [ itr + 1 : ] NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 1 , 5 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE countInversions ( arr , n ) NEW_LINE DEDENT
Find all possible pairs with given Bitwise OR and Bitwise XOR values | Function to find pairs with XOR equal to A and OR equal to B ; Iterate from 1 to B ; Check if ( i OR y ) is B ; Driver Code
def findPairs ( A , B ) : NEW_LINE INDENT for i in range ( 1 , B + 1 ) : NEW_LINE INDENT y = A ^ i NEW_LINE if ( y > 0 and ( i y ) == B ) : NEW_LINE INDENT print ( i , " ▁ " , y ) NEW_LINE DEDENT DEDENT DEDENT A = 8 NEW_LINE B = 10 NEW_LINE findPairs ( A , B ) NEW_LINE
Count distinct elements from a range of a sorted sequence from a given frequency array | Function to find the first index with value is at least element ; Update the value of left ; Binary search for the element ; Find the middle element ; Check if the value lies between the elements at index mid - 1 and mid ; Check in the right subarray ; Update the value of left ; Check in left subarray ; Update the value of right ; Function to count the number of distinct elements over the range [ L , R ] in the sorted sequence ; Stores the count of distinct elements ; Create the prefix sum array ; Update the value of count ; Update the value of pref [ i ] ; Calculating the first index of L and R using binary search ; Print the resultant count ; Driver Code
def binarysearch ( array , right , element ) : NEW_LINE INDENT left = 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = ( left + right // 2 ) NEW_LINE if ( array [ mid ] == element ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( mid - 1 > 0 and array [ mid ] > element and array [ mid - 1 ] < element ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( array [ mid ] < element ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def countDistinct ( arr , L , R ) : NEW_LINE INDENT count = 0 NEW_LINE pref = [ 0 ] * ( len ( arr ) + 1 ) NEW_LINE for i in range ( 1 , len ( arr ) + 1 ) : NEW_LINE INDENT count += arr [ i - 1 ] NEW_LINE pref [ i ] = count NEW_LINE DEDENT left = binarysearch ( pref , len ( arr ) + 1 , L ) NEW_LINE right = binarysearch ( pref , len ( arr ) + 1 , R ) NEW_LINE print ( right - left + 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 6 , 7 , 1 , 8 ] NEW_LINE L = 3 NEW_LINE R = 7 NEW_LINE countDistinct ( arr , L , R ) NEW_LINE DEDENT
Find Unique ID and Domain Name of a Website from a string | Function to check if a character is alphabet or not ; Function to check if a character is a numeric or not ; Function to find ID and Domain name from a given ; Stores ID and the domain names ; Stores the words of S ; Stores the temporary word ; Traverse the S ; If the current character is space ; Push the curr in words ; Update the curr ; Otherwise ; If curr is not empty ; If length of ss is 10 ; Traverse the ss ; If j is in the range [ 5 , 9 ) ; If current character is not numeric ; Mark flag 1 ; Otherwise ; If current character is not alphabet ; Mark flag 1 ; If flag is false ; Assign ss to ID ; If sub formed by the first 3 character is " www " and last 3 character is " moc " ; Update the domain name ; Print ID and Domain ; Driver Code
def ischar ( x ) : NEW_LINE INDENT if ( ( x >= ' A ' and x <= ' Z ' ) or ( x >= ' a ' and x <= ' z ' ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def isnum ( x ) : NEW_LINE INDENT if ( x >= '0' and x <= '9' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def findIdandDomain ( S , N ) : NEW_LINE INDENT ID , Domain = " " , " " NEW_LINE words = [ ] NEW_LINE curr = " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == ' ▁ ' ) : NEW_LINE INDENT words . append ( curr ) NEW_LINE curr = " " NEW_LINE DEDENT else : NEW_LINE INDENT if ( S [ i ] == ' . ' ) : NEW_LINE INDENT if ( i + 1 == N or ( i + 1 < N and S [ i + 1 ] == ' ▁ ' ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT DEDENT curr += S [ i ] NEW_LINE DEDENT DEDENT if ( len ( curr ) ) : NEW_LINE INDENT words . append ( curr ) NEW_LINE DEDENT for ss in words : NEW_LINE INDENT if ( len ( ss ) == 10 ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( 10 ) : NEW_LINE INDENT if ( j >= 5 and j < 9 ) : NEW_LINE INDENT if ( isnum ( ss [ j ] ) == 0 ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( ischar ( ss [ j ] ) == 0 ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT DEDENT if ( not flag ) : NEW_LINE INDENT ID = ss NEW_LINE DEDENT DEDENT if ( ss [ 0 : 3 ] == " www " and ss [ len ( ss ) - 3 : ] == " com " ) : NEW_LINE INDENT Domain = ss [ 4 : len ( ss ) ] NEW_LINE DEDENT DEDENT print ( " ID ▁ = " , ID ) NEW_LINE print ( " Domain ▁ = " , Domain ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " We ▁ thank ▁ ABCDE1234F ▁ for ▁ visiting ▁ us ▁ " " and ▁ buying ▁ products ▁ item ▁ AMZrr @ ! k . ▁ " N = len ( S ) NEW_LINE findIdandDomain ( S , N ) NEW_LINE DEDENT
Capacity To Ship Packages Within D Days | Function to check if the weights can be delivered in D days or not ; Stores the count of days required to ship all the weights if the maximum capacity is mx ; Traverse all the weights ; If total weight is more than the maximum capacity ; If days are more than D , then return false ; Return true for the days < D ; Function to find the least weight capacity of a boat to ship all the weights within D days ; Stores the total weights to be shipped ; Find the sum of weights ; Stores the maximum weight in the array that has to be shipped ; Store the ending value for the search space ; Store the required result ; Perform binary search ; Store the middle value ; If mid can be shipped , then update the result and end value of the search space ; Search for minimum value in the right part ; Print the result ; Driver Code
def isValid ( weight , n , D , mx ) : NEW_LINE INDENT st = 1 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += weight [ i ] NEW_LINE if ( sum > mx ) : NEW_LINE INDENT st += 1 NEW_LINE sum = weight [ i ] NEW_LINE DEDENT if ( st > D ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def shipWithinDays ( weight , D , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += weight [ i ] NEW_LINE DEDENT s = weight [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT s = max ( s , weight [ i ] ) NEW_LINE DEDENT e = sum NEW_LINE res = - 1 NEW_LINE while ( s <= e ) : NEW_LINE INDENT mid = s + ( e - s ) // 2 NEW_LINE if ( isValid ( weight , n , D , mid ) ) : NEW_LINE INDENT res = mid NEW_LINE e = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT s = mid + 1 NEW_LINE DEDENT DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT weight = [ 9 , 8 , 10 ] NEW_LINE D = 3 NEW_LINE N = len ( weight ) NEW_LINE shipWithinDays ( weight , D , N ) NEW_LINE DEDENT
Find a point whose sum of distances from all given points on a line is K | Function to find the sum of distances of all points from a given point ; Stores sum of distances ; Traverse the array ; Return the sum ; Function to find such a point having sum of distances of all other points from this point equal to K ; If N is odd keep left as arr [ n / 2 ] else keep left as arr [ n / 2 - 1 ] + 1 ; ; Keep right as arr [ N - 1 ] ; Perform binary search in the right half ; Calculate the mid index of the range ; If temp is equal to K ; Print the value of mid ; If the value of K < temp ; Update right to mid - 1 ; If the value of K > temp ; Update left to mid + 1 ; Update the value of left ; Update the value of right ; Perform binary search on the left half ; Calculate the mid index of the range ; If temp is equal to K ; Print mid ; if K > temp ; Update right to mid - 1 ; If K < temp ; Update left to mid + 1 ; If no such point found ; Driver Code
def findSum ( arr , N , pt ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += abs ( arr [ i ] - pt ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def findPoint ( arr , N , K ) : NEW_LINE INDENT left = 0 NEW_LINE if ( N % 2 ) : NEW_LINE INDENT left = arr [ N // 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT left = arr [ N // 2 - 1 ] + 1 NEW_LINE DEDENT right = arr [ N - 1 ] NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = ( left + right ) // 2 NEW_LINE temp = findSum ( arr , N , mid ) NEW_LINE if ( temp == K ) : NEW_LINE INDENT print ( mid ) NEW_LINE return NEW_LINE DEDENT elif ( K < temp ) : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT DEDENT left = arr [ 0 ] NEW_LINE right = arr [ N // 2 ] - 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = ( left + right ) // 2 NEW_LINE temp = findSum ( arr , N , mid ) NEW_LINE if ( temp == K ) : NEW_LINE INDENT print ( mid ) NEW_LINE return NEW_LINE DEDENT elif ( K > temp ) : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT DEDENT print ( " - 1" ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 6 , 7 , 11 ] NEW_LINE K = 18 NEW_LINE N = len ( arr ) NEW_LINE findPoint ( arr , N , K ) NEW_LINE DEDENT
Generate an array consisting of most frequent greater elements present on the right side of each array element | Function to generate an array containing the most frequent greater element on the right side of each array element ; Stores the generated array ; Traverse the array arr [ ] ; Store the result for the current index and its frequency ; Iterate over the right subarray ; Store the frequency of the current array element ; If the frequencies are equal ; Update ans to smaller of the two elements ; If count of new element is more than count of ans ; Insert answer in the array ; Print the resultant array ; Driver Code ; Given Input
def findArray ( arr , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = - 1 NEW_LINE old_c = 0 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] > arr [ i ] ) : NEW_LINE INDENT curr_c = arr [ j : n + 1 ] . count ( arr [ j ] ) NEW_LINE if ( curr_c == old_c ) : NEW_LINE INDENT if ( arr [ j ] < ans ) : NEW_LINE INDENT ans = arr [ j ] NEW_LINE DEDENT DEDENT if ( curr_c > old_c ) : NEW_LINE INDENT ans = arr [ j ] NEW_LINE old_c = curr_c NEW_LINE DEDENT DEDENT DEDENT v . append ( ans ) NEW_LINE DEDENT for i in range ( len ( v ) ) : NEW_LINE INDENT print ( v [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 5 , 2 , 25 , 10 , 5 , 10 , 3 , 10 , 5 ] NEW_LINE size = len ( arr ) NEW_LINE findArray ( arr , size ) NEW_LINE DEDENT
Smallest index that splits an array into two subarrays with equal product | Function to find the smallest index that splits the array into two subarrays with equal product ; Stores the product of the array ; Traverse the given array ; Stores the product of left and the right subarrays ; Traverse the given array ; Update the products ; Check if product is equal ; Print resultant index ; If no partition exists , then print - 1. ; Driver Code
def prodEquilibrium ( arr , N ) : NEW_LINE INDENT product = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT product *= arr [ i ] NEW_LINE DEDENT left = 1 NEW_LINE right = product NEW_LINE for i in range ( N ) : NEW_LINE INDENT left = left * arr [ i ] NEW_LINE right = right // arr [ i ] NEW_LINE if ( left == right ) : NEW_LINE INDENT print ( i + 1 ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 3 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE prodEquilibrium ( arr , N ) NEW_LINE DEDENT
Count triplets from a sorted array having difference between adjacent elements equal to D | Function to count the number of triplets having difference between adjacent elements equal to D ; Stores the frequency of array elements ; Stores the count of resultant triplets ; Traverse the array ; Check if arr [ i ] - D and arr [ i ] - 2 * D exists in the Hashmap or not ; Update the value of ans ; Increase the frequency of the current element ; Return the resultant count ; Driver Code
def countTriplets ( D , arr ) : NEW_LINE INDENT freq = { } NEW_LINE ans = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( ( ( arr [ i ] - D ) in freq ) and ( arr [ i ] - 2 * D ) in freq ) : NEW_LINE INDENT ans += ( freq [ arr [ i ] - D ] * freq [ arr [ i ] - 2 * D ] ) NEW_LINE DEDENT freq [ arr [ i ] ] = freq . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 5 , 7 , 8 , 10 ] NEW_LINE D = 1 NEW_LINE print ( countTriplets ( D , arr ) ) NEW_LINE DEDENT
Find the array element having equal sum of Prime Numbers on its left and right | Python3 program for the above approach ; Function to find an index in the array having sum of prime numbers to its left and right equal ; Stores the maximum value present in the array ; Stores all positive elements which are <= max_value ; If 1 is present ; Remove 1 ; Sieve of Eratosthenes to store all prime numbers which are <= max_value in the Map ; Erase non - prime numbers ; Stores the sum of prime numbers from left ; Stores the sum of prime numbers to the left of each index ; Stores the sum of prime numbers to the left of the current index ; Add current value to the prime sum if the current value is prime ; Stores the sum of prime numbers from right ; Stores the sum of prime numbers to the right of each index ; Stores the sum of prime numbers to the right of the current index ; Add current value to the prime sum if the current value is prime ; Traverse through the two arrays to find the index ; Compare the values present at the current index ; Return the index where both the values are same ; No index is found . ; Driver Code ; Given array arr [ ] ; Size of Array ; Function Call
from math import sqrt NEW_LINE def find_index ( arr , N ) : NEW_LINE INDENT max_value = - 10 ** 9 NEW_LINE for i in range ( N ) : NEW_LINE INDENT max_value = max ( max_value , arr [ i ] ) NEW_LINE DEDENT store = { } NEW_LINE for i in range ( 1 , max_value + 1 ) : NEW_LINE INDENT store [ i ] = store . get ( i , 0 ) + 1 NEW_LINE DEDENT if ( 1 in store ) : NEW_LINE INDENT del store [ 1 ] NEW_LINE DEDENT for i in range ( 2 , int ( sqrt ( max_value ) ) + 1 ) : NEW_LINE INDENT multiple = 2 NEW_LINE while ( ( i * multiple ) <= max_value ) : NEW_LINE INDENT if ( i * multiple in store ) : NEW_LINE INDENT del store [ i * multiple ] NEW_LINE DEDENT multiple += 1 NEW_LINE DEDENT DEDENT prime_sum_from_left = 0 NEW_LINE first_array = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT first_array [ i ] = prime_sum_from_left NEW_LINE if arr [ i ] in store : NEW_LINE INDENT prime_sum_from_left += arr [ i ] NEW_LINE DEDENT DEDENT prime_sum_from_right = 0 NEW_LINE second_array = [ 0 ] * N NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT second_array [ i ] = prime_sum_from_right NEW_LINE if ( arr [ i ] in store ) : NEW_LINE INDENT prime_sum_from_right += arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( first_array [ i ] == second_array [ i ] ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 11 , 4 , 7 , 6 , 13 , 1 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( find_index ( arr , N ) ) NEW_LINE DEDENT
Convert an array to reduced form | Set 3 ( Binary Search ) | Function to find the reduced form of the given array arr [ ] ; Stores the sorted form of the the given array arr [ ] ; Sort the array brr [ ] ; Traverse the given array arr [ ] ; Perform the Binary Search ; Calculate the value of mid ; Prthe current index and break ; Update the value of l ; Update the value of r ; Driver Code
def convert ( arr , n ) : NEW_LINE INDENT brr = [ i for i in arr ] NEW_LINE brr = sorted ( brr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT l , r , mid = 0 , n - 1 , 0 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = ( l + r ) // 2 NEW_LINE if ( brr [ mid ] == arr [ i ] ) : NEW_LINE INDENT print ( mid , end = " ▁ " ) NEW_LINE break NEW_LINE DEDENT elif ( brr [ mid ] < arr [ i ] ) : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 20 , 15 , 12 , 11 , 50 ] NEW_LINE N = len ( arr ) NEW_LINE convert ( arr , N ) NEW_LINE DEDENT
Find the array element having equal count of Prime Numbers on its left and right | Python 3 program for the above approach ; Function to find the index of the array such that the count of prime numbers to its either ends are same ; Store the maximum value in the array ; Traverse the array arr [ ] ; / Stores all the numbers ; Iterate over the range [ 1 , Max ] ; Increment the value of st [ i ] ; Removes 1 from the map St ; Perform Sieve of Prime Numbers ; While i * j is less than the maxValue ; If i * j is in map St ; Erase the value ( i * j ) ; Increment the value of j ; Stores the count of prime from index 0 to i ; Stores the count of prime numbers ; Traverse the array arr [ ] ; If arr [ i ] is present in the map st ; Stores the count of prime from index i to N - 1 ; Stores the count of prime numbers ; Iterate over the range [ 0 , N - 1 ] in reverse order ; If arr [ i ] is in map st ; Iterate over the range [ 0 , N - 1 ] ; If prefix [ i ] is equal to the Suffix [ i ] ; Return - 1 if no such index is present ; Driver Code
from collections import defaultdict NEW_LINE import sys NEW_LINE import math NEW_LINE def findIndex ( arr , N ) : NEW_LINE INDENT maxValue = - sys . maxsize - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT maxValue = max ( maxValue , arr [ i ] ) NEW_LINE DEDENT St = defaultdict ( int ) NEW_LINE for i in range ( 1 , maxValue + 1 ) : NEW_LINE INDENT St [ i ] += 1 NEW_LINE DEDENT if ( 1 in St ) : NEW_LINE INDENT St . pop ( 1 ) NEW_LINE DEDENT for i in range ( 2 , int ( math . sqrt ( maxValue ) ) + 1 ) : NEW_LINE INDENT j = 2 NEW_LINE while ( ( i * j ) <= maxValue ) : NEW_LINE INDENT if ( i * j ) in St : NEW_LINE INDENT St . pop ( i * j ) NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT LeftCount = 0 NEW_LINE Prefix = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT Prefix [ i ] = LeftCount NEW_LINE if ( arr [ i ] in St ) : NEW_LINE INDENT LeftCount += 1 NEW_LINE DEDENT DEDENT RightCount = 0 NEW_LINE Suffix = [ 0 ] * N NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT Suffix [ i ] = RightCount NEW_LINE if arr [ i ] in St : NEW_LINE INDENT RightCount += 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( Prefix [ i ] == Suffix [ i ] ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 7 , 5 , 10 , 1 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findIndex ( arr , N ) ) NEW_LINE DEDENT
Numbers of pairs from an array whose average is also present in the array | Function to count the number of pairs from the array having sum S ; Stores the total count of pairs whose sum is 2 * S ; Generate all possible pairs and check their sums ; If the sum is S , then increment the count ; Return the total count of pairs ; Function to count of pairs having whose average exists in the array ; Initialize the count ; Use set to remove duplicates ; Add elements in the set ; For every sum , count all possible pairs ; Return the total count ; Driver Code
def getCountPairs ( arr , N , S ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( arr ) ) : NEW_LINE INDENT if ( ( arr [ i ] + arr [ j ] ) == S ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT def countPairs ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE S = set ( [ ] ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT S . add ( arr [ i ] ) NEW_LINE DEDENT for ele in S : NEW_LINE INDENT sum = 2 * ele NEW_LINE count += getCountPairs ( arr , N , sum ) NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 2 , 5 , 1 , 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countPairs ( arr , N ) ) NEW_LINE DEDENT
Sort array of strings after sorting each string after removing characters whose frequencies are not a powers of 2 | Python3 program for the above approach ; Function to check if N is power of 2 or not ; Base Case ; Return true if N is power of 2 ; Function to print array of strings in ascending order ; Sort strings in ascending order ; Print the array ; Function to sort the strings after modifying each string according to the given conditions ; Store the frequency of each characters of the string ; Stores the required array of strings ; Traverse the array of strings ; Temporary string ; Stores frequency of each alphabet of the string ; Update frequency of S [ i ] [ j ] ; Traverse the map freq ; Check if the frequency of i . first is a power of 2 ; Update string st ; Clear the map ; Null string ; Sort the string in descending order ; Update res ; Print the array of strings ; Driver Code
from collections import defaultdict NEW_LINE import math NEW_LINE def isPowerOfTwo ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( math . ceil ( math . log2 ( n ) ) == math . floor ( math . log2 ( n ) ) ) NEW_LINE DEDENT def printArray ( res ) : NEW_LINE INDENT res . sort ( ) NEW_LINE for i in range ( len ( res ) ) : NEW_LINE INDENT print ( res [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def sortedStrings ( S , N ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE res = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT st = " " NEW_LINE for j in range ( len ( S [ i ] ) ) : NEW_LINE INDENT freq [ S [ i ] [ j ] ] += 1 NEW_LINE DEDENT for i in freq : NEW_LINE INDENT if ( isPowerOfTwo ( freq [ i ] ) ) : NEW_LINE INDENT for j in range ( freq [ i ] ) : NEW_LINE INDENT st += i NEW_LINE DEDENT DEDENT DEDENT freq . clear ( ) NEW_LINE if ( len ( st ) == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT st = list ( st ) NEW_LINE st . sort ( reverse = True ) NEW_LINE st = ' ' . join ( st ) NEW_LINE res . append ( st ) NEW_LINE DEDENT printArray ( res ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " aaacbb " , " geeks " , " aaa " ] NEW_LINE N = len ( arr ) NEW_LINE sortedStrings ( arr , N ) NEW_LINE DEDENT
Modify string by replacing all occurrences of given characters by specified replacing characters | Function to modify given string by replacing characters ; Store the size of string and the number of pairs ; Initialize 2 character arrays ; Traverse the string s Update arrays arr [ ] and brr [ ] ; Traverse the array of pairs p ; a -> Character to be replaced b -> Replacing character ; Iterate over the range [ 0 , 25 ] ; If it is equal to current character , then replace it in the array b ; Print the array brr [ ] ; Driver Code
def replaceCharacters ( s , p ) : NEW_LINE INDENT n , k = len ( s ) , len ( p ) NEW_LINE arr = [ 0 ] * 26 NEW_LINE brr = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ ord ( s [ i ] ) - ord ( ' a ' ) ] = s [ i ] NEW_LINE brr [ ord ( s [ i ] ) - ord ( ' a ' ) ] = s [ i ] NEW_LINE DEDENT for j in range ( k ) : NEW_LINE INDENT a , b = p [ j ] [ 0 ] , p [ j ] [ 1 ] NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( arr [ i ] == a ) : NEW_LINE INDENT brr [ i ] = b NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( brr [ ord ( s [ i ] ) - ord ( ' a ' ) ] , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " aabbgg " NEW_LINE P = [ [ ' a ' , ' b ' ] , [ ' b ' , ' g ' ] , [ ' g ' , ' a ' ] ] NEW_LINE replaceCharacters ( S , P ) NEW_LINE DEDENT
Smallest Semi | Python3 program for the above approach ; Function to find all the prime numbers using Sieve of Eratosthenes ; Set 0 and 1 as non - prime ; If p is a prime ; Set all multiples of p as non - prime ; Function to find the smallest semi - prime number having a difference between any of its two divisors at least N ; Stores the prime numbers ; Fill the prime array ; Initialize the first divisor ; Find the value of the first prime number ; Initialize the second divisor ; Find the second prime number ; Print the semi - prime number ; Driver Code
MAX = 100001 NEW_LINE def SieveOfEratosthenes ( prime ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p < MAX : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , MAX , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def smallestSemiPrime ( n ) : NEW_LINE INDENT prime = [ True ] * MAX NEW_LINE SieveOfEratosthenes ( prime ) NEW_LINE num1 = n + 1 NEW_LINE while ( prime [ num1 ] != True ) : NEW_LINE INDENT num1 += 1 NEW_LINE DEDENT num2 = num1 + n NEW_LINE while ( prime [ num2 ] != True ) : NEW_LINE INDENT num2 += 1 NEW_LINE DEDENT print ( num1 * num2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE smallestSemiPrime ( N ) NEW_LINE DEDENT
Check if a number can be represented as product of two positive perfect cubes | Function to check if N can be represented as the product of two perfect cubes or not ; Stores the perfect cubes ; Traverse the Map ; Stores the first number ; Stores the second number ; Search the pair for the first number to obtain product N from the Map ; If N cannot be represented as the product of the two positive perfect cubes ; Driver Code
def productOfTwoPerfectCubes ( N ) : NEW_LINE INDENT cubes = { } NEW_LINE i = 1 NEW_LINE while i * i * i <= N : NEW_LINE INDENT cubes [ i * i * i ] = i NEW_LINE i += 1 NEW_LINE DEDENT for itr in cubes : NEW_LINE INDENT firstNumber = itr NEW_LINE if ( N % itr == 0 ) : NEW_LINE INDENT secondNumber = N // itr NEW_LINE if ( secondNumber in cubes ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( " No " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 216 NEW_LINE productOfTwoPerfectCubes ( N ) NEW_LINE DEDENT
Check if a number can be represented as product of two positive perfect cubes | Function to check if the number N can be represented as the product of two perfect cubes or not ; If cube of cube_root is N ; Otherwise , prNo ; Driver Code
def productOfTwoPerfectCubes ( N ) : NEW_LINE INDENT cube_root = round ( ( N ) ** ( 1 / 3 ) ) NEW_LINE print ( cube_root ) NEW_LINE if ( cube_root * cube_root * cube_root == N ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 216 NEW_LINE productOfTwoPerfectCubes ( N ) NEW_LINE DEDENT
Size of smallest square that contains N non | Function to check if side of square X can pack all the N rectangles or not ; Find the number of rectangle it can pack ; If val is atleast N , then return true ; Otherwise , return false ; Function to find the size of the smallest square that can contain N rectangles of dimensions W * H ; Stores the lower bound ; Stores the upper bound ; Iterate until i is less than j ; Calculate the mid value ; If the current size of square cam contain N rectangles ; Otherwise , update i ; Return the minimum size of the square required ; Driver Code ; Function Call
def bound ( w , h , N , x ) : NEW_LINE INDENT val = ( x // w ) * ( x // h ) NEW_LINE if ( val >= N ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def FindSquare ( N , W , H ) : NEW_LINE INDENT i = 1 NEW_LINE j = W * H * N NEW_LINE while ( i < j ) : NEW_LINE INDENT mid = i + ( j - i ) // 2 NEW_LINE if ( bound ( W , H , N , mid ) ) : NEW_LINE INDENT j = mid NEW_LINE DEDENT else : NEW_LINE INDENT i = mid + 1 NEW_LINE DEDENT DEDENT return j NEW_LINE DEDENT W = 2 NEW_LINE H = 3 NEW_LINE N = 10 NEW_LINE print ( FindSquare ( N , W , H ) ) NEW_LINE
Count integers up to N that are equal to at least 2 nd power of any integer exceeding 1 | Python 3 program for the above approach ; Function to count the integers up to N that can be represented as a ^ b , where a & b > 1 ; Initialize a HashSet ; Iterating over the range [ 2 , sqrt ( N ) ] ; Generate all possible power of x ; Multiply x by i ; If the generated number lies in the range [ 1 , N ] then insert it in HashSet ; Print the total count ; Driver code
from math import sqrt NEW_LINE def printNumberOfPairs ( N ) : NEW_LINE INDENT st = set ( ) NEW_LINE for i in range ( 2 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT x = i NEW_LINE while ( x <= N ) : NEW_LINE INDENT x *= i NEW_LINE if ( x <= N ) : NEW_LINE INDENT st . add ( x ) NEW_LINE DEDENT DEDENT DEDENT print ( len ( st ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10000 NEW_LINE printNumberOfPairs ( N ) NEW_LINE DEDENT
Maximize product of lengths of strings having no common characters | Function to count the number of set bits in the integer n ; Stores the count of set bits in n ; Return the count ; Function to find the maximum product of pair of strings having no common characters ; Stores the integer equivalent of the strings ; Traverse the array of strings ; Traverse the current string ; Store the current bit position in bits [ i ] ; Store the required result ; Traverse the array , bits [ ] to get all unique pairs ( i , j ) ; Check whether the strings have no common characters ; Update the overall maximum product ; Print the maximum product ; Driver Code
def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def maximumProduct ( words ) : NEW_LINE INDENT bits = [ 0 for i in range ( len ( words ) ) ] NEW_LINE for i in range ( len ( words ) ) : NEW_LINE INDENT for j in range ( len ( words [ i ] ) ) : NEW_LINE INDENT bits [ i ] = bits [ i ] | 1 << ( ord ( words [ i ] [ j ] ) - 97 ) NEW_LINE DEDENT DEDENT result = 0 NEW_LINE for i in range ( len ( bits ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( bits ) ) : NEW_LINE INDENT if ( ( bits [ i ] & bits [ j ] ) == 0 ) : NEW_LINE INDENT L = countSetBits ( bits [ i ] ) NEW_LINE R = countSetBits ( bits [ j ] ) NEW_LINE result = max ( L * R , result ) NEW_LINE DEDENT DEDENT DEDENT print ( result ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " abcw " , " baz " , " foo " , " bar " , " xtfn " , " abcdef " ] NEW_LINE maximumProduct ( arr ) NEW_LINE DEDENT
Modify a sentence by reversing order of occurrences of all Palindrome Words | Function to check if a string S is a palindrome ; Function to print the modified string after reversing teh order of occurrences of all palindromic words in the sentence ; Stores the palindromic words ; Stores the words in the list ; Traversing the list ; If current word is a palindrome ; Update newlist ; Reverse the newlist ; Traverse the list ; If current word is a palindrome ; Update lis [ i ] ; Increment j ; Print the updated sentence ; Driver Code
def palindrome ( string ) : NEW_LINE INDENT if ( string == string [ : : - 1 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def printReverse ( sentence ) : NEW_LINE INDENT newlist = [ ] NEW_LINE lis = list ( sentence . split ( ) ) NEW_LINE for i in lis : NEW_LINE INDENT if ( palindrome ( i ) ) : NEW_LINE INDENT newlist . append ( i ) NEW_LINE DEDENT DEDENT newlist . reverse ( ) NEW_LINE j = 0 NEW_LINE for i in range ( len ( lis ) ) : NEW_LINE INDENT if ( palindrome ( lis [ i ] ) ) : NEW_LINE INDENT lis [ i ] = newlist [ j ] NEW_LINE j = j + 1 NEW_LINE DEDENT DEDENT for i in lis : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT sentence = " mom ▁ and ▁ dad ▁ went ▁ to ▁ eye ▁ hospital " NEW_LINE printReverse ( sentence ) NEW_LINE
Convert an array into another by repeatedly removing the last element and placing it at any arbitrary index | Function to count the minimum number of operations required to convert the array A [ ] into array B [ ] ; Stores the index in the first permutation A [ ] which is same as the subsequence in B [ ] ; Find the first i elements in A [ ] which is a subsequence in B [ ] ; If element A [ i ] is same as B [ j ] ; Return the count of operations required ; Driver Code
def minCount ( A , B , N ) : NEW_LINE INDENT i = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( A [ i ] == B [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT return N - i NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE B = [ 1 , 5 , 2 , 3 , 4 ] NEW_LINE N = len ( A ) NEW_LINE print ( minCount ( A , B , N ) ) NEW_LINE DEDENT
Minimize maximum array element possible by at most K splits on the given array | Function to check if all array elements can be reduced to at most mid by at most K splits ; Stores the number of splits required ; Traverse the array arr [ ] ; Update count ; If possible , return true . Otherwise return false ; Function to find the minimum possible value of maximum array element that can be obtained by at most K splits ; Set lower and upper limits ; Perform Binary Search ; Calculate mid ; Check if all array elements can be reduced to at most mid value by at most K splits ; Update the value of hi ; Otherwise ; Update the value of lo ; Return the minimized maximum element in the array ; Driver Code
def possible ( A , N , mid , K ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT count += ( A [ i ] - 1 ) // mid NEW_LINE DEDENT return count <= K NEW_LINE DEDENT def minimumMaximum ( A , N , K ) : NEW_LINE INDENT lo = 1 NEW_LINE hi = max ( A ) NEW_LINE while ( lo < hi ) : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE if ( possible ( A , N , mid , K ) ) : NEW_LINE INDENT hi = mid NEW_LINE DEDENT else : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT DEDENT return hi NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 8 , 2 ] NEW_LINE K = 4 NEW_LINE N = len ( arr ) NEW_LINE print ( minimumMaximum ( arr , N , K ) ) NEW_LINE DEDENT
Maximum value of X such that difference between any array element and X does not exceed K | Function to find maximum value of X such that | A [ i ] - X | a K ; Stores the smallest array element ; Store the possible value of X ; Traverse the array A [ ] ; If required criteria is not satisfied ; Update ans ; Print the result ; Driver Code
def maximumNumber ( arr , N , K ) : NEW_LINE INDENT minimum = min ( arr ) NEW_LINE ans = minimum + K NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( abs ( arr [ i ] - ans ) > K ) : NEW_LINE INDENT ans = - 1 NEW_LINE break NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 5 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE maximumNumber ( arr , N , K ) NEW_LINE DEDENT