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 pr...
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 ...
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 pr...
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...
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...
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 ...
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 ( minRevolution...
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 b...
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 = ma...
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 defege...
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_LI...
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 th...
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 su...
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 += ...
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 numb...
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 ...
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) ; ''...
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_L...
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...
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 + ...
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 ...
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 ( ...
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...
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 = ...
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 cyc...
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 ] NE...
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 ...
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 , ...
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 '...
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 i...
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 " ...
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 ans...
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_L...
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 declaratio...
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 = " ▁ " ) ...
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_LIN...
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...
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 INDE...
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 " pri...
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 ...
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...
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 powe...
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 chang...
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...
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 ...
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 )...
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 , 2...
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...
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 ; Pre...
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 ...
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 r...
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 matri...
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 I...
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 , ...
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 ) ...
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 zer...
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...
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 ; Ini...
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...
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 ; It...
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 N...
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 ...
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 ) ...
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 cu...
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 , ...
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 ...
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 ...
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 r...
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 NE...
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 valu...
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 ...
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 ...
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...
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 re...
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 maxim...
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...
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 ]...
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 * ( i...
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 re...
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 ;...
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_ma...
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 c...
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 [ s...
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 cos...
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 ) ]...
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 ] == ' / '...
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 ;...
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 )...
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...
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 I...
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 ; ...
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 ) : NE...
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 frequ...
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 ...
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 a...
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_LI...
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 re...
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 DEDEN...
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...
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 ] ...
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 answ...
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 a...
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 n...
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 " ) ...
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 pr...
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 ...
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 ...
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 (...
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 curre...
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...
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 sub...
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 ...
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 ; Traver...
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...
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 i...
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 : N...
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...
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 DEDE...
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 eq...
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 D...
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 large...
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 ] ...
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 ; I...
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 ]...
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 ...
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...
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 n...
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 ) : ...
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 ; ...
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...
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 th...
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 *...
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 ...
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...
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...
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 //...
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...
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_...
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...
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 ; Fi...
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 ...
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 val...
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...
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 st...
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 = [ '...
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 e...
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 ( ...
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 ...
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...
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 shorte...
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...
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 ...
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...
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 ...
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 ...
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...
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 th...
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 I...
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 p...
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_LIN...
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 rea...
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 )...
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 adjace...
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 IN...