text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Queries for decimal values of subarrays of a binary array | implementation of finding number represented by binary subarray ; Fills pre [ ] ; returns the number represented by a binary subarray l to r ; if r is equal to n - 1 r + 1 does not exist ; Driver Code
from math import pow NEW_LINE def precompute ( arr , n , pre ) : NEW_LINE INDENT pre [ n - 1 ] = arr [ n - 1 ] * pow ( 2 , 0 ) NEW_LINE i = n - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT pre [ i ] = ( pre [ i + 1 ] + arr [ i ] * ( 1 << ( n - 1 - i ) ) ) NEW_LINE i -= 1 NEW_LINE DEDENT DEDENT def decimalOfSubarr ( ar...
Count elements which divide all numbers in range L | function to count element Time complexity O ( n ^ 2 ) worst case ; answer for query ; 0 based index ; iterate for all elements ; check if the element divides all numbers in range ; no of elements ; if all elements are divisible by a [ i ] ; answer for every query ; D...
def answerQuery ( a , n , l , r ) : NEW_LINE INDENT count = 0 NEW_LINE l = l - 1 NEW_LINE for i in range ( l , r , 1 ) : NEW_LINE INDENT element = a [ i ] NEW_LINE divisors = 0 NEW_LINE for j in range ( l , r , 1 ) : NEW_LINE INDENT if ( a [ j ] % a [ i ] == 0 ) : NEW_LINE INDENT divisors += 1 NEW_LINE DEDENT else : NE...
Minimum number of Binary strings to represent a Number | Function to find the minimum number of binary strings to represent a number ; Storing digits in correct order ; Find the maximum digit in the array ; Traverse for all the binary strings ; If digit at jth position is greater than 0 then substitute 1 ; Driver code
def minBinary ( n ) : NEW_LINE INDENT digit = [ 0 for i in range ( 3 ) ] NEW_LINE len = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit [ len ] = n % 10 NEW_LINE len += 1 NEW_LINE n //= 10 NEW_LINE DEDENT digit = digit [ : : - 1 ] NEW_LINE ans = 0 NEW_LINE for i in range ( len ) : NEW_LINE INDENT ans = max ( ans , d...
Number whose sum of XOR with given array range is maximum | Python3 program to find smallest integer X such that sum of its XOR with range is maximum . ; Function to make prefix array which counts 1 's of each bit up to that number ; Making a prefix array which sums number of 1 's up to that position ; If j - th bit o...
import math NEW_LINE one = [ [ 0 for x in range ( 32 ) ] for y in range ( 100001 ) ] NEW_LINE MAX = 2147483647 NEW_LINE def make_prefix ( A , n ) : NEW_LINE INDENT global one , MAX NEW_LINE for j in range ( 0 , 32 ) : NEW_LINE INDENT one [ 0 ] [ j ] = 0 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT a =...
Array range queries over range queries | Function to execute type 1 query ; incrementing the array by 1 for type 1 queries ; Function to execute type 2 query ; If the query is of type 1 function call to type 1 query ; If the query is of type 2 recursive call to type 2 query ; Input size of array amd number of queries ;...
def type1 ( arr , start , limit ) : NEW_LINE INDENT for i in range ( start , limit + 1 ) : NEW_LINE INDENT arr [ i ] += 1 NEW_LINE DEDENT DEDENT def type2 ( arr , query , start , limit ) : NEW_LINE INDENT for i in range ( start , limit + 1 ) : NEW_LINE INDENT if ( query [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT type1 ( arr ...
Array range queries over range queries | Function to create the record array ; Driver Code ; Build query matrix ; If query is of type 2 then function call to record_sum ; If query is of type 1 then simply add 1 to the record array ; for type 1 queries adding the contains of record array to the main array record array ;...
def record_sum ( record , l , r , n , adder ) : NEW_LINE INDENT for i in range ( l , r + 1 ) : NEW_LINE INDENT record [ i ] += adder NEW_LINE DEDENT DEDENT n = 5 NEW_LINE m = 5 NEW_LINE arr = [ 0 ] * n NEW_LINE query = [ [ 1 , 1 , 2 ] , [ 1 , 4 , 5 ] , [ 2 , 1 , 2 ] , [ 2 , 1 , 3 ] , [ 2 , 3 , 4 ] ] NEW_LINE record = [...
Array range queries over range queries | Python3 program to perform range queries over range queries . ; For prefix sum array ; This function is used to apply square root decomposition in the record array ; Traversing first block in range ; Traversing completely overlapped blocks in range ; Traversing last block in ran...
import math NEW_LINE max = 10000 NEW_LINE def update ( arr , l ) : NEW_LINE INDENT arr [ l ] += arr [ l - 1 ] NEW_LINE DEDENT def record_func ( block_size , block , record , l , r , value ) : NEW_LINE INDENT while ( l < r and l % block_size != 0 and l != 0 ) : NEW_LINE INDENT record [ l ] += value NEW_LINE l += 1 NEW_L...
Array range queries for searching an element | Structure to represent a query range ; Find the root of the group containing the element at index x ; merge the two groups containing elements at indices x and y into one group ; make n subsets with every element as its root ; consecutive elements equal in value are merged...
class Query : NEW_LINE INDENT def __init__ ( self , L , R , X ) : NEW_LINE INDENT self . L = L NEW_LINE self . R = R NEW_LINE self . X = X NEW_LINE DEDENT DEDENT maxn = 100 NEW_LINE root = [ 0 ] * maxn NEW_LINE def find ( x ) : NEW_LINE INDENT if x == root [ x ] : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LIN...
Count of pairs from 1 to a and 1 to b whose sum is divisible by N | Function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; Iterate over 1 to a to find distinct pairs ; For each integer from 1 to a b / n integers exists such that pair / sum is divisible by n ; If ( i % n + b % n...
def findCountOfPairs ( a , b , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , a + 1 ) : NEW_LINE INDENT ans += b // n NEW_LINE ans += 1 if ( i % n + b % n ) >= n else 0 NEW_LINE DEDENT return ans NEW_LINE DEDENT a = 5 ; b = 13 ; n = 3 NEW_LINE print ( findCountOfPairs ( a , b , n ) ) NEW_LINE
Count of pairs from 1 to a and 1 to b whose sum is divisible by N | Function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; if first element is bigger then swap ; count is store the number of pair . ; we use temp for breaking a loop . ; count when a is greater . ; Count when a i...
def findCountOfPairs ( a , b , n ) : NEW_LINE INDENT if ( a > b ) : NEW_LINE INDENT a , b = b , a NEW_LINE DEDENT temp = 1 NEW_LINE count = 0 NEW_LINE i = n NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT if ( a >= i ) : NEW_LINE INDENT temp = i - 1 NEW_LINE DEDENT elif ( b >= i ) : NEW_LINE INDENT temp = a NEW_LINE DEDE...
Array range queries for elements with frequency same as value | Python 3 Program to answer Q queries to find number of times an element x appears x times in a Query subarray ; Returns the count of number x with frequency x in the subarray from start to end ; map for frequency of elements ; store frequency of each eleme...
import math as mt NEW_LINE def solveQuery ( start , end , arr ) : NEW_LINE INDENT frequency = dict ( ) NEW_LINE for i in range ( start , end + 1 ) : NEW_LINE INDENT if arr [ i ] in frequency . keys ( ) : NEW_LINE INDENT frequency [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT frequency [ arr [ i ] ] = 1 NEW_...
Buy minimum items without change and given coins | Python3 implementation of above approach ; See if we can buy less than 10 items Using 10 Rs coins and one r Rs coin ; We can always buy 10 items ; Driver Code
def minItems ( k , r ) : NEW_LINE INDENT for i in range ( 1 , 10 ) : NEW_LINE INDENT if ( ( i * k - r ) % 10 == 0 or ( i * k ) % 10 == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return 10 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k , r = 15 , 2 ; NEW_LINE print ( minItems ( k , r ) ...
Number of indexes with equal elements in given range | function that answers every query in O ( r - l ) ; traverse from l to r and count the required indexes ; Driver Code ; 1 - st query ; 2 nd query
def answer_query ( a , n , l , r ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( l , r ) : NEW_LINE INDENT if ( a [ i ] == a [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT a = [ 1 , 2 , 2 , 2 , 3 , 3 , 4 , 4 , 4 ] NEW_LINE n = len ( a ) NEW_LINE L = 1 NEW_LINE R = 8...
Diagonal Sum of a Binary Tree | Python3 program calculate the sum of diagonal nodes . ; A binary tree node structure ; To map the node with level - index ; Recursvise function to calculate sum of elements where level - index is same ; If there is no child then return ; Add the element in the group of node whose level -...
from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT grid = { } NEW_LINE def addConsideringGrid ( root , level , index ) : NEW_LINE INDENT global grid NEW_LINE i...
Number of indexes with equal elements in given range | Python program to count the number of indexes in range L R such that Ai = Ai + 1 ; array to store count of index from 0 to i that obey condition ; precomputing prefixans [ ] array ; traverse to compute the prefixans [ ] array ; def that answers every query in O ( 1...
N = 1000 NEW_LINE prefixans = [ 0 ] * N ; NEW_LINE def countIndex ( a , n ) : NEW_LINE INDENT global N , prefixans NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( a [ i ] == a [ i + 1 ] ) : NEW_LINE INDENT prefixans [ i ] = 1 NEW_LINE DEDENT if ( i != 0 ) : NEW_LINE INDENT prefixans [ i ] = ( prefixans [ i...
Count subarrays with Prime sum | Function to count subarrays with Prime sum ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not ...
def primeSubarrays ( A , n ) : NEW_LINE INDENT max_val = 10 ** 7 NEW_LINE prime = [ True ] * ( max_val + 1 ) NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( max_val ** ( 0.5 ) ) + 1 ) : NEW_LINE INDENT if prime [ p ] == True : NEW_LINE INDENT for i in range ( 2 * p , max_va...
Total numbers with no repeated digits in a range | Function to check if the given number has repeated digit or not ; Traversing through each digit ; if the digit is present more than once in the number ; return 0 if the number has repeated digit ; return 1 if the number has no repeated digit ; Function to find total nu...
def repeated_digit ( n ) : NEW_LINE INDENT a = [ ] NEW_LINE while n != 0 : NEW_LINE INDENT d = n % 10 NEW_LINE if d in a : NEW_LINE INDENT return 0 NEW_LINE DEDENT a . append ( d ) NEW_LINE n = n // 10 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def calculate ( L , R ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ...
Minimum swaps required to make a binary string alternating | returns the minimum number of swaps of a binary string passed as the argument to make it alternating ; counts number of zeroes at odd and even positions ; counts number of ones at odd and even positions ; alternating string starts with 0 ; alternating string ...
def countMinSwaps ( st ) : NEW_LINE INDENT min_swaps = 0 NEW_LINE odd_0 , even_0 = 0 , 0 NEW_LINE odd_1 , even_1 = 0 , 0 NEW_LINE n = len ( st ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT if st [ i ] == "1" : NEW_LINE INDENT even_1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT eve...
Total numbers with no repeated digits in a range | Maximum ; Prefix Array ; Function to check if the given number has repeated digit or not ; Traversing through each digit ; if the digit is present more than once in the number ; return 0 if the number has repeated digit ; return 1 if the number has no repeated digit ; ...
MAX = 1000 NEW_LINE Prefix = [ 0 ] NEW_LINE def repeated_digit ( n ) : NEW_LINE INDENT a = [ ] NEW_LINE while n != 0 : NEW_LINE INDENT d = n % 10 NEW_LINE if d in a : NEW_LINE INDENT return 0 NEW_LINE DEDENT a . append ( d ) NEW_LINE n = n // 10 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def pre_calculation ( MAX ) : NEW...
Difference Array | Range update query in O ( 1 ) | Creates a diff array D [ ] for A [ ] and returns it after filling initial values . ; We use one extra space because update ( l , r , x ) updates D [ r + 1 ] ; Does range update ; Prints updated Array ; Note that A [ 0 ] or D [ 0 ] decides values of rest of the elements...
def initializeDiffArray ( A ) : NEW_LINE INDENT n = len ( A ) NEW_LINE D = [ 0 for i in range ( 0 , n + 1 ) ] NEW_LINE D [ 0 ] = A [ 0 ] ; D [ n ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT D [ i ] = A [ i ] - A [ i - 1 ] NEW_LINE DEDENT return D NEW_LINE DEDENT def update ( D , l , r , x ) : NEW_LINE INDE...
Largest Sum Contiguous Subarray | Python program to find maximum contiguous subarray Function to find the maximum contiguous subarray ; Driver function to check the above function
from sys import maxint NEW_LINE def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - maxint - 1 NEW_LINE max_ending_here = 0 NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] NEW_LINE if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_endi...
Place N ^ 2 numbers in matrix such that every row has an equal sum | Python3 program to distribute n ^ 2 numbers to n people ; 2D array for storing the final result ; Using modulo to go to the firs column after the last column ; Making a 2D array containing numbers ; Driver Code
def solve ( arr , n ) : NEW_LINE INDENT ans = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT ans [ i ] [ j ] = arr [ j ] [ ( i + j ) % n ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def show ( arr , n ) : NEW_LINE INDENT ...
Largest Sum Contiguous Subarray | ; Do not compare for all elements . Compare only when max_ending_here > 0
def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = a [ 0 ] NEW_LINE max_ending_here = 0 NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] NEW_LINE if max_ending_here < 0 : NEW_LINE INDENT max_ending_here = 0 NEW_LINE DEDENT elif ( max_so_far < max_ending_here...
Minimum rooms for m events of n batches with given schedule | Returns minimum number of rooms required to perform classes of n groups in m slots with given schedule . ; Store count of classes happening in every slot . ; initialize all values to zero ; Number of rooms required is equal to maximum classes happening in a ...
def findMinRooms ( slots , n , m ) : NEW_LINE INDENT counts = [ 0 ] * m ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( slots [ i ] [ j ] == '1' ) : NEW_LINE INDENT counts [ j ] += 1 ; NEW_LINE DEDENT DEDENT DEDENT return max ( counts ) ; NEW_LINE DEDENT n = 3 ; NEW_LINE m ...
Largest Sum Contiguous Subarray | Python program to find maximum contiguous subarray ; Driver function to check the above function
def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = a [ 0 ] NEW_LINE curr_max = a [ 0 ] NEW_LINE for i in range ( 1 , size ) : NEW_LINE INDENT curr_max = max ( a [ i ] , curr_max + a [ i ] ) NEW_LINE max_so_far = max ( max_so_far , curr_max ) NEW_LINE DEDENT return max_so_far NEW_LINE DEDENT a = [ - 2 , - 3 ...
Largest Sum Contiguous Subarray | Function to find the maximum contiguous subarray and print its starting and end index ; Driver program to test maxSubArraySum
from sys import maxsize NEW_LINE def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - maxsize - 1 NEW_LINE max_ending_here = 0 NEW_LINE start = 0 NEW_LINE end = 0 NEW_LINE s = 0 NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT max_ending_here += a [ i ] NEW_LINE if max_so_far < max_ending_here : NEW_L...
Minimum sum by choosing minimum of pairs from array | Returns minimum possible sum in array B [ ] ; driver code
def minSum ( A ) : NEW_LINE INDENT min_val = min ( A ) ; NEW_LINE return min_val * ( len ( A ) - 1 ) NEW_LINE DEDENT A = [ 7 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE print ( minSum ( A ) ) NEW_LINE
Program for Next Fit algorithm in Memory Management | Function to allocate memory to blocks as per Next fit algorithm ; Initially no block is assigned to any process ; pick each process and find suitable blocks according to its size ad assign to it ; Do not start from beginning ; allocate block j to p [ i ] process ; R...
def NextFit ( blockSize , m , processSize , n ) : NEW_LINE INDENT allocation = [ - 1 ] * n NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT while j < m : NEW_LINE INDENT if blockSize [ j ] >= processSize [ i ] : NEW_LINE INDENT allocation [ i ] = j NEW_LINE blockSize [ j ] -= processSize [ i ] NEW_LINE br...
Find if there is a pair in root to a leaf path with sum equals to root 's data | utility that allocates a new node with the given data and None left and right pointers . ; Function to prroot to leaf path which satisfies the condition ; Base condition ; Check if current node makes a pair with any of the existing element...
class newnode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def printPathUtil ( node , s , root_data ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT rem = root_data - node . dat...
Find the subarray with least average | Prints beginning and ending indexes of subarray of size k with minimum average ; k must be smaller than or equal to n ; Initialize beginning index of result ; Compute sum of first subarray of size k ; Initialize minimum sum as current sum ; Traverse from ( k + 1 ) ' th ▁ ▁ element...
def findMinAvgSubarray ( arr , n , k ) : NEW_LINE INDENT if ( n < k ) : return 0 NEW_LINE res_index = 0 NEW_LINE curr_sum = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT curr_sum += arr [ i ] NEW_LINE DEDENT min_sum = curr_sum NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT curr_sum += arr [ i ] - arr [ i - k ]...
Find the Largest number with given number of digits and sum of digits | Prints the smalles possible number with digit sum ' s ' and ' m ' number of digits . ; If sum of digits is 0 , then a number is possible only if number of digits is 1. ; Sum greater than the maximum possible sum . ; Create an array to store digits ...
def findLargest ( m , s ) : NEW_LINE INDENT if ( s == 0 ) : NEW_LINE INDENT if ( m == 1 ) : NEW_LINE INDENT print ( " Largest ▁ number ▁ is ▁ " , "0" , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ possible " , end = " " ) NEW_LINE DEDENT return NEW_LINE DEDENT if ( s > 9 * m ) : NEW_LINE INDENT pr...
Minimum number of jumps to reach end | Returns minimum number of jumps to reach arr [ h ] from arr [ l ] ; Base case : when source and destination are same ; when nothing is reachable from the given source ; Traverse through all the points reachable from arr [ l ] . Recursively get the minimum number of jumps needed to...
def minJumps ( arr , l , h ) : NEW_LINE INDENT if ( h == l ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( arr [ l ] == 0 ) : NEW_LINE INDENT return float ( ' inf ' ) NEW_LINE DEDENT min = float ( ' inf ' ) NEW_LINE for i in range ( l + 1 , h + 1 ) : NEW_LINE INDENT if ( i < l + arr [ l ] + 1 ) : NEW_LINE INDENT jump...
Camel and Banana Puzzle | DP | Stores the overlapping state ; Recursive function to find the maximum number of bananas that can be transferred to A distance using memoization ; Base Case where count of bananas is less that the given distance ; Base Case where count of bananas is less that camel 's capacity ; Base Case ...
dp = [ [ - 1 for i in range ( 3001 ) ] for j in range ( 1001 ) ] NEW_LINE def recBananaCnt ( A , B , C ) : NEW_LINE INDENT if ( B <= A ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( B <= C ) : NEW_LINE INDENT return B - A NEW_LINE DEDENT if ( A == 0 ) : NEW_LINE INDENT return B NEW_LINE DEDENT if ( dp [ A ] [ B ] !=...
Count of valid arrays of size P with elements in range [ 1 , N ] having duplicates at least M distance apart | Function to calculate the total number of arrays ; If the size of the array is P ; Check if all elements are used atlease once ; Check if this state is already calculated ; Initialize the result ; Use a number...
def calculate ( position , used , unused , P , M , dp ) : NEW_LINE INDENT if ( position == P ) : NEW_LINE INDENT if unused == 0 : NEW_LINE return 1 NEW_LINE else : NEW_LINE return 0 NEW_LINE DEDENT if ( dp [ position ] [ used ] [ unused ] != - 1 ) : NEW_LINE INDENT return dp [ position ] [ used ] [ unused ] NEW_LINE DE...
Minimum number of jumps to reach end | Returns Minimum number of jumps to reach end ; jumps [ 0 ] will hold the result ; Start from the second element , move from right to left and construct the jumps [ ] array where jumps [ i ] represents minimum number of jumps needed to reach arr [ m - 1 ] form arr [ i ] ; If arr [ ...
def minJumps ( arr , n ) : NEW_LINE INDENT jumps = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT jumps [ i ] = float ( ' inf ' ) NEW_LINE DEDENT elif ( arr [ i ] >= n - i - 1 ) : NEW_LINE INDENT jumps [ i ] = 1 NEW_LINE DEDENT else : N...
Count N | Stores the dp states ; Check if a number is a prime or not ; Function to generate all prime numbers that are less than or equal to n ; Base cases . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of as non - prime ; Function to find the count of N - digit numbers such that the sum ...
dp = [ [ - 1 ] * 100 ] * 1000 NEW_LINE prime = [ True ] * 1005 NEW_LINE def SieveOfEratosthenes ( n ) : NEW_LINE INDENT prime [ 0 ] = prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT pri...
Maximum number of groups that can receive fresh donuts distributed in batches of size K | Stores the result of the same recursive calls ; Recursive function to find the maximum number of groups that will receive fresh donuts ; Store the result for the current state ; Store the key and check if it is present in the hash...
memo = { } NEW_LINE def dfs ( V , left , K ) : NEW_LINE INDENT q = 0 NEW_LINE v = [ str ( int ) for int in V ] NEW_LINE key = " , " . join ( v ) NEW_LINE key += str ( left ) NEW_LINE if key in memo : NEW_LINE INDENT return memo [ key ] NEW_LINE DEDENT elif left == 0 : NEW_LINE INDENT for i in range ( 1 , K ) : NEW_LINE...
Smallest subarray with sum greater than a given value | Returns length of smallest subarray with sum greater than x . If there is no subarray with given sum , then returns n + 1 ; Initialize length of smallest subarray as n + 1 ; Pick every element as starting point ; Initialize sum starting with current start ; If fir...
def smallestSubWithSum ( arr , n , x ) : NEW_LINE INDENT min_len = n + 1 NEW_LINE for start in range ( 0 , n ) : NEW_LINE INDENT curr_sum = arr [ start ] NEW_LINE if ( curr_sum > x ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for end in range ( start + 1 , n ) : NEW_LINE INDENT curr_sum += arr [ end ] NEW_LINE if curr_...
Smallest subarray with sum greater than a given value | Returns length of smallest subarray with sum greater than x . If there is no subarray with given sum , then returns n + 1 ; Initialize current sum and minimum length ; Initialize starting and ending indexes ; Keep adding array elements while current sum is smaller...
def smallestSubWithSum ( arr , n , x ) : NEW_LINE INDENT curr_sum = 0 NEW_LINE min_len = n + 1 NEW_LINE start = 0 NEW_LINE end = 0 NEW_LINE while ( end < n ) : NEW_LINE INDENT while ( curr_sum <= x and end < n ) : NEW_LINE INDENT curr_sum += arr [ end ] NEW_LINE end += 1 NEW_LINE DEDENT while ( curr_sum > x and start <...
Sum of nodes on the longest path from root to leaf node | function to get a new node ; put in the data ; function to find the Sum of nodes on the longest path from root to leaf node ; if true , then we have traversed a root to leaf path ; update maximum Length and maximum Sum according to the given conditions ; recur f...
class getNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def SumOfLongRootToLeafPath ( root , Sum , Len , maxLen , maxSum ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT if ( maxLen [ 0 ] < Len ) : NEW_LINE ...
Count L | Function to find the number of arrays of length L such that each element divides the next element ; Stores the number of sequences of length i that ends with j ; Base Case ; Iterate over the range [ 0 , l ] ; Iterate for all multiples of j ; Incrementing dp [ i + 1 ] [ k ] by dp [ i ] [ j ] as the next elemen...
def numberOfArrays ( n , l ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for i in range ( l + 1 ) ] NEW_LINE dp [ 0 ] [ 1 ] = 1 NEW_LINE for i in range ( l ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT for k in range ( j , n + 1 , j ) : NEW_LINE INDENT dp [ i + 1 ] [ k ] += dp [ i ] [ j...
Count minimum steps to get the given desired array | Returns count of minimum operations to convert a zero array to target array with increment and doubling operations . This function computes count by doing reverse steps , i . e . , convert target to zero array . ; Initialize result ( Count of minimum moves ) ; Keep l...
def countMinOperations ( target , n ) : NEW_LINE INDENT result = 0 ; NEW_LINE while ( True ) : NEW_LINE INDENT zero_count = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( ( target [ i ] & 1 ) > 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT elif ( target [ i ] == 0 ) : NEW_LINE INDENT zero_count +=...
Maximize sum of odd | Function to find the maximum sum of array elements chosen by Player A according to the given criteria ; Store the key ; Corner Case ; Check if all the elements can be taken or not ; If the difference is less than or equal to the available chances then pick all numbers ; Find the sum of array eleme...
def recursiveChoosing ( arr , start , M , dp ) : NEW_LINE INDENT key = ( start , M ) NEW_LINE if start >= N : NEW_LINE INDENT return 0 NEW_LINE DEDENT if N - start <= 2 * M : NEW_LINE INDENT return sum ( arr [ start : ] ) NEW_LINE DEDENT psa = 0 NEW_LINE total = sum ( arr [ start : ] ) NEW_LINE if key in dp : NEW_LINE ...
Number of subsets with product less than k | Python3 to find the count subset having product less than k ; declare four vector for dividing array into two halves and storing product value of possible subsets for them ; ignore element greater than k and divide array into 2 halves ; ignore element if greater than k ; gen...
import bisect NEW_LINE def findSubset ( arr , n , k ) : NEW_LINE INDENT vect1 , vect2 , subset1 , subset2 = [ ] , [ ] , [ ] , [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] > k : NEW_LINE INDENT continue NEW_LINE DEDENT if i <= n // 2 : NEW_LINE INDENT vect1 . append ( arr [ i ] ) NEW_LINE DEDENT ...
Maximum Sum Subsequence made up of consecutive elements of different parity | Function to calculate the maximum sum subsequence with consecutive terms having different parity ; Base Case ; Store the parity of number at the ith position ; If the dp state has already been calculated , return it ; If the array is traverse...
def maxSum ( arr , i , n , prev , is_selected , dp ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT cur = abs ( arr [ i ] ) % 2 NEW_LINE if ( dp [ i ] [ prev ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ prev ] NEW_LINE DEDENT if ( i == n - 1 and is_selected == 0 ) : NEW_LINE INDENT dp [ i ...
Find minimum number of merge operations to make an array palindrome | Returns minimum number of count operations required to make arr [ ] palindrome ; Initialize result ; Start from two corners ; If corner elements are same , problem reduces arr [ i + 1. . j - 1 ] ; If left element is greater , then we merge right two ...
def findMinOps ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE i , j = 0 , n - 1 NEW_LINE while i <= j : NEW_LINE INDENT if arr [ i ] == arr [ j ] : NEW_LINE INDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT elif arr [ i ] > arr [ j ] : NEW_LINE INDENT j -= 1 NEW_LINE arr [ j ] += arr [ j + 1 ] NEW_LINE ans += 1 NEW_LINE DE...
Find the smallest positive integer value that cannot be represented as sum of any subset of a given array | Returns the smallest number that cannot be represented as sum of subset of elements from set represented by sorted array arr [ 0. . n - 1 ] ; Initialize result ; Traverse the array and increment ' res ' if arr [ ...
def findSmallest ( arr , n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] <= res : NEW_LINE INDENT res = res + arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr1 = [ 1 , 3 , 4 , 5 ] NEW_LINE n1 = len ( arr1 ) NEW_LI...
Count distinct possible Bitwise XOR values of subsets of an array | Stores the Bitwise XOR of every possible subset ; Function to generate all combinations of subsets and store their Bitwise XOR in set S ; If the end of the subset is reached ; Stores the Bitwise XOR of the current subset ; Iterate comb [ ] to find XOR ...
s = set ( [ ] ) NEW_LINE def countXOR ( arr , comb , start , end , index , r ) : NEW_LINE INDENT if ( index == r ) : NEW_LINE INDENT new_xor = 0 NEW_LINE for j in range ( r ) : NEW_LINE INDENT new_xor ^= comb [ j ] NEW_LINE DEDENT s . add ( new_xor ) NEW_LINE return NEW_LINE DEDENT i = start NEW_LINE while i <= end and...
Size of The Subarray With Maximum Sum | Python3 program to print largest contiguous array sum ; Function to find the maximum contiguous subarray and print its starting and end index ; Driver program to test maxSubArraySum
from sys import maxsize NEW_LINE def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - maxsize - 1 NEW_LINE max_ending_here = 0 NEW_LINE start = 0 NEW_LINE end = 0 NEW_LINE s = 0 NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT max_ending_here += a [ i ] NEW_LINE if max_so_far < max_ending_here : NEW_L...
Longest subarray of an array which is a subsequence in another array | Function to find the length of the longest subarray in arr1 which is a subsequence in arr2 ; Length of the array arr1 ; Length of the array arr2 ; Length of the required longest subarray ; Initialize DParray ; Traverse array arr1 ; Traverse array ar...
def LongSubarrSeq ( arr1 , arr2 ) : NEW_LINE INDENT M = len ( arr1 ) ; NEW_LINE N = len ( arr2 ) ; NEW_LINE maxL = 0 ; NEW_LINE DP = [ [ 0 for i in range ( N + 1 ) ] for j in range ( M + 1 ) ] ; NEW_LINE for i in range ( 1 , M + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( arr1 [ i - 1 ] ==...
Find minimum difference between any two elements | Returns minimum difference between any pair ; Initialize difference as infinite ; Find the min diff by comparing difference of all possible pairs in given array ; Return min diff ; Driver code
def findMinDiff ( arr , n ) : NEW_LINE INDENT diff = 10 ** 20 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if abs ( arr [ i ] - arr [ j ] ) < diff : NEW_LINE INDENT diff = abs ( arr [ i ] - arr [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return diff NEW_LINE DEDENT arr = ...
Count possible N | DP array for memoization ; Utility function to count N digit numbers with digit i not appearing more than max_digit [ i ] consecutively ; If number with N digits is generated ; Create a reference variable ; Check if the current state is already computed before ; Initialize ans as zero ; Check if coun...
dp = [ [ [ - 1 for i in range ( 5005 ) ] for i in range ( 12 ) ] for i in range ( 12 ) ] NEW_LINE def findCountUtil ( N , maxDigit , position , previous , count ) : NEW_LINE INDENT global dp NEW_LINE if ( position == N ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT ans = dp [ position ] [ previous ] [ count ] NEW_LINE if...
Find minimum difference between any two elements | Returns minimum difference between any pair ; Sort array in non - decreasing order ; Initialize difference as infinite ; Find the min diff by comparing adjacent pairs in sorted array ; Return min diff ; Driver code
def findMinDiff ( arr , n ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE diff = 10 ** 20 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if arr [ i + 1 ] - arr [ i ] < diff : NEW_LINE INDENT diff = arr [ i + 1 ] - arr [ i ] NEW_LINE DEDENT DEDENT return diff NEW_LINE DEDENT arr = [ 1 , 5 , 3 , 19 , 18 , 25 ] NEW...
Space optimization using bit manipulations | Python3 program to mark numbers as multiple of 2 or 5 ; Driver code ; Iterate through a to b , If it is a multiple of 2 or 5 Mark index in array as 1
import math NEW_LINE a = 2 NEW_LINE b = 10 NEW_LINE size = abs ( b - a ) + 1 NEW_LINE array = [ 0 ] * size NEW_LINE for i in range ( a , b + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 or i % 5 == 0 ) : NEW_LINE INDENT array [ i - a ] = 1 NEW_LINE DEDENT DEDENT print ( " MULTIPLES ▁ of ▁ 2 ▁ and ▁ 5 : " ) NEW_LINE for i in r...
Remove all nodes which don 't lie in any path with sum>= k | A utility function to create a new Binary Tree node with given data ; print the tree in LVR ( Inorder traversal ) way . ; Main function which truncates the binary tree . ; Base Case ; Initialize left and right Sums as Sum from root to this node ( including th...
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def Print ( root ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT Print ( root . left ) NEW_LINE print ( root . data , end = " ▁ " ) NEW_LINE Print...
Tree Traversals ( Inorder , Preorder and Postorder ) | A class that represents an individual node in a Binary Tree ; A function to do postorder tree traversal ; First recur on left child ; the recur on right child ; now print the data of node ; A function to do inorder tree traversal ; First recur on left child ; then ...
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . val = key NEW_LINE DEDENT DEDENT def printPostorder ( root ) : NEW_LINE INDENT if root : NEW_LINE INDENT printPostorder ( root . left ) NEW_LINE printPostorder ( root . right ) NEW_...
Maximum subarray sum possible after removing at most K array elements | Python3 program to implement the above approach ; Function to find the maximum subarray sum greater than or equal to 0 by removing K array elements ; Base case ; If overlapping subproblems already occurred ; Include current element in the subarray ...
M = 100 NEW_LINE def mxSubSum ( i , arr , j ) : NEW_LINE INDENT global dp NEW_LINE if ( i == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( 0 , arr [ i ] ) NEW_LINE return dp [ i ] [ j ] NEW_LINE DEDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT X = max ( 0 , arr [ i ] + mxSubSum...
Minimum number of operations required to make all elements of at least one row of given Matrix prime | Python 3 program to implement the above approach ; Function to generate all prime numbers using Sieve of Eratosthenes ; Function to check if a number is prime or not ; prime [ i ] : Check if i is a prime number or not...
from math import sqrt NEW_LINE prime = [ True for i in range ( 10001 ) ] NEW_LINE def sieve ( n ) : NEW_LINE INDENT global prime NEW_LINE for p in range ( 2 , int ( sqrt ( 10000 ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , 10001 , p ) : NEW_LINE INDENT prime [ i ...
Minimize cost to empty given array where cost of removing an element is its absolute difference with Time instant | Python3 program for the above approach ; Function to find the minimum cost to delete all array elements ; Sort the input array ; Store the maximum time to delete the array in the worst case ; Store the re...
INF = 10000 NEW_LINE def minCost ( arr , n ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE m = 2 * n NEW_LINE cost = [ [ INF for i in range ( m + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE cost [ 0 ] [ 0 ] = 0 NEW_LINE prev = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT prev = cost [ i - 1 ] [ 0 ] NEW_LIN...
Space optimization using bit manipulations | Python3 code to for marking multiples ; index >> 5 corresponds to dividing index by 32 index & 31 corresponds to modulo operation of index by 32 Function to check value of bit position whether it is zero or one ; Sets value of bit for corresponding index ; Driver code ; Size...
import math NEW_LINE def checkbit ( array , index ) : NEW_LINE INDENT return array [ index >> 5 ] & ( 1 << ( index & 31 ) ) NEW_LINE DEDENT def setbit ( array , index ) : NEW_LINE INDENT array [ index >> 5 ] |= ( 1 << ( index & 31 ) ) NEW_LINE DEDENT a = 2 NEW_LINE b = 10 NEW_LINE size = abs ( b - a ) NEW_LINE size = m...
Longest Span with same Sum in two Binary arrays | Returns length of the longest common subarray with same sum ; Initialize result ; One by one pick all possible starting points of subarrays ; Initialize sums of current subarrays ; Conider all points for starting with arr [ i ] ; Update sums ; If sums are same and curre...
def longestCommonSum ( arr1 , arr2 , n ) : NEW_LINE INDENT maxLen = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT sum1 += arr1 [ j ] NEW_LINE sum2 += arr2 [ j ] NEW_LINE if ( sum1 == sum2 ) : NEW_LINE INDENT len = j - i + 1 NEW_LINE ...
Number of Longest Increasing Subsequences | Function to count the number of LIS in the array nums [ ] ; Base Case ; Initialize dp_l array with 1 s ; Initialize dp_c array with 1 s ; If current element is smaller ; Store the maximum element from dp_l ; Stores the count of LIS ; Traverse dp_l and dp_c simultaneously ; Up...
def findNumberOfLIS ( nums ) : NEW_LINE INDENT if not nums : NEW_LINE INDENT return 0 NEW_LINE DEDENT n = len ( nums ) NEW_LINE dp_l = [ 1 ] * n NEW_LINE dp_c = [ 1 ] * n NEW_LINE for i , num in enumerate ( nums ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if nums [ i ] <= nums [ j ] : NEW_LINE INDENT con...
Check if a Binary Tree contains node values in strictly increasing and decreasing order at even and odd levels | ''Tree node ; ''Function to return new tree node ; ''Function to check if the tree is even-odd tree ; '' Stores nodes of each level ; '' Store the current level of the binary tree ; '' Traverse until the q...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . val = data NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE return temp NEW_LINE DEDENT def checkEvenOddLevel ( root ) : NEW_LINE INDENT ...
Longest Span with same Sum in two Binary arrays | Returns largest common subarray with equal number of 0 s and 1 s ; Find difference between the two ; Creates an empty hashMap hM ; Initialize sum of elements ; Initialize result ; Traverse through the given array ; Add current element to sum ; To handle sum = 0 at last ...
def longestCommonSum ( arr1 , arr2 , n ) : NEW_LINE INDENT arr = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = arr1 [ i ] - arr2 [ i ] ; NEW_LINE DEDENT hm = { } NEW_LINE sum = 0 NEW_LINE max_len = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE if ( ...
Minimum length of Run Length Encoding possible by removing at most K characters from a given string | Python3 program to implement the above approach ; Function which solves the desired problem ; Base Case ; If the entire string has been traversed ; If precomputed subproblem occurred ; Minimum run length encoding by re...
maxN = 20 NEW_LINE dp = [ [ [ [ 0 for i in range ( maxN ) ] for j in range ( 27 ) ] for k in range ( 27 ) ] for l in range ( maxN ) ] NEW_LINE def solve ( s , n , idx , k , last , count ) : NEW_LINE INDENT if ( k < 0 ) : NEW_LINE INDENT return n + 1 NEW_LINE DEDENT if ( idx == n ) : NEW_LINE INDENT return 0 NEW_LINE DE...
Count unique paths is a matrix whose product of elements contains odd number of divisors | Python3 program for the above approach ; Function to calculate and store all the paths product in vector ; Base Case ; If reaches the bottom right corner and product is a perfect square ; Find square root ; If square root is an i...
import math NEW_LINE countPaths = 0 ; NEW_LINE def CountUniquePaths ( a , i , j , m , n , ans ) : NEW_LINE INDENT if ( i >= m or j >= n ) : NEW_LINE INDENT return ; NEW_LINE DEDENT global countPaths ; NEW_LINE if ( i == m - 1 and j == n - 1 ) : NEW_LINE INDENT sr = math . sqrt ( ans * a [ i ] [ j ] ) ; NEW_LINE if ( ( ...
Maximize sum by selecting M elements from the start or end of rows of a Matrix | Function to select m elements having maximum sum ; Base case ; If precomputed subproblem occurred ; Either skip the current row ; Iterate through all the possible segments of current row ; Check if it is possible to select elements from i ...
def mElementsWithMaxSum ( matrix , M , block , dp ) : NEW_LINE INDENT if block == len ( matrix ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ block ] [ M ] != - 1 ) : NEW_LINE INDENT return dp [ block ] [ M ] NEW_LINE DEDENT ans = mElementsWithMaxSum ( matrix , M , block + 1 , dp ) NEW_LINE for i in range ( len...
Find the last remaining element after repeated removal of odd and even indexed elements alternately | Function to calculate the last remaining element from the sequence ; If dp [ n ] is already calculated ; Base Case : ; Recursive Call ; Return the value of dp [ n ] ; Given N ; Stores the ; Function Call
def lastRemaining ( n , dp ) : NEW_LINE INDENT if n in dp : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ n ] = 2 * ( 1 + n // 2 - lastRemaining ( n // 2 , dp ) ) NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT N = 5 NEW_LINE dp = { } NE...
Maximum subsequence sum possible by multiplying each element by its index | Initialize dp array ; Function to find the maximum sum of the subsequence formed ; Base Case ; If already calculated state occurs ; Include the current element ; Exclude the current element ; Update the maximum ans ; Function to calculate maxim...
dp = [ [ - 1 for x in range ( 1005 ) ] for y in range ( 1005 ) ] NEW_LINE def maximumSumUtil ( a , index , count , n ) : NEW_LINE INDENT if ( index > n or count > n + 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ index ] [ count ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ count ] NEW_LINE DEDENT ans1 ...
Sort an array according to absolute difference with given value | Function to sort an array according absolute difference with x . ; Store values in a map with the difference with X as key ; Update the values of array ; Function to print the array ; Driver code
def rearrange ( arr , n , x ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ arr [ i ] ] = abs ( x - arr [ i ] ) NEW_LINE DEDENT m = { k : v for k , v in sorted ( m . items ( ) , key = lambda item : item [ 1 ] ) } NEW_LINE i = 0 NEW_LINE for it in m . keys ( ) : NEW_LINE INDENT arr [ i ] ...
Minimum Steps to obtain N from 1 by the given operations | Python3 program to implement the above approach ; Base Case ; Recursive Call for n - 1 ; Check if n is divisible by 2 ; Check if n is divisible by 3 ; Returns a tuple ( a , b ) , where a : Minimum steps to obtain x from 1 b : Previous number ; Function that fin...
def find_sequence ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 1 , - 1 NEW_LINE DEDENT ans = ( find_sequence ( n - 1 ) [ 0 ] + 1 , n - 1 ) NEW_LINE if n % 2 == 0 : NEW_LINE INDENT div_by_2 = find_sequence ( n // 2 ) NEW_LINE if div_by_2 [ 0 ] < ans [ 0 ] : NEW_LINE INDENT ans = ( div_by_2 [ 0 ] + 1 , n //...
Count of vessels completely filled after a given time | Function to find the number of completely filled vessels ; Store the vessels ; Assuming all water is present in the vessel at the first level ; Store the number of vessel that are completely full ; Traverse all the levels ; Number of vessel at each level is j ; Ca...
def FindNoOfFullVessels ( n , t ) : NEW_LINE INDENT Matrix = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE Matrix [ 0 ] [ 0 ] = t * 1.0 NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT exceededwater = Matrix [ i ] [ j ] - 1.0 NEW_LINE if ( exceed...
Sort an array in wave form | Python function to sort the array arr [ 0. . n - 1 ] in wave form , i . e . , arr [ 0 ] >= arr [ 1 ] <= arr [ 2 ] >= arr [ 3 ] <= arr [ 4 ] >= arr [ 5 ] ; sort the array ; Swap adjacent elements ; Driver program
def sortInWave ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( 0 , n - 1 , 2 ) : NEW_LINE INDENT arr [ i ] , arr [ i + 1 ] = arr [ i + 1 ] , arr [ i ] NEW_LINE DEDENT DEDENT arr = [ 10 , 90 , 49 , 2 , 1 , 5 , 23 ] NEW_LINE sortInWave ( arr , len ( arr ) ) NEW_LINE for i in range ( 0 , len ( arr )...
Count of maximum occurring subsequence using only those characters whose indices are in GP | Function to count maximum occurring subsequence using only those characters whose indexes are in GP ; Initialize 1 - D array and 2 - D dp array to 0 ; Iterate till the length of the given string ; Update ans for 1 - length subs...
def findMaxTimes ( S ) : NEW_LINE INDENT arr = [ 0 ] * 26 NEW_LINE dp = [ [ 0 for x in range ( 26 ) ] for y in range ( 26 ) ] NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT now = ord ( S [ i ] ) - ord ( ' a ' ) NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT dp [ j ] [ now ] += arr [ j ] NEW_LINE DEDENT arr [...
Sort an array in wave form | Python function to sort the array arr [ 0. . n - 1 ] in wave form , i . e . , arr [ 0 ] >= arr [ 1 ] <= arr [ 2 ] >= arr [ 3 ] <= arr [ 4 ] >= arr [ 5 ] ; Traverse all even elements ; If current even element is smaller than previous ; If current even element is smaller than next ; Driver pr...
def sortInWave ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n , 2 ) : NEW_LINE INDENT if ( i > 0 and arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT arr [ i ] , arr [ i - 1 ] = arr [ i - 1 ] , arr [ i ] NEW_LINE DEDENT if ( i < n - 1 and arr [ i ] < arr [ i + 1 ] ) : NEW_LINE INDENT arr [ i ] , arr [ i + 1 ] = arr ...
Remove all nodes which don 't lie in any path with sum>= k | binary tree node contains data field , left and right pointer ; inorder traversal ; Function to remove all nodes which do not lie in th sum path ; Base case ; Recur for left and right subtree ; if node is leaf and sum is found greater than data than remove no...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def inorder ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( root . left ) NEW_LINE print ( root . d...
Count all possible unique sum of series K , K + 1 , K + 2 , K + 3 , K + 4 , ... , K + N | Function to count the unique sum ; Set fsum [ 0 ] as ar [ 0 ] ; Set rsum [ 0 ] as ar [ n ] ; For each i update fsum [ i ] with ar [ i ] + fsum [ i - 1 ] ; For each i from n - 1 , update rsum [ i ] with ar [ i ] + fsum [ i + 1 ] ; ...
def count_unique_sum ( n ) : NEW_LINE INDENT ar = [ 0 ] * ( n + 1 ) NEW_LINE fsum = [ 0 ] * ( n + 1 ) NEW_LINE rsum = [ 0 ] * ( n + 1 ) NEW_LINE ans = 1 NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT ar [ i ] = i NEW_LINE DEDENT fsum [ 0 ] = ar [ 0 ] NEW_LINE rsum [ n ] = ar [ n ] NEW_LINE for i in range ( 1 ,...
Merge an array of size n into another array of size m + n | Python program to Merge an array of size n into another array of size m + n ; Function to move m elements at the end of array mPlusN [ ] ; Merges array N [ ] of size n into array mPlusN [ ] of size m + n ; Current index of i / p part of mPlusN [ ] ; Current in...
NA = - 1 NEW_LINE def moveToEnd ( mPlusN , size ) : NEW_LINE INDENT i = 0 NEW_LINE j = size - 1 NEW_LINE for i in range ( size - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( mPlusN [ i ] != NA ) : NEW_LINE INDENT mPlusN [ j ] = mPlusN [ i ] NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT DEDENT def merge ( mPlusN , N , m , n ) : NEW_...
Count of N | Function to return the count of such numbers ; For 1 - digit numbers , the count is 10 irrespective of K ; dp [ j ] stores the number of such i - digit numbers ending with j ; Stores the results of length i ; Initialize count for 1 - digit numbers ; Compute values for count of digits greater than 1 ; Find ...
def getCount ( n , K ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 10 NEW_LINE DEDENT dp = [ 0 ] * 11 NEW_LINE next = [ 0 ] * 11 NEW_LINE for i in range ( 1 , 9 + 1 ) : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 9 + 1 ) : NEW_LINE INDENT l =...
Sort 1 to N by swapping adjacent elements | Return true if array can be sorted otherwise false ; Check bool array B and sorts elements for continuous sequence of 1 ; Sort array A from i to j ; Check if array is sorted or not ; Driver program to test sortedAfterSwap ( )
def sortedAfterSwap ( A , B , n ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( B [ i ] == 1 ) : NEW_LINE INDENT j = i NEW_LINE while ( B [ j ] == 1 ) : NEW_LINE INDENT j = j + 1 NEW_LINE DEDENT A = A [ 0 : i ] + sorted ( A [ i : j + 1 ] ) + A [ j + 1 : ] NEW_LINE i = j NEW_LINE DEDENT DEDENT fo...
Print negative weight cycle in a Directed Graph | Structure to represent a weighted edge in graph ; Structure to represent a directed and weighted graph ; V . Number of vertices , E . Number of edges ; Graph is represented as an array of edges . ; Creates a new graph with V vertices and E edges ; Function runs Bellman ...
class Edge : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . src = 0 NEW_LINE self . dest = 0 NEW_LINE self . weight = 0 NEW_LINE DEDENT DEDENT class Graph : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . V = 0 NEW_LINE self . E = 0 NEW_LINE self . edge = [ ] NEW_LINE DEDENT DEDENT def cr...
Sort 1 to N by swapping adjacent elements | Return true if array can be sorted otherwise false ; Check if array is sorted or not ; Driver program
def sortedAfterSwap ( A , B , n ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if B [ i ] : NEW_LINE INDENT if A [ i ] != i + 1 : NEW_LINE INDENT A [ i ] , A [ i + 1 ] = A [ i + 1 ] , A [ i ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if A [ i ] != i + 1 : NEW_LINE INDENT r...
Sort an array containing two types of elements | Method for segregation 0 and 1 given input array ; Driver Code
def segregate0and1 ( arr , n ) : NEW_LINE INDENT type0 = 0 ; type1 = n - 1 NEW_LINE while ( type0 < type1 ) : NEW_LINE INDENT if ( arr [ type0 ] == 1 ) : NEW_LINE INDENT arr [ type0 ] , arr [ type1 ] = arr [ type1 ] , arr [ type0 ] NEW_LINE type1 -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT type0 += 1 NEW_LINE DEDENT DE...
Pentanacci Numbers | Recursive program to find the Nth Pentanacci number ; Function to print the Nth Pentanacci number ; Driver code
def printpentaRec ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 or \ n == 2 or n == 3 or n == 4 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( n == 5 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( printpentaRec ( n - 1 ) + printpentaRec ( n - 2 ) + printpentaRec ( n - 3 ) + printpenta...
Count Inversions in an array | Set 1 ( Using Merge Sort ) | Python3 program to count inversions in an array ; Driver Code
def getInvCount ( arr , n ) : NEW_LINE INDENT inv_count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] ) : NEW_LINE INDENT inv_count += 1 NEW_LINE DEDENT DEDENT DEDENT return inv_count NEW_LINE DEDENT arr = [ 1 , 20 , 6 , 4 , 5 ] NEW_LINE n ...
Find if there is a path between two vertices in an undirected graph | Python3 program to check if there is exist a path between two vertices of an undirected graph . ; A BFS based function to check whether d is reachable from s . ; Base case ; Mark all the vertices as not visited ; Create a queue for BFS ; Mark the cur...
from collections import deque NEW_LINE def addEdge ( v , w ) : NEW_LINE INDENT global adj NEW_LINE adj [ v ] . append ( w ) NEW_LINE adj [ w ] . append ( v ) NEW_LINE DEDENT def isReachable ( s , d ) : NEW_LINE INDENT if ( s == d ) : NEW_LINE INDENT return True NEW_LINE DEDENT visited = [ False for i in range ( V ) ] N...
Range queries for alternatively addition and subtraction on given Array | Function to find the result of alternatively adding and subtracting elements in the range [ L , R ] ; A boolean variable flag to alternatively add and subtract ; Iterate from [ L , R ] ; If flag is False , then add & toggle the flag ; If flag is ...
def findResultUtil ( arr , L , R ) : NEW_LINE INDENT result = 0 NEW_LINE flag = False NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( flag == False ) : NEW_LINE INDENT result = result + arr [ i ] NEW_LINE flag = True NEW_LINE DEDENT else : NEW_LINE INDENT result = result - arr [ i ] NEW_LINE flag = False N...
Two elements whose sum is closest to zero | Python3 code to find Two elements whose sum is closest to zero ; Array should have at least two elements ; Initialization of values ; Driver program to test above function
def minAbsSumPair ( arr , arr_size ) : NEW_LINE INDENT inv_count = 0 NEW_LINE if arr_size < 2 : NEW_LINE INDENT print ( " Invalid ▁ Input " ) NEW_LINE return NEW_LINE DEDENT min_l = 0 NEW_LINE min_r = 1 NEW_LINE min_sum = arr [ 0 ] + arr [ 1 ] NEW_LINE for l in range ( 0 , arr_size - 1 ) : NEW_LINE INDENT for r in rang...
Maximize sum of topmost elements of S stacks by popping at most N elements | Python3 program to maximize the sum of top of the stack values of S stacks by popping at most N element ; Function for computing the maximum sum at the top of the stacks after popping at most N elements from S stack ; Constructing a dp matrix ...
import sys NEW_LINE def maximumSum ( S , M , N , stacks ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( N + 1 ) ] for y in range ( S + 1 ) ] NEW_LINE for i in range ( S ) : NEW_LINE INDENT for j in range ( N + 1 ) : NEW_LINE INDENT for k in range ( min ( j , M ) + 1 ) : NEW_LINE INDENT dp [ i + 1 ] [ j ] = max ( dp [ i...
Abstraction of Binary Search | ''Function to find X such that it is less than the target value and function is f(x) = x ^ 2 ; '' Initialise start and end ; '' Loop till start <= end ; '' Find the mid ; '' Check for the left half ; Store the result ; Reinitialize the start point ; '' Check for the right half ; '' Print ...
def findX ( targetValue ) : NEW_LINE INDENT start = 0 ; NEW_LINE end = targetValue ; NEW_LINE mid = 0 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = start + ( end - start ) // 2 ; NEW_LINE if ( mid * mid <= targetValue ) : NEW_LINE INDENT result = mid NEW_LINE start = mid + 1 ; NEW_LINE DEDENT else : NEW_LIN...
Two elements whose sum is closest to zero | Python3 implementation using STL ; Modified to sort by abolute values ; Absolute value shows how close it is to zero ; If found an even close value update min and store the index ; Driver code
import sys NEW_LINE def findMinSum ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( not abs ( arr [ i - 1 ] ) < abs ( arr [ i ] ) ) : NEW_LINE INDENT arr [ i - 1 ] , arr [ i ] = arr [ i ] , arr [ i - 1 ] NEW_LINE DEDENT DEDENT Min = sys . maxsize NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i...
Number of ways to paint K cells in 3 x N grid such that no P continuous columns are left unpainted | Python 3 implementation to find the number of ways to paint K cells of 3 x N grid such that No two adjacent cells are painted ; Visited array to keep track of which columns were painted ; Recursive Function to compute t...
mod = 1e9 + 7 NEW_LINE MAX = 301 NEW_LINE MAXP = 3 NEW_LINE MAXK = 600 NEW_LINE MAXPREV = 4 NEW_LINE dp = [ [ [ [ - 1 for x in range ( MAXPREV + 1 ) ] for y in range ( MAXK ) ] for z in range ( MAXP + 1 ) ] for k in range ( MAX ) ] NEW_LINE vis = [ False ] * MAX NEW_LINE def helper ( col , prevCol , painted , prev , N ...
Convert undirected connected graph to strongly connected directed graph | To store the assigned Edges ; Flag variable to check Bridges ; Function to implement DFS Traversal ; Mark the current node as visited ; Update the order of node v ; Update the bridge_detect for node v ; Traverse the adjacency list of Node v ; Ign...
ans = [ ] NEW_LINE flag = 1 ; NEW_LINE def dfs ( adj , order , bridge_detect , mark , v , l ) : NEW_LINE INDENT global flag NEW_LINE mark [ v ] = 1 ; NEW_LINE order [ v ] = order [ l ] + 1 ; NEW_LINE bridge_detect [ v ] = order [ v ] ; NEW_LINE for i in range ( len ( adj [ v ] ) ) : NEW_LINE INDENT u = adj [ v ] [ i ] ...
Shortest Un | Bool function for checking an array elements are in increasing ; Bool function for checking an array elements are in decreasing ; increasing and decreasing are two functions . if function return True value then print 0 otherwise 3. ; Driver code
def increasing ( a , n ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( a [ i ] >= a [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def decreasing ( a , n ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( a [ i ] < a [ i + 1 ] )...
Find the maximum path sum between two leaves of a binary tree | Python program to find maximumpath sum between two leaves of a binary tree ; A binary tree node ; Utility function to find maximum sum between anytwo leaves . This function calculates two values : 1 ) Maximum path sum between two leaves which are stored in...
INT_MIN = - 2 ** 32 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def maxPathSumUtil ( root , res ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT ls = ...
Minimum number of swaps required to sort an array | Function returns the minimum number of swaps required to sort the array ; Create two arrays and use as pairs where first array is element and second array is position of first element ; Sort the array by array element values to get right position of every element as t...
def minSwaps ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE arrpos = [ * enumerate ( arr ) ] NEW_LINE arrpos . sort ( key = lambda it : it [ 1 ] ) NEW_LINE vis = { k : False for k in range ( n ) } NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if vis [ i ] or arrpos [ i ] [ 0 ] == i : NEW_LINE IND...
Minimum number of swaps required to sort an array | swap function ; indexOf function ; Return the minimum number of swaps required to sort the array ; This is checking whether the current element is at the right place or not ; Swap the current element with the right index so that arr [ 0 ] to arr [ i ] is sorted ; Driv...
def swap ( arr , i , j ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE arr [ i ] = arr [ j ] NEW_LINE arr [ j ] = temp NEW_LINE DEDENT def indexOf ( arr , ele ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] == ele ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE ...
Minimum number of swaps required to sort an array | Return the minimum number of swaps required to sort the array ; Dictionary which stores the indexes of the input array ; This is checking whether the current element is at the right place or not ; If not , swap this element with the index of the element which should c...
def minSwap ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE temp = arr . copy ( ) NEW_LINE h = { } NEW_LINE temp . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT h [ arr [ i ] ] = i NEW_LINE DEDENT init = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != temp [ i ] ) : NEW_LINE INDENT ans += ...
Union and Intersection of two sorted arrays | Function prints union of arr1 [ ] and arr2 [ ] m is the number of elements in arr1 [ ] n is the number of elements in arr2 [ ] ; Print remaining elements of the larger array ; Driver program to test above function
def printUnion ( arr1 , arr2 , m , n ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE while i < m and j < n : NEW_LINE INDENT if arr1 [ i ] < arr2 [ j ] : NEW_LINE INDENT print ( arr1 [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT elif arr2 [ j ] < arr1 [ i ] : NEW_LINE INDENT print ( arr2 [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT el...
Union and Intersection of two sorted arrays | Python3 program to find union of two sorted arrays ( Handling Duplicates ) ; Taking max element present in either array ; Finding elements from 1 st array ( non duplicates only ) . Using another array for storing union elements of both arrays Assuming max element present in...
def UnionArray ( arr1 , arr2 ) : NEW_LINE INDENT m = arr1 [ - 1 ] NEW_LINE n = arr2 [ - 1 ] NEW_LINE ans = 0 NEW_LINE if m > n : NEW_LINE INDENT ans = m NEW_LINE DEDENT else : NEW_LINE INDENT ans = n NEW_LINE DEDENT newtable = [ 0 ] * ( ans + 1 ) NEW_LINE print ( arr1 [ 0 ] , end = " ▁ " ) NEW_LINE newtable [ arr1 [ 0 ...