text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Find number of pairs ( x , y ) in an Array such that x ^ y > y ^ x | Set 2 | Function to return the count of pairs ; Compute suffix sums till i = 3 ; Base Case : x = 0 ; No valid pairs ; Base Case : x = 1 ; Store the count of 0 's ; Base Case : x = 2 ; Store suffix sum upto 5 ; Base Case : x = 3 ; Store count of 2 and ...
def countPairs ( X , Y , m , n ) : NEW_LINE INDENT suffix = [ 0 ] * 1005 NEW_LINE total_pairs = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT suffix [ Y [ i ] ] += 1 NEW_LINE DEDENT for i in range ( int ( 1e3 ) , 2 , - 1 ) : NEW_LINE INDENT suffix [ i ] += suffix [ i + 1 ] NEW_LINE DEDENT for i in range ( m ) : NEW...
Min number of moves to traverse entire Matrix through connected cells with equal values | Function to find the minimum number of moves to traverse the given matrix ; Constructing another matrix consisting of distinct values ; Updating the array B by checking the values of A that if there are same values connected throu...
def solve ( A , N , M ) : NEW_LINE INDENT B = [ ] NEW_LINE c = 1 NEW_LINE s = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT new = [ ] NEW_LINE for j in range ( M ) : NEW_LINE INDENT new . append ( c ) NEW_LINE c = c + 1 NEW_LINE DEDENT B . append ( new ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT ...
Number of times an array can be partitioned repetitively into two subarrays with equal sum | Recursion Function to calculate the possible splitting ; If there are less than two elements , we cannot partition the sub - array . ; Iterate from the start to end - 1. ; Recursive call to the left and the right sub - array . ...
def splitArray ( start , end , arr , prefix_sum ) : NEW_LINE INDENT if ( start >= end ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for k in range ( start , end ) : NEW_LINE INDENT if ( ( prefix_sum [ k ] - prefix_sum [ start - 1 ] ) == ( prefix_sum [ end ] - prefix_sum [ k ] ) ) : NEW_LINE INDENT return ( 1 + splitArra...
Minimise the maximum element of N subarrays of size K | Function to choose N subarrays of size K such that the maximum element of subarrays is minimum ; Condition to check if it is not possible to choose k sized N subarrays ; Using binary search ; calculating mid ; Loop to find the count of the K sized subarrays possib...
def minDays ( arr , n , k ) : NEW_LINE INDENT l = len ( arr ) NEW_LINE left = 1 NEW_LINE right = 1e9 NEW_LINE if ( n * k > l ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT while ( left < right ) : NEW_LINE INDENT mid = ( left + right ) // 2 NEW_LINE cnt = 0 NEW_LINE product = 0 NEW_LINE for j in range ( l ) : NEW_LINE ...
Count of distinct power of prime factor of N | Function to count the number of distinct positive power of prime factor of integer N ; Iterate for all prime factor ; If it is a prime factor , count the total number of times it divides n . ; Find the Number of distinct possible positive numbers ; Return the final count ;...
def countFac ( n ) : NEW_LINE INDENT m = n NEW_LINE count = 0 NEW_LINE i = 2 NEW_LINE while ( ( i * i ) <= m ) : NEW_LINE INDENT total = 0 NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n /= i NEW_LINE total += 1 NEW_LINE DEDENT temp = 0 NEW_LINE j = 1 NEW_LINE while ( ( temp + j ) <= total ) : NEW_LINE INDENT temp +=...
Minimum total sum from the given two arrays | Function that prints minimum sum after selecting N elements ; Initialise the dp array ; Base Case ; Adding the element of array a if previous element is also from array a ; Adding the element of array a if previous element is from array b ; Adding the element of array b if ...
def minimumSum ( a , b , c , n ) : NEW_LINE INDENT dp = [ [ 1e6 for i in range ( 2 ) ] for j in range ( n ) ] NEW_LINE dp [ 0 ] [ 0 ] = a [ 0 ] NEW_LINE dp [ 0 ] [ 1 ] = b [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] [ 0 ] = min ( dp [ i ] [ 0 ] , dp [ i - 1 ] [ 0 ] + a [ i ] ) NEW_LINE dp [ i ] [...
Minimum flips required in a binary string such that all K | Function to calculate and return the minimum number of flips to make string valid ; Stores the count of required flips ; Stores the last index of '1' in the string ; Check for the first substring of length K ; If i - th character is '1 ; If the substring had n...
def minimumMoves ( S , K ) : NEW_LINE INDENT N = len ( S ) NEW_LINE ops = 0 NEW_LINE last_idx = - 1 NEW_LINE for i in range ( K ) : NEW_LINE DEDENT ' NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT last_idx = i NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( last_idx == - 1 ) : NEW_LINE INDENT ops += 1 NEW_LINE S...
Lexicographically smallest string which differs from given strings at exactly K indices | Python3 program for the above approach ; Function to find the string which differ at exactly K positions ; Initialise s3 as s2 ; Number of places at which s3 differ from s2 ; Minimum possible value is ceil ( d / 2 ) if it is not p...
arr = [ ' a ' , ' b ' , ' c ' ] NEW_LINE def findString ( n , k , s1 , s2 ) : NEW_LINE INDENT s3 = s2 NEW_LINE s3 = list ( s3 ) NEW_LINE d = 0 NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( s1 [ i ] != s2 [ i ] ) : NEW_LINE INDENT d += 1 NEW_LINE DEDENT DEDENT if ( ( d + 1 ) // 2 > k ) : NEW_LINE INDENT ...
Count of pairs of integers whose difference of squares is equal to N | Python3 program for the above approach ; Function to find the integral solutions of the given equation ; Initialise count to 0 ; Iterate till sqrt ( N ) ; If divisor 's pair sum is even ; Print the total possible solutions ; Given number N ; Functio...
import math ; NEW_LINE def findSolutions ( N ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( 1 , int ( math . sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( ( i + N // i ) % 2 == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT print ( 4 * count ) ; NEW_LINE DEDE...
Find the integral roots of a given Cubic equation | Function to find the value at x of the given equation ; Find the value equation at x ; Return the value of ans ; Function to find the integral solution of the given equation ; Initialise start and end ; Implement Binary Search ; Find mid ; Find the value of f ( x ) us...
def check ( A , B , C , D , x ) : NEW_LINE INDENT ans = 0 ; NEW_LINE ans = ( A * x * x * x + B * x * x + C * x + D ) ; NEW_LINE return ans ; NEW_LINE DEDENT def findSolution ( A , B , C , D , E ) : NEW_LINE INDENT start = 0 ; end = 100000 ; NEW_LINE mid = 0 ; NEW_LINE ans = 0 ; NEW_LINE while ( start <= end ) : NEW_LIN...
Count of ordered triplets ( R , G , B ) in a given original string | function to count the ordered triplets ( R , G , B ) ; count the B ( blue ) colour ; Driver Code
def countTriplets ( color ) : NEW_LINE INDENT result = 0 ; Blue_Count = 0 ; NEW_LINE Red_Count = 0 ; NEW_LINE for c in color : NEW_LINE INDENT if ( c == ' B ' ) : NEW_LINE INDENT Blue_Count += 1 ; NEW_LINE DEDENT DEDENT for c in color : NEW_LINE INDENT if ( c == ' B ' ) : NEW_LINE INDENT Blue_Count -= 1 ; NEW_LINE DEDE...
Minimum value of K such that sum of cubes of first K natural number is greater than equal to N | Function to determine the minimum value of K such that the sum of cubes of first K natural number is greater than or equal to N ; Variable to store the sum of cubes ; Loop to find the number K ; If C is just greater then N ...
def naive_find_x ( N ) : NEW_LINE INDENT c = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT c += i * i * i NEW_LINE if c >= N : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return i NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 100 NEW_LINE print ( naive_find_x ( N ) ) NEW_LINE DEDENT
Minimum value of K such that sum of cubes of first K natural number is greater than equal to N | Function to determine the minimum value of K such that the sum of cubes of first K natural number is greater than or equal to N ; Left bound ; Right bound ; Variable to store the answer ; Applying binary search ; Calculatin...
def binary_searched_find_x ( k ) : NEW_LINE INDENT l = 0 NEW_LINE r = k NEW_LINE ans = 0 NEW_LINE while l <= r : NEW_LINE INDENT mid = l + ( r - l ) // 2 NEW_LINE if ( ( mid * ( mid + 1 ) ) // 2 ) ** 2 >= k : NEW_LINE INDENT ans = mid NEW_LINE r = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDE...
Length of the longest ZigZag subarray of the given array | Function to find the length of longest zigZag contiguous subarray ; ' _ max ' to store the length of longest zigZag subarray ; ' _ len ' to store the lengths of longest zigZag subarray at different instants of time ; Traverse the array from the beginning ; Chec...
def lenOfLongZigZagArr ( a , n ) : NEW_LINE INDENT _max = 1 NEW_LINE _len = 1 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if i % 2 == 0 and a [ i ] < a [ i + 1 ] : NEW_LINE INDENT _len += 1 NEW_LINE DEDENT elif i % 2 == 1 and a [ i ] > a [ i + 1 ] : NEW_LINE INDENT _len += 1 NEW_LINE DEDENT else : NEW_LINE DEDE...
Check if a given number is a Perfect square using Binary Search | Function to check for perfect square number ; Find the mid value from start and last ; Check if we got the number which is square root of the perfect square number N ; If the square ( mid ) is greater than N it means only lower values then mid will be po...
def checkPerfectSquare ( N , start , last ) : NEW_LINE INDENT mid = int ( ( start + last ) / 2 ) NEW_LINE if ( start > last ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( mid * mid == N ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( mid * mid > N ) : NEW_LINE INDENT return checkPerfectSquare ( N , start , m...
Maximum count number of valley elements in a subarray of size K | Function to find the valley elements in the array which contains in the subarrays of the size K ; Increment min_point if element at index i is smaller than element at index i + 1 and i - 1 ; final_point to maintain maximum of min points of subarray ; Ite...
def minpoint ( arr , n , k ) : NEW_LINE INDENT min_point = 0 NEW_LINE for i in range ( 1 , k - 1 ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i - 1 ] and arr [ i ] < arr [ i + 1 ] ) : NEW_LINE INDENT min_point += 1 NEW_LINE DEDENT DEDENT final_point = min_point NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT if ( arr...
For each lowercase English alphabet find the count of strings having these alphabets | Function to find the countStrings for each letter [ a - z ] ; Initialize result as zero ; Mark all letter as not visited ; Loop through each strings ; Increment the global counter for current character of string ; Instead of re - ini...
def CountStrings ( s ) : NEW_LINE INDENT size = len ( s ) NEW_LINE count = [ 0 ] * 26 NEW_LINE visited = [ False ] * 26 NEW_LINE for i in range ( size ) : NEW_LINE INDENT for j in range ( len ( s [ i ] ) ) : NEW_LINE INDENT if visited [ ord ( s [ i ] [ j ] ) - ord ( ' a ' ) ] == False : NEW_LINE INDENT count [ ord ( s ...
Find subarray of Length K with Maximum Peak | Function to find the subarray ; Make prefix array to store the prefix sum of peak count ; Count peak for previous index ; Check if this element is a peak ; Increment the count ; Check if number of peak in the sub array whose l = i is greater or not ; Print the result ; Driv...
def findSubArray ( a , n , k ) : NEW_LINE INDENT pref = [ 0 for i in range ( n ) ] NEW_LINE pref [ 0 ] = 0 NEW_LINE for i in range ( 1 , n - 1 , 1 ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] NEW_LINE if ( a [ i ] > a [ i - 1 ] and a [ i ] > a [ i + 1 ] ) : NEW_LINE INDENT pref [ i ] += 1 NEW_LINE DEDENT DEDENT peak...
Sort integers in array according to their distance from the element K | Function to get sorted array based on their distance from given integer K ; Vector to store respective elements with their distance from integer K ; Find the position of integer K ; Insert the elements with their distance from K in vector ; Element...
def distanceSort ( arr , K , n ) : NEW_LINE INDENT vd = [ [ ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == K ) : NEW_LINE INDENT pos = i NEW_LINE break NEW_LINE DEDENT DEDENT i = pos - 1 NEW_LINE j = pos + 1 NEW_LINE vd [ 0 ] . append ( arr [ pos ] ) NEW_LINE while ( i >= 0 )...
Find Quotient and Remainder of two integer without using division operators | Function to the quotient and remainder ; Check if start is greater than the end ; Calculate mid ; Check if n is greater than divisor then increment the mid by 1 ; Check if n is less than 0 then decrement the mid by 1 ; Check if n equals to di...
def find ( dividend , divisor , start , end ) : NEW_LINE INDENT if ( start > end ) : NEW_LINE INDENT return ( 0 , dividend ) ; NEW_LINE DEDENT mid = start + ( end - start ) // 2 ; NEW_LINE n = dividend - divisor * mid ; NEW_LINE if ( n > divisor ) : NEW_LINE INDENT start = mid + 1 ; NEW_LINE DEDENT elif ( n < 0 ) : NEW...
Count the number of unordered triplets with elements in increasing order and product less than or equal to integer X | Function to count the number of triplets ; Iterate through all the triplets ; Rearrange the numbers in ascending order ; Check if the necessary conditions satisfy ; Increment count ; Return the answer ...
def countTriplets ( a , n , x ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT temp = [ ] NEW_LINE temp . append ( a [ i ] ) NEW_LINE temp . append ( a [ j ] ) NEW_LINE temp . append ( a [ k ] ) N...
Largest value of x such that axx is N | Python3 implementation of the above approach ; Function to find log_b ( a ) ; Set two pointer for binary search ; Calculating number of digits of a * mid ^ mid in base b ; If number of digits > n we can simply ignore it and decrease our pointer ; if number of digits <= n , we can...
from math import log10 , ceil , log NEW_LINE def log1 ( a , b ) : NEW_LINE INDENT return log10 ( a ) // log10 ( b ) NEW_LINE DEDENT def get ( a , b , n ) : NEW_LINE INDENT lo = 0 NEW_LINE hi = 1e6 NEW_LINE ans = 0 NEW_LINE while ( lo <= hi ) : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE dig = ceil ( ( mid * log ( m...
Maximum size square Sub | Function to find the maximum size of matrix with sum <= K ; N size of rows and M size of cols ; To store the prefix sum of matrix ; Create Prefix Sum ; Traverse each rows ; Update the prefix sum till index i x j ; To store the maximum size of matrix with sum <= K ; Traverse the sum matrix ; In...
def findMaxMatrixSize ( arr , K ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE m = len ( arr [ 0 ] ) NEW_LINE sum = [ [ 0 for i in range ( m + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( m + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT sum [ i ]...
Rank of all elements in a Stream in descending order when they arrive | FindRank function to find rank ; Rank of first element is always 1 ; Iterate over array ; As element let say its rank is 1 ; Element is compared with previous elements ; If greater than previous than rank is incremented ; print rank ; Driver code ;...
def FindRank ( arr , length ) : NEW_LINE INDENT print ( 1 , end = " ▁ " ) NEW_LINE for i in range ( 1 , length ) : NEW_LINE INDENT rank = 1 NEW_LINE for j in range ( 0 , i ) : NEW_LINE INDENT if ( arr [ j ] > arr [ i ] ) : NEW_LINE INDENT rank = rank + 1 NEW_LINE DEDENT DEDENT print ( rank , end = " ▁ " ) NEW_LINE DEDE...
Longest permutation subsequence in a given array | Program to find length of Longest Permutation Subsequence in a given array ; Function to find the longest permutation subsequence ; Map data structure to count the frequency of each element ; If frequency of element is 0 , then we can not move forward as every element ...
from collections import defaultdict NEW_LINE def longestPermutation ( a , n ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ a [ i ] ] += 1 NEW_LINE DEDENT length = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( freq [ i ] == 0 ) : NEW_LINE INDENT bre...
Pair of fibonacci numbers with a given sum and minimum absolute difference | Python 3 program to find the pair of Fibonacci numbers with a given sum and minimum absolute difference ; Hash to store all the Fibonacci numbers ; Function to generate fibonacci Series and create hash table to check Fibonacci numbers ; Adding...
MAX = 10005 NEW_LINE fib = set ( ) NEW_LINE def fibonacci ( ) : NEW_LINE INDENT global fib NEW_LINE global MAX NEW_LINE prev = 0 NEW_LINE curr = 1 NEW_LINE l = 2 NEW_LINE fib . add ( prev ) NEW_LINE fib . add ( curr ) NEW_LINE while ( l <= MAX ) : NEW_LINE INDENT temp = curr + prev NEW_LINE fib . add ( temp ) NEW_LINE ...
Check if sum of Fibonacci elements in an Array is a Fibonacci number or not | Python 3 program to check whether the sum of fibonacci elements of the array is a Fibonacci number or not ; Hash to store the Fibonacci numbers up to Max ; Function to create the hash table to check Fibonacci numbers ; Inserting the first two...
MAX = 100005 NEW_LINE fibonacci = set ( ) NEW_LINE def createHash ( ) : NEW_LINE INDENT global fibonacci NEW_LINE prev , curr = 0 , 1 NEW_LINE fibonacci . add ( prev ) NEW_LINE fibonacci . add ( curr ) NEW_LINE while ( curr <= MAX ) : NEW_LINE INDENT temp = curr + prev NEW_LINE if temp <= MAX : NEW_LINE INDENT fibonacc...
Count of numbers whose difference with Fibonacci count upto them is atleast K | Python 3 program to find the count of numbers whose difference with Fibonacci count upto them is atleast K ; fibUpto [ i ] denotes the count of fibonacci numbers upto i ; Function to compute all the Fibonacci numbers and update fibUpto arra...
MAX = 1000005 NEW_LINE fibUpto = [ 0 ] * ( MAX + 1 ) NEW_LINE def compute ( sz ) : NEW_LINE INDENT isFib = [ False ] * ( sz + 1 ) NEW_LINE prev = 0 NEW_LINE curr = 1 NEW_LINE isFib [ prev ] = True NEW_LINE isFib [ curr ] = True NEW_LINE while ( curr <= sz ) : NEW_LINE INDENT temp = curr + prev NEW_LINE if ( temp <= sz ...
Smallest Palindromic Subsequence of Even Length in Range [ L , R ] | Python3 program to find lexicographically smallest palindromic subsequence of even length ; Frequency array for each character ; Preprocess the frequency array calculation ; Frequency array to track each character in position 'i ; Calculating prefix s...
N = 100001 NEW_LINE f = [ [ 0 for x in range ( N ) ] for y in range ( 26 ) ] NEW_LINE def precompute ( s , n ) : NEW_LINE ' NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT f [ ord ( s [ i ] ) - ord ( ' a ' ) ] [ i ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE ...
Length of longest Fibonacci subarray formed by removing only one element | Python3 program to find length of the longest subarray with all fibonacci numbers ; Function to create hash table to check for Fibonacci numbers ; Insert first two fibnonacci numbers ; Summation of last two numbers ; Update the variable each tim...
N = 100000 NEW_LINE def createHash ( hash , maxElement ) : NEW_LINE INDENT prev = 0 NEW_LINE curr = 1 NEW_LINE hash . add ( prev ) NEW_LINE hash . add ( curr ) NEW_LINE while ( curr <= maxElement ) : NEW_LINE INDENT temp = curr + prev NEW_LINE hash . add ( temp ) NEW_LINE prev = curr NEW_LINE curr = temp NEW_LINE DEDEN...
Minimum window size containing atleast P primes in every window of given range | Python3 implementation to find the minimum window size in the range such that each window of that size contains atleast P primes ; Function to check that a number is a prime or not in O ( sqrt ( N ) ) ; Loop to check if any number number i...
from math import sqrt NEW_LINE def isPrime ( N ) : NEW_LINE INDENT if ( N < 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( N < 4 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ( N & 1 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( N % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT ...
XOR of pairwise sum of every unordered pairs in an array | Function to find XOR of pairwise sum of every unordered pairs ; Loop to choose every possible pairs in the array ; Driver Code
def xorOfSum ( a , n ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT answer ^= ( a [ i ] + a [ j ] ) NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE A = [ 1 , 2 , 3 ] NEW_L...
Maximum size of square such that all submatrices of that size have sum less than K | Size of matrix ; Function to preprocess the matrix for computing the sum of every possible matrix of the given size ; Loop to copy the first row of the matrix into the aux matrix ; Computing the sum column - wise ; Computing row wise s...
N = 4 NEW_LINE M = 5 NEW_LINE def preProcess ( mat , aux ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT aux [ 0 ] [ i ] = mat [ 0 ] [ i ] NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT aux [ i ] [ j ] = ( mat [ i ] [ j ] + aux [ i - 1 ] [ j ] ) NEW_LINE DED...
Find two Fibonacci numbers whose sum can be represented as N | Function to create hash table to check Fibonacci numbers ; Storing the first two numbers in the hash ; Finding Fibonacci numbers up to N and storing them in the hash ; Function to find the Fibonacci pair with the given sum ; creating a set containing all fi...
def createHash ( hash1 , maxElement ) : NEW_LINE INDENT prev , curr = 0 , 1 NEW_LINE hash1 . add ( prev ) NEW_LINE hash1 . add ( curr ) NEW_LINE while ( curr < maxElement ) : NEW_LINE INDENT temp = curr + prev NEW_LINE hash1 . add ( temp ) NEW_LINE prev = curr NEW_LINE curr = temp NEW_LINE DEDENT DEDENT def findFibonac...
Count of multiples in an Array before every element | Python 3 program to count of multiples in an Array before every element ; Function to find all factors of N and keep their count in map ; Traverse from 1 to sqrt ( N ) if i divides N , increment i and N / i in map ; Function to count of multiples in an Array before ...
from collections import defaultdict NEW_LINE import math NEW_LINE def add_factors ( n , mp ) : NEW_LINE INDENT for i in range ( 1 , int ( math . sqrt ( n ) ) + 1 , ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n // i == i ) : NEW_LINE INDENT mp [ i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ i ] +...
Reduce the array such that each element appears at most 2 times | Function to remove duplicates ; Initialise 2 nd pointer ; Iterate over the array ; Updating the 2 nd pointer ; Driver code ; Function call
def removeDuplicates ( arr , n ) : NEW_LINE INDENT st = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i < n - 2 and arr [ i ] == arr [ i + 1 ] and arr [ i ] == arr [ i + 2 ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT else : NEW_LINE INDENT arr [ st ] = arr [ i ] ; NEW_LINE st += 1 ; NEW_LINE DEDENT DEDEN...
Check if an Array is a permutation of numbers from 1 to N | Function to check if an array represents a permutation or not ; Set to check the count of non - repeating elements ; Insert all elements in the set ; Calculating the max element ; Check if set size is equal to n ; Driver code
def permutation ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE maxEle = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( arr [ i ] ) ; NEW_LINE maxEle = max ( maxEle , arr [ i ] ) ; NEW_LINE DEDENT if ( maxEle != n ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( len ( s ) == n ) : NEW_LINE INDENT...
D 'Esopo | Python3 implementation for D 'Esopo-Pape algorithm ; Number of vertices in graph ; Adjacency list of graph ; Queue to store unoperated vertices ; Distance from source vertex ; Status of vertex ; let 0 be the source vertex ; Pop from front of the queue ; scan adjacent vertices of u ; e < - [ weight , vertex ]...
from collections import defaultdict , deque NEW_LINE def desopo ( graph ) : NEW_LINE INDENT v = len ( graph ) NEW_LINE adj = defaultdict ( list ) NEW_LINE for i in range ( v ) : NEW_LINE INDENT for j in range ( i + 1 , v ) : NEW_LINE INDENT if graph [ i ] [ j ] != 0 : NEW_LINE INDENT adj [ i ] . append ( [ graph [ i ] ...
Count of Subsets of a given Set with element X present in it | Python3 code to implement the above approach ; N stores total number of subsets ; Generate each subset one by one ; Check every bit of i ; if j 'th bit of i is set, check arr[j] with X ; Driver code
def CountSubSet ( arr , n , X ) : NEW_LINE INDENT N = 2 ** n ; NEW_LINE count = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i & ( 1 << j ) ) : NEW_LINE INDENT if ( arr [ j ] == X ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return count ; NEW_...
Count of Subsets of a given Set with element X present in it | Function to calculate ( 2 ^ ( n - 1 ) ) ; Initially initialize answer to 1 ; If e is odd , multiply b with answer ; Function to count subsets in which X element is present ; Check if X is present in given subset or not ; If X is present in set then calculat...
def calculatePower ( b , e ) : NEW_LINE INDENT ans = 1 ; NEW_LINE while ( e > 0 ) : NEW_LINE INDENT if ( e % 2 == 1 ) : NEW_LINE INDENT ans = ans * b ; NEW_LINE DEDENT e = e // 2 ; NEW_LINE b = b * b ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def CountSubSet ( arr , n , X ) : NEW_LINE INDENT count = 0 ; checkX = 0 ...
Value to be subtracted from array elements to make sum of all elements equals K | Function to return the amount of wood collected if the cut is made at height m ; Function that returns Height at which cut should be made ; Sort the heights of the trees ; The minimum and the maximum cut that can be made ; Binary search t...
def woodCollected ( height , n , m ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( height [ i ] - m <= 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT sum += ( height [ i ] - m ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def collectKWood ( height , n , k ) : NEW_LINE INDENT...
Check if given string contains all the digits | Python3 implementation of the approach ; Function that returns true if ch is a digit ; Function that returns true if st contains all the digits from 0 to 9 ; To mark the present digits ; For every character of the string ; If the current character is a digit ; Mark the cu...
MAX = 10 NEW_LINE def isDigit ( ch ) : NEW_LINE INDENT ch = ord ( ch ) NEW_LINE if ( ch >= ord ( '0' ) and ch <= ord ( '9' ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def allDigits ( st , le ) : NEW_LINE INDENT present = [ False for i in range ( MAX ) ] NEW_LINE for i in range ( le ) ...
Check if a symmetric plus is possible from the elements of the given array | Function that return true if a symmetric is possible with the elements of the array ; Map to store the frequency of the array elements ; Traverse through array elements and count frequencies ; For every unique element ; Element has already bee...
def isPlusPossible ( arr , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] = mp . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT foundModOne = False NEW_LINE for x in mp : NEW_LINE INDENT element = x NEW_LINE frequency = mp [ x ] NEW_LINE if ( frequency % 4 == 0 ) : NEW_L...
Queries for elements greater than K in the given index range using Segment Tree | Python3 implementation of the approach ; Merge procedure to merge two vectors into a single vector ; Final vector to return after merging ; Loop continues until it reaches the end of one of the vectors ; Here , simply add the remaining el...
from bisect import bisect_left as lower_bound NEW_LINE def merge ( v1 , v2 ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE v = [ ] NEW_LINE while ( i < len ( v1 ) and j < len ( v2 ) ) : NEW_LINE INDENT if ( v1 [ i ] <= v2 [ j ] ) : NEW_LINE INDENT v . append ( v1 [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LIN...
Queries for elements greater than K in the given index range using Segment Tree | Python implementation of the approach ; combine function to make parent node ; building the tree ; leaf node ; merging the nodes while backtracking ; performing query ; out of bounds ; complete overlaps ; partial overlaps ; Driver Code ; ...
import math NEW_LINE def combine ( a , b ) : NEW_LINE INDENT if a != 0 and b != 0 : NEW_LINE INDENT return a NEW_LINE DEDENT if a >= b : NEW_LINE INDENT return a NEW_LINE DEDENT return b NEW_LINE DEDENT def build_tree ( arr , tree , ind , low , high , x ) : NEW_LINE INDENT if low == high : NEW_LINE INDENT if arr [ low ...
Calculate the Sum of GCD over all subarrays | Utility function to calculate sum of gcd of all sub - arrays . ; Fixing the starting index of a subarray ; Fixing the ending index of a subarray ; Finding the GCD of this subarray ; Adding this GCD in our sum ; Driver Code
def findGCDSum ( n , a ) : NEW_LINE INDENT GCDSum = 0 ; NEW_LINE tempGCD = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT tempGCD = 0 ; NEW_LINE for k in range ( i , j + 1 ) : NEW_LINE INDENT tempGCD = __gcd ( tempGCD , a [ k ] ) ; NEW_LINE DEDENT GCDSum += tempGCD ; NEW_...
Check if the array has an element which is equal to XOR of remaining elements | Function that returns true if the array contains an element which is equal to the XOR of the remaining elements ; To store the XOR of all the array elements ; For every element of the array ; Take the XOR after excluding the current element...
def containsElement ( arr , n ) : NEW_LINE INDENT xorArr = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT xorArr ^= arr [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT x = xorArr ^ arr [ i ] NEW_LINE if ( arr [ i ] == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT ...
Find the winner of the match | Multiple Queries | Function to add edge between two nodes ; Function returns topological order of given graph ; Indeg vector will store indegrees of all vertices ; Answer vector will have our final topological order ; Visited will be true if that vertex has been visited ; q will store the...
def add ( adj , u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE DEDENT def topo ( adj , n ) : NEW_LINE INDENT indeg = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for x in adj [ i ] : NEW_LINE INDENT indeg [ x ] += 1 NEW_LINE DEDENT DEDENT answer = [ ] NEW_LINE visited = [ Fals...
Square root of a number without using sqrt ( ) function | Python3 implementation of the approach ; Recursive function that returns square root of a number with precision upto 5 decimal places ; If mid itself is the square root , return mid ; If mul is less than n , recur second half ; Else recur first half ; Function t...
import math NEW_LINE def Square ( n , i , j ) : NEW_LINE INDENT mid = ( i + j ) / 2 ; NEW_LINE mul = mid * mid ; NEW_LINE if ( ( mul == n ) or ( abs ( mul - n ) < 0.00001 ) ) : NEW_LINE INDENT return mid ; NEW_LINE DEDENT elif ( mul < n ) : NEW_LINE INDENT return Square ( n , mid , j ) ; NEW_LINE DEDENT else : NEW_LINE...
Length of longest substring having all characters as K | Function to find the length of longest sub - string having all characters same as character K ; Initialize variables ; Iterate till size of string ; Check if current character is K ; Assingning the max value to max_len ; Driver code ; Function call
def length_substring ( S , K ) : NEW_LINE INDENT curr_cnt = 0 NEW_LINE prev_cnt = 0 NEW_LINE max_len = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( S [ i ] == K ) : NEW_LINE INDENT curr_cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT prev_cnt = max ( prev_cnt , curr_cnt ) NEW_LINE curr_cnt = 0 NEW_LIN...
Find a partition point in array to maximize its xor sum | Function to find partition point in array to maximize xor sum ; Traverse through the array ; Calculate xor of elements left of index i including ith element ; Calculate xor of the elements right of index i ; Keep the maximum possible xor sum ; Return the 1 based...
def Xor_Sum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE index , left_xor = 0 , 0 NEW_LINE right_xor = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT left_xor = left_xor ^ arr [ i ] NEW_LINE right_xor = 0 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT right_xor = right_xor ^ arr [ j ] NEW_LINE DEDENT if (...
Find a partition point in array to maximize its xor sum | Function to calculate Prefix Xor array ; Calculating prefix xor ; Function to find partition point in array to maximize xor sum ; To store prefix xor ; Compute the prefix xor ; To store sum and index ; Calculate the maximum sum that can be obtained splitting the...
def ComputePrefixXor ( arr , PrefixXor , n ) : NEW_LINE INDENT PrefixXor [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT PrefixXor [ i ] = PrefixXor [ i - 1 ] ^ arr [ i ] ; NEW_LINE DEDENT DEDENT def Xor_Sum ( arr , n ) : NEW_LINE INDENT PrefixXor = [ 0 ] * n ; NEW_LINE ComputePrefixXor ( arr , ...
Find the color of given node in an infinite binary tree | Function to find color of the node ; Maximum is to store maximum color ; Loop to check all the parent values to get maximum color ; Find the number into map and get maximum color ; Take the maximum color and assign into maximum variable ; Find parent index ; Ret...
def findColor ( mapWithColor , query ) : NEW_LINE INDENT maximum = 0 NEW_LINE while ( query >= 1 ) : NEW_LINE INDENT if ( query ) in mapWithColor . keys ( ) : NEW_LINE INDENT maximum = max ( maximum , mapWithColor [ query ] ) NEW_LINE DEDENT if ( query % 2 == 1 ) : NEW_LINE INDENT query = ( query - 1 ) // 2 NEW_LINE DE...
Count of strings in the first array which are smaller than every string in the second array | Python3 implementation of the approach ; Function to count the number of smaller strings in A for every in B ; Count the frequency of all characters ; Iterate for all possible strings in A ; Increase the frequency of every cha...
from bisect import bisect_left as lower_bound NEW_LINE MAX = 26 NEW_LINE def findCount ( a , b , n , m ) : NEW_LINE INDENT freq = [ 0 for i in range ( MAX ) ] NEW_LINE smallestFreq = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = a [ i ] NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT freq [ i ] = 0 NEW_LINE...
Find Leftmost and Rightmost node of BST from its given preorder traversal | Function to return the leftmost and rightmost nodes of the BST whose preorder traversal is given ; Variables for finding minimum and maximum values of the array ; Update the minimum ; Update the maximum ; Print the values ; Driver Code
def LeftRightNode ( preorder , n ) : NEW_LINE INDENT min = 10 ** 9 NEW_LINE max = - 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( min > preorder [ i ] ) : NEW_LINE INDENT min = preorder [ i ] NEW_LINE DEDENT if ( max < preorder [ i ] ) : NEW_LINE INDENT max = preorder [ i ] NEW_LINE DEDENT DEDENT print (...
Find the position of the given row in a 2 | Python3 implementation of the approach ; Function that compares both the arrays and returns - 1 , 0 and 1 accordingly ; Return 1 if mid row is less than arr [ ] ; Return 1 if mid row is greater than arr [ ] ; Both the arrays are equal ; Function to find a row in the given mat...
m = 6 ; NEW_LINE n = 4 ; NEW_LINE def compareRow ( a1 , a2 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( a1 [ i ] < a2 [ i ] ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( a1 [ i ] > a2 [ i ] ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT return 0 ; NEW_LINE DEDENT def binaryCheck ( ar...
Number of subarrays having absolute sum greater than K | Set | Python3 implementation of the above approach ; Function to find required value ; Variable to store final answer ; Loop to find prefix - sum ; Sorting prefix - sum array ; Loop to find upper_bound for each element ; Returning final answer ; Driver code ; Fun...
from bisect import bisect as upper_bound NEW_LINE maxLen = 30 NEW_LINE def findCnt ( arr , n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT arr [ i ] += arr [ i - 1 ] NEW_LINE if ( arr [ i ] > k or arr [ i ] < - 1 * k ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT if ( arr [ 0 ...
Number of intersections between two ranges | Python3 implementation of above approach ; Function to return total number of intersections ; Maximum possible number of intersections ; Store all starting points of type1 ranges ; Store all endpoints of type1 ranges ; Starting point of type2 ranges ; Ending point of type2 r...
from bisect import bisect as upper_bound NEW_LINE def FindIntersection ( type1 , n , type2 , m ) : NEW_LINE INDENT ans = n * m NEW_LINE start = [ ] NEW_LINE end = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT start . append ( type1 [ i ] [ 0 ] ) NEW_LINE end . append ( type1 [ i ] [ 1 ] ) NEW_LINE DEDENT start = ...
Find the Nth term divisible by a or b or c | Function to return gcd of a and b ; Function to return the lcm of a and b ; Function to return the count of numbers from 1 to num which are divisible by a , b or c ; Calculate number of terms divisible by a and by b and by c then , remove the terms which is are divisible by ...
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def lcm ( a , b ) : NEW_LINE INDENT return ( ( a * b ) // gcd ( a , b ) ) NEW_LINE DEDENT def divTermCount ( a , b , c , num ) : NEW_LINE INDENT return ( ( num // a ) + ( num // b ) + ( ...
Split the given array into K sub | Function to check if mid can be maximum sub - arrays sum ; If individual element is greater maximum possible sum ; Increase sum of current sub - array ; If the sum is greater than mid increase count ; Check condition ; Function to find maximum subarray sum which is minimum ; start = m...
def check ( mid , array , n , K ) : NEW_LINE INDENT count = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( array [ i ] > mid ) : NEW_LINE INDENT return False NEW_LINE DEDENT sum += array [ i ] NEW_LINE if ( sum > mid ) : NEW_LINE INDENT count += 1 NEW_LINE sum = array [ i ] NEW_LINE DEDENT DEDE...
Count number of common elements between two arrays by using Bitset and Bitwise operation | Python3 implementation of the approach ; Function to return the count of common elements ; Traverse the first array ; Set 1 at ( index ) position a [ i ] ; Traverse the second array ; Set 1 at ( index ) position b [ i ] ; Bitwise...
MAX = 100000 NEW_LINE bit1 , bit2 , bit3 = 0 , 0 , 0 NEW_LINE def count_common ( a , n , b , m ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT global bit1 , bit2 , bit3 NEW_LINE bit1 = bit1 | ( 1 << a [ i ] ) NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT bit2 = bit2 | ( 1 << b [ i ] ) NEW_LINE DEDEN...
Create a Sorted Array Using Binary Search | Function to create a new sorted array using Binary Search ; Auxiliary Array ; if b is empty any element can be at first place ; Perform Binary Search to find the correct position of current element in the new array ; let the element should be at first index ; if a [ j ] is al...
def createSorted ( a : list , n : int ) : NEW_LINE INDENT b = [ ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT if len ( b ) == 0 : NEW_LINE INDENT b . append ( a [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT start = 0 NEW_LINE end = len ( b ) - 1 NEW_LINE pos = 0 NEW_LINE while start <= end : NEW_LINE INDENT mid = ...
Largest sub | Python3 implementation of the approach ; Function that return true if frequency of all the present characters is at least k ; If the character is present and its frequency is less than k ; Function to set every frequency to zero ; Function to return the length of the longest sub - string such that it cont...
MAX = 26 NEW_LINE def atLeastK ( freq , k ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT if ( freq [ i ] != 0 and freq [ i ] < k ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def setZero ( freq ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT freq [ i ...
Minimum increments to convert to an array of consecutive integers | Function that return true if the required array can be generated with m as the last element ; Build the desired array ; Check if the given array can be converted to the desired array with the given operation ; Function to return the minimum number of o...
def check ( m , n , arr ) : NEW_LINE INDENT desired = [ 0 ] * n ; NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT desired [ i ] = m ; NEW_LINE m -= 1 ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > desired [ i ] or desired [ i ] < 1 ) : NEW_LINE INDENT return False ; NEW_LINE D...
Count duplicates in a given linked list | Node of a linked list ; Function to insert a node at the beginning ; Function to count the number of duplicate nodes in the linked list ; Create a hash table insert head ; Traverse through remaining nodes ; Return the count of duplicate nodes ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , data = None , next = None ) : NEW_LINE INDENT self . next = next NEW_LINE self . data = data NEW_LINE DEDENT DEDENT head = None NEW_LINE def insert ( ref_head , item ) : NEW_LINE INDENT global head NEW_LINE temp = Node ( ) NEW_LINE temp . data = item NEW_LINE temp . ne...
Minimize the number of steps required to reach the end of the array | Set 2 | Function to return the minimum steps required to reach the end of the given array ; Array to determine whether a cell has been visited before ; Queue for bfs ; Push the source i . e . index 0 ; Variable to store the depth of search ; BFS algo...
def minSteps ( arr , n ) : NEW_LINE INDENT v = [ 0 for i in range ( n ) ] NEW_LINE q = [ ] NEW_LINE q . append ( 0 ) NEW_LINE depth = 0 NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT x = len ( q ) NEW_LINE while ( x >= 1 ) : NEW_LINE INDENT i = q [ 0 ] NEW_LINE q . remove ( i ) NEW_LINE x -= 1 NEW_LINE if ( v [ i ...
Find the winner of the game based on greater number of divisors | Python3 implementation of the approach ; Function to return the count of divisors of elem ; Function to return the winner of the game ; Convert every element of A [ ] to their divisor count ; Convert every element of B [ ] to their divisor count ; Sort b...
from math import * NEW_LINE def divisorcount ( elem ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , int ( sqrt ( elem ) ) + 1 ) : NEW_LINE INDENT if ( elem % i == 0 ) : NEW_LINE INDENT if ( i * i == elem ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += 2 NEW_LINE DEDENT DEDENT DEDENT...
Minimum time required to transport all the boxes from source to the destination under the given constraints | Function that returns true if it is possible to transport all the boxes in the given amount of time ; If all the boxes can be transported in the given time ; If all the boxes can 't be transported in the given...
def isPossible ( box , truck , n , m , min_time ) : NEW_LINE INDENT temp = 0 NEW_LINE count = 0 NEW_LINE while ( count < m ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < min_time and temp < n and truck [ count ] >= box [ temp ] ) : NEW_LINE INDENT temp += 1 NEW_LINE j += 2 NEW_LINE DEDENT count += 1 NEW_LINE DEDENT if ...
Maximum points covered after removing an Interval | Function To find the required interval ; Total Count of covered numbers ; Array to store numbers that occur exactly in one interval till ith interval ; Calculate New count by removing all numbers in range [ l , r ] occurring exactly once ; Driver code
def solve ( interval , N , Q ) : NEW_LINE INDENT Mark = [ 0 for i in range ( Q ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT l = interval [ i ] [ 0 ] - 1 NEW_LINE r = interval [ i ] [ 1 ] - 1 NEW_LINE for j in range ( l , r + 1 ) : NEW_LINE INDENT Mark [ j ] += 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for i in...
Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps | Function that returns true if it is possible to reach end of the array in exactly k jumps ; Variable to store the number of steps required to reach the end ; If it is possible to reach the end in exactly k jumps ; Return...
def isPossible ( arr , n , dist , k ) : NEW_LINE INDENT req = 0 NEW_LINE curr = 0 NEW_LINE prev = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT while ( curr != n and ( arr [ curr ] - arr [ prev ] ) <= dist ) : NEW_LINE INDENT curr = curr + 1 NEW_LINE DEDENT req = req + 1 NEW_LINE if ( curr == n ) : NEW_LINE IND...
Find the kth element in the series generated by the given N ranges | Function to return the kth element of the required series ; To store the number of integers that lie upto the ith index ; Compute the number of integers ; Stores the index , lying from 1 to n , ; Using binary search , find the index in which the kth e...
def getKthElement ( n , k , L , R ) : NEW_LINE INDENT l = 1 NEW_LINE h = n NEW_LINE total = [ 0 for i in range ( n + 1 ) ] NEW_LINE total [ 0 ] = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT total [ i + 1 ] = total [ i ] + ( R [ i ] - L [ i ] ) + 1 NEW_LINE DEDENT index = - 1 NEW_LINE while ( l <= h ) : NEW_LINE I...
Find minimum positive integer x such that a ( x ^ 2 ) + b ( x ) + c >= k | Function to return the minimum positive integer satisfying the given equation ; Binary search to find the value of x ; Return the answer ; Driver code
def MinimumX ( a , b , c , k ) : NEW_LINE INDENT x = 10 ** 9 NEW_LINE if ( k <= c ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT h = k - c NEW_LINE l = 0 NEW_LINE while ( l <= h ) : NEW_LINE INDENT m = ( l + h ) // 2 NEW_LINE if ( ( a * m * m ) + ( b * m ) > ( k - c ) ) : NEW_LINE INDENT x = min ( x , m ) NEW_LINE h = m ...
Divide array into two parts with equal sum according to the given constraints | Function that checks if the given conditions are satisfied ; To store the prefix sum of the array elements ; Sort the array ; Compute the prefix sum array ; Maximum element in the array ; Variable to check if there exists any number ; Store...
def IfExists ( arr , n ) : NEW_LINE INDENT sum = [ 0 ] * n ; NEW_LINE arr . sort ( ) ; NEW_LINE sum [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT sum [ i ] = sum [ i - 1 ] + arr [ i ] ; NEW_LINE DEDENT max = arr [ n - 1 ] ; NEW_LINE flag = False ; NEW_LINE for i in range ( 1 , max + 1 ) : NEW_...
Find missing element in a sorted array of consecutive numbers | Function to return the missing element ; Check if middle element is consistent ; No inconsistency till middle elements When missing element is just after the middle element ; Move right ; Inconsistency found When missing element is just before the middle e...
def findMissing ( arr , n ) : NEW_LINE INDENT l , h = 0 , n - 1 NEW_LINE mid = 0 NEW_LINE while ( h > l ) : NEW_LINE INDENT mid = l + ( h - l ) // 2 NEW_LINE if ( arr [ mid ] - mid == arr [ 0 ] ) : NEW_LINE INDENT if ( arr [ mid + 1 ] - arr [ mid ] > 1 ) : NEW_LINE INDENT return arr [ mid ] + 1 NEW_LINE DEDENT else : N...
Find maximum sum taking every Kth element in the array | Python 3 implementation of the approach ; Function to return the maximum sum for every possible sequence such that a [ i ] + a [ i + k ] + a [ i + 2 k ] + ... + a [ i + qk ] is maximized ; Initialize the maximum with the smallest value ; Find maximum from all seq...
import sys NEW_LINE def maxSum ( arr , n , K ) : NEW_LINE INDENT maximum = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sumk = 0 NEW_LINE for j in range ( i , n , K ) : NEW_LINE INDENT sumk = sumk + arr [ j ] NEW_LINE DEDENT maximum = max ( maximum , sumk ) NEW_LINE DEDENT return maximum NEW_LINE...
Find the number of elements greater than k in a sorted array | Function to return the count of elements from the array which are greater than k ; Stores the index of the left most element from the array which is greater than k ; Finds number of elements greater than k ; If mid element is greater than k update leftGreat...
def countGreater ( arr , n , k ) : NEW_LINE INDENT l = 0 NEW_LINE r = n - 1 NEW_LINE leftGreater = n NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = int ( l + ( r - l ) / 2 ) NEW_LINE if ( arr [ m ] > k ) : NEW_LINE INDENT leftGreater = m NEW_LINE r = m - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 NEW_LINE DEDE...
Count the number of operations required to reduce the given number | Python3 implementation of the approach ; To store the normalized value of all the operations ; Minimum possible value for a series of operations ; If k can be reduced with first ( i + 1 ) operations ; Impossible to reduce k ; Number of times all the o...
def operations ( op , n , k ) : NEW_LINE INDENT i , count = 0 , 0 NEW_LINE nVal = 0 NEW_LINE minimum = 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT nVal += op [ i ] NEW_LINE minimum = min ( minimum , nVal ) NEW_LINE if ( ( k + nVal ) <= 0 ) : NEW_LINE INDENT return ( i + 1 ) NEW_LINE DEDENT DEDENT if ( nVal ...
Uniform Binary Search | Python3 implementation of above approach ; lookup table ; create the lookup table for an array of length n ; power and count variable ; multiply by 2 ; initialize the lookup table ; binary search ; mid point of the array ; count ; if the value is found ; if value is less than the mid value ; if ...
MAX_SIZE = 1000 NEW_LINE lookup_table = [ 0 ] * MAX_SIZE NEW_LINE def create_table ( n ) : NEW_LINE INDENT pow = 1 NEW_LINE co = 0 NEW_LINE while True : NEW_LINE INDENT pow <<= 1 NEW_LINE lookup_table [ co ] = ( n + ( pow >> 1 ) ) // pow NEW_LINE if lookup_table [ co ] == 0 : NEW_LINE INDENT break NEW_LINE DEDENT co +=...
Find the smallest number X such that X ! contains at least Y trailing zeros . | Function to count the number of factors P in X ! ; Function to find the smallest X such that X ! contains Y trailing zeros ; Driver code
def countFactor ( P , X ) : NEW_LINE INDENT if ( X < P ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT return ( X // P + countFactor ( P , X // P ) ) ; NEW_LINE DEDENT def findSmallestX ( Y ) : NEW_LINE INDENT low = 0 ; NEW_LINE high = 5 * Y ; NEW_LINE N = 0 ; NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( hig...
Find maximum N such that the sum of square of first N natural numbers is not more than X | Function to return the sum of the squares of first N natural numbers ; Function to return the maximum N such that the sum of the squares of first N natural numbers is not more than X ; Driver code
def squareSum ( N ) : NEW_LINE INDENT Sum = ( N * ( N + 1 ) * ( 2 * N + 1 ) ) // 6 NEW_LINE return Sum NEW_LINE DEDENT def findMaxN ( X ) : NEW_LINE INDENT low , high , N = 1 , 100000 , 0 NEW_LINE while low <= high : NEW_LINE INDENT mid = ( high + low ) // 2 NEW_LINE if squareSum ( mid ) <= X : NEW_LINE INDENT N = mid ...
Search an element in given N ranges | Function to return the index of the range in which K lies and uses linear search ; Iterate and find the element ; If K lies in the current range ; K doesn 't lie in any of the given ranges ; Driver code
def findNumber ( a , n , K ) : NEW_LINE INDENT for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( K >= a [ i ] [ 0 ] and K <= a [ i ] [ 1 ] ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ [ 1 , 3 ] , [ 4 , 7 ] , [ 8 , 11 ] ] NEW_LIN...
Search an element in given N ranges | Function to return the index of the range in which K lies and uses binary search ; Binary search ; Find the mid element ; If element is found ; Check in first half ; Check in second half ; Not found ; Driver code
def findNumber ( a , n , K ) : NEW_LINE INDENT low = 0 NEW_LINE high = n - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) >> 1 NEW_LINE if ( K >= a [ mid ] [ 0 ] and K <= a [ mid ] [ 1 ] ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( K < a [ mid ] [ 0 ] ) : NEW_LINE INDENT high = mid - 1...
Two equal sum segment range queries | Function to find the required prefix Sum ; Function to hash all the values of prefix Sum array in an unordered map ; Function to check if a range can be divided into two equal parts ; To store the value of Sum of entire range ; If value of Sum is odd ; To store p_arr [ l - 1 ] ; If...
def prefixSum ( p_arr , arr , n ) : NEW_LINE INDENT p_arr [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT p_arr [ i ] = arr [ i ] + p_arr [ i - 1 ] NEW_LINE DEDENT DEDENT def hashPrefixSum ( p_arr , n , q ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT q [ p_arr [ i ] ] = 1 NEW_LINE DED...
Search element in a Spirally sorted Matrix | Function to return the ring , the number x belongs to . ; Returns - 1 if number x is smaller than least element of arr ; l and r represent the diagonal elements to search in ; Returns - 1 if number x is greater than the largest element of arr ; Function to perform binary sea...
def findRing ( arr , x ) : NEW_LINE INDENT if arr [ 0 ] [ 0 ] > x : NEW_LINE INDENT return - 1 NEW_LINE DEDENT l , r = 0 , ( n + 1 ) // 2 - 1 NEW_LINE if n % 2 == 1 and arr [ r ] [ r ] < x : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if n % 2 == 0 and arr [ r + 1 ] [ r ] < x : NEW_LINE INDENT return - 1 NEW_LINE DEDENT...
Cost to make a string Panagram | Set 2 | Function to return the cost to make string a Panagram ; Count the occurrences of each lowercase character ; To store the total gain ; If some character is missing , it has to be added at twice the cost ; If some character appears more than once all of its occurrences except 1 ca...
def costToPanagram ( string , cost ) : NEW_LINE INDENT n = len ( string ) NEW_LINE occurrences = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT occurrences [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT gain = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if occurrences [ i ] == 0 : NEW_...
Weighted sum of the characters of a string in an array | Set 2 | Function to return the required string score ; create a hash map of strings in str ; Store every string in the map along with its position in the array ; If given string is not present in str [ ] ; Multiply sum of alphabets with position ; Driver code
def strScore ( string , s , n ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ string [ i ] ] = i + 1 NEW_LINE DEDENT if s not in m . keys ( ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT score = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT score += ord ( s [ i ] ) - ord ( ' a ...
Number of subarrays have bitwise OR >= K | Function to return the count of required sub - arrays ; Traverse sub - array [ i . . j ] ; Driver code
def countSubArrays ( arr , n , K ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT bitwise_or = 0 NEW_LINE for k in range ( i , j + 1 ) : NEW_LINE INDENT bitwise_or = bitwise_or | arr [ k ] NEW_LINE DEDENT if ( bitwise_or >= K ) : NEW_LINE INDENT ...
Number of subarrays have bitwise OR >= K | Python implementation of the approach ; Function to build the segment tree ; Function to return the bitwise OR of segment [ L . . R ] ; Function to return the count of required sub - arrays ; Build segment tree ; Query segment tree for bitwise OR of sub - array [ i . . j ] ; D...
N = 100002 NEW_LINE tree = [ 0 ] * ( 4 * N ) NEW_LINE def build ( arr , node , start , end ) : NEW_LINE INDENT if start == end : NEW_LINE INDENT tree [ node ] = arr [ start ] NEW_LINE return NEW_LINE DEDENT mid = ( start + end ) >> 1 NEW_LINE build ( arr , 2 * node , start , mid ) NEW_LINE build ( arr , 2 * node + 1 , ...
Number of subarrays have bitwise OR >= K | Python3 program to implement the above approach ; Function which builds the segment tree ; Function that returns bitwise OR of segment [ L . . R ] ; Function to count requisite number of subarrays ; Check for subarrays starting with index i ; If OR of subarray [ i . . mid ] >=...
N = 100002 NEW_LINE tree = [ 0 for i in range ( 4 * N ) ] ; NEW_LINE def build ( arr , node , start , end ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT tree [ node ] = arr [ start ] ; NEW_LINE return ; NEW_LINE DEDENT mid = ( start + end ) >> 1 ; NEW_LINE build ( arr , 2 * node , start , mid ) ; NEW_LINE bu...
Occurrences of a pattern in binary representation of a number | Function to return the count of occurrence of pat in binary representation of n ; To store decimal value of the pattern ; To store a number that has all ones in its binary representation and length of ones equal to length of the pattern ; Find values of pa...
def countPattern ( n , pat ) : NEW_LINE INDENT pattern_int = 0 NEW_LINE power_two = 1 NEW_LINE all_ones = 0 NEW_LINE i = len ( pat ) - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT current_bit = ord ( pat [ i ] ) - ord ( '0' ) NEW_LINE pattern_int += ( power_two * current_bit ) NEW_LINE all_ones = all_ones + power_two ...
Pairs with same Manhattan and Euclidean distance | Python3 implementation of the above approach ; Function to return the number of non coincident pairs of points with manhattan distance equal to euclidean distance ; To store frequency of all distinct Xi ; To store Frequency of all distinct Yi ; To store Frequency of al...
from collections import defaultdict NEW_LINE def findManhattanEuclidPair ( arr , n ) : NEW_LINE INDENT X = defaultdict ( lambda : 0 ) NEW_LINE Y = defaultdict ( lambda : 0 ) NEW_LINE XY = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT xi = arr [ i ] [ 0 ] NEW_LINE yi = arr [ i ] [ 1 ] NE...
Remove exactly one element from the array such that max | function to calculate max - min ; Driver code
def max_min ( a , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE return min ( a [ n - 2 ] - a [ 0 ] , a [ n - 1 ] - a [ 1 ] ) NEW_LINE DEDENT a = [ 1 , 3 , 3 , 7 ] NEW_LINE n = len ( a ) NEW_LINE print ( max_min ( a , n ) ) NEW_LINE
Count numbers < = N whose difference with the count of primes upto them is > = K | Python3 implementation of the above approach ; primeUpto [ i ] denotes count of prime numbers upto i ; Function to compute all prime numbers and update primeUpto array ; 0 and 1 are not primes ; If i is prime ; Set all multiples of i as ...
MAX = 1000001 NEW_LINE MAX_sqrt = MAX ** ( 0.5 ) NEW_LINE primeUpto = [ 0 ] * ( MAX ) NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT isPrime = [ 1 ] * ( MAX ) NEW_LINE isPrime [ 0 ] , isPrime [ 1 ] = 0 , 0 NEW_LINE for i in range ( 2 , int ( MAX_sqrt ) ) : NEW_LINE INDENT if isPrime [ i ] == 1 : NEW_LINE INDENT...
Find the element whose multiplication with | Function to find minimum index such that sum becomes 0 when the element is multiplied by - 1 ; Find array sum ; Find element with value equal to sum / 2 ; when sum is equal to 2 * element then this is our required element ; Driver code
def minIndex ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( 2 * arr [ i ] == sum ) : NEW_LINE INDENT return ( i + 1 ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 1 , 3 , - 5 , 3 , 4 ...
Ceiling of every element in same array | Python implementation of efficient algorithm to find floor of every element ; Prints greater elements on left side of every element ; Create a sorted copy of arr [ ] ; Traverse through arr [ ] and do binary search for every element ; Find the location of first element that is gr...
import bisect NEW_LINE def printPrevGreater ( arr , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT v = list ( arr ) NEW_LINE v . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT it = bisect . bisect_right ( v , arr [ i ] ) NEW_LINE if ( it - 1 ) != 0 and v [ i...
Floor of every element in same array | Prints greater elements on left side of every element ; Create a sorted copy of arr ; Traverse through arr [ ] and do binary search for every element . ; Floor of first element is - 1 if there is only one occurrence of it . ; Find the first element that is greater than or or equal...
def printPrevGreater ( arr , n ) : NEW_LINE INDENT v = arr . copy ( ) NEW_LINE v . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == v [ 0 ] ) : NEW_LINE INDENT if ( arr [ i ] == v [ 1 ] ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 , e...
Find smallest and largest element from square matrix diagonals | Python3 program to find smallest and largest elements of both diagonals ; Function to find smallest and largest element from principal and secondary diagonal ; take length of matrix ; declare and initialize variables with appropriate value ; take new smal...
n = 5 NEW_LINE def diagonalsMinMax ( mat ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT principalMin = mat [ 0 ] [ 0 ] NEW_LINE principalMax = mat [ 0 ] [ 0 ] NEW_LINE secondaryMin = mat [ n - 1 ] [ 0 ] NEW_LINE secondaryMax = mat [ n - 1 ] [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDE...
Check if array can be sorted with one swap | A linear Python 3 program to check if array becomes sorted after one swap ; Find counts and positions of elements that are out of order . ; If there are more than two elements which are out of order . ; If all elements are sorted already ; Cases like { 1 , 5 , 3 , 4 , 2 } We...
def checkSorted ( n , arr ) : NEW_LINE INDENT first , second = 0 , 0 NEW_LINE count = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] < arr [ i - 1 ] : NEW_LINE INDENT count += 1 NEW_LINE if first == 0 : NEW_LINE INDENT first = i NEW_LINE DEDENT else : NEW_LINE INDENT second = i NEW_LINE DEDENT DEDEN...
Find the intersection of two Matrices | Python 3 program to find intersection of two matrices ; Function to print the resultant matrix ; print element value for equal elements else * ; Driver Code
N , M = 4 , 4 NEW_LINE def printIntersection ( A , B ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( A [ i ] [ j ] == B [ i ] [ j ] ) : NEW_LINE INDENT print ( A [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " * ▁ " , end = " ▁ " ) NEW_...
Count Triplets such that one of the numbers can be written as sum of the other two | Python3 program to count Triplets such that at least one of the numbers can be written as sum of the other two ; Function to count the number of ways to choose the triples ; compute the max value in the array and create frequency array...
import math as mt NEW_LINE def countWays ( arr , n ) : NEW_LINE INDENT max_val = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT max_val = max ( max_val , arr [ i ] ) NEW_LINE DEDENT freq = [ 0 for i in range ( max_val + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT ans...