text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Check if a point is inside , outside or on the parabola | Function to check the point ; checking the equation of parabola with the given point ; Driver code | def checkpoint ( h , k , x , y , a ) : NEW_LINE INDENT p = pow ( ( y - k ) , 2 ) - 4 * a * ( x - h ) NEW_LINE return p NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT h = 0 NEW_LINE k = 0 NEW_LINE x = 2 NEW_LINE y = 1 NEW_LINE a = 4 NEW_LINE if checkpoint ( h , k , x , y , a ) > 0 : NEW_LINE INDENT print ( " Outside " ) NEW_LINE DEDENT elif checkpoint ( h , k , x , y , a ) == 0 : NEW_LINE INDENT print ( " On the parabola " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Inside " ) ; NEW_LINE DEDENT DEDENT |
Check if a point is inside , outside or on the ellipse | Python 3 Program to check if the point lies within the ellipse or not ; Function to check the point ; checking the equation of ellipse with the given point ; Driver code | import math NEW_LINE def checkpoint ( h , k , x , y , a , b ) : NEW_LINE INDENT p = ( ( math . pow ( ( x - h ) , 2 ) // math . pow ( a , 2 ) ) + ( math . pow ( ( y - k ) , 2 ) // math . pow ( b , 2 ) ) ) NEW_LINE return p NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT h = 0 NEW_LINE k = 0 NEW_LINE x = 2 NEW_LINE y = 1 NEW_LINE a = 4 NEW_LINE b = 5 NEW_LINE if ( checkpoint ( h , k , x , y , a , b ) > 1 ) : NEW_LINE INDENT print ( " Outside " ) NEW_LINE DEDENT elif ( checkpoint ( h , k , x , y , a , b ) == 1 ) : NEW_LINE INDENT print ( " On β the β ellipse " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Inside " ) NEW_LINE DEDENT DEDENT |
Area of circle inscribed within rhombus | Function to find the area of the inscribed circle ; the diagonals cannot be negative ; area of the circle ; Driver code | def circlearea ( a , b ) : NEW_LINE INDENT if ( a < 0 or b < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT A = ( ( 3.14 * pow ( a , 2 ) * pow ( b , 2 ) ) / ( 4 * ( pow ( a , 2 ) + pow ( b , 2 ) ) ) ) NEW_LINE return A NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 8 NEW_LINE b = 10 NEW_LINE print ( circlearea ( a , b ) ) NEW_LINE DEDENT |
The biggest possible circle that can be inscribed in a rectangle | Function to find the area of the biggest circle ; the length and breadth cannot be negative ; area of the circle ; Driver code | def circlearea ( l , b ) : NEW_LINE INDENT if ( l < 0 or b < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( l < b ) : NEW_LINE INDENT return 3.14 * pow ( l // 2 , 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return 3.14 * pow ( b // 2 , 2 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 4 NEW_LINE b = 8 NEW_LINE print ( circlearea ( l , b ) ) NEW_LINE DEDENT |
Centered cube number | Centered cube number function ; Formula to calculate nth Centered cube number return it into main function . ; Driver Code | def centered_cube ( n ) : NEW_LINE INDENT return ( 2 * n + 1 ) * ( n * n + n + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE print ( n , " th β Centered β cube β " + " number β : β " , centered_cube ( n ) ) NEW_LINE n = 10 NEW_LINE print ( n , " th β Centered β cube β " + " number β : β " , centered_cube ( n ) ) NEW_LINE DEDENT |
Find the center of the circle using endpoints of diameter | Function to find the center of the circle ; Driver Code | def center ( x1 , x2 , y1 , y2 ) : NEW_LINE INDENT print ( int ( ( x1 + x2 ) / 2 ) , end = " " ) NEW_LINE print ( " , " , int ( ( y1 + y2 ) / 2 ) ) NEW_LINE DEDENT x1 = - 9 ; y1 = 3 ; x2 = 5 ; y2 = - 7 NEW_LINE center ( x1 , x2 , y1 , y2 ) NEW_LINE |
Program to calculate volume of Octahedron | Python3 Program to calculate volume of Octahedron ; utility Function ; Driver Function | import math NEW_LINE def vol_of_octahedron ( side ) : NEW_LINE INDENT return ( ( side * side * side ) * ( math . sqrt ( 2 ) / 3 ) ) NEW_LINE DEDENT side = 3 NEW_LINE print ( " Volume β of β octahedron β = " , round ( vol_of_octahedron ( side ) , 4 ) ) NEW_LINE |
Program to calculate volume of Ellipsoid | Python3 program to Volume of ellipsoid ; Function To calculate Volume ; Driver Code | import math NEW_LINE def volumeOfEllipsoid ( r1 , r2 , r3 ) : NEW_LINE INDENT return 1.33 * math . pi * r1 * r2 * r3 NEW_LINE DEDENT r1 = float ( 2.3 ) NEW_LINE r2 = float ( 3.4 ) NEW_LINE r3 = float ( 5.7 ) NEW_LINE print ( " Volume β of β ellipsoid β is β : β " , volumeOfEllipsoid ( r1 , r2 , r3 ) ) NEW_LINE |
Program to calculate Area Of Octagon | Python3 program to find area of octagon ; Utility function ; Driver function | import math NEW_LINE def areaOctagon ( side ) : NEW_LINE INDENT return ( 2 * ( 1 + ( math . sqrt ( 2 ) ) ) * side * side ) NEW_LINE DEDENT side = 4 NEW_LINE print ( " Area β of β Regular β Octagon β = " , round ( areaOctagon ( side ) , 4 ) ) NEW_LINE |
Program for Volume and Surface Area of Cube | utility function ; driver function | def areaCube ( a ) : NEW_LINE INDENT return ( a * a * a ) NEW_LINE DEDENT def surfaceCube ( a ) : NEW_LINE INDENT return ( 6 * a * a ) NEW_LINE DEDENT a = 5 NEW_LINE print ( " Area β = " , areaCube ( a ) ) NEW_LINE print ( " Total β surface β area β = " , surfaceCube ( a ) ) NEW_LINE |
Find mirror image of a point in 2 | Python function which finds coordinates of mirror image . This function return a pair of double ; Driver code to test above function | def mirrorImage ( a , b , c , x1 , y1 ) : NEW_LINE INDENT temp = - 2 * ( a * x1 + b * y1 + c ) / ( a * a + b * b ) NEW_LINE x = temp * a + x1 NEW_LINE y = temp * b + y1 NEW_LINE return ( x , y ) NEW_LINE DEDENT a = - 1.0 NEW_LINE b = 1.0 NEW_LINE c = 0.0 NEW_LINE x1 = 1.0 NEW_LINE y1 = 0.0 NEW_LINE x , y = mirrorImage ( a , b , c , x1 , y1 ) ; NEW_LINE print ( " Image β of β point β ( " + str ( x1 ) + " , β " + str ( y1 ) + " ) β " ) NEW_LINE print ( " by β mirror β ( " + str ( a ) + " ) x β + β ( " + str ( b ) + " ) y β + β ( " + str ( c ) + " ) β = β 0 , β is β : " ) NEW_LINE print ( " ( " + str ( x ) + " , β " + str ( y ) + " ) " ) NEW_LINE |
Minimum revolutions to move center of a circle to a target | Python program to find minimum number of revolutions to reach a target center ; Minimum revolutions to move center from ( x1 , y1 ) to ( x2 , y2 ) ; Driver code | import math NEW_LINE def minRevolutions ( r , x1 , y1 , x2 , y2 ) : NEW_LINE INDENT d = math . sqrt ( ( x1 - x2 ) * ( x1 - x2 ) + ( y1 - y2 ) * ( y1 - y2 ) ) NEW_LINE return math . ceil ( d / ( 2 * r ) ) NEW_LINE DEDENT r = 2 NEW_LINE x1 = 0 NEW_LINE y1 = 0 NEW_LINE x2 = 0 NEW_LINE y2 = 4 NEW_LINE print ( minRevolutions ( r , x1 , y1 , x2 , y2 ) ) NEW_LINE |
Find all sides of a right angled triangle from given hypotenuse and area | Set 1 | limit for float comparison define eps 1e-6 ; Utility method to get area of right angle triangle , given base and hypotenuse ; Prints base and height of triangle using hypotenuse and area information ; maximum area will be obtained when base and height are equal ( = sqrt ( h * h / 2 ) ) ; if given area itself is larger than maxArea then no solution is possible ; binary search for base ; get height by pythagorean rule ; Driver code to test above methods | import math NEW_LINE def getArea ( base , hypotenuse ) : NEW_LINE INDENT height = math . sqrt ( hypotenuse * hypotenuse - base * base ) ; NEW_LINE return 0.5 * base * height NEW_LINE DEDENT def printRightAngleTriangle ( hypotenuse , area ) : NEW_LINE INDENT hsquare = hypotenuse * hypotenuse NEW_LINE sideForMaxArea = math . sqrt ( hsquare / 2.0 ) NEW_LINE maxArea = getArea ( sideForMaxArea , hypotenuse ) NEW_LINE if ( area > maxArea ) : NEW_LINE INDENT print ( " Not β possiblen " ) NEW_LINE return NEW_LINE DEDENT low = 0.0 NEW_LINE high = sideForMaxArea NEW_LINE while ( abs ( high - low ) > 1e-6 ) : NEW_LINE INDENT base = ( low + high ) / 2.0 NEW_LINE if ( getArea ( base , hypotenuse ) >= area ) : NEW_LINE INDENT high = base NEW_LINE DEDENT else : NEW_LINE INDENT low = base NEW_LINE DEDENT DEDENT height = math . ceil ( math . sqrt ( hsquare - base * base ) ) NEW_LINE base = math . floor ( base ) NEW_LINE print ( base , height ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT hypotenuse = 5 NEW_LINE area = 6 NEW_LINE printRightAngleTriangle ( hypotenuse , area ) NEW_LINE DEDENT |
Circle and Lattice Points | Python3 program to find countLattice podefs on a circle ; Function to count Lattice podefs on a circle ; Initialize result as 4 for ( r , 0 ) , ( - r . 0 ) , ( 0 , r ) and ( 0 , - r ) ; Check every value that can be potential x ; Find a potential y ; checking whether square root is an defeger or not . Count increments by 4 for four different quadrant values ; Driver program | import math NEW_LINE def countLattice ( r ) : NEW_LINE INDENT if ( r <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT result = 4 NEW_LINE for x in range ( 1 , r ) : NEW_LINE INDENT ySquare = r * r - x * x NEW_LINE y = int ( math . sqrt ( ySquare ) ) NEW_LINE if ( y * y == ySquare ) : NEW_LINE INDENT result += 4 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT r = 5 NEW_LINE print ( countLattice ( r ) ) NEW_LINE |
Count of subarrays of size K with average at least M | Function to count the subarrays of size K having average at least M ; Stores the resultant count of subarray ; Stores the sum of subarrays of size K ; Add the values of first K elements to the sum ; Increment the count if the current subarray is valid ; Traverse the given array ; Find the updated sum ; Check if current subarray is valid or not ; Return the count of subarrays ; Driver Code | def countSubArrays ( arr , N , K , M ) : NEW_LINE INDENT count = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if sum >= K * M : NEW_LINE INDENT count += 1 NEW_LINE DEDENT for i in range ( K , N ) : NEW_LINE INDENT sum += ( arr [ i ] - arr [ i - K ] ) NEW_LINE if sum >= K * M : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 3 , 2 , 1 , 3 , 9 ] NEW_LINE K = 2 NEW_LINE M = 4 NEW_LINE N = len ( arr ) NEW_LINE count = countSubArrays ( arr , N , K , M ) NEW_LINE print ( count ) NEW_LINE DEDENT |
Count of Ks in the Array for a given range of indices after array updates for Q queries | ''Function to perform all the queries ; ''Stores the count of 0s ; ''Count the number of 0s for query of type 1 ; '' Update the array element for query of type 2 ; ''Driver Code | def performQueries ( n , q , k , arr , query ) : NEW_LINE INDENT for i in range ( 1 , q + 1 , 1 ) : NEW_LINE count = 0 NEW_LINE if ( query [ i - 1 ] [ 0 ] == 1 ) : NEW_LINE DEDENT for j in range ( query [ i - 1 ] [ 1 ] , query [ i - 1 ] [ 2 ] + 1 , 1 ) : NEW_LINE INDENT if ( arr [ j ] == k ) : NEW_LINE DEDENT count += 1 NEW_LINE INDENT print ( count ) NEW_LINE else : NEW_LINE DEDENT arr [ query [ i - 1 ] [ 1 ] ] = query [ i - 1 ] [ 2 ] NEW_LINE if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 5 , 7 , 6 , 9 , 0 , 0 , 0 , 0 , 5 , 6 , 7 , 3 , 9 , 0 , 7 , 0 , 9 , 0 ] NEW_LINE Q = 5 NEW_LINE INDENT query = [ [ 1 , 5 , 14 ] , [ 2 , 6 , 1 ] , [ 1 , 0 , 8 ] , [ 2 , 13 , 0 ] , [ 1 , 6 , 18 ] ] NEW_LINE DEDENT N = len ( arr ) NEW_LINE DEDENT K = 0 NEW_LINE INDENT performQueries ( N , Q , K , arr , query ) NEW_LINE DEDENT |
Minimum count of consecutive integers till N whose bitwise AND is 0 with N | Function to count the minimum count of integers such that bitwise AND of that many consecutive elements is equal to 0 ; Stores the binary representation of N ; Excludes first two characters "0b " ; Stores the MSB bit ; Stores the count of numbers ; Return res ; Driver Code Given Input ; Function Call | def count ( N ) : NEW_LINE INDENT a = bin ( N ) NEW_LINE a = a [ 2 : ] NEW_LINE m = len ( a ) - 1 NEW_LINE res = N - ( 2 ** m - 1 ) NEW_LINE return res NEW_LINE DEDENT N = 18 NEW_LINE print ( count ( N ) ) NEW_LINE |
Find smallest value of K such that bitwise AND of numbers in range [ N , N | Function is to find the largest no which gives the sequence n & ( n - 1 ) & ( n - 2 ) & ... . . & ( n - k ) = 0. ; Since , we need the largest no , we start from n itself , till 0 ; Driver Code | def findSmallestNumK ( n ) : NEW_LINE INDENT cummAnd = n NEW_LINE i = n - 1 NEW_LINE while ( cummAnd != 0 ) : NEW_LINE INDENT cummAnd = cummAnd & i NEW_LINE if ( cummAnd == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 17 NEW_LINE lastNum = findSmallestNumK ( N ) ; NEW_LINE K = lastNum if lastNum == - 1 else N - lastNum NEW_LINE print ( K ) NEW_LINE DEDENT |
Program to find the value of P ( N + r ) for a polynomial of a degree N such that P ( i ) = 1 for 1 Γ Β’ Γ’ β¬Β°Β€ i Γ Β’ Γ’ β¬Β°Β€ N and P ( N + 1 ) = a | ''Function to calculate factorial of N ; '' Base Case ; '' Otherwise, recursively calculate the factorial ; ''Function to find the value of P(n + r) for polynomial P(X) ; ''Stores the value of k ; '' Store the required answer ; '' Iterate in the range [1, N] and multiply (n + r - i) with answer ; '' Add the constant value C as 1 ; '' Return the result ; ''Driver Code | def fact ( n ) : NEW_LINE INDENT if n == 1 or n == 0 : NEW_LINE return 1 NEW_LINE else : NEW_LINE return n * fact ( n - 1 ) NEW_LINE DEDENT def findValue ( n , r , a ) : NEW_LINE INDENT k = ( a - 1 ) // fact ( n ) NEW_LINE answer = k NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE answer = answer * ( n + r - i ) NEW_LINE DEDENT answer = answer + 1 NEW_LINE INDENT return answer NEW_LINE DEDENT N = 1 NEW_LINE A = 2 NEW_LINE R = 3 NEW_LINE print ( findValue ( N , R , A ) ) NEW_LINE |
Find winner in game of N balls , in which a player can remove any balls in range [ A , B ] in a single move | Function to find the winner of the game ; Stores sum of A and B ; If N is of the form m * ( A + B ) + y ; Otherwise , ; Input ; Function call | def NimGame ( N , A , B ) : NEW_LINE INDENT sum = A + B NEW_LINE if ( N % sum <= A - 1 ) : NEW_LINE INDENT return " Bob " NEW_LINE DEDENT else : NEW_LINE INDENT return " Alice " NEW_LINE DEDENT DEDENT N = 3 NEW_LINE A = 1 NEW_LINE B = 2 NEW_LINE print ( NimGame ( N , A , B ) ) NEW_LINE |
Find Nth number in a sequence which is not a multiple of a given number | Python3 program for the above approach ; Function to find Nth number not a multiple of A in range [ L , R ] ; Calculate the Nth no ; Check for the edge case ; ; Input parameters ; Function Call | import math NEW_LINE def countNo ( A , N , L , R ) : NEW_LINE INDENT ans = L - 1 + N + math . floor ( ( N - 1 ) / ( A - 1 ) ) NEW_LINE if ans % A == 0 : NEW_LINE INDENT ans = ans + 1 ; NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT / * Driver Code * / NEW_LINE A , N , L , R = 5 , 10 , 4 , 20 NEW_LINE countNo ( A , N , L , R ) NEW_LINE |
Count of paths in given Binary Tree with odd bitwise AND for Q queries | Function to count number of paths in binary tree such that bitwise AND of all nodes is Odd ; vector dp to store the count of bitwise odd paths till that vertex ; Precomputing for each value ; Check for odd value ; Number of odd elements will be + 1 till the parent node ; For even case ; Since node is even Number of odd elements will be 0 ; Even value node will not contribute in answer hence dp [ i ] = previous answer ; Printing the answer for each query ; Vector to store queries | def compute ( query ) : NEW_LINE INDENT v = [ None ] * 100001 NEW_LINE dp = [ None ] * 100001 NEW_LINE v [ 1 ] = 1 NEW_LINE v [ 2 ] = 0 NEW_LINE dp [ 1 ] = 0 NEW_LINE dp [ 2 ] = 0 NEW_LINE for i in range ( 3 , 100001 ) : NEW_LINE INDENT if ( i % 2 != 0 ) : NEW_LINE INDENT if ( ( i // 2 ) % 2 == 0 ) : NEW_LINE INDENT v [ i ] = 1 NEW_LINE dp [ i ] = dp [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT v [ i ] = v [ i // 2 ] + 1 NEW_LINE dp [ i ] = dp [ i - 1 ] + v [ i ] - 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT v [ i ] = 0 NEW_LINE dp [ i ] = dp [ i - 1 ] NEW_LINE DEDENT DEDENT for x in query : NEW_LINE INDENT print ( dp [ x ] ) NEW_LINE DEDENT DEDENT query = [ 5 , 2 ] NEW_LINE compute ( query ) NEW_LINE |
Number of cycles formed by joining vertices of n sided polygon at the center | Function to calculate number of cycles ; BigInteger is used here if N = 10 ^ 9 then multiply will result into value greater than 10 ^ 18 ; BigInteger multiply function ; Return the final result ; Driver Code ; Given N ; Function Call | def findCycles ( N ) : NEW_LINE INDENT res = 0 NEW_LINE finalResult = 0 NEW_LINE val = 2 * N - 1 ; NEW_LINE s = val NEW_LINE res = ( N - 1 ) * ( N - 2 ) NEW_LINE finalResult = res + s ; NEW_LINE return finalResult ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE print ( findCycles ( N ) ) ; NEW_LINE DEDENT |
Split a given array into K subarrays minimizing the difference between their maximum and minimum | Function to find the subarray ; Add the difference to vectors ; Sort vector to find minimum k ; Initialize result ; Adding first k - 1 values ; Return the minimized sum ; Driver code ; Length of array ; Given K ; Function Call | def find ( a , n , k ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT v . append ( a [ i - 1 ] - a [ i ] ) NEW_LINE DEDENT v . sort ( ) NEW_LINE res = a [ n - 1 ] - a [ 0 ] NEW_LINE for i in range ( k - 1 ) : NEW_LINE INDENT res += v [ i ] NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 4 , 8 , 15 , 16 , 23 , 42 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( find ( arr , N , K ) ) NEW_LINE |
Last digit of a number raised to last digit of N factorial | Function to find a ^ b using binary exponentiation ; Initialise result ; If b is odd then , multiply result by a ; b must be even now Change b to b / 2 ; Change a = a ^ 2 ; Function to find the last digit of the given equation ; To store cyclicity ; Store cyclicity from 1 - 10 ; Observation 1 ; Observation 3 ; To store the last digits of factorial 2 , 3 , and 4 ; Find the last digit of X ; Step 1 ; Divide a [ N ] by cyclicity of v ; If remainder is 0 ; Step 1.1 ; Step 1.2 ; Step 1.3 ; If r is non - zero , then return ( l ^ r ) % 10 ; Else return 0 ; Else return 1 ; Driver Code ; Given numbers ; Function call ; Print the result | def power ( a , b , c ) : NEW_LINE INDENT result = 1 NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( ( b & 1 ) == 1 ) : NEW_LINE INDENT result = ( result * a ) % c NEW_LINE DEDENT b //= 2 NEW_LINE a = ( a * a ) % c NEW_LINE DEDENT return result NEW_LINE DEDENT def calculate ( X , N ) : NEW_LINE INDENT a = 10 * [ 0 ] NEW_LINE cyclicity = 11 * [ 0 ] NEW_LINE cyclicity [ 1 ] = 1 NEW_LINE cyclicity [ 2 ] = 4 NEW_LINE cyclicity [ 3 ] = 4 NEW_LINE cyclicity [ 4 ] = 2 NEW_LINE cyclicity [ 5 ] = 1 NEW_LINE cyclicity [ 6 ] = 1 NEW_LINE cyclicity [ 7 ] = 4 NEW_LINE cyclicity [ 8 ] = 4 NEW_LINE cyclicity [ 9 ] = 2 NEW_LINE cyclicity [ 10 ] = 1 NEW_LINE if ( N == 0 or N == 1 ) : NEW_LINE INDENT return ( X % 10 ) NEW_LINE DEDENT elif ( N == 2 or N == 3 or N == 4 ) : NEW_LINE INDENT temp = 1e18 ; NEW_LINE a [ 2 ] = 2 NEW_LINE a [ 3 ] = 6 NEW_LINE a [ 4 ] = 4 NEW_LINE v = X % 10 NEW_LINE if ( v != 0 ) : NEW_LINE INDENT u = cyclicity [ v ] NEW_LINE r = a [ N ] % u NEW_LINE if ( r == 0 ) : NEW_LINE INDENT if ( v == 2 or v == 4 or v == 6 or v == 8 ) : NEW_LINE INDENT return 6 NEW_LINE DEDENT elif ( v == 5 ) : NEW_LINE INDENT return 5 NEW_LINE DEDENT elif ( v == 1 or v == 3 or v == 7 or v == 9 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return ( power ( v , r , temp ) % 10 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 18 NEW_LINE N = 4 NEW_LINE result = calculate ( X , N ) NEW_LINE print ( result ) NEW_LINE DEDENT |
Maximize 3 rd element sum in quadruplet sets formed from given Array | Function to find the maximum possible value of Y ; Pairs contain count of minimum elements that will be utilized at place of Z . It is equal to count of possible pairs that is size of array divided by 4 ; Sorting the array in descending order so as to bring values with minimal difference closer to arr [ i ] ; Here , i + 2 acts as a pointer that points to the third value of every possible quadruplet ; Returning the optimally maximum possible value ; Array declaration ; Size of array | def formQuadruplets ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE pairs = 0 NEW_LINE pairs = n // 4 NEW_LINE arr . sort ( reverse = True ) NEW_LINE for i in range ( 0 , n - pairs , 3 ) : NEW_LINE INDENT ans += arr [ i + 2 ] NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 1 , 7 , 5 , 5 , 4 , 1 , 1 , 3 , 3 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( formQuadruplets ( arr , n ) ) NEW_LINE |
Minimum concatenation required to get strictly LIS for array with repetitive elements | Set | Python3 implementation to Find the minimum concatenation required to get strictly Longest Increasing Subsequence for the given array with repetitive elements ; ordered map containing value and a vector containing index of it 's occurrences <int, vector<int> > m; ; Mapping index with their values in ordered map ; k refers to present minimum index ; Stores the number of concatenation required ; Iterate over map m ; it . second . back refers to the last element of corresponding vector ; find the index of next minimum element in the sequence ; Return the final answer ; Driver code | from bisect import bisect_left NEW_LINE def LIS ( arr , n ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ arr [ i ] ] = m . get ( arr [ i ] , [ ] ) NEW_LINE m [ arr [ i ] ] . append ( i ) NEW_LINE DEDENT k = n NEW_LINE ans = 1 NEW_LINE for key , value in m . items ( ) : NEW_LINE INDENT if ( value [ len ( value ) - 1 ] < k ) : NEW_LINE INDENT k = value [ 0 ] NEW_LINE ans += 1 NEW_LINE DEDENT else : NEW_LINE INDENT k = bisect_left ( value , k ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE LIS ( arr , n ) NEW_LINE DEDENT |
Two Balls Reachability Game | Recursive function to return gcd of a and b ; Function returns if it 's possible to have X white and Y black balls or not. ; Finding gcd of ( x , y ) and ( a , b ) ; If gcd is same , it 's always possible to reach (x, y) ; Here it 's never possible if gcd is not same ; Driver Code | def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT return gcd ( b , a % b ) ; NEW_LINE DEDENT def IsPossible ( a , b , x , y ) : NEW_LINE INDENT final = gcd ( x , y ) ; NEW_LINE initial = gcd ( a , b ) ; NEW_LINE if ( initial == final ) : NEW_LINE INDENT print ( " POSSIBLE " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NOT β POSSIBLE " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 1 ; B = 2 ; X = 4 ; Y = 11 ; NEW_LINE IsPossible ( A , B , X , Y ) ; NEW_LINE A = 2 ; B = 2 ; X = 3 ; Y = 6 ; NEW_LINE IsPossible ( A , B , X , Y ) ; NEW_LINE DEDENT |
Number of ways to color N | Python3 program for the above approach ; Function to count the ways to color block ; For storing powers of 2 ; For storing binomial coefficient values ; Calculating binomial coefficient using DP ; Calculating powers of 2 ; Sort the indices to calculate length of each section ; Initialise answer to 1 ; Find the length of each section ; Merge this section ; Return the final count ; Driver Code ; Number of blocks ; Number of colored blocks ; Function call | mod = 1000000007 NEW_LINE def waysToColor ( arr , n , k ) : NEW_LINE INDENT global mod NEW_LINE powOf2 = [ 0 for i in range ( 500 ) ] NEW_LINE c = [ [ 0 for i in range ( 500 ) ] for j in range ( 500 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT c [ i ] [ 0 ] = 1 ; NEW_LINE for j in range ( 1 , i + 1 ) : NEW_LINE INDENT c [ i ] [ j ] = ( c [ i - 1 ] [ j ] + c [ i - 1 ] [ j - 1 ] ) % mod ; NEW_LINE DEDENT DEDENT powOf2 [ 0 ] = 1 NEW_LINE powOf2 [ 1 ] = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT powOf2 [ i ] = ( powOf2 [ i - 1 ] * 2 ) % mod ; NEW_LINE DEDENT rem = n - k ; NEW_LINE arr [ k ] = n + 1 ; NEW_LINE k += 1 NEW_LINE arr . sort ( ) NEW_LINE answer = 1 ; NEW_LINE for i in range ( k ) : NEW_LINE INDENT x = 0 NEW_LINE if i - 1 >= 0 : NEW_LINE INDENT x = arr [ i ] - arr [ i - 1 ] - 1 NEW_LINE DEDENT else : NEW_LINE INDENT x = arr [ i ] - 1 NEW_LINE DEDENT answer = answer * ( c [ rem ] [ x ] % mod ) * ( ( powOf2 [ x ] if ( i != 0 and i != k - 1 ) else 1 ) ) % mod NEW_LINE rem -= x ; NEW_LINE DEDENT return answer ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 ; NEW_LINE K = 3 ; NEW_LINE arr = [ 1 , 2 , 6 , 0 ] NEW_LINE print ( waysToColor ( arr , N , K ) ) NEW_LINE DEDENT |
Rearrange array such that difference of adjacent elements is in descending order | Function to print array in given order ; Sort the array ; Check elements till the middle index ; Check if length is odd print the middle index at last ; Print the remaining elements in the described order ; Driver code ; Array declaration ; Size of array | def printArray ( a , n ) : NEW_LINE INDENT a . sort ( ) ; NEW_LINE i = 0 ; NEW_LINE j = n - 1 ; NEW_LINE while ( i <= j ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( a [ j ] , end = " β " ) ; NEW_LINE print ( a [ i ] , end = " β " ) ; NEW_LINE DEDENT i = i + 1 ; NEW_LINE j = j - 1 ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr1 = [ 1 , 2 , 3 , 4 , 5 , 6 ] ; NEW_LINE n1 = len ( arr1 ) ; NEW_LINE printArray ( arr1 , n1 ) ; NEW_LINE DEDENT |
Find the Smallest number that divides X ^ X | Function to find the required smallest number ; Finding smallest number that divides n ; i divides n and return this value immediately ; If n is a prime number then answer should be n , As we can 't take 1 as our answer. ; Driver Code | def SmallestDiv ( n ) : NEW_LINE INDENT i = 2 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return n NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 385 NEW_LINE ans = SmallestDiv ( X ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Find an array of size N that satisfies the given conditions | Utility function to print the contents of an array ; Function to generate and print the required array ; Initially all the positions are empty ; To store the count of positions i such that arr [ i ] = s ; To store the final array elements ; Set arr [ i ] = s and the gap between them is exactly 2 so in for loop we use i += 2 ; Mark the i 'th position as visited as we put arr[i] = s ; Increment the count ; Finding the next odd number after s ; If the i 'th position is not visited it means we did not put any value at position i so we put 1 now ; Print the final array ; 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 findArray ( n , k , s ) : NEW_LINE INDENT vis = [ 0 ] * n ; NEW_LINE cnt = 0 ; NEW_LINE arr = [ 0 ] * n ; NEW_LINE i = 0 ; NEW_LINE while ( i < n and cnt < k ) : NEW_LINE INDENT arr [ i ] = s ; NEW_LINE vis [ i ] = 1 ; NEW_LINE cnt += 1 ; NEW_LINE i += 2 ; NEW_LINE DEDENT val = s ; NEW_LINE if ( s % 2 == 0 ) : NEW_LINE INDENT val += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT val = val + 2 ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( vis [ i ] == 0 ) : NEW_LINE INDENT arr [ i ] = val ; NEW_LINE DEDENT DEDENT printArr ( arr , n ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 8 ; k = 3 ; s = 12 ; NEW_LINE findArray ( n , k , s ) ; NEW_LINE DEDENT |
Sum of numbers in a range [ L , R ] whose count of divisors is prime | Python3 implementation of the approach ; divi [ i ] stores the count of divisors of i ; sum [ i ] will store the sum of all the integers from 0 to i whose count of divisors is prime ; Function for Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be 0 if i is Not a prime , else true . prime [ i ] stores 1 if i is prime ; 0 and 1 is not prime ; 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 . ; Function to count the divisors ; For each number i we will go to each of the multiple of i and update the count of divisor of its multiple j as i is one of the factor of j ; Function for pre - computation ; If count of divisors of i is prime ; taking prefix sum ; Driver code ; Find all the prime numbers till N ; Update the count of divisors of all the numbers till N ; Precomputation for the prefix sum array ; Perform query | from math import sqrt NEW_LINE N = 100000 ; NEW_LINE divi = [ 0 ] * N ; NEW_LINE sum = [ 0 ] * N ; NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT prime [ i ] = 1 ; NEW_LINE DEDENT DEDENT prime = [ 1 ] * N ; NEW_LINE INDENT prime [ 0 ] = prime [ 1 ] = 0 ; NEW_LINE for p in range ( 2 , int ( sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( prime [ p ] == 1 ) : NEW_LINE INDENT for i in range ( p * p , N , p ) : NEW_LINE INDENT prime [ i ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def DivisorCount ( ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( i , N , i ) : NEW_LINE INDENT divi [ j ] += 1 ; NEW_LINE DEDENT DEDENT DEDENT def pre ( ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( prime [ divi [ i ] ] == 1 ) : NEW_LINE INDENT sum [ i ] = i ; NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT sum [ i ] += sum [ i - 1 ] ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l = 5 ; r = 8 ; NEW_LINE SieveOfEratosthenes ( ) ; NEW_LINE DivisorCount ( ) ; NEW_LINE pre ( ) ; NEW_LINE print ( sum [ r ] - sum [ l - 1 ] ) ; NEW_LINE DEDENT |
Count total number of even sum sequences | Python3 implementation of the approach ; Iterative function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is greater than or equal to p ; If y is odd then multiply x with the result ; y must be even now y = y >> 1 y = y / 2 ; Function to return n ^ ( - 1 ) mod p ; Function to return ( nCr % p ) using Fermat 's little theorem ; Base case ; Fill factorial array so that we can find all factorial of r , n and n - r ; Function to return the count of odd numbers from 1 to n ; Function to return the count of even numbers from 1 to n ; Function to return the count of the required sequences ; Take i even and n - i odd numbers ; Number of odd numbers must be even ; Total ways of placing n - i odd numbers in the sequence of n numbers ; Add this number to the final answer ; Driver code | M = 1000000007 NEW_LINE def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def modInverse ( n , p ) : NEW_LINE INDENT return power ( n , p - 2 , p ) NEW_LINE DEDENT def nCrModPFermat ( n , r , p ) : NEW_LINE INDENT if ( r == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT fac = [ 0 ] * ( n + 1 ) NEW_LINE fac [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fac [ i ] = fac [ i - 1 ] * i % p NEW_LINE DEDENT return ( fac [ n ] * modInverse ( fac [ r ] , p ) % p * modInverse ( fac [ n - r ] , p ) % p ) % p NEW_LINE DEDENT def countOdd ( n ) : NEW_LINE INDENT x = n // 2 NEW_LINE if ( n % 2 == 1 ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT return x NEW_LINE DEDENT def counteEven ( n ) : NEW_LINE INDENT x = n // 2 NEW_LINE return x NEW_LINE DEDENT def CountEvenSumSequences ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT even = i NEW_LINE odd = n - i NEW_LINE if ( odd % 2 == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT tot = ( power ( countOdd ( n ) , odd , M ) * nCrModPFermat ( n , odd , M ) ) % M NEW_LINE tot = ( tot * power ( counteEven ( n ) , i , M ) ) % M NEW_LINE count += tot NEW_LINE count %= M NEW_LINE DEDENT return count NEW_LINE DEDENT n = 5 NEW_LINE print ( CountEvenSumSequences ( n ) ) NEW_LINE |
Find the sum of prime numbers in the Kth array | Python3 implementation of the approach ; Function for Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; 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 . ; Function to return the sum of primes in the Kth array ; Update vector v to store all the prime numbers upto MAX ; To store the sum of primes in the kth array ; Count of primes which are in the arrays from 1 to k - 1 ; k is the number of primes in the kth array ; A prime has been added to the sum ; Driver code | from math import sqrt NEW_LINE MAX = 1000000 NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT for p in range ( 2 , int ( sqrt ( MAX ) ) + 1 ) : NEW_LINE DEDENT prime = [ True ] * MAX NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * p , MAX , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT DEDENT def sumPrime ( k ) : NEW_LINE INDENT SieveOfEratosthenes ( ) ; NEW_LINE v = [ ] ; NEW_LINE for i in range ( 2 , MAX ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT v . append ( i ) ; NEW_LINE DEDENT DEDENT sum = 0 ; NEW_LINE skip = ( k * ( k - 1 ) ) // 2 ; NEW_LINE while ( k > 0 ) : NEW_LINE INDENT sum += v [ skip ] ; NEW_LINE skip += 1 ; NEW_LINE k -= 1 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k = 3 ; NEW_LINE print ( sumPrime ( k ) ) ; NEW_LINE DEDENT |
Count all substrings having character K | Function to return the index of the next occurrence of character ch in strr starting from the given index ; Return the index of the first occurrence of ch ; No occurrence found ; Function to return the count of all the substrings of strr which contain the character ch at least one ; To store the count of valid substrings ; Index of the first occurrence of ch in strr ; No occurrence of ch after index i in strr ; Substrings starting at index i and ending at indices j , j + 1 , ... , n - 1 are all valid substring ; Driver code | def nextOccurrence ( strr , n , start , ch ) : NEW_LINE INDENT for i in range ( start , n ) : NEW_LINE INDENT if ( strr [ i ] == ch ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def countSubStr ( strr , n , ch ) : NEW_LINE INDENT cnt = 0 NEW_LINE j = nextOccurrence ( strr , n , 0 , ch ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( j != - 1 and j < i ) : NEW_LINE INDENT j = nextOccurrence ( strr , n , j + 1 , ch ) NEW_LINE DEDENT if ( j == - 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT cnt += ( n - j ) NEW_LINE DEDENT return cnt NEW_LINE DEDENT strr = " geeksforgeeks " NEW_LINE n = len ( strr ) NEW_LINE ch = ' k ' NEW_LINE print ( countSubStr ( strr , n , ch ) ) NEW_LINE |
Check whether bitwise AND of N numbers is Even or Odd | Function to check if the bitwise AND of the array elements is even or odd ; If at least an even element is present then the bitwise AND of the array elements will be even ; Driver code | def checkEvenOdd ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT print ( " Even " , end = " " ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT print ( " Odd " , end = " " ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 12 , 20 , 36 , 38 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE checkEvenOdd ( arr , n ) ; NEW_LINE DEDENT |
Find number of magical pairs of string of length L | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is >= p ; If y is odd , multiply x with result ; Y must be even now y = y >> 1 ; y = y / 2 ; Driver Code | def power ( x , y , p ) : NEW_LINE INDENT res = 1 ; NEW_LINE x = x % p ; NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y % 2 == 1 ) : NEW_LINE INDENT res = ( res * x ) % p ; NEW_LINE DEDENT x = ( x * x ) % p ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT L = 2 ; P = pow ( 10 , 9 ) ; NEW_LINE ans = power ( 325 , L , P ) ; NEW_LINE print ( ans ) ; NEW_LINE |
Longest substring of only 4 's from the first N characters of the infinite string | Python 3 implementation of the approach ; Function to return the length of longest contiguous string containing only 4 aTMs from the first N characters of the string ; Initialize prefix sum array of characters and product variable ; Preprocessing of prefix sum array ; Finding the string length where N belongs to ; Driver Code | MAXN = 30 NEW_LINE def countMaxLength ( N ) : NEW_LINE INDENT pre = [ 0 for i in range ( MAXN ) ] NEW_LINE p = 1 NEW_LINE pre [ 0 ] = 0 NEW_LINE for i in range ( 1 , MAXN , 1 ) : NEW_LINE INDENT p *= 2 NEW_LINE pre [ i ] = pre [ i - 1 ] + i * p NEW_LINE DEDENT for i in range ( 1 , MAXN , 1 ) : NEW_LINE INDENT if ( pre [ i ] >= N ) : NEW_LINE INDENT ind = i NEW_LINE break NEW_LINE DEDENT DEDENT x = N - pre [ ind - 1 ] NEW_LINE y = 2 * ind - 1 NEW_LINE if ( x >= y ) : NEW_LINE INDENT res = min ( x , y ) NEW_LINE DEDENT else : NEW_LINE INDENT res = max ( x , 2 * ( ind - 2 ) + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 25 NEW_LINE print ( countMaxLength ( N ) ) NEW_LINE DEDENT |
Difference between Recursion and Iteration | -- -- - Recursion -- -- - method to find factorial of given number ; recursion call ; -- -- - Iteration -- -- - Method to find the factorial of a given number ; using iteration ; Driver method | def factorialUsingRecursion ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return n * factorialUsingRecursion ( n - 1 ) ; NEW_LINE DEDENT def factorialUsingIteration ( n ) : NEW_LINE INDENT res = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res *= i ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT num = 5 ; NEW_LINE print ( " Factorial β of " , num , " using β Recursion β is : " , factorialUsingRecursion ( 5 ) ) ; NEW_LINE print ( " Factorial β of " , num , " using β Iteration β is : " , factorialUsingIteration ( 5 ) ) ; NEW_LINE |
Jump Pointer Algorithm | Python3 program to implement Jump pointer algorithm ; n -> it represent total number of nodes len -> it is the maximum length of array to hold parent of each node . In worst case , the highest value of parent a node can have is n - 1. 2 ^ len <= n - 1 len = O ( log2n ) ; jump represent 2D matrix to hold parent of node in jump matrix here we pass reference of 2D matrix so that the change made occur directly to the original matrix len is same as defined above n is total nodes in graph ; c -> it represent child p -> it represent parent i -> it represent node number p = 0 means the node is root node here also we pass reference of 2D matrix and depth vector so that the change made occur directly to the original matrix and original vector ; Enter the node in node array it stores all the nodes in the graph ; To confirm that no child node have 2 parents ; Make parent of x as y ; function to jump to Lth parent of any node ; To check if node is present in graph or not ; In this loop we decrease the value of L by L / 2 and increment j by 1 after each iteration , and check for set bit if we get set bit then we update x with jth parent of x as L becomes less than or equal to zero means we have jumped to Lth parent of node x ; To check if last bit is 1 or not ; Use of shift operator to make L = L / 2 after every iteration ; Driver code ; n represent number of nodes ; Initialization of parent matrix suppose max range of a node is up to 1000 if there are 1000 nodes than also length of jump matrix will not exceed 10 ; Node array is used to store all nodes ; isNode is an array to check whether a node is present in graph or not ; Function to calculate len len -> it is the maximum length of array to hold parent of each node . ; R stores root node ; Construction of graph here 0 represent that the node is root node ; Function to pre compute jump matrix ; Query to jump to parent using jump pointers query to jump to 1 st parent of node 2 ; Query to jump to 2 nd parent of node 4 ; Query to jump to 3 rd parent of node 8 ; Query to jump to 5 th parent of node 20 | import math NEW_LINE def getLen ( n ) : NEW_LINE INDENT len = int ( ( math . log ( n ) ) // ( math . log ( 2 ) ) ) + 1 NEW_LINE return len NEW_LINE DEDENT def set_jump_pointer ( len , n ) : NEW_LINE INDENT global jump , node NEW_LINE for j in range ( 1 , len + 1 ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT jump [ node [ i ] ] [ j ] = jump [ jump [ node [ i ] ] [ j - 1 ] ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT def constructGraph ( c , p , i ) : NEW_LINE INDENT global jump , node , isNode NEW_LINE node [ i ] = c NEW_LINE if ( isNode == 0 ) : NEW_LINE INDENT isNode = 1 NEW_LINE jump [ 0 ] = p NEW_LINE DEDENT return NEW_LINE DEDENT def jumpPointer ( x , L ) : NEW_LINE INDENT j = 0 NEW_LINE n = x NEW_LINE k = L NEW_LINE global jump , isNode NEW_LINE if ( isNode [ x ] == 0 ) : NEW_LINE INDENT print ( " Node β is β not β present β in β graph β " ) NEW_LINE return NEW_LINE DEDENT while ( L > 0 ) : NEW_LINE INDENT if ( ( L & 1 ) != 0 ) : NEW_LINE INDENT x = jump [ x ] [ j ] NEW_LINE DEDENT L = L >> 1 NEW_LINE j += 1 NEW_LINE DEDENT print ( str ( k ) + " th β parent β of β node β " + str ( n ) + " β is β = β " + str ( x ) ) NEW_LINE return NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 11 NEW_LINE DEDENT jump = [ [ 0 for j in range ( 10 ) ] for i in range ( 1000 ) ] NEW_LINE node = [ 0 for i in range ( 1000 ) ] NEW_LINE isNode = [ 0 for i in range ( 1000 ) ] NEW_LINE INDENT len = getLen ( n ) NEW_LINE R = 2 NEW_LINE constructGraph ( 2 , 0 , 0 ) NEW_LINE constructGraph ( 5 , 2 , 1 ) NEW_LINE constructGraph ( 3 , 5 , 2 ) NEW_LINE constructGraph ( 4 , 5 , 3 ) NEW_LINE constructGraph ( 1 , 5 , 4 ) NEW_LINE constructGraph ( 7 , 1 , 5 ) NEW_LINE constructGraph ( 9 , 1 , 6 ) NEW_LINE constructGraph ( 10 , 9 , 7 ) NEW_LINE constructGraph ( 11 , 10 , 8 ) NEW_LINE constructGraph ( 6 , 10 , 9 ) NEW_LINE constructGraph ( 8 , 10 , 10 ) NEW_LINE set_jump_pointer ( len , n ) NEW_LINE jumpPointer ( 2 , 0 ) NEW_LINE jumpPointer ( 4 , 2 ) NEW_LINE jumpPointer ( 8 , 3 ) NEW_LINE jumpPointer ( 20 , 5 ) NEW_LINE DEDENT |
In | Function to reverse arr [ ] from start to end ; Create a copy array and store reversed elements ; Now copy reversed elements back to arr [ ] ; Driver code | def revereseArray ( arr , n ) : NEW_LINE INDENT rev = n * [ 0 ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT rev [ n - i - 1 ] = arr [ i ] NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT arr [ i ] = rev [ i ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( * arr ) NEW_LINE revereseArray ( arr , n ) ; NEW_LINE print ( " Reversed β array β is " ) NEW_LINE print ( * arr ) NEW_LINE DEDENT |
In | Function to reverse arr [ ] from start to end ; Driver code | def revereseArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , int ( n / 2 ) ) : NEW_LINE INDENT arr [ i ] , arr [ n - i - 1 ] = arr [ n - i - 1 ] , arr [ i ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( * arr ) NEW_LINE revereseArray ( arr , n ) NEW_LINE print ( " Reversed β array β is " ) NEW_LINE print ( * arr ) NEW_LINE DEDENT |
Find Binary string by converting all 01 or 10 to 11 after M iterations | Function to find the modified binary string after M iterations ; Set the value of M to the minimum of N or M . ; Declaration of current string state ; Loop over M iterations ; Set the current state as null before each iteration ; Check if this zero has exactly one 1 as neighbour ; Flip the zero ; If there is no change , then no need for further iterations . ; Set the current state as the new previous state ; Driver Code ; Given String ; Number of Iterations ; Function Call | def findString ( str , M ) : NEW_LINE INDENT N = len ( str ) NEW_LINE M = min ( M , N ) NEW_LINE s1 = " " NEW_LINE while ( M != 0 ) : NEW_LINE INDENT s1 = " " NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT if ( ( str [ i - 1 ] == '1' and str [ i + 1 ] != '1' ) or ( str [ i - 1 ] != '1' and str [ i + 1 ] == '1' ) ) : NEW_LINE INDENT s1 += '1' NEW_LINE DEDENT else : NEW_LINE INDENT s1 += '0' NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT s1 += '1' NEW_LINE DEDENT DEDENT if ( str == s1 ) : NEW_LINE INDENT break NEW_LINE DEDENT s1 += '1' NEW_LINE str = s1 NEW_LINE M -= 1 NEW_LINE DEDENT print ( s1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "0110100" NEW_LINE M = 3 NEW_LINE findString ( str , M ) NEW_LINE DEDENT |
Count of subsequences with a sum in range [ L , R ] and difference between max and min element at least X | Python3 program for the above approach ; Function to find the number of subsequences of the given array with a sum in range [ L , R ] and the difference between the maximum and minimum element is at least X ; Initialize answer as 0 ; Creating mask from [ 0 , 2 ^ n - 1 ] ; Stores the count and sum of selected elements respectively ; Variables to store the value of Minimum and maximum element ; Traverse the array ; If the jth bit of the ith mask is on ; Add the selected element ; Update maxVal and minVal value ; Check if the given conditions are true , increment ans by 1. ; Driver Code ; Given Input ; Function Call | import sys NEW_LINE def numberofSubsequences ( a , L , R , X , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , ( 1 << n ) , 1 ) : NEW_LINE INDENT cnt = 0 NEW_LINE sum = 0 NEW_LINE minVal = sys . maxsize NEW_LINE maxVal = - sys . maxsize - 1 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( ( i & ( 1 << j ) ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE sum += a [ j ] NEW_LINE maxVal = max ( maxVal , a [ j ] ) NEW_LINE minVal = min ( minVal , a [ j ] ) NEW_LINE DEDENT DEDENT if ( cnt >= 2 and sum >= L and sum <= R and ( maxVal - minVal >= X ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 10 , 20 , 30 , 25 ] NEW_LINE L = 40 NEW_LINE R = 50 NEW_LINE X = 10 NEW_LINE N = len ( a ) NEW_LINE print ( numberofSubsequences ( a , L , R , X , N ) ) NEW_LINE DEDENT |
Minimum count of numbers needed from 1 to N that yields the sum as K | Function to find minimum number of elements required to obtain sum K ; Stores the maximum sum that can be obtained ; If K is greater than the Maximum sum ; If K is less than or equal to to N ; Stores the sum ; Stores the count of numbers needed ; Iterate until N is greater than or equal to 1 and sum is less than K ; Increment count by 1 ; Increment sum by N ; Update the sum ; Finally , return the count ; Driver Code ; Given Input ; Function Call | def Minimum ( N , K ) : NEW_LINE INDENT sum = N * ( N + 1 ) // 2 NEW_LINE if ( K > sum ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( K <= N ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT sum = 0 NEW_LINE count = 0 NEW_LINE while ( N >= 1 and sum < K ) : NEW_LINE INDENT count += 1 NEW_LINE sum += N NEW_LINE N -= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 10 NEW_LINE print ( Minimum ( N , K ) ) NEW_LINE DEDENT |
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 the result ; Iterate until low is less than or equal to high ; Stores the sum of first mid natural numbers ; If sum is less than or equal to K ; Update res and low ; Otherwise , ; Update ; 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 res = 0 NEW_LINE low = 1 NEW_LINE high = N NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE sum = ( mid * mid + mid ) // 2 NEW_LINE if ( sum <= K ) : NEW_LINE INDENT res = max ( 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 N = 6 NEW_LINE K = 14 NEW_LINE print ( Count ( N , K ) ) 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 array elements ; Initialize a variable res as 0 to store maximum element while traversing the array ; Iterate through array arr ; Add the current element into the st ; Check if the negative of this element is also present in the st or not ; Return the resultant element ; Drive Code | def largestNum ( arr , n ) : NEW_LINE INDENT st = set ( [ ] ) NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT st . add ( arr [ i ] ) NEW_LINE if ( - 1 * arr [ i ] ) in st : NEW_LINE INDENT res = max ( res , abs ( arr [ i ] ) ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 3 , 2 , - 2 , 5 , - 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( largestNum ( arr , n ) ) NEW_LINE |
Check if an element is present in an array using at most floor ( N / 2 ) + 2 comparisons | Function to check whether X is present in the array A [ ] ; Initialise a pointer ; Store the number of comparisons ; Variable to store product ; Check is N is odd ; Update i and T ; Traverse the array ; Check if i < N ; Update T ; Check if T is equal to 0 ; Driver Code ; Given Input ; Function Call | def findElement ( A , N , X ) : NEW_LINE INDENT i = 0 NEW_LINE Comparisons = 0 NEW_LINE T = 1 NEW_LINE Found = " No " NEW_LINE Comparisons += 1 NEW_LINE if ( N % 2 == 1 ) : NEW_LINE INDENT i = 1 NEW_LINE T *= ( A [ 0 ] - X ) NEW_LINE DEDENT while ( i < N ) : NEW_LINE INDENT Comparisons += 1 NEW_LINE T *= ( A [ i ] - X ) NEW_LINE T *= ( A [ i + 1 ] - X ) NEW_LINE i += 2 NEW_LINE DEDENT Comparisons += 1 NEW_LINE if ( T == 0 ) : NEW_LINE INDENT print ( " Yes " , Comparisons ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ - 3 , 5 , 11 , 3 , 100 , 2 , 88 , 22 , 7 , 900 , 23 , 4 , 1 ] NEW_LINE N = len ( A ) NEW_LINE X = 1 NEW_LINE findElement ( A , N , X ) NEW_LINE DEDENT |
Search an element in a sorted array formed by reversing subarrays from a random index | Function to search an element in a sorted array formed by reversing subarrays from a random index ; Set the boundaries for binary search ; Apply binary search ; Initialize the middle element ; If element found ; Random point is on right side of mid ; From l to mid arr is reverse sorted ; Random point is on the left side of mid ; From mid to h arr is reverse sorted ; Return Not Found ; Driver Code ; Given Input ; Function Call | def find ( arr , N , key ) : NEW_LINE INDENT l = 0 NEW_LINE h = N - 1 NEW_LINE while l <= h : NEW_LINE INDENT mid = ( l + h ) // 2 NEW_LINE if arr [ mid ] == key : NEW_LINE INDENT return mid NEW_LINE DEDENT if arr [ l ] >= arr [ mid ] : NEW_LINE INDENT if arr [ l ] >= key >= arr [ mid ] : NEW_LINE INDENT h = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if arr [ mid ] >= key >= arr [ h ] : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT h = mid - 1 NEW_LINE DEDENT DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 8 , 6 , 5 , 2 , 1 , 13 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE key = 8 NEW_LINE ans = find ( arr , N , key ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Maximum elements that can be removed from front of two arrays such that their sum is at most K | Function to find the maximum number of items that can be removed from both the arrays ; Stores the maximum item count ; Stores the prefix sum of the cost of items ; Build the prefix sum for the array A [ ] ; Update the value of A [ i ] ; Build the prefix sum for the array B [ ] ; Update the value of B [ i ] ; Iterate through each item of the array A [ ] ; If A [ i ] exceeds K ; Store the remaining amount after taking top i elements from the array A ; Store the number of items possible to take from the array B [ ] ; Store low and high bounds for binary search ; Binary search to find number of item that can be taken from stack B in rem amount ; Calculate the mid value ; Update the value of j and lo ; Update the value of the hi ; Store the maximum of total item count ; Print the result ; Driver Code | def maxItems ( n , m , a , b , K ) : NEW_LINE INDENT count = 0 NEW_LINE A = [ 0 for i in range ( n + 1 ) ] NEW_LINE B = [ 0 for i in range ( m + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT A [ i ] = a [ i - 1 ] + A [ i - 1 ] NEW_LINE DEDENT for i in range ( 1 , m + 1 , 1 ) : NEW_LINE INDENT B [ i ] = b [ i - 1 ] + B [ i - 1 ] NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT if ( A [ i ] > K ) : NEW_LINE INDENT break NEW_LINE DEDENT rem = K - A [ i ] NEW_LINE j = 0 NEW_LINE lo = 0 NEW_LINE hi = m NEW_LINE while ( lo <= hi ) : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE if ( B [ mid ] <= rem ) : NEW_LINE INDENT j = mid NEW_LINE lo = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT hi = mid - 1 NEW_LINE DEDENT DEDENT count = max ( j + i , count ) NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE m = 5 NEW_LINE K = 7 NEW_LINE A = [ 2 , 4 , 7 , 3 ] NEW_LINE B = [ 1 , 9 , 3 , 4 , 5 ] NEW_LINE maxItems ( n , m , A , B , K ) NEW_LINE DEDENT |
Number which is co | Function to check whether the given number N is prime or not ; Base Case ; If N has more than one factor , then return false ; Otherwise , return true ; Function to find X which is co - prime with the integers from the range [ L , R ] ; Store the resultant number ; Check for prime integers greater than R ; If the current number is prime , then update coPrime and break out of loop ; Print the resultant number ; Driver Code | def isPrime ( N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT if ( N % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def findCoPrime ( L , R ) : NEW_LINE INDENT coPrime , i = 0 , R + 1 NEW_LINE while True : NEW_LINE INDENT if ( isPrime ( i ) ) : NEW_LINE INDENT coPrime = i NEW_LINE break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return coPrime NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R = 16 , 17 NEW_LINE print ( findCoPrime ( L , R ) ) NEW_LINE DEDENT |
Maximum value of arr [ i ] + arr [ j ] + i Γ’ β¬β j for any pair of an array | Function to find the maximum value of arr [ i ] + arr [ j ] + i - j over all pairs ; Stores the required result ; Traverse over all the pairs ( i , j ) ; Calculate the value of the expression and update the overall maximum value ; Print the result ; Driver Code | def maximumValue ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT ans = max ( ans , arr [ i ] + arr [ j ] + i - j ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 1 , 9 , 3 , 6 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE maximumValue ( arr , N ) NEW_LINE |
Maximum value of arr [ i ] + arr [ j ] + i Γ’ β¬β j for any pair of an array | Function to find the maximum value of ( arr [ i ] + arr [ j ] + i - j ) possible for a pair in the array ; Stores the maximum value of ( arr [ i ] + i ) ; Stores the required result ; Traverse the array arr [ ] ; Calculate for current pair and update maximum value ; Update maxValue if ( arr [ i ] + I ) is greater than maxValue ; Print the result ; Driver code | def maximumValue ( arr , n ) : NEW_LINE INDENT maxvalue = arr [ 0 ] NEW_LINE result = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT result = max ( result , maxvalue + arr [ i ] - i ) NEW_LINE maxvalue = max ( maxvalue , arr [ i ] + i ) NEW_LINE DEDENT print ( result ) NEW_LINE DEDENT arr = [ 1 , 9 , 3 , 6 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE maximumValue ( arr , N ) NEW_LINE |
Minimum sum of absolute differences of pairs in a triplet from three arrays | Lower_bound function ; Function to find the value closest to K in the array A [ ] ; Initialize close value as the end element ; Find lower bound of the array ; If lower_bound is found ; If lower_bound is not the first array element ; If * ( it - 1 ) is closer to k ; Return closest value of k ; Function to find the minimum sum of abs ( arr [ i ] - brr [ j ] ) and abs ( brr [ j ] - crr [ k ] ) ; Sort the vectors arr and crr ; Initialize minimum as LET_MAX ; Traverse the array brr [ ] ; Stores the element closest to val from the array arr [ ] ; Stores the element closest to val from the array crr [ ] ; If sum of differences is minimum ; Update the minimum ; Print the minimum absolute difference possible ; Driver code ; Function Call | def lower_bound ( arr , key ) : NEW_LINE INDENT low = 0 ; NEW_LINE high = len ( arr ) - 1 ; NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 ; NEW_LINE if ( arr [ mid ] >= key ) : NEW_LINE INDENT high = mid ; NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT DEDENT return low ; NEW_LINE DEDENT def closestValue ( A , k ) : NEW_LINE INDENT close = A [ - 1 ] ; NEW_LINE it = lower_bound ( A , k ) ; NEW_LINE if ( it != len ( A ) ) : NEW_LINE INDENT close = A [ it ] ; NEW_LINE if ( it != 0 ) : NEW_LINE INDENT if ( ( k - A [ it - 1 ] ) < ( close - k ) ) : NEW_LINE INDENT close = A [ it - 1 ] ; NEW_LINE DEDENT DEDENT DEDENT return close ; NEW_LINE DEDENT def minPossible ( arr , brr , crr ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE crr . sort ( ) ; NEW_LINE minimum = 10 ** 9 ; NEW_LINE for val in brr : NEW_LINE INDENT arr_close = closestValue ( arr , val ) ; NEW_LINE crr_close = closestValue ( crr , val ) ; NEW_LINE if ( abs ( val - arr_close ) + abs ( val - crr_close ) < minimum ) : NEW_LINE INDENT minimum = abs ( val - arr_close ) + abs ( val - crr_close ) ; NEW_LINE DEDENT DEDENT print ( minimum ) ; NEW_LINE DEDENT a = [ 1 , 8 , 5 ] ; NEW_LINE b = [ 2 , 9 ] ; NEW_LINE c = [ 5 , 4 ] ; NEW_LINE minPossible ( a , b , c ) ; NEW_LINE |
Minimize swaps required to make the first and last elements the largest and smallest elements in the array respectively | Function to find the minimum number of swaps required to make the first and the last elements the largest and smallest element in the array ; Stores the count of swaps ; Stores the maximum element ; Stores the minimum element ; If the array contains a single distinct element ; Stores the indices of the maximum and minimum elements ; If the first index of the maximum element is found ; If current index has the minimum element ; Update the count of operations to place largest element at the first ; Update the count of operations to place largest element at the last ; If smallest element is present before the largest element initially ; Driver Code | def minimum_swaps ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE max_el = max ( arr ) NEW_LINE min_el = min ( arr ) NEW_LINE if ( min_el == max_el ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT index_max = - 1 NEW_LINE index_min = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == max_el and index_max == - 1 ) : NEW_LINE INDENT index_max = i NEW_LINE DEDENT if ( arr [ i ] == min_el ) : NEW_LINE INDENT index_min = i NEW_LINE DEDENT DEDENT count += index_max NEW_LINE count += ( n - 1 - index_min ) NEW_LINE if ( index_min < index_max ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 1 , 6 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minimum_swaps ( arr , N ) ) NEW_LINE DEDENT |
Maximum difference between node and its ancestor in a Directed Acyclic Graph ( DAG ) | Python3 program for the above approach ; Function to perform DFS Traversal on the given graph ; Update the value of ans ; Update the currentMin and currentMax ; Traverse the adjacency list of the node src ; Recursively call for the child node ; Function to calculate maximum absolute difference between a node and its ancestor ; Stores the adjacency list of graph ; Create Adjacency list ; Add a directed edge ; Perform DFS Traversal ; Print the maximum absolute difference ; Driver Code | ans = 0 NEW_LINE def DFS ( src , Adj , arr , currentMin , currentMax ) : NEW_LINE INDENT global ans NEW_LINE ans = max ( ans , max ( abs ( currentMax - arr [ src - 1 ] ) , abs ( currentMin - arr [ src - 1 ] ) ) ) NEW_LINE currentMin = min ( currentMin , arr [ src - 1 ] ) NEW_LINE currentMax = min ( currentMax , arr [ src - 1 ] ) NEW_LINE for child in Adj [ src ] : NEW_LINE INDENT DFS ( child , Adj , arr , currentMin , currentMax ) NEW_LINE DEDENT DEDENT def getMaximumDifference ( Edges , arr , N , M ) : NEW_LINE INDENT global ans NEW_LINE Adj = [ [ ] for i in range ( N + 1 ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT u = Edges [ i ] [ 0 ] NEW_LINE v = Edges [ i ] [ 1 ] NEW_LINE Adj [ u ] . append ( v ) NEW_LINE DEDENT DFS ( 1 , Adj , arr , arr [ 0 ] , arr [ 0 ] ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE M = 4 NEW_LINE Edges = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 4 , 5 ] , [ 1 , 3 ] ] NEW_LINE arr = [ 13 , 8 , 3 , 15 , 18 ] NEW_LINE getMaximumDifference ( Edges , arr , N , M ) NEW_LINE DEDENT |
Minimum cost path from source node to destination node via K intermediate nodes | Function to find the minimum cost path from the source vertex to destination vertex via K intermediate vertices ; Initialize the adjacency list ; Generate the adjacency list ; Initialize the minimum priority queue ; Stores the minimum cost to travel between vertices via K intermediate nodes ; Push the starting vertex , cost to reach and the number of remaining vertices ; Pop the top element of the stack ; If destination is reached ; Return the cost ; If all stops are exhausted ; Find the neighbour with minimum cost ; Pruning ; Update cost ; Update priority queue ; If no path exists ; Driver Code ; Function Call to find the path from src to dist via k nodes having least sum of weights | def leastWeightedSumPath ( n , edges , src , dst , K ) : NEW_LINE INDENT graph = [ [ ] for i in range ( 3 ) ] NEW_LINE for edge in edges : NEW_LINE INDENT graph [ edge [ 0 ] ] . append ( [ edge [ 1 ] , edge [ 2 ] ] ) NEW_LINE DEDENT pq = [ ] NEW_LINE costs = [ [ 10 ** 9 for i in range ( K + 2 ) ] for i in range ( n ) ] NEW_LINE costs [ src ] [ K + 1 ] = 0 NEW_LINE pq . append ( [ 0 , src , K + 1 ] ) NEW_LINE pq = sorted ( pq ) [ : : - 1 ] NEW_LINE while ( len ( pq ) > 0 ) : NEW_LINE INDENT top = pq [ - 1 ] NEW_LINE del pq [ - 1 ] NEW_LINE if ( top [ 1 ] == dst ) : NEW_LINE INDENT return top [ 0 ] NEW_LINE DEDENT if ( top [ 2 ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for neighbor in graph [ top [ 1 ] ] : NEW_LINE INDENT if ( costs [ neighbor [ 0 ] ] [ top [ 2 ] - 1 ] < neighbor [ 1 ] + top [ 0 ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT costs [ neighbor [ 0 ] ] [ top [ 2 ] - 1 ] = neighbor [ 1 ] + top [ 0 ] NEW_LINE pq . append ( [ neighbor [ 1 ] + top [ 0 ] , neighbor [ 0 ] , top [ 2 ] - 1 ] ) NEW_LINE DEDENT pq = sorted ( pq ) [ : : - 1 ] NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n , src , dst , k = 3 , 0 , 2 , 1 NEW_LINE edges = [ [ 0 , 1 , 100 ] , [ 1 , 2 , 100 ] , [ 0 , 2 , 500 ] ] NEW_LINE print ( leastWeightedSumPath ( n , edges , src , dst , k ) ) NEW_LINE DEDENT |
Check if a given string is a comment or not | Function to check if the given string is a comment or not ; If two continuous slashes preceeds the comment ; Driver Code ; Given string ; Function call to check whether then given string is a comment or not | def isComment ( line ) : NEW_LINE INDENT if ( line [ 0 ] == ' / ' and line [ 1 ] == ' / ' and line [ 2 ] != ' / ' ) : NEW_LINE INDENT print ( " It β is β a β single - line β comment " ) NEW_LINE return NEW_LINE DEDENT if ( line [ len ( line ) - 2 ] == ' * ' and line [ len ( line ) - 1 ] == ' / ' and line [ 0 ] == ' / ' and line [ 1 ] == ' * ' ) : NEW_LINE INDENT print ( " It β is β a β multi - line β comment " ) NEW_LINE return NEW_LINE DEDENT print ( " It β is β not β a β comment " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT line = " GeeksForGeeks β GeeksForGeeks " NEW_LINE isComment ( line ) NEW_LINE DEDENT |
Print digits for each array element that does not divide any digit of that element | Function to find digits for each array element that doesn 't divide any digit of the that element ; Traverse the array arr [ ] ; Iterate over the range [ 2 , 9 ] ; Stores if there exists any digit in arr [ i ] which is divisible by j ; If any digit of the number is divisible by j ; If the digit j doesn 't divide any digit of arr[i] ; Driver Code | def indivisibleDigits ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT num = 0 NEW_LINE print ( arr [ i ] , end = ' β ' ) NEW_LINE for j in range ( 2 , 10 ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE flag = True NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT if ( ( temp % 10 ) != 0 and ( temp % 10 ) % j == 0 ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT temp //= 10 NEW_LINE DEDENT if ( flag ) : NEW_LINE INDENT print ( j , end = ' β ' ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT arr = [ 4162 , 1152 , 99842 ] NEW_LINE N = len ( arr ) NEW_LINE indivisibleDigits ( arr , N ) NEW_LINE |
Length of longest non | Function to find the longest non - decreasing subsequence with difference between adjacent elements exactly equal to 1 ; Base case ; Sort the array in ascending order ; Stores the maximum length ; Traverse the array ; If difference between current pair of adjacent elements is 1 or 0 ; Extend the current sequence Update len and max_len ; Otherwise , start a new subsequence ; Print the maximum length ; Driver Code ; Given array ; Size of the array ; Function call to find the longest subsequence | def longestSequence ( arr , N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT print ( 0 ) ; NEW_LINE return ; NEW_LINE DEDENT arr . sort ( ) ; NEW_LINE maxLen = 1 ; NEW_LINE len = 1 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i - 1 ] or arr [ i ] == arr [ i - 1 ] + 1 ) : NEW_LINE INDENT len += 1 ; NEW_LINE maxLen = max ( maxLen , len ) ; NEW_LINE DEDENT else : NEW_LINE INDENT len = 1 ; NEW_LINE DEDENT DEDENT print ( maxLen ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 5 , 4 , 8 , 4 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE longestSequence ( arr , N ) ; NEW_LINE DEDENT |
Queries to find the minimum array sum possible by removing elements from either end | Function to find the minimum sum for each query after removing elements from either ends ; Traverse the query array ; Traverse the array from the front ; If element equals val , then break out of loop ; Traverse the array from rear ; If element equals val , break ; Prthe minimum of the two as the answer ; Driver Code ; Function Call | def minSum ( arr , N , Q , M ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT val = Q [ i ] NEW_LINE front , rear = 0 , 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT front += arr [ j ] NEW_LINE if ( arr [ j ] == val ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for j in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT rear += arr [ j ] NEW_LINE if ( arr [ j ] == val ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( min ( front , rear ) , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 6 , 7 , 4 , 5 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE Q = [ 7 , 6 ] NEW_LINE M = len ( Q ) NEW_LINE minSum ( arr , N , Q , M ) NEW_LINE DEDENT |
Frequency of lexicographically Kth smallest character in the a string | Function to find the frequency of the lexicographically Kth smallest character ; Convert the string to array of characters ; Sort the array in ascending order ; Store the Kth character ; Store the frequency of the K - th character ; Count the frequency of the K - th character ; Prthe count ; Driver Code | def KthCharacter ( S , N , K ) : NEW_LINE INDENT strarray = [ char for char in S ] ; NEW_LINE strarray . sort ( ) ; NEW_LINE ch = strarray [ K - 1 ] ; NEW_LINE count = 0 ; NEW_LINE for c in strarray : NEW_LINE INDENT if ( c == ch ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT print ( count ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " geeksforgeeks " ; NEW_LINE N = len ( S ) ; NEW_LINE K = 3 ; NEW_LINE KthCharacter ( S , N , K ) ; NEW_LINE DEDENT |
Longest substring with no pair of adjacent characters are adjacent English alphabets | Function to find the longest substring satisfying the given condition ; Stores all temporary substrings ; Stores the longest substring ; Stores the length of the subT ; Stores the first character of S ; Traverse the string ; If the absolute difference is 1 ; Update the length of subT ; Update the longest substring ; Otherwise , stores the current character ; Again checking for longest substring and update accordingly ; Print the longest substring ; Driver Code ; Given string ; Function call to find the longest substring satisfying given condition | def findSubstring ( S ) : NEW_LINE INDENT T = " " NEW_LINE ans = " " NEW_LINE l = 0 NEW_LINE T += S [ 0 ] NEW_LINE for i in range ( 1 , len ( S ) ) : NEW_LINE INDENT if ( abs ( ord ( S [ i ] ) - ord ( S [ i - 1 ] ) ) == 1 ) : NEW_LINE INDENT l = len ( T ) NEW_LINE if ( l > len ( ans ) ) : NEW_LINE INDENT ans = T NEW_LINE DEDENT T = " " NEW_LINE T += S [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT T += S [ i ] NEW_LINE DEDENT DEDENT l = len ( T ) NEW_LINE if ( l > len ( ans ) ) : NEW_LINE INDENT ans = T NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " aabdml " NEW_LINE findSubstring ( S ) NEW_LINE DEDENT |
Minimize length of an array by removing similar subarrays from both ends | Function to minimize length of the array by removing similar subarrays from both ends of the array ; Initialize two pointers ; Stores the current integer ; Check if the elements at both ends are same or not ; Move the front pointer ; Move the rear pointer ; Print the minimized length of the array ; Input ; Function call to find the minimized length of the array | def findMinLength ( arr , N ) : NEW_LINE INDENT front = 0 NEW_LINE back = N - 1 NEW_LINE while ( front < back ) : NEW_LINE INDENT x = arr [ front ] NEW_LINE if arr [ front ] != arr [ back ] : NEW_LINE INDENT break NEW_LINE DEDENT while ( arr [ front ] == x and front <= back ) : NEW_LINE INDENT front += 1 NEW_LINE DEDENT while ( arr [ back ] == x and front <= back ) : NEW_LINE INDENT back -= 1 NEW_LINE DEDENT DEDENT print ( back - front + 1 ) NEW_LINE DEDENT arr = [ 1 , 1 , 2 , 3 , 3 , 1 , 2 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE findMinLength ( arr , N ) NEW_LINE |
Queries to find the maximum and minimum array elements excluding elements from a given range | Function to find the maximum and minimum array elements up to the i - th index ; Traverse the array ; Compare current value with maximum and minimum values up to previous index ; Function to find the maximum and minimum array elements from i - th index ; Traverse the array in reverse ; Compare current value with maximum and minimum values in the next index ; Function to find the maximum and minimum array elements for each query ; If no index remains after excluding the elements in a given range ; Find maximum and minimum from from the range [ R + 1 , N - 1 ] ; Find maximum and minimum from from the range [ 0 , N - 1 ] ; Find maximum and minimum values from the ranges [ 0 , L - 1 ] and [ R + 1 , N - 1 ] ; Print maximum and minimum value ; Function to perform queries to find the minimum and maximum array elements excluding elements from a given range ; Size of the array ; Size of query array ; prefix [ i ] [ 0 ] : Stores the maximum prefix [ i ] [ 1 ] : Stores the minimum value ; suffix [ i ] [ 0 ] : Stores the maximum suffix [ i ] [ 1 ] : Stores the minimum value ; Function calls to store maximum and minimum values for respective ranges ; Driver Code ; Given array | def prefixArr ( arr , prefix , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT prefix [ i ] [ 0 ] = arr [ i ] NEW_LINE prefix [ i ] [ 1 ] = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT prefix [ i ] [ 0 ] = max ( prefix [ i - 1 ] [ 0 ] , arr [ i ] ) NEW_LINE prefix [ i ] [ 1 ] = min ( prefix [ i - 1 ] [ 1 ] , arr [ i ] ) NEW_LINE DEDENT DEDENT return prefix NEW_LINE DEDENT def suffixArr ( arr , suffix , N ) : NEW_LINE INDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( i == N - 1 ) : NEW_LINE INDENT suffix [ i ] [ 0 ] = arr [ i ] NEW_LINE suffix [ i ] [ 1 ] = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT suffix [ i ] [ 0 ] = max ( suffix [ i + 1 ] [ 0 ] , arr [ i ] ) NEW_LINE suffix [ i ] [ 1 ] = min ( suffix [ i + 1 ] [ 1 ] , arr [ i ] ) NEW_LINE DEDENT DEDENT return suffix NEW_LINE DEDENT def maxAndmin ( prefix , suffix , N , L , R ) : NEW_LINE INDENT maximum , minimum = 0 , 0 NEW_LINE if ( L == 0 and R == N - 1 ) : NEW_LINE INDENT print ( " No β maximum β and β minimum β value " ) NEW_LINE return NEW_LINE DEDENT elif ( L == 0 ) : NEW_LINE INDENT maximum = suffix [ R + 1 ] [ 0 ] NEW_LINE minimum = suffix [ R + 1 ] [ 1 ] NEW_LINE DEDENT elif ( R == N - 1 ) : NEW_LINE INDENT maximum = prefix [ L - 1 ] [ 0 ] NEW_LINE minimum = prefix [ R - 1 ] [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT maximum = max ( prefix [ L - 1 ] [ 0 ] , suffix [ R + 1 ] [ 0 ] ) NEW_LINE minimum = min ( prefix [ L - 1 ] [ 1 ] , suffix [ R + 1 ] [ 1 ] ) NEW_LINE DEDENT print ( maximum , minimum ) NEW_LINE DEDENT def MinMaxQueries ( a , queries ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE q = len ( queries ) NEW_LINE prefix = [ [ 0 for i in range ( 2 ) ] for i in range ( N ) ] NEW_LINE suffix = [ [ 0 for i in range ( 2 ) ] for i in range ( N ) ] NEW_LINE prefix = prefixArr ( arr , prefix , N ) NEW_LINE suffix = suffixArr ( arr , suffix , N ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT L = queries [ i ] [ 0 ] NEW_LINE R = queries [ i ] [ 1 ] NEW_LINE maxAndmin ( prefix , suffix , N , L , R ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 1 , 8 , 3 , 5 , 7 , 4 ] NEW_LINE queries = [ [ 4 , 6 ] , [ 0 , 4 ] , [ 3 , 7 ] , [ 2 , 5 ] ] NEW_LINE MinMaxQueries ( arr , queries ) NEW_LINE DEDENT |
Digits whose alphabetic representations are jumbled in a given string | Function to convert the jumbled into digits ; Strings of digits 0 - 9 ; Initialize vector ; Initialize answer ; Size of the string ; Traverse the string ; Update the elements of the vector ; Print the digits into their original format ; Return answer ; Driver Code | def finddigits ( s ) : NEW_LINE INDENT num = [ " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " ] NEW_LINE arr = [ 0 ] * ( 10 ) NEW_LINE ans = " " NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' z ' ) : NEW_LINE INDENT arr [ 0 ] += 1 NEW_LINE DEDENT if ( s [ i ] == ' w ' ) : NEW_LINE INDENT arr [ 2 ] += 1 NEW_LINE DEDENT if ( s [ i ] == ' g ' ) : NEW_LINE INDENT arr [ 8 ] += 1 NEW_LINE DEDENT if ( s [ i ] == ' x ' ) : NEW_LINE INDENT arr [ 6 ] += 1 NEW_LINE DEDENT if ( s [ i ] == ' v ' ) : NEW_LINE INDENT arr [ 5 ] += 1 NEW_LINE DEDENT if ( s [ i ] == ' o ' ) : NEW_LINE INDENT arr [ 1 ] += 1 NEW_LINE DEDENT if ( s [ i ] == ' s ' ) : NEW_LINE INDENT arr [ 7 ] += 1 NEW_LINE DEDENT if ( s [ i ] == ' f ' ) : NEW_LINE INDENT arr [ 4 ] += 1 NEW_LINE DEDENT if ( s [ i ] == ' h ' ) : NEW_LINE INDENT arr [ 3 ] += 1 NEW_LINE DEDENT if ( s [ i ] == ' i ' ) : NEW_LINE INDENT arr [ 9 ] += 1 NEW_LINE DEDENT DEDENT arr [ 7 ] -= arr [ 6 ] NEW_LINE arr [ 5 ] -= arr [ 7 ] NEW_LINE arr [ 4 ] -= arr [ 5 ] NEW_LINE arr [ 1 ] -= ( arr [ 2 ] + arr [ 4 ] + arr [ 0 ] ) NEW_LINE arr [ 3 ] -= arr [ 8 ] NEW_LINE arr [ 9 ] -= ( arr [ 5 ] + arr [ 6 ] + arr [ 8 ] ) NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT for j in range ( arr [ i ] ) : NEW_LINE INDENT ans += chr ( ( i ) + ord ( '0' ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " owoftnuoer " NEW_LINE print ( finddigits ( s ) ) NEW_LINE DEDENT |
Check if two binary strings can be made equal by swapping pairs of unequal characters | Function to check if a string s1 can be converted into s2 ; Count of '0' in strings in s1 and s2 ; Iterate both the strings and count the number of occurrences of ; Count is not equal ; Iterating over both the arrays and count the number of occurrences of '0 ; If the count of occurrences of '0' in S2 exceeds that in S1 ; Driver code | def check ( s1 , s2 ) : NEW_LINE INDENT s1_0 = 0 NEW_LINE s2_0 = 0 NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( s1 [ i ] == '0' ) : NEW_LINE INDENT s1_0 += 1 NEW_LINE DEDENT if ( s2 [ i ] == '0' ) : NEW_LINE INDENT s2_0 += 1 NEW_LINE DEDENT DEDENT if ( s1_0 != s2_0 ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT Count1 = 0 NEW_LINE Count2 = 0 ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( s1 [ i ] == '0' ) : NEW_LINE INDENT Count1 += 1 NEW_LINE DEDENT if ( s2 [ i ] == '0' ) : NEW_LINE INDENT Count2 += 1 NEW_LINE DEDENT if ( Count1 < Count2 ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " YES " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = "100111" NEW_LINE s2 = "111010" NEW_LINE check ( s1 , s2 ) NEW_LINE s1 = "110100" NEW_LINE s2 = "010101" NEW_LINE check ( s1 , s2 ) NEW_LINE DEDENT |
Check if two binary strings can be made equal by swapping 1 s occurring before 0 s | Function to check if it is possible to make two binary strings equal by given operations ; Stores count of 1 ' s β and β 0' s of the string str1 ; Stores count of 1 ' s β and β 0' s of the string str2 ; Stores current count of 1 's presenty in the string str1 ; Count the number of 1 ' s β and β 0' s present in the strings str1 and str2 ; If the number of 1 ' s β and β 0' s are not same of the strings str1 and str2 then prnot possible ; Traversing through the strings str1 and str2 ; If the str1 character not equals to str2 character ; Swaps 0 with 1 of the string str1 ; Breaks the loop as the count of 1 's is zero. Hence, no swaps possible ; Swaps 1 with 0 in the string str1 ; Prnot possible ; Given Strings ; Function Call | def isBinaryStringsEqual ( list1 , list2 ) : NEW_LINE INDENT str1 = list ( list1 ) NEW_LINE str2 = list ( list2 ) NEW_LINE str1Zeros = 0 NEW_LINE str1Ones = 0 NEW_LINE str2Zeros = 0 NEW_LINE str2Ones = 0 NEW_LINE flag = 0 NEW_LINE curStr1Ones = 0 NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT if ( str1 [ i ] == '1' ) : NEW_LINE INDENT str1Ones += 1 NEW_LINE DEDENT elif ( str1 [ i ] == '0' ) : NEW_LINE INDENT str1Zeros += 1 NEW_LINE DEDENT if ( str2 [ i ] == '1' ) : NEW_LINE INDENT str2Ones += 1 NEW_LINE DEDENT elif ( str2 [ i ] == '0' ) : NEW_LINE INDENT str2Zeros += 1 NEW_LINE DEDENT DEDENT if ( str1Zeros != str2Zeros and str1Ones != str2Ones ) : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( len ( str1 ) ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ i ] ) : NEW_LINE INDENT if ( str1 [ i ] == '0' and curStr1Ones > 0 ) : NEW_LINE INDENT str1 [ i ] = '1' NEW_LINE curStr1Ones -= 1 NEW_LINE DEDENT if ( str1 [ i ] == '0' and curStr1Ones == 0 ) : NEW_LINE INDENT flag += 1 NEW_LINE break NEW_LINE DEDENT if ( str1 [ i ] == '1' and str2 [ i ] == '0' ) : NEW_LINE INDENT str1 [ i ] = '0' NEW_LINE curStr1Ones += 1 NEW_LINE DEDENT DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( " Possible " ) NEW_LINE DEDENT else : NEW_LINE print ( " Not β Possible " ) NEW_LINE DEDENT DEDENT str1 = "0110" NEW_LINE str2 = "0011" NEW_LINE isBinaryStringsEqual ( str1 , str2 ) NEW_LINE |
Count array elements whose all distinct digits appear in K | Function to the count of array elements whose distinct digits are a subst of the digits of K ; Stores distinct digits of K ; Iterate over all the digits of K ; Insert current digit into st ; Update K ; Stores the count of array elements whose distinct digits are a subst of the digits of K ; Traverse the array , arr [ ] ; Stores current element ; Check if all the digits of arr [ i ] are present in K or not ; Iterate over all the digits of arr [ i ] ; Stores current digit ; If digit not present in the st ; Update flag ; Update no ; If all the digits of arr [ i ] present in st ; Update count ; Driver Code | def noOfValidKbers ( K , arr ) : NEW_LINE INDENT st = { } NEW_LINE while ( K != 0 ) : NEW_LINE INDENT if ( K % 10 in st ) : NEW_LINE INDENT st [ K % 10 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT st [ K % 10 ] = st . get ( K % 10 , 0 ) + 1 NEW_LINE DEDENT K = K // 10 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT no = arr [ i ] NEW_LINE flag = True NEW_LINE while ( no != 0 ) : NEW_LINE INDENT digit = no % 10 NEW_LINE if ( digit not in st ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT no = no // 10 NEW_LINE DEDENT if ( flag == True ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 12 NEW_LINE arr = [ 1 , 12 , 1222 , 13 , 2 ] NEW_LINE print ( noOfValidKbers ( K , arr ) ) NEW_LINE DEDENT |
Queries to find the minimum index in a range [ L , R ] having at least value X with updates | Python 3 program for the above approach ; Stores nodes value of the Tree ; Function to build segment tree ; Base Case ; Find the value of mid ; Update for left subtree ; Update for right subtree ; Update the value at the current index ; Function for finding the index of the first element at least x ; If current range does not lie in query range ; If current range is inside of query range ; Maximum value in this range is less than x ; Finding index of first value in this range ; Update the value of the minimum index ; Find mid of the current range ; Left subtree ; If it does not lie in left subtree ; Function for updating segment tree ; Update the value , we reached leaf node ; Find the mid ; If pos lies in the left subtree ; pos lies in the right subtree ; Update the maximum value in the range ; Function to print the answer for the given queries ; Build segment tree ; Find index of first value atleast 2 in range [ 0 , n - 1 ] ; Update value at index 2 to 5 ; Find index of first value atleast 4 in range [ 0 , n - 1 ] ; Find index of first value atleast 0 in range [ 0 , n - 1 ] ; Driver Code ; Function Call | maxN = 100 NEW_LINE Tree = [ 0 for i in range ( 4 * maxN ) ] NEW_LINE def build ( arr , index , s , e ) : NEW_LINE INDENT global Tree NEW_LINE global max NEW_LINE if ( s == e ) : NEW_LINE INDENT Tree [ index ] = arr [ s ] NEW_LINE DEDENT else : NEW_LINE INDENT m = ( s + e ) // 2 NEW_LINE build ( arr , 2 * index , s , m ) NEW_LINE build ( arr , 2 * index + 1 , m + 1 , e ) NEW_LINE Tree [ index ] = max ( Tree [ 2 * index ] , Tree [ 2 * index + 1 ] ) NEW_LINE DEDENT DEDENT def atleast_x ( index , s , e , ql , qr , x ) : NEW_LINE INDENT global Tree NEW_LINE global max NEW_LINE if ( ql > e or qr < s ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( s <= ql and e <= qr ) : NEW_LINE INDENT if ( Tree [ index ] < x ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT while ( s != e ) : NEW_LINE INDENT m = ( s + e ) // 2 NEW_LINE if ( Tree [ 2 * index ] >= x ) : NEW_LINE INDENT e = m NEW_LINE index = 2 * index NEW_LINE DEDENT else : NEW_LINE INDENT s = m + 1 NEW_LINE index = 2 * index + 1 NEW_LINE DEDENT DEDENT return s NEW_LINE DEDENT m = ( s + e ) // 2 NEW_LINE val = atleast_x ( 2 * index , s , m , ql , qr , x ) NEW_LINE if ( val != - 1 ) : NEW_LINE INDENT return val NEW_LINE DEDENT return atleast_x ( 2 * index + 1 , m + 1 , e , ql , qr , x ) NEW_LINE DEDENT def update ( index , s , e , new_val , pos ) : NEW_LINE INDENT global Tree NEW_LINE global max NEW_LINE if ( s == e ) : NEW_LINE INDENT Tree [ index ] = new_val NEW_LINE DEDENT else : NEW_LINE INDENT m = ( s + e ) // 2 NEW_LINE if ( pos <= m ) : NEW_LINE INDENT update ( 2 * index , s , m , new_val , pos ) NEW_LINE DEDENT else : NEW_LINE INDENT update ( 2 * index + 1 , m + 1 , e , new_val , pos ) NEW_LINE DEDENT Tree [ index ] = max ( Tree [ 2 * index ] , Tree [ 2 * index + 1 ] ) NEW_LINE DEDENT DEDENT def printAnswer ( arr , n ) : NEW_LINE INDENT global Tree NEW_LINE global max NEW_LINE build ( arr , 1 , 0 , n - 1 ) NEW_LINE print ( atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 2 ) ) NEW_LINE arr [ 2 ] = 5 NEW_LINE update ( 1 , 0 , n - 1 , 5 , 2 ) NEW_LINE print ( atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 4 ) ) NEW_LINE print ( atleast_x ( 1 , 0 , n - 1 , 0 , n - 1 , 0 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 4 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE printAnswer ( arr , N ) NEW_LINE DEDENT |
Smallest Subtree with all the Deepest Nodes | Structure of a Node ; Function to return depth of the Tree from root ; If current node is a leaf node ; Function to find the root of the smallest subtree consisting of all deepest nodes ; Stores height of left subtree ; Stores height of right subtree ; If height of left subtree exceeds that of the right subtree ; Traverse left subtree ; If height of right subtree exceeds that of the left subtree ; Otherwise ; Return current node ; Driver Code | class TreeNode : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . val = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def find_ht ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return max ( find_ht ( root . left ) , find_ht ( root . right ) ) + 1 NEW_LINE DEDENT def find_node ( root ) : NEW_LINE INDENT global req_node NEW_LINE if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT left_ht = find_ht ( root . left ) NEW_LINE right_ht = find_ht ( root . right ) NEW_LINE if ( left_ht > right_ht ) : NEW_LINE INDENT find_node ( root . left ) NEW_LINE DEDENT elif ( right_ht > left_ht ) : NEW_LINE INDENT find_node ( root . right ) NEW_LINE DEDENT else : NEW_LINE INDENT req_node = root NEW_LINE return NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = TreeNode ( 1 ) NEW_LINE root . left = TreeNode ( 2 ) NEW_LINE root . right = TreeNode ( 3 ) NEW_LINE req_node = None NEW_LINE find_node ( root ) NEW_LINE print ( req_node . val ) NEW_LINE DEDENT |
Maximum even numbers present in any subarray of size K | Function to find the maximum count of even numbers from all the subarrays of size K ; Stores the maximum count of even numbers from all the subarrays of size K ; Generate all subarrays of size K ; Store count of even numbers in current subarray of size K ; Traverse the current subarray ; If current element is an even number ; Update the answer ; Return answer ; Driver Code ; Size of the input array | def maxEvenIntegers ( arr , N , K ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( N - K + 1 ) : NEW_LINE INDENT cnt = 0 NEW_LINE for j in range ( 0 , K ) : NEW_LINE INDENT if arr [ i + j ] % 2 == 0 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT ans = max ( cnt , ans ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 4 , 7 , 6 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( maxEvenIntegers ( arr , N , K ) ) NEW_LINE DEDENT |
Count maximum concatenation of pairs from given array that are divisible by 3 | Function to count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; Stores count of array elements whose remainder is 0 by taking modulo by 3 ; Stores count of array elements whose remainder is 1 by taking modulo by 3 ; Stores count of array elements whose remainder is 2 by taking modulo by 3 ; Traverse the array ; Stores sum of digits of arr [ i ] ; Update digitSum ; If remainder of digitSum by by taking modulo 3 is 0 ; Update rem0 ; If remainder of digitSum by by taking modulo 3 is 1 ; Update rem1 ; Update rem2 ; Driver Code ; To display the result | def countDiv ( arr ) : NEW_LINE INDENT rem0 = 0 NEW_LINE rem1 = 0 NEW_LINE rem2 = 0 NEW_LINE for i in arr : NEW_LINE INDENT digitSum = 0 NEW_LINE for digit in str ( i ) : NEW_LINE INDENT digitSum += int ( digit ) NEW_LINE DEDENT if digitSum % 3 == 0 : NEW_LINE INDENT rem0 += 1 NEW_LINE DEDENT elif digitSum % 3 == 1 : NEW_LINE INDENT rem1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT rem2 += 1 NEW_LINE DEDENT DEDENT return ( rem0 // 2 + min ( rem1 , rem2 ) ) NEW_LINE DEDENT arr = [ 5 , 3 , 2 , 8 , 7 ] NEW_LINE print ( countDiv ( arr ) ) NEW_LINE |
Maximum Sum Subsequence | Function to print the maximum non - emepty subsequence sum ; Stores the maximum non - emepty subsequence sum in an array ; Stores the largest element in the array ; Traverse the array ; If a [ i ] is greater than 0 ; Update sum ; Driver Code | def MaxNonEmpSubSeq ( a , n ) : NEW_LINE INDENT sum = 0 NEW_LINE maxm = max ( a ) NEW_LINE if ( maxm <= 0 ) : NEW_LINE INDENT return maxm NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > 0 ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 2 , 11 , - 4 , 2 , - 3 , - 10 ] NEW_LINE N = len ( arr ) NEW_LINE print ( MaxNonEmpSubSeq ( arr , N ) ) NEW_LINE DEDENT |
Count numbers up to N having Kth bit set | Function to return the count of number of 1 's at ith bit in a range [1, n - 1] ; Store count till nearest power of 2 less than N ; If K - th bit is set in N ; Add to result the nearest power of 2 less than N ; Return result ; Driver Code ; Function Call | def getcount ( n , k ) : NEW_LINE INDENT res = ( n >> ( k + 1 ) ) << k NEW_LINE if ( ( n >> k ) & 1 ) : NEW_LINE INDENT res += n & ( ( 1 << k ) - 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 14 NEW_LINE K = 2 NEW_LINE print ( getcount ( N + 1 , K ) ) NEW_LINE DEDENT |
Check if a string can be split into two substrings such that one substring is a substring of the other | Function to check if a can be divided into two substrings such that one subis subof the other ; Store the last character of S ; Traverse the characters at indices [ 0 , N - 2 ] ; Check if the current character is equal to the last character ; If true , set f = 1 ; Break out of the loop ; Driver Code ; Given string , S ; Store the size of S ; Function Call | def splitString ( S , N ) : NEW_LINE INDENT c = S [ N - 1 ] NEW_LINE f = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( S [ i ] == c ) : NEW_LINE INDENT f = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( f ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcdab " NEW_LINE N = len ( S ) NEW_LINE splitString ( S , N ) NEW_LINE DEDENT |
Find the light bulb with maximum glowing time | Python3 program for the above approach ; Function to find the bulb having maximum glow ; Initialize variables ; Traverse the array consisting of glowing time of the bulbs ; For 1 st bulb ; Calculate the glowing time ; Update the maximum glow ; Find lexicographically largest bulb ; Bulb with maximum time ; Return the resultant bulb ; Driver Code ; Function call | import sys NEW_LINE INT_MIN = ( sys . maxsize - 1 ) NEW_LINE def longestLastingBulb ( onTime , s ) : NEW_LINE INDENT n = len ( onTime ) NEW_LINE maxDur = INT_MIN NEW_LINE maxPos = INT_MIN NEW_LINE currentDiff = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT currentDiff = onTime [ i ] NEW_LINE maxDur = currentDiff NEW_LINE maxPos = i NEW_LINE DEDENT else : NEW_LINE INDENT currentDiff = onTime [ i ] - onTime [ i - 1 ] NEW_LINE if ( maxDur < currentDiff ) : NEW_LINE INDENT maxDur = currentDiff NEW_LINE maxPos = i NEW_LINE DEDENT else : NEW_LINE INDENT if ( maxDur == currentDiff ) : NEW_LINE INDENT one = s [ i ] NEW_LINE two = s [ maxPos ] NEW_LINE if ( one > two ) : NEW_LINE INDENT maxDur = currentDiff NEW_LINE maxPos = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT ans = s [ maxPos ] NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " spuda " NEW_LINE arr = [ 12 , 23 , 36 , 46 , 62 ] NEW_LINE print ( longestLastingBulb ( arr , S ) ) NEW_LINE DEDENT |
Find a pair of intersecting ranges from a given array | Function to find a pair of intersecting ranges ; Stores ending po of every range ; Stores the maximum ending poobtained ; Iterate from 0 to N - 1 ; Starting point of the current range ; End point of the current range ; Push pairs into tup ; Sort the tup vector ; Iterate over the ranges ; If starting points are equal ; Prthe indices of the intersecting ranges ; If no such pair of segments exist ; Driver Code ; Given N ; Given 2d ranges [ ] [ ] array ; Function call | def findIntersectingRange ( tup , N , ranges ) : NEW_LINE INDENT curr = 0 NEW_LINE currPos = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = ranges [ i ] [ 0 ] NEW_LINE y = ranges [ i ] [ 1 ] NEW_LINE tup . append ( [ [ x , y ] , i + 1 ] ) NEW_LINE DEDENT tup = sorted ( tup ) NEW_LINE curr = tup [ 0 ] [ 0 ] [ 1 ] NEW_LINE currPos = tup [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT Q = tup [ i - 1 ] [ 0 ] [ 0 ] NEW_LINE R = tup [ i ] [ 0 ] [ 0 ] NEW_LINE if ( Q == R ) : NEW_LINE INDENT if ( tup [ i - 1 ] [ 0 ] [ 1 ] < tup [ i ] [ 0 ] [ 1 ] ) : NEW_LINE INDENT print ( tup [ i - 1 ] [ 1 ] , tup [ i ] [ 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( tup [ i ] [ 1 ] , tup [ i - 1 ] [ 1 ] ) NEW_LINE DEDENT return NEW_LINE DEDENT T = tup [ i ] [ 0 ] [ 1 ] NEW_LINE if ( T <= curr ) : NEW_LINE INDENT print ( tup [ i ] [ 1 ] , currPos ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT curr = T NEW_LINE currPos = tup [ i ] [ 1 ] NEW_LINE DEDENT DEDENT print ( " - 1 β - 1" ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE ranges = [ [ 1 , 5 ] , [ 2 , 10 ] , [ 3 , 10 ] , [ 2 , 2 ] , [ 2 , 15 ] ] NEW_LINE findIntersectingRange ( [ ] , N , ranges ) NEW_LINE DEDENT |
Find the next greater element in a Circular Array | Set 2 | Function to find the NGE for the given circular array arr [ ] ; create stack list ; Initialize nge [ ] array to - 1 ; Traverse the array ; If stack is not empty and current element is greater than top element of the stack ; Assign next greater element for the top element of the stack ; Pop the top element of the stack ; Print the nge [ ] array ; Driver Code ; Function Call | def printNGE ( arr , n ) : NEW_LINE INDENT s = [ ] ; NEW_LINE nge = [ - 1 ] * n ; NEW_LINE i = 0 ; NEW_LINE while ( i < 2 * n ) : NEW_LINE INDENT while ( len ( s ) != 0 and arr [ i % n ] > arr [ s [ - 1 ] ] ) : NEW_LINE INDENT nge [ s [ - 1 ] ] = arr [ i % n ] ; NEW_LINE s . pop ( ) ; NEW_LINE DEDENT s . append ( i % n ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( nge [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , - 2 , 5 , 8 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE printNGE ( arr , N ) ; NEW_LINE DEDENT |
Count array elements whose product of digits is a Composite Number | Python3 program for the above approach ; Function to generate 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 calculate the product of digits of the given number ; Stores the product of digits ; Extract digits and add to the sum ; Return the product of its digits ; Function to print number of distinct values with digit product as composite ; Initialize set ; Initialize boolean array ; Pre - compute primes ; Traverse array ; of the current array element ; If Product of digits is less than or equal to 1 ; If Product of digits is not a prime ; Print the answer ; Driver Code ; Given array ; Given size ; Function call | N = 100005 NEW_LINE from math import sqrt NEW_LINE def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( p_size ) ) , 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , p_size + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def digitProduct ( number ) : NEW_LINE INDENT res = 1 NEW_LINE while ( number > 0 ) : NEW_LINE INDENT res *= ( number % 10 ) NEW_LINE number //= 10 NEW_LINE DEDENT return res NEW_LINE DEDENT def DistinctCompositeDigitProduct ( arr , n ) : NEW_LINE INDENT output = set ( ) NEW_LINE prime = [ True for i in range ( N + 1 ) ] NEW_LINE SieveOfEratosthenes ( prime , N ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = digitProduct ( arr [ i ] ) NEW_LINE if ( ans <= 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( prime [ ans ] == False ) : NEW_LINE INDENT output . add ( ans ) NEW_LINE DEDENT DEDENT print ( len ( output ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 13 , 55 , 7 , 13 , 11 , 71 , 233 , 233 , 144 , 89 ] NEW_LINE n = len ( arr ) NEW_LINE DistinctCompositeDigitProduct ( arr , n ) NEW_LINE DEDENT |
Count pairs from a given range whose sum is a Prime Number in that range | Python program to implement the above approach ; Function to find all prime numbers in range [ 1 , lmt ] using sieve of Eratosthenes ; segmentedSieve [ i ] : Stores if i is a prime number ( True ) or not ( False ) ; Set 0 and 1 as non - prime ; Iterate over the range [ 2 , lmt ] ; If i is a prime number ; Append i into prime ; Set all multiple of i non - prime ; Update Sieve [ j ] ; Function to find all the prime numbers in the range [ low , high ] ; Stores square root of high + 1 ; Stores all the prime numbers in the range [ 1 , lmt ] ; Find all the prime numbers in the range [ 1 , lmt ] ; Stores count of elements in the range [ low , high ] ; segmentedSieve [ i ] : Check if ( i - low ) is a prime number or not ; Traverse the array prime [ ] ; Store smallest multiple of prime [ i ] in the range [ low , high ] ; If lowLim is less than low ; Update lowLim ; Iterate over all multiples of prime [ i ] ; If j not equal to prime [ i ] ; Update segmentedSieve [ j - low ] ; Function to count the number of pairs in the range [ L , R ] whose sum is a prime number in the range [ L , R ] ; segmentedSieve [ i ] : Check if ( i - L ) is a prime number or not ; Stores count of pairs whose sum of elements is a prime and in range [ L , R ] ; Iterate over [ L , R ] ; If ( i - L ) is a prime ; Update cntPairs ; Driver Code | import math NEW_LINE def simpleSieve ( lmt , prime ) : NEW_LINE INDENT Sieve = [ True ] * ( lmt + 1 ) NEW_LINE Sieve [ 0 ] = Sieve [ 1 ] = False NEW_LINE for i in range ( 2 , lmt + 1 ) : NEW_LINE INDENT if ( Sieve [ i ] == True ) : NEW_LINE INDENT prime . append ( i ) NEW_LINE for j in range ( i * i , int ( math . sqrt ( lmt ) ) + 1 , i ) : NEW_LINE INDENT Sieve [ j ] = false NEW_LINE DEDENT DEDENT DEDENT return prime NEW_LINE DEDENT def SegmentedSieveFn ( low , high ) : NEW_LINE INDENT lmt = int ( math . sqrt ( high ) ) + 1 NEW_LINE prime = [ ] NEW_LINE prime = simpleSieve ( lmt , prime ) NEW_LINE n = high - low + 1 NEW_LINE segmentedSieve = [ True ] * ( n + 1 ) NEW_LINE for i in range ( 0 , len ( prime ) ) : NEW_LINE INDENT lowLim = int ( low // prime [ i ] ) * prime [ i ] NEW_LINE if ( lowLim < low ) : NEW_LINE INDENT lowLim += prime [ i ] NEW_LINE for j in range ( lowLim , high + 1 , prime [ i ] ) : NEW_LINE INDENT if ( j != prime [ i ] ) : NEW_LINE INDENT segmentedSieve [ j - low ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT return segmentedSieve NEW_LINE DEDENT def countPairsWhoseSumPrimeL_R ( L , R ) : NEW_LINE INDENT segmentedSieve = SegmentedSieveFn ( L , R ) NEW_LINE cntPairs = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( segmentedSieve [ i - L ] == True ) : NEW_LINE INDENT cntPairs += i / 2 NEW_LINE DEDENT DEDENT return cntPairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 1 NEW_LINE R = 5 NEW_LINE print ( countPairsWhoseSumPrimeL_R ( L , R ) ) NEW_LINE DEDENT |
Lexicographically smallest permutation of a string that can be reduced to length K by removing K | Function to count the number of zeroes present in the string ; Traverse the string ; Return the count ; Function to rearrange the string s . t the string can be reduced to a length K as per the given rules ; Distribute the count of 0 s and 1 s in segment of length 2 k ; Store string that are initially have formed lexicographically smallest 2 k length substring ; Store the lexicographically smallest string of length n that satisfy the condition ; Insert temp_str into final_str ( n / 2 k ) times and add ( n % 2 k ) characters of temp_str at end ; Return the final string ; Function to reduce the string to length K that follows the given conditions ; If the string contains either 0 s or 1 s then it always be reduced into a K length string ; If the string contains only 0 s 1 s then it always reduces to a K length string ; If K = 1 ; Check whether the given string is K reducing string or not ; Otherwise recursively find the string ; Driver Code ; Function Call | def count_zeroes ( n , str ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE cnt += 1 NEW_LINE DEDENT return cnt NEW_LINE DEDENT def kReducingStringUtil ( n , k , str , no_of_zeroes ) : NEW_LINE INDENT zeroes_in_2k = ( ( ( no_of_zeroes ) * ( 2 * k ) ) // n ) NEW_LINE ones_in_2k = 2 * k - zeroes_in_2k NEW_LINE temp_str = " " NEW_LINE for i in range ( 0 , ( zeroes_in_2k ) // 2 ) : NEW_LINE INDENT temp_str += '0' NEW_LINE DEDENT for i in range ( 0 , ( ones_in_2k ) ) : NEW_LINE INDENT temp_str += '1' NEW_LINE DEDENT for i in range ( 0 , ( zeroes_in_2k ) // 2 ) : NEW_LINE INDENT temp_str += '0' NEW_LINE DEDENT final_str = " " NEW_LINE for i in range ( 0 , n // ( 2 * k ) ) : NEW_LINE INDENT final_str += ( temp_str ) NEW_LINE DEDENT for i in range ( 0 , n % ( 2 * k ) ) : NEW_LINE INDENT final_str += ( temp_str [ i ] ) NEW_LINE DEDENT return final_str NEW_LINE DEDENT def kReducingString ( n , k , str ) : NEW_LINE INDENT no_of_zeroes = count_zeroes ( n , str ) NEW_LINE no_of_ones = n - no_of_zeroes NEW_LINE if ( no_of_zeroes == 0 or no_of_zeroes == n ) : NEW_LINE INDENT return str NEW_LINE DEDENT if ( k == 1 ) : NEW_LINE INDENT if ( no_of_zeroes == 0 or no_of_zeroes == n ) : NEW_LINE return str NEW_LINE else : NEW_LINE return " Not β Possible " NEW_LINE DEDENT check = 0 NEW_LINE for i in range ( ( n // k ) , n , ( n // k ) ) : NEW_LINE INDENT if ( no_of_zeroes == i or no_of_ones == i ) : NEW_LINE check = 1 NEW_LINE break NEW_LINE DEDENT if ( check == 0 ) : NEW_LINE INDENT return " Not β Possible " NEW_LINE DEDENT return kReducingStringUtil ( n , k , str , no_of_zeroes ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "0000100001100001" NEW_LINE K = 4 ; NEW_LINE N = len ( str ) NEW_LINE print ( kReducingString ( N , K , str ) ) NEW_LINE DEDENT |
Count quadruplets with sum K from given array | Python3 program for the above approach ; Function to return the number of quadruplets having the given sum ; Initialize answer ; Store the frequency of sum of first two elements ; Traverse from 0 to N - 1 , where arr [ i ] is the 3 rd element ; All possible 4 th elements ; Sum of last two element ; Frequency of sum of first two elements ; Store frequency of all possible sums of first two elements ; Return the answer ; Driver Code ; Given array arr [ ] ; Given sum S ; Function Call | from collections import defaultdict NEW_LINE def countSum ( a , n , sum ) : NEW_LINE INDENT count = 0 NEW_LINE m = defaultdict ( int ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT temp = a [ i ] + a [ j ] NEW_LINE if ( temp < sum ) : NEW_LINE INDENT count += m [ sum - temp ] NEW_LINE DEDENT DEDENT for j in range ( i ) : NEW_LINE INDENT temp = a [ i ] + a [ j ] NEW_LINE if ( temp < sum ) : NEW_LINE INDENT m [ temp ] += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 5 , 3 , 1 , 2 , 4 ] NEW_LINE S = 13 NEW_LINE N = len ( arr ) NEW_LINE print ( countSum ( arr , N , S ) ) NEW_LINE DEDENT |
Count pairs whose product modulo 10 ^ 9 + 7 is equal to 1 | Python3 program to implement the above approach ; Iterative Function to calculate ( x ^ y ) % MOD ; Initialize result ; Update x if it exceeds MOD ; If x is divisible by MOD ; If y is odd ; Multiply x with res ; y must be even now ; Function to count number of pairs whose product modulo 1000000007 is 1 ; Stores the count of desired pairs ; Stores the frequencies of each array element ; Traverse the array and update frequencies in hash ; Calculate modular inverse of arr [ i ] under modulo 1000000007 ; Update desired count of pairs ; If arr [ i ] and its modular inverse is equal under modulo MOD ; Updating count of desired pairs ; Return the final count ; Driver code | from collections import defaultdict NEW_LINE MOD = 1000000007 NEW_LINE def modPower ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % MOD NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % MOD NEW_LINE DEDENT y = y // 2 NEW_LINE x = ( x * x ) % MOD NEW_LINE DEDENT return res NEW_LINE DEDENT def countPairs ( arr , N ) : NEW_LINE INDENT pairCount = 0 NEW_LINE hash1 = defaultdict ( int ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT hash1 [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT modularInverse = modPower ( arr [ i ] , MOD - 2 ) NEW_LINE pairCount += hash1 [ modularInverse ] NEW_LINE if ( arr [ i ] == modularInverse ) : NEW_LINE INDENT pairCount -= 1 NEW_LINE DEDENT DEDENT return pairCount // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 236426 , 280311812 , 500000004 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countPairs ( arr , N ) ) NEW_LINE DEDENT |
Check if all subarrays contains at least one unique element | Python3 program for the above approach ; Function to check if all subarrays of array have at least one unique element ; Stores frequency of subarray elements ; Generate all subarrays ; Insert first element in map ; Update frequency of current subarray in the HashMap ; Check if at least one element occurs once in current subarray ; If any subarray doesn 't have unique element ; Clear map for next subarray ; Return Yes if all subarray having at least 1 unique element ; Driver Code ; Given array arr [ ] ; Function Call | from collections import defaultdict NEW_LINE def check ( arr , n ) : NEW_LINE INDENT hm = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT hm [ arr [ i ] ] += 1 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT hm [ arr [ j ] ] += 1 NEW_LINE flag = False NEW_LINE for k in hm . values ( ) : NEW_LINE INDENT if ( k == 1 ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( not flag ) : NEW_LINE return " No " NEW_LINE DEDENT hm . clear ( ) NEW_LINE DEDENT return " Yes " NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( check ( arr , N ) ) NEW_LINE DEDENT |
Search insert position of K in a sorted array | Function to find insert position of K ; Lower and upper bounds ; Traverse the search space ; If K is found ; Return the insert position ; Driver Code | def find_index ( arr , n , B ) : NEW_LINE INDENT start = 0 NEW_LINE end = n - 1 NEW_LINE while start <= end : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE if arr [ mid ] == K : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ mid ] < K : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT return end + 1 NEW_LINE DEDENT arr = [ 1 , 3 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( find_index ( arr , n , K ) ) NEW_LINE |
Queries to find minimum swaps required to sort given array with updates | Function to return the position of the given value using binary search ; Return 0 if every value is greater than the given value ; Return N - 1 if every value is smaller than the given value ; Perform Binary Search ; Iterate till start < end ; Find the mid ; Update start and end ; Return the position of the given value ; Function to return the number of make the array sorted ; Index x to update ; Increment value by y ; Set newElement equals to x + y ; Compute the new index ; Print the minimum number of swaps ; Driver Code ; Given array arr [ ] ; Given Queries ; Function Call | def computePos ( arr , n , value ) : NEW_LINE INDENT if ( value < arr [ 0 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( value > arr [ n - 1 ] ) : NEW_LINE INDENT return n - 1 NEW_LINE DEDENT start = 0 NEW_LINE end = n - 1 NEW_LINE while ( start < end ) : NEW_LINE INDENT mid = ( start + end + 1 ) // 2 NEW_LINE if ( arr [ mid ] >= value ) : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = mid NEW_LINE DEDENT DEDENT return start NEW_LINE DEDENT def countShift ( arr , n , queries ) : NEW_LINE INDENT for q in queries : NEW_LINE INDENT index = q [ 0 ] NEW_LINE update = q [ 1 ] NEW_LINE newElement = arr [ index ] + update NEW_LINE newIndex = computePos ( arr , n , newElement ) NEW_LINE print ( abs ( newIndex - index ) , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE queries = [ [ 0 , - 1 ] , [ 4 , - 11 ] ] NEW_LINE countShift ( arr , N , queries ) NEW_LINE DEDENT |
Count nodes having smallest value in the path from root to itself in a Binary Tree | Python3 program for the above approach ; Class of a tree node ; Function to create new tree node ; Function to find the total number of required nodes ; If current node is null then return to the parent node ; Check if current node value is less than or equal to minNodeVal ; Update the value of minNodeVal ; Update the count ; Go to the left subtree ; Go to the right subtree ; Driver Code ; Binary Tree creation 8 / \ / \ 6 5 / \ / \ / \ / \ 6 7 3 9 ; Function Call ; Print the result | import sys NEW_LINE ans = 0 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def countReqNodes ( root , minNodeVal ) : NEW_LINE INDENT global ans NEW_LINE if root == None : NEW_LINE INDENT return NEW_LINE DEDENT if root . key <= minNodeVal : NEW_LINE INDENT minNodeVal = root . key NEW_LINE ans += 1 NEW_LINE DEDENT countReqNodes ( root . left , minNodeVal ) NEW_LINE countReqNodes ( root . right , minNodeVal ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 8 ) NEW_LINE root . left = Node ( 6 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . left . left = Node ( 6 ) NEW_LINE root . left . right = Node ( 7 ) NEW_LINE root . right . left = Node ( 3 ) NEW_LINE root . right . right = Node ( 9 ) NEW_LINE minNodeVal = sys . maxsize NEW_LINE countReqNodes ( root , minNodeVal ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings | Function to check if a string is palindrome or not ; Start and end of the string ; Iterate the string until i > j ; If there is a mismatch ; Increment first pointer and decrement the other ; Given string is a palindrome ; Function two check if the strings can be combined to form a palindrome ; Initialize array of characters ; Stores character of string in the character array ; Find left and right parts of strings a and b ; Substring a [ j ... i - 1 ] ; Substring b [ j ... i - 1 ] ; Substring a [ i ... n ] ; Substring b [ i ... n ] ; Check is left part of a + right part of b or vice versa is a palindrome ; Print the result ; Otherwise ; Driver Code | def isPalindrome ( st ) : NEW_LINE INDENT i = 0 NEW_LINE j = len ( st ) - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( st [ i ] != st [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def formPalindrome ( a , b , n ) : NEW_LINE INDENT aa = [ ' β ' ] * ( n + 2 ) NEW_LINE bb = [ ' β ' ] * ( n + 2 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT aa [ i ] = a [ i - 1 ] NEW_LINE bb [ i ] = b [ i - 1 ] NEW_LINE DEDENT ok = False NEW_LINE for i in range ( n + 2 ) : NEW_LINE INDENT la = " " NEW_LINE ra = " " NEW_LINE lb = " " NEW_LINE rb = " " NEW_LINE for j in range ( 1 , i ) : NEW_LINE INDENT if ( aa [ j ] == ' β ' ) : NEW_LINE INDENT la += " " NEW_LINE DEDENT else : NEW_LINE INDENT la += aa [ j ] NEW_LINE DEDENT if ( bb [ j ] == ' β ' ) : NEW_LINE INDENT lb += " " NEW_LINE DEDENT else : NEW_LINE INDENT lb += bb [ j ] NEW_LINE DEDENT DEDENT for j in range ( i , n + 2 ) : NEW_LINE INDENT if ( aa [ j ] == ' β ' ) : NEW_LINE INDENT ra += " " NEW_LINE DEDENT else : NEW_LINE INDENT ra += aa [ j ] NEW_LINE DEDENT if ( bb [ j ] == ' β ' ) : NEW_LINE INDENT rb += " " NEW_LINE DEDENT else : NEW_LINE INDENT rb += bb [ j ] NEW_LINE DEDENT DEDENT if ( isPalindrome ( str ( la ) + str ( rb ) ) or isPalindrome ( str ( lb ) + str ( ra ) ) ) : NEW_LINE INDENT ok = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( ok ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = " bdea " NEW_LINE B = " abbb " NEW_LINE N = 4 NEW_LINE formPalindrome ( A , B , N ) NEW_LINE DEDENT |
Minimize elements to be added to a given array such that it contains another given array as its subsequence | Set 2 | Function to return minimum element to be added in array B so that array A become subsequence of array B ; Stores indices of the array elements ; Iterate over the array ; Store the indices of the array elements ; Stores the LIS ; Check if element B [ i ] is in array A [ ] ; Perform Binary Search ; Find the value of mid m ; Update l and r ; If found better element ' e ' for pos r + 1 ; Otherwise , extend the current subsequence ; Return the answer ; Driver Code ; Given arrays ; Function call | def minElements ( A , B , N , M ) : NEW_LINE INDENT map = { } NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT map [ A [ i ] ] = i NEW_LINE DEDENT subseq = [ ] NEW_LINE l = 0 NEW_LINE r = - 1 NEW_LINE for i in range ( M ) : NEW_LINE INDENT if B [ i ] in map : NEW_LINE INDENT e = map [ B [ i ] ] NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = l + ( r - l ) // 2 NEW_LINE if ( subseq [ m ] < e ) : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE DEDENT DEDENT if ( r + 1 < len ( subseq ) ) : NEW_LINE INDENT subseq [ r + 1 ] = e NEW_LINE DEDENT else : NEW_LINE INDENT subseq . append ( e ) NEW_LINE DEDENT l = 0 NEW_LINE r = len ( subseq ) - 1 NEW_LINE DEDENT DEDENT return N - len ( subseq ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE B = [ 2 , 5 , 6 , 4 , 9 , 12 ] NEW_LINE M = len ( A ) NEW_LINE N = len ( B ) NEW_LINE print ( minElements ( A , B , M , N ) ) NEW_LINE DEDENT |
Detect a negative cycle in a Graph using Shortest Path Faster Algorithm | Python3 program for the above approach ; Stores the adjacency list of the given graph ; Create Adjacency List ; Stores the distance of all reachable vertex from source ; Check if vertex is present in queue or not ; Counts the relaxation for each vertex ; Distance from src to src is 0 ; Create a queue ; Push source in the queue ; Mark source as visited ; Front vertex of Queue ; Relaxing all edges of vertex from the Queue ; Update the dist [ v ] to minimum distance ; If vertex v is in Queue ; Negative cycle ; No cycle found ; Driver Code ; Number of vertices ; Given source node src ; Number of Edges ; Given Edges with weight ; If cycle is present | import sys NEW_LINE def sfpa ( V , src , Edges , M ) : NEW_LINE INDENT g = [ [ ] for i in range ( V ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT u = Edges [ i ] [ 0 ] NEW_LINE v = Edges [ i ] [ 1 ] NEW_LINE w = Edges [ i ] [ 2 ] NEW_LINE g [ u ] . append ( [ v , w ] ) NEW_LINE DEDENT dist = [ sys . maxsize for i in range ( V ) ] NEW_LINE inQueue = [ False for i in range ( V ) ] NEW_LINE cnt = [ 0 for i in range ( V ) ] NEW_LINE dist [ src ] = 0 NEW_LINE q = [ ] NEW_LINE q . append ( src ) NEW_LINE inQueue [ src ] = True NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT u = q [ 0 ] NEW_LINE q . remove ( q [ 0 ] ) NEW_LINE inQueue [ u ] = False NEW_LINE for x in g [ u ] : NEW_LINE INDENT v = x [ 0 ] NEW_LINE cost = x [ 1 ] NEW_LINE if ( dist [ v ] > dist [ u ] + cost ) : NEW_LINE INDENT dist [ v ] = dist [ u ] + cost NEW_LINE if ( inQueue [ v ] == False ) : NEW_LINE INDENT q . append ( v ) NEW_LINE inQueue [ v ] = True NEW_LINE cnt [ v ] += 1 NEW_LINE if ( cnt [ v ] >= V ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE src = 0 NEW_LINE M = 4 NEW_LINE Edges = [ [ 0 , 1 , 1 ] , [ 1 , 2 , - 1 ] , [ 2 , 3 , - 1 ] , [ 3 , 0 , - 1 ] ] NEW_LINE if ( sfpa ( N , src , Edges , M ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Sum of all pair shortest paths in a Tree | Python3 program for the above approach ; Function that performs the Floyd Warshall to find all shortest paths ; Initialize the distance matrix ; Pick all vertices as source one by one ; Pick all vertices as destination for the above picked source ; If vertex k is on the shortest path from i to j then update dist [ i ] [ j ] ; Sum the upper diagonal of the shortest distance matrix ; Traverse the given dist [ ] [ ] ; Add the distance ; Return the final sum ; Function to generate the tree ; Add edges ; Get source and destination with weight ; Add the edges ; Perform Floyd Warshal Algorithm ; Driver code ; Number of Vertices ; Number of Edges ; Given Edges with weight ; Function Call | INF = 99999 NEW_LINE def floyd_warshall ( graph , V ) : NEW_LINE INDENT dist = [ [ 0 for i in range ( V ) ] for i in range ( V ) ] NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT dist [ i ] [ j ] = graph [ i ] [ j ] NEW_LINE DEDENT DEDENT for k in range ( V ) : NEW_LINE INDENT for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT if ( dist [ i ] [ k ] + dist [ k ] [ j ] < dist [ i ] [ j ] ) : NEW_LINE INDENT dist [ i ] [ j ] = dist [ i ] [ k ] + dist [ k ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT sum = 0 NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( i + 1 , V ) : NEW_LINE INDENT sum += dist [ i ] [ j ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT def sumOfshortestPath ( N , E , edges ) : NEW_LINE INDENT g = [ [ INF for i in range ( N ) ] for i in range ( N ) ] NEW_LINE for i in range ( E ) : NEW_LINE INDENT u = edges [ i ] [ 0 ] NEW_LINE v = edges [ i ] [ 1 ] NEW_LINE w = edges [ i ] [ 2 ] NEW_LINE g [ u ] [ v ] = w NEW_LINE g [ v ] [ u ] = w NEW_LINE DEDENT return floyd_warshall ( g , N ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE E = 3 NEW_LINE Edges = [ [ 0 , 1 , 1 ] , [ 1 , 2 , 2 ] , [ 2 , 3 , 3 ] ] NEW_LINE print ( sumOfshortestPath ( N , E , Edges ) ) NEW_LINE DEDENT |
Kth space | Function to prkth integer in a given string ; Size of the string ; If space char found decrement K ; If K becomes 1 , the next string is the required one ; Print required number ; Driver Code ; Given string ; Given K ; Function call | def print_kth_string ( s , K ) : NEW_LINE INDENT N = len ( s ) ; NEW_LINE for i in range ( 0 , N , 1 ) : NEW_LINE INDENT if ( s [ i ] == ' β ' ) : NEW_LINE INDENT K -= 1 ; NEW_LINE DEDENT if ( K == 1 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT while ( i < N ) : NEW_LINE INDENT if ( s [ i ] != ' β ' ) : NEW_LINE INDENT print ( s [ i ] , end = " " ) ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "10 β 20 β 30 β 40" ; NEW_LINE K = 4 ; NEW_LINE print_kth_string ( s , K ) ; NEW_LINE DEDENT |
Minimum peak elements from an array by their repeated removal at every iteration of the array | Python3 program for the above approach ; Function to return the list of minimum peak elements ; Length of original list ; Initialize resultant list ; Traverse each element of list ; Length of original list after removing the peak element ; Traverse new list after removal of previous min peak element ; Update min and index , if first element of list > next element ; Update min and index , if last element of list > previous one ; Update min and index , if list has single element ; Update min and index , if current element > adjacent elements ; Remove current min peak element from list ; Insert min peak into resultant list ; Print resultant list ; Driver Code ; Given array arr [ ] ; Function call | import sys NEW_LINE def minPeaks ( list1 ) : NEW_LINE INDENT n = len ( list1 ) NEW_LINE result = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT min = sys . maxsize NEW_LINE index = - 1 NEW_LINE size = len ( list1 ) NEW_LINE for j in range ( size ) : NEW_LINE INDENT if ( j == 0 and j + 1 < size ) : NEW_LINE INDENT if ( list1 [ j ] > list1 [ j + 1 ] and min > list1 [ j ] ) : NEW_LINE INDENT min = list1 [ j ] ; NEW_LINE index = j ; NEW_LINE DEDENT DEDENT elif ( j == size - 1 and j - 1 >= 0 ) : NEW_LINE INDENT if ( list1 [ j ] > list1 [ j - 1 ] and min > list1 [ j ] ) : NEW_LINE INDENT min = list1 [ j ] NEW_LINE index = j NEW_LINE DEDENT DEDENT elif ( size == 1 ) : NEW_LINE INDENT min = list1 [ j ] NEW_LINE index = j NEW_LINE DEDENT elif ( list1 [ j ] > list1 [ j - 1 ] and list1 [ j ] > list1 [ j + 1 ] and min > list1 [ j ] ) : NEW_LINE INDENT min = list1 [ j ] NEW_LINE index = j NEW_LINE DEDENT DEDENT list1 . pop ( index ) NEW_LINE result . append ( min ) NEW_LINE DEDENT print ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 9 , 7 , 8 , 2 , 6 ] NEW_LINE minPeaks ( arr ) NEW_LINE DEDENT |
Search an element in a reverse sorted array | Function to search if element X is present in reverse sorted array ; Store the first index of the subarray in which X lies ; Store the last index of the subarray in which X lies ; Store the middle index of the subarray ; Check if value at middle index of the subarray equal to X ; Element is found ; If X is smaller than the value at middle index of the subarray ; Search in right half of subarray ; Search in left half of subarray ; If X not found ; Driver Code | def binarySearch ( arr , N , X ) : NEW_LINE INDENT start = 0 NEW_LINE end = N NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = start + ( end - start ) // 2 NEW_LINE if ( X == arr [ mid ] ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( X < arr [ mid ] ) : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 4 , 3 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE X = 5 NEW_LINE print ( binarySearch ( arr , N , X ) ) NEW_LINE DEDENT |
Construct an AP series consisting of A and B having minimum possible Nth term | Python3 program for the above approach ; Function to check if both a and b are present in the AP series or not ; Iterate over the array arr [ ] ; If a is present ; If b is present ; If both are present ; Otherwise ; Function to print all the elements of the Arithmetic Progression ; Function to construct AP series consisting of A and B with minimum Nth term ; Stores the resultant series ; Initialise ans [ i ] as INT_MAX ; Maintain a smaller than b ; Swap a and b ; Difference between a and b ; Check for all possible combination of start and common difference d ; Initialise arr [ 0 ] as start ; Check if both a and b are present or not and the Nth term is the minimum or not ; Update the answer ; Print the resultant array ; Driver Code ; Function call | import sys NEW_LINE def check_both_present ( arr , N , a , b ) : NEW_LINE INDENT f1 = False NEW_LINE f2 = False NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if arr [ i ] == a : NEW_LINE INDENT f1 = True NEW_LINE DEDENT if arr [ i ] == b : NEW_LINE INDENT f2 = True NEW_LINE DEDENT DEDENT if f1 and f2 : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def print_array ( ans , N ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def build_AP ( N , a , b ) : NEW_LINE INDENT INT_MAX = sys . maxsize NEW_LINE arr = [ None for i in range ( N ) ] NEW_LINE ans = [ INT_MAX for i in range ( N ) ] NEW_LINE flag = 0 NEW_LINE if a > b : NEW_LINE INDENT a , b = b , a NEW_LINE DEDENT diff = b - a NEW_LINE for start in range ( 1 , a + 1 ) : NEW_LINE INDENT for d in range ( 1 , diff + 1 ) : NEW_LINE INDENT arr [ 0 ] = start NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] + d NEW_LINE DEDENT if ( ( check_both_present ( arr , N , a , b ) and arr [ N - 1 ] < ans [ N - 1 ] ) ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT ans [ i ] = arr [ i ] NEW_LINE DEDENT DEDENT DEDENT DEDENT print_array ( ans , N ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE A = 20 NEW_LINE B = 50 NEW_LINE build_AP ( N , A , B ) NEW_LINE DEDENT |
Find the word from a given sentence having given word as prefix | Function to find the position of the string having word as prefix ; Initialize an List ; Extract words from the sentence ; Traverse each word ; Traverse the characters of word ; If prefix does not match ; Otherwise ; Return the word ; Return - 1 if not present ; Driver code | def isPrefixOfWord ( sentence , word ) : NEW_LINE INDENT a = sentence . split ( " β " ) NEW_LINE v = [ ] NEW_LINE for i in a : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT for i in range ( len ( v ) ) : NEW_LINE INDENT for j in range ( len ( v [ i ] ) ) : NEW_LINE INDENT if ( v [ i ] [ j ] != word [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT elif ( j == len ( word ) - 1 ) : NEW_LINE INDENT return v [ i ] NEW_LINE DEDENT DEDENT DEDENT return - 1 NEW_LINE DEDENT s = " Welcome β to β Geeksforgeeks " NEW_LINE word = " Gee " NEW_LINE print ( isPrefixOfWord ( s , word ) ) NEW_LINE |
Paths requiring minimum number of jumps to reach end of array | Python3 program to implement the above approach ; Pair Class instance ; Stores the current index ; Stores the path travelled so far ; Stores the minimum jumps required to reach the last index from current index ; Constructor ; Minimum jumps required to reach end of the array ; Stores the maximum number of steps that can be taken from the current index ; Checking if index stays within bounds ; Stores the minimum number of jumps required to jump from ( i + j ) - th index ; Function to find all possible paths to reach end of array requiring minimum number of steps ; Storing the neighbours of current index element ; Function to find the minimum steps and corresponding paths to reach end of an array ; Stores the minimum jumps from each position to last position ; Driver Code | from queue import Queue NEW_LINE import sys NEW_LINE class Pair ( object ) : NEW_LINE INDENT idx = 0 NEW_LINE psf = " " NEW_LINE jmps = 0 NEW_LINE def __init__ ( self , idx , psf , jmps ) : NEW_LINE INDENT self . idx = idx NEW_LINE self . psf = psf NEW_LINE self . jmps = jmps NEW_LINE DEDENT DEDENT def minJumps ( arr ) : NEW_LINE INDENT MAX_VALUE = sys . maxsize NEW_LINE dp = [ MAX_VALUE for i in range ( len ( arr ) ) ] NEW_LINE n = len ( dp ) NEW_LINE dp [ n - 1 ] = 0 NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT steps = arr [ i ] NEW_LINE minimum = MAX_VALUE NEW_LINE for j in range ( 1 , steps + 1 , 1 ) : NEW_LINE INDENT if i + j >= n : NEW_LINE INDENT break NEW_LINE DEDENT if ( ( dp [ i + j ] != MAX_VALUE ) and ( dp [ i + j ] < minimum ) ) : NEW_LINE INDENT minimum = dp [ i + j ] NEW_LINE DEDENT DEDENT if minimum != MAX_VALUE : NEW_LINE INDENT dp [ i ] = minimum + 1 NEW_LINE DEDENT DEDENT return dp NEW_LINE DEDENT def possiblePath ( arr , dp ) : NEW_LINE INDENT queue = Queue ( maxsize = 0 ) NEW_LINE p1 = Pair ( 0 , "0" , dp [ 0 ] ) NEW_LINE queue . put ( p1 ) NEW_LINE while queue . qsize ( ) > 0 : NEW_LINE INDENT tmp = queue . get ( ) NEW_LINE if tmp . jmps == 0 : NEW_LINE INDENT print ( tmp . psf ) NEW_LINE continue NEW_LINE DEDENT for step in range ( 1 , arr [ tmp . idx ] + 1 , 1 ) : NEW_LINE INDENT if ( ( tmp . idx + step < len ( arr ) ) and ( tmp . jmps - 1 == dp [ tmp . idx + step ] ) ) : NEW_LINE INDENT p2 = Pair ( tmp . idx + step , tmp . psf + " β - > β " + str ( ( tmp . idx + step ) ) , tmp . jmps - 1 ) NEW_LINE queue . put ( p2 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def Solution ( arr ) : NEW_LINE INDENT dp = minJumps ( arr ) NEW_LINE possiblePath ( arr , dp ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 3 , 0 , 2 , 1 , 2 , 4 , 2 , 0 , 0 ] NEW_LINE size = len ( arr ) NEW_LINE Solution ( arr ) NEW_LINE DEDENT |
Length of longest increasing absolute even subsequence | Function to find the longest increasing absolute even subsequence ; Length of arr ; Stores length of required subsequence ; Traverse the array ; Traverse prefix of current array element ; Check if the subsequence is LIS and have even absolute difference of adjacent pairs ; Update lis [ ] ; Stores maximum length ; Find the length of longest absolute even subsequence ; Return the maximum length of absolute even subsequence ; Given arr [ ] ; Function Call | def EvenLIS ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE lis = [ 1 ] * n NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 0 , i ) : NEW_LINE INDENT if abs ( arr [ i ] ) > abs ( arr [ j ] ) and abs ( arr [ i ] % 2 ) == 0 and abs ( arr [ j ] % 2 ) == 0 and lis [ i ] < lis [ j ] + 1 : NEW_LINE INDENT lis [ i ] = lis [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT maxlen = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxlen = max ( maxlen , lis [ i ] ) NEW_LINE DEDENT print ( maxlen ) NEW_LINE DEDENT arr = [ 11 , - 22 , 43 , - 54 , 66 , 5 ] NEW_LINE EvenLIS ( arr ) NEW_LINE |