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 suffix sum upto 4 ; For all other values of x ; For all x >= 2 , every y = 0 and every y = 1 makes a valid pair ; Return the count of pairs ; Driver code
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_LINE INDENT if ( X [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( X [ i ] == 1 ) : NEW_LINE INDENT total_pairs += suffix [ 0 ] NEW_LINE continue NEW_LINE DEDENT elif ( X [ i ] == 2 ) : NEW_LINE INDENT total_pairs += suffix [ 5 ] NEW_LINE DEDENT elif ( X [ i ] == 3 ) : NEW_LINE INDENT total_pairs += ( suffix [ 2 ] + suffix [ 4 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT total_pairs += suffix [ X [ i ] + 1 ] NEW_LINE DEDENT total_pairs += suffix [ 0 ] + suffix [ 1 ] NEW_LINE DEDENT return total_pairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = [ 10 , 19 , 18 ] NEW_LINE Y = [ 11 , 15 , 9 ] NEW_LINE m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE print ( countPairs ( X , Y , m , n ) ) NEW_LINE DEDENT
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 through an edge or not ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Store all distinct elements in a set ; Return answer ; Driver code ; Function call
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 for j in range ( M ) : NEW_LINE INDENT if i != 0 : NEW_LINE INDENT if A [ i - 1 ] [ j ] == A [ i ] [ j ] : NEW_LINE INDENT B [ i - 1 ] [ j ] = B [ i ] [ j ] NEW_LINE DEDENT DEDENT if ( i != N - 1 ) : NEW_LINE INDENT if A [ i + 1 ] [ j ] == A [ i ] [ j ] : NEW_LINE INDENT B [ i + 1 ] [ j ] = B [ i ] [ j ] NEW_LINE DEDENT DEDENT if ( j != 0 ) : NEW_LINE INDENT if A [ i ] [ j - 1 ] == A [ i ] [ j ] : NEW_LINE INDENT B [ i ] [ j - 1 ] = B [ i ] [ j ] NEW_LINE DEDENT DEDENT if ( j != M - 1 ) : NEW_LINE INDENT if ( A [ i ] [ j + 1 ] == A [ i ] [ j ] ) : NEW_LINE INDENT B [ i ] [ j + 1 ] = B [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT s . add ( B [ i ] [ j ] ) NEW_LINE DEDENT DEDENT return len ( s ) NEW_LINE DEDENT N = 2 NEW_LINE M = 3 NEW_LINE A = [ [ 2 , 1 , 3 ] , [ 1 , 1 , 2 ] ] NEW_LINE print ( solve ( A , N , M ) ) NEW_LINE
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 . ; If there is no such partition , then return 0 ; Function to find the total splitting ; Prefix array to store the prefix - sum using 1 based indexing ; Store the prefix - sum ; Function Call to count the number of splitting ; Given array ; Function call
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 + splitArray ( start , k , arr , prefix_sum ) + splitArray ( k + 1 , end , arr , prefix_sum ) ) NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT def solve ( arr , n ) : NEW_LINE INDENT prefix_sum = [ 0 ] * ( n + 1 ) NEW_LINE prefix_sum [ 0 ] = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT prefix_sum [ i ] = ( prefix_sum [ i - 1 ] + arr [ i - 1 ] ) NEW_LINE DEDENT print ( splitArray ( 1 , n , arr , prefix_sum ) ) NEW_LINE DEDENT arr = [ 12 , 3 , 3 , 0 , 3 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE solve ( arr , N ) NEW_LINE
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 possible with elements less than mid ; Condition to check if the answer is in right subarray ; Driver Code ; Function Call
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 INDENT if ( arr [ j ] > mid ) : NEW_LINE INDENT cnt = 0 NEW_LINE DEDENT else : NEW_LINE INDENT cnt += 1 NEW_LINE if ( cnt >= k ) : NEW_LINE INDENT product += 1 NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT DEDENT if ( product < n ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid NEW_LINE DEDENT DEDENT return left NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 10 , 3 , 10 , 2 ] NEW_LINE n = 3 NEW_LINE k = 1 NEW_LINE print ( int ( minDays ( arr , n , k ) ) ) NEW_LINE DEDENT
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 ; Given number N ; Function call
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 += j NEW_LINE count += 1 NEW_LINE j += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( n != 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT N = 24 NEW_LINE print ( countFac ( N ) ) NEW_LINE
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 previous element is from array a with an extra penalty of integer C ; Adding the element of array b if previous element is also from array b ; Print the minimum sum ; Driver code ; Given array arr [ ] ; Given cost ; Function Call
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 ] [ 0 ] = min ( dp [ i ] [ 0 ] , dp [ i - 1 ] [ 1 ] + a [ i ] + c ) NEW_LINE dp [ i ] [ 1 ] = min ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 0 ] + b [ i ] + c ) NEW_LINE dp [ i ] [ 1 ] = min ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 1 ] + b [ i ] ) NEW_LINE DEDENT print ( min ( dp [ n - 1 ] [ 0 ] , dp [ n - 1 ] [ 1 ] ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 7 , 6 , 18 , 6 , 16 , 18 , 1 , 17 , 17 ] NEW_LINE arr2 = [ 6 , 9 , 3 , 10 , 9 , 1 , 10 , 1 , 5 ] NEW_LINE C = 2 NEW_LINE N = len ( arr1 ) NEW_LINE minimumSum ( arr1 , arr2 , C , N ) NEW_LINE DEDENT
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 no '1 ; Increase the count of required flips ; Flip the last index of the window ; Update the last index which contains 1 ; Check for remaining substrings ; If last_idx does not belong to current window make it - 1 ; If the last character of the current substring is '1' , then update last_idx to i + k - 1 ; ; If last_idx == - 1 , then the current substring has no 1 ; Increase the count of flips ; Update the last index of the current window ; Store the last index of current window as the index of last '1' in the string ; Return the number of operations ; Driver Code
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 [ K - 1 ] = '1' NEW_LINE last_idx = K - 1 NEW_LINE DEDENT for i in range ( N - K + 1 ) : NEW_LINE INDENT if ( last_idx < i ) : NEW_LINE INDENT last_idx = - 1 NEW_LINE DEDENT if ( S [ i + K - 1 ] == '1' ) : NEW_LINE INDENT last_idx = i + K - 1 NEW_LINE DEDENT if ( last_idx == - 1 ) : NEW_LINE INDENT ops += 1 NEW_LINE S = S [ : i + K - 1 ] + '1' + S [ i + K : ] NEW_LINE last_idx = i + K - 1 NEW_LINE DEDENT DEDENT return ops NEW_LINE DEDENT S = "001010000" NEW_LINE K = 3 ; NEW_LINE print ( minimumMoves ( S , K ) ) NEW_LINE
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 possible then - 1 ; Case 2 when K is less equal d ; X show the modification such that this position only differ from only one string ; Modify the position such that this differ from both S1 & S2 & decrease the T at each step ; Finding the character which is different from both S1 and S2 ; After we done T start modification to meet our requirement for X type ; Resultant string ; Case 1 when K > d In first step , modify all the character which are not same in S1 and S3 ; Finding character which is different from both S1 and S2 ; Our requirement not satisfied by performing step 1. We need to modify the position which matches in both string ; Finding the character which is different from both S1 and S2 ; Resultant string ; Driver Code ; Given two strings ; Function call
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 print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT if ( k <= d ) : NEW_LINE INDENT X = d - k NEW_LINE T = 2 * k - d NEW_LINE for i in range ( len ( s3 ) ) : NEW_LINE INDENT if ( s1 [ i ] != s2 [ i ] ) : NEW_LINE INDENT if ( T > 0 ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT if ( arr [ j ] != s1 [ i ] and arr [ j ] != s2 [ i ] ) : NEW_LINE INDENT s3 [ i ] = arr [ j ] NEW_LINE T -= 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT elif ( X > 0 ) : NEW_LINE INDENT s3 [ i ] = s1 [ i ] NEW_LINE X -= 1 NEW_LINE DEDENT DEDENT DEDENT print ( " " . join ( s3 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( s1 [ i ] != s3 [ i ] ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT if ( arr [ j ] != s1 [ i ] and arr [ j ] != s3 [ i ] ) : NEW_LINE INDENT s3 [ i ] = arr [ j ] NEW_LINE k -= 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( s1 [ i ] == s3 [ i ] and k ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT if ( arr [ j ] != s1 [ i ] and arr [ j ] != s3 [ i ] ) : NEW_LINE INDENT s3 [ i ] = arr [ j ] NEW_LINE k -= 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( " " . join ( s3 ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE k = 2 NEW_LINE S1 = " zzyy " NEW_LINE S2 = " zxxy " NEW_LINE findString ( N , k , S1 , S2 ) NEW_LINE DEDENT
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 ; Function Call
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 DEDENT N = 80 ; NEW_LINE findSolutions ( N ) ; NEW_LINE
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 ) using current mid ; Check if current mid satisfy the equation ; Print mid and return ; Print " NA " if not found any integral solution ; Driver Code ; Function Call
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_LINE INDENT mid = start + ( end - start ) // 2 ; NEW_LINE ans = check ( A , B , C , D , mid ) ; NEW_LINE if ( ans == E ) : NEW_LINE INDENT print ( mid ) ; NEW_LINE return ; NEW_LINE DEDENT if ( ans < E ) : NEW_LINE INDENT start = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 ; NEW_LINE DEDENT DEDENT print ( " NA " ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 1 ; B = 0 ; C = 0 ; NEW_LINE D = 0 ; E = 27 ; NEW_LINE findSolution ( A , B , C , D , E ) ; NEW_LINE DEDENT
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 DEDENT if ( c == ' R ' ) : NEW_LINE INDENT Red_Count += 1 ; NEW_LINE DEDENT if ( c == ' G ' ) : NEW_LINE INDENT result += Red_Count * Blue_Count ; NEW_LINE DEDENT DEDENT return result ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT color = " RRGGBBRGGBB " ; NEW_LINE print ( countTriplets ( color ) ) ; 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 ; Variable to store the sum of cubes ; Loop to find the number K ; If C is just greater then N , then break the loop ; Driver code
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 ; Calculating mid value of the range ; If the sum of cubes of first mid natural numbers is greater than equal to N iterate the left half ; Sum of cubes of first mid natural numbers is less than N , then move to the right segment ; Driver code
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 DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 100 NEW_LINE print ( binary_searched_find_x ( N ) ) NEW_LINE DEDENT
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 ; Check if ' _ max ' length is less than the length of the current zigzag subarray . If true , then update '_max ; Reset ' _ len ' to 1 as from this element , again the length of the new zigzag subarray is being calculated ; Comparing the length of the last zigzag subarray with '_max ; Return required maximum length ; Driver code
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 DEDENT DEDENT ' NEW_LINE INDENT if _max < _len : NEW_LINE INDENT _max = _len NEW_LINE DEDENT _len = 1 NEW_LINE DEDENT ' NEW_LINE INDENT if _max < _len : NEW_LINE INDENT _max = _len NEW_LINE DEDENT return _max NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( lenOfLongZigZagArr ( arr , n ) ) NEW_LINE
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 possibly the square root of N ; If the square ( mid ) is less than N it means only higher values then mid will be possibly the square root of N ; Driver code
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 , mid - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return checkPerfectSquare ( N , mid + 1 , last ) NEW_LINE DEDENT DEDENT N = 65 NEW_LINE print ( checkPerfectSquare ( N , 1 , N ) ) NEW_LINE
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 ; Iterate over array from kth element ; Leftmost element of subarray ; Rightmost element of subarray ; if new subarray have greater number of min points than previous subarray , then final_point is modified ; Max minimum points in subarray of size k ; Driver Code
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 [ i - ( k - 1 ) ] < arr [ i - ( k - 1 ) + 1 ] and arr [ i - ( k - 1 ) ] < arr [ i - ( k - 1 ) - 1 ] ) : NEW_LINE INDENT min_point -= 1 NEW_LINE DEDENT if ( arr [ i - 1 ] < arr [ i ] and arr [ i - 1 ] < arr [ i - 2 ] ) : NEW_LINE INDENT min_point += 1 NEW_LINE DEDENT if ( min_point > final_point ) : NEW_LINE INDENT final_point = min_point NEW_LINE DEDENT DEDENT print ( final_point ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 1 , 4 , 2 , 3 , 4 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 4 NEW_LINE minpoint ( arr , n , k ) NEW_LINE DEDENT
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 - initialising boolean vector every time we just reset all visited letter to false ; Print count for each letter ; Driver code ; Given array of strings ; Call the countStrings function
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 [ i ] [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT visited [ ord ( s [ i ] [ j ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT for j in range ( len ( s [ i ] ) ) : NEW_LINE INDENT visited [ ord ( s [ i ] [ j ] ) - ord ( ' a ' ) ] = False NEW_LINE DEDENT DEDENT for i in range ( 26 ) : NEW_LINE INDENT print ( count [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = [ " i " , " will " , " practice " , " everyday " ] NEW_LINE CountStrings ( s ) NEW_LINE DEDENT
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 ; Driver code
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 = 0 NEW_LINE left = 0 NEW_LINE for i in range ( 0 , n - k + 1 , 1 ) : NEW_LINE INDENT if ( pref [ i + k - 2 ] - pref [ i ] > peak ) : NEW_LINE INDENT peak = pref [ i + k - 2 ] - pref [ i ] NEW_LINE left = i NEW_LINE DEDENT DEDENT print ( " Left ▁ = " , left + 1 ) NEW_LINE print ( " Right ▁ = " , left + k ) NEW_LINE print ( " Peak ▁ = " , peak ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 3 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE findSubArray ( arr , n , k ) NEW_LINE DEDENT
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 at distance 0 ; Elements at left side of K ; Elements at right side of K ; Print the vector content in sorted order ; Sort elements at same distance ; Print elements at distance i from K ; Driver code
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 ) : NEW_LINE INDENT vd [ pos - i ] . append ( arr [ i ] ) NEW_LINE i -= 1 NEW_LINE DEDENT while ( j < n ) : NEW_LINE INDENT vd [ j - pos ] . append ( arr [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT for i in range ( max ( pos , n - pos - 1 ) + 1 ) : NEW_LINE INDENT vd [ i ] . sort ( reverse = False ) NEW_LINE for element in vd [ i ] : NEW_LINE INDENT print ( element , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 14 , 1101 , 10 , 35 , 0 ] NEW_LINE K = 35 NEW_LINE n = len ( arr ) NEW_LINE distanceSort ( arr , K , n ) NEW_LINE DEDENT
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 divisor ; Return the final answer ; Recursive calls ; Driver code
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_LINE INDENT end = mid - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( n == divisor ) : NEW_LINE INDENT mid += 1 ; NEW_LINE n = 0 ; NEW_LINE DEDENT return ( mid , n ) ; NEW_LINE DEDENT return find ( dividend , divisor , start , end ) ; NEW_LINE DEDENT def divide ( dividend , divisor ) : NEW_LINE INDENT return find ( dividend , divisor , 1 , dividend ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT dividend = 10 ; divisor = 3 ; NEW_LINE ans = divide ( dividend , divisor ) ; NEW_LINE print ( ans [ 0 ] , " , ▁ " , ans [ 1 ] ) NEW_LINE DEDENT
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 ; Driver code
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 ] ) NEW_LINE temp . sort ( ) NEW_LINE if ( temp [ 0 ] < temp [ 1 ] and temp [ 1 ] < temp [ 2 ] and temp [ 0 ] * temp [ 1 ] * temp [ 2 ] <= x ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT A = [ 3 , 2 , 5 , 7 ] NEW_LINE N = len ( A ) NEW_LINE X = 42 NEW_LINE print ( countTriplets ( A , N , X ) ) NEW_LINE
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 go higher to reach value exactly equal to n ; return the largest value of x ; Driver Code
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 ( mid , b ) + log ( a , b ) ) ) NEW_LINE if ( dig > n ) : NEW_LINE INDENT hi = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans = mid NEW_LINE lo = mid + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 2 NEW_LINE b = 2 NEW_LINE n = 6 NEW_LINE print ( int ( get ( a , b , n ) ) ) NEW_LINE DEDENT
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 ; Index out of bound ; Maximum possible size of matrix ; Binary Search ; Find middle index ; Check whether sum <= K or not If Yes check for other half of the search ; Else check it in first half ; Update the maximum size matrix ; Print the final answer ; Driver Code ; Given target sum ; Function Call
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 ] [ j ] = 0 NEW_LINE continue NEW_LINE DEDENT sum [ i ] [ j ] = arr [ i - 1 ] [ j - 1 ] + sum [ i - 1 ] [ j ] + sum [ i ] [ j - 1 ] - sum [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( i + ans - 1 > n or j + ans - 1 > m ) : NEW_LINE INDENT break NEW_LINE DEDENT mid = ans NEW_LINE lo = ans NEW_LINE hi = min ( n - i + 1 , m - j + 1 ) NEW_LINE while ( lo < hi ) : NEW_LINE INDENT mid = ( hi + lo + 1 ) // 2 NEW_LINE if ( sum [ i + mid - 1 ] [ j + mid - 1 ] + sum [ i - 1 ] [ j - 1 ] - sum [ i + mid - 1 ] [ j - 1 ] - sum [ i - 1 ] [ j + mid - 1 ] <= K ) : NEW_LINE INDENT lo = mid NEW_LINE DEDENT else : NEW_LINE INDENT hi = mid - 1 NEW_LINE DEDENT DEDENT ans = max ( ans , lo ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 1 , 3 , 2 , 4 , 3 , 2 ] , [ 1 , 1 , 3 , 2 , 4 , 3 , 2 ] , [ 1 , 1 , 3 , 2 , 4 , 3 , 2 ] ] NEW_LINE K = 4 NEW_LINE findMaxMatrixSize ( arr , K ) NEW_LINE DEDENT
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 ; array named arr ; length of arr
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 DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 88 , 14 , 69 , 30 , 29 , 89 ] NEW_LINE length = len ( arr ) NEW_LINE FindRank ( arr , length ) NEW_LINE DEDENT
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 should be present ; Increasing the length by one ; Driver Code
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 break NEW_LINE DEDENT length += 1 NEW_LINE DEDENT return length NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 6 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestPermutation ( arr , n ) ) NEW_LINE DEDENT
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 the first two Fibonacci numbers into the Hash set ; Computing the remaining Fibonacci numbers based on the previous two numbers ; Function to find the pair of Fibonacci numbers with the given sum and minimum absolute difference ; Start from N / 2 such that the difference between i and N - i will be minimum ; If both ' i ' and ' sum ▁ - ▁ i ' are fibonacci numbers then print them and break the loop ; If there is no Fibonacci pair possible ; Driver code ; Generate the Fibonacci numbers ; Find the Fibonacci pair
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 prev = curr NEW_LINE curr = temp NEW_LINE l += 1 NEW_LINE DEDENT DEDENT def findFibonacci ( N ) : NEW_LINE INDENT global fib NEW_LINE i = N // 2 NEW_LINE while ( i > 1 ) : NEW_LINE INDENT if ( i in fib and ( N - i ) in fib ) : NEW_LINE INDENT print ( i , ( N - i ) ) NEW_LINE return NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT print ( " - 1" ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT fibonacci ( ) NEW_LINE sum = 199 NEW_LINE findFibonacci ( sum ) NEW_LINE DEDENT
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 Fibonacci numbers into the hash ; Add the remaining Fibonacci numbers based on the previous two numbers ; Function to check if the sum of Fibonacci numbers is Fibonacci or not ; Find the sum of all Fibonacci numbers ; Iterating through the array ; If the sum is Fibonacci then return true ; Driver code ; array of elements ; Creating a set containing all fibonacci numbers
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 fibonacci . add ( temp ) NEW_LINE DEDENT prev = curr NEW_LINE curr = temp NEW_LINE DEDENT DEDENT def checkArray ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] in fibonacci ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT DEDENT if ( sum in fibonacci ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 8 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE createHash ( ) NEW_LINE if ( checkArray ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 array ; Store the first two Fibonacci numbers ; Compute the Fibonacci numbers and store them in isFib array ; Compute fibUpto array ; Function to return the count of valid numbers ; Compute fibUpto array ; Binary search to find the minimum number that follows the condition ; Check if the number is valid , try to reduce it ; Ans is the minimum valid number ; Driver Code
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 ) : NEW_LINE INDENT isFib [ temp ] = True NEW_LINE DEDENT prev = curr NEW_LINE curr = temp NEW_LINE DEDENT fibUpto [ 0 ] = 1 NEW_LINE for i in range ( 1 , sz + 1 ) : NEW_LINE INDENT fibUpto [ i ] = fibUpto [ i - 1 ] NEW_LINE if ( isFib [ i ] ) : NEW_LINE INDENT fibUpto [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT def countOfNumbers ( N , K ) : NEW_LINE INDENT compute ( N ) NEW_LINE low , high , ans = 1 , N , 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) >> 1 NEW_LINE if ( mid - fibUpto [ mid ] >= K ) : NEW_LINE INDENT ans = mid NEW_LINE high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT if ( ans ) : NEW_LINE INDENT return ( N - ans + 1 ) NEW_LINE DEDENT return 0 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 10 NEW_LINE K = 3 NEW_LINE print ( countOfNumbers ( N , K ) ) NEW_LINE DEDENT
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 sum over this frequency array to get frequency of a character in a range [ L , R ] . ; Util function for palindromic subsequences ; Find frequency of all characters ; For each character find it 's frequency in range [L, R] ; If frequency in this range is > 1 , then we must take this character , as it will give lexicographically smallest one ; There is no character in range [ L , R ] such that it 's frequency is > 1. ; Return the character 's value ; Function to find lexicographically smallest palindromic subsequence of even length ; Find in the palindromic subsequences ; No such subsequence exists ; Driver Code ; Function calls
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 INDENT f [ i ] [ j ] += f [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT def palindromicSubsequencesUtil ( L , R ) : NEW_LINE INDENT ok = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT cnt = f [ i ] [ R ] NEW_LINE if ( L > 0 ) : NEW_LINE INDENT cnt -= f [ i ] [ L - 1 ] NEW_LINE DEDENT if ( cnt > 1 ) : NEW_LINE INDENT ok = 1 NEW_LINE c = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( ok == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return c NEW_LINE DEDENT def palindromicSubsequences ( Q , l ) : NEW_LINE INDENT for i in range ( l ) : NEW_LINE INDENT x = palindromicSubsequencesUtil ( Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) NEW_LINE if ( x == - 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT c = ord ( ' a ' ) + x NEW_LINE print ( 2 * chr ( c ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " dbdeke " NEW_LINE Q = [ [ 0 , 5 ] , [ 1 , 5 ] , [ 1 , 3 ] ] NEW_LINE n = len ( st ) NEW_LINE l = len ( Q ) NEW_LINE precompute ( st , n ) NEW_LINE palindromicSubsequences ( Q , l ) NEW_LINE DEDENT
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 time ; Function to find the longest fibonacci subarray ; Find maximum value in the array ; Creating a set containing Fibonacci numbers ; Left array is used to count number of continuous fibonacci numbers starting from left of current element ; Check if current element is a fibonacci number ; Right array is used to count number of continuous fibonacci numbers starting from right of current element ; Check if current element is a fibonacci number ; Driver code
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 DEDENT DEDENT def longestFibSubarray ( arr , n ) : NEW_LINE INDENT max_val = max ( arr ) NEW_LINE hash = { int } NEW_LINE createHash ( hash , max_val ) NEW_LINE left = [ 0 for i in range ( n ) ] NEW_LINE right = [ 0 for i in range ( n ) ] NEW_LINE fibcount = 0 NEW_LINE res = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT left [ i ] = fibcount NEW_LINE if ( arr [ i ] in hash ) : NEW_LINE INDENT fibcount += 1 NEW_LINE DEDENT else : NEW_LINE INDENT fibcount = 0 NEW_LINE DEDENT DEDENT fibcount = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT right [ i ] = fibcount NEW_LINE if ( arr [ i ] in hash ) : NEW_LINE INDENT fibcount += 1 NEW_LINE DEDENT else : NEW_LINE INDENT fibcount = 0 NEW_LINE DEDENT DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT res = max ( res , left [ i ] + right [ i ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 2 , 8 , 5 , 7 , 3 , 5 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestFibSubarray ( arr , n ) ) NEW_LINE
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 is divisible by any other number or not ; Function to check whether window size satisfies condition or not ; Loop to check each window of size have atleast P primes ; Checking condition using prefix sum ; Function to find the minimum window size possible for the given range in X and Y ; Prefix array ; Mark those numbers which are primes as 1 ; Convert to prefix sum ; Applying binary search over window size ; Check whether mid satisfies the condition or not ; If satisfies search in first half ; Else search in second half ; Driver Code
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 curr = 5 NEW_LINE s = sqrt ( N ) NEW_LINE while ( curr <= s ) : NEW_LINE INDENT if ( N % curr == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT curr += 2 NEW_LINE if ( N % curr == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT curr += 4 NEW_LINE DEDENT return True NEW_LINE DEDENT def check ( s , p , prefix_sum , n ) : NEW_LINE INDENT satisfies = True NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i + s - 1 >= n ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( i - 1 >= 0 ) : NEW_LINE INDENT x = prefix_sum [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT x = 0 NEW_LINE DEDENT if ( prefix_sum [ i + s - 1 ] - x < p ) : NEW_LINE INDENT satisfies = False NEW_LINE DEDENT DEDENT return satisfies NEW_LINE DEDENT def minimumWindowSize ( x , y , p ) : NEW_LINE INDENT prefix_sum = [ 0 ] * ( y - x + 1 ) NEW_LINE for i in range ( x , y + 1 ) : NEW_LINE INDENT if ( isPrime ( i ) ) : NEW_LINE INDENT prefix_sum [ i - x ] = 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , y - x + 1 ) : NEW_LINE INDENT prefix_sum [ i ] += prefix_sum [ i - 1 ] NEW_LINE DEDENT low = 1 NEW_LINE high = y - x + 1 NEW_LINE while ( high - low > 1 ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( check ( mid , p , prefix_sum , y - x + 1 ) ) : NEW_LINE INDENT high = mid NEW_LINE DEDENT else : NEW_LINE INDENT low = mid NEW_LINE DEDENT DEDENT if ( check ( low , p , prefix_sum , y - x + 1 ) ) : NEW_LINE INDENT return low NEW_LINE DEDENT return high NEW_LINE DEDENT x = 12 NEW_LINE y = 42 NEW_LINE p = 3 NEW_LINE print ( minimumWindowSize ( x , y , p ) ) NEW_LINE
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_LINE print ( xorOfSum ( A , n ) ) NEW_LINE DEDENT
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 sum ; Function to find the sum of a submatrix with the given indices ; Overall sum from the top to right corner of matrix ; Removing the sum from the top corer of the matrix ; Remove the overlapping sum ; Add the sum of top corner which is subtracted twice ; Function to find the maximum square size possible with the such that every submatrix have sum less than the given sum ; Loop to choose the size of matrix ; Loop to find the sum of the matrix of every possible submatrix ; Driver Code
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 DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( 1 , M ) : NEW_LINE INDENT aux [ i ] [ j ] += aux [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT def sumQuery ( aux , tli , tlj , rbi , rbj ) : NEW_LINE INDENT res = aux [ rbi ] [ rbj ] NEW_LINE if ( tli > 0 ) : NEW_LINE INDENT res = res - aux [ tli - 1 ] [ rbj ] NEW_LINE DEDENT if ( tlj > 0 ) : NEW_LINE INDENT res = res - aux [ rbi ] [ tlj - 1 ] NEW_LINE DEDENT if ( tli > 0 and tlj > 0 ) : NEW_LINE INDENT res = ( res + aux [ tli - 1 ] [ tlj - 1 ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT def maximumSquareSize ( mat , K ) : NEW_LINE INDENT aux = [ [ 0 for x in range ( M ) ] for y in range ( N ) ] NEW_LINE preProcess ( mat , aux ) NEW_LINE for i in range ( min ( N , M ) , 0 , - 1 ) : NEW_LINE INDENT satisfies = True NEW_LINE for x in range ( N ) : NEW_LINE INDENT for y in range ( M ) : NEW_LINE INDENT if ( x + i - 1 <= N - 1 and y + i - 1 <= M - 1 ) : NEW_LINE INDENT if ( sumQuery ( aux , x , y , x + i - 1 , y + i - 1 ) > K ) : NEW_LINE INDENT satisfies = False NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( satisfies == True ) : NEW_LINE INDENT return ( i ) NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT K = 30 NEW_LINE mat = [ [ 1 , 2 , 3 , 4 , 6 ] , [ 5 , 3 , 8 , 1 , 2 ] , [ 4 , 6 , 7 , 5 , 5 ] , [ 2 , 4 , 8 , 9 , 4 ] ] NEW_LINE print ( maximumSquareSize ( mat , K ) ) NEW_LINE DEDENT
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 fibonacci numbers ; Traversing all numbers to find first pair ; If both i and ( N - i ) are Fibonacci ; Printing the pair because i + ( N - i ) = N ; If no fibonacci pair is found whose sum is equal to n ; Driven code
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 findFibonacciPair ( n ) : NEW_LINE INDENT hash1 = set ( ) NEW_LINE createHash ( hash1 , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i in hash1 and ( n - i ) in hash1 ) : NEW_LINE INDENT print ( i , " , ▁ " , ( n - i ) ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " - 1" ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 90 NEW_LINE findFibonacciPair ( N ) NEW_LINE DEDENT
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 every element ; To store factors all of all numbers ; Traverse for all possible i 's ; Printing value of a [ i ] in map ; Now updating the factors of a [ i ] in the map ; Driver code ; Function call
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 ] += 1 NEW_LINE mp [ n // i ] += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def count_divisors ( a , n ) : NEW_LINE INDENT mp = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( mp [ a [ i ] ] , end = " ▁ " ) NEW_LINE add_factors ( a [ i ] , mp ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 8 , 1 , 28 , 4 , 2 , 6 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE count_divisors ( arr , n ) NEW_LINE DEDENT
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 DEDENT print ( " { " , end = " " ) NEW_LINE for i in range ( st ) : NEW_LINE INDENT print ( arr [ i ] , end = " " ) ; NEW_LINE if ( i != st - 1 ) : NEW_LINE INDENT print ( " , ▁ " , end = " " ) ; NEW_LINE DEDENT DEDENT print ( " } " , end = " " ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 3 , 3 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE removeDuplicates ( arr , n ) ; NEW_LINE DEDENT
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 return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE if ( permutation ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 ] ; if e [ 1 ] is entering first time in the queue ; Append at back of queue ; Append at front of queue ; Driver Code ; Adjacency matrix of graph
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 ] [ j ] , j ] ) NEW_LINE adj [ j ] . append ( [ graph [ i ] [ j ] , i ] ) NEW_LINE DEDENT DEDENT DEDENT q = deque ( [ ] ) NEW_LINE distance = [ float ( ' inf ' ) ] * v NEW_LINE is_in_queue = [ False ] * v NEW_LINE source = 0 NEW_LINE distance = 0 NEW_LINE q . append ( source ) NEW_LINE is_in_queue = True NEW_LINE while q : NEW_LINE INDENT u = q . popleft ( ) NEW_LINE is_in_queue [ u ] = False NEW_LINE for e in adj [ u ] : NEW_LINE INDENT if distance [ e [ 1 ] ] > distance [ u ] + e [ 0 ] : NEW_LINE INDENT distance [ e [ 1 ] ] = distance [ u ] + e [ 0 ] NEW_LINE if is_in_queue [ e [ 1 ] ] == False : NEW_LINE INDENT if distance [ e [ 1 ] ] == float ( ' inf ' ) : NEW_LINE INDENT q . append ( e [ 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT q . appendleft ( e [ 1 ] ) NEW_LINE DEDENT is_in_queue [ e [ 1 ] ] = True NEW_LINE DEDENT DEDENT DEDENT DEDENT return distance NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT graph = [ [ 0 , 4 , 0 , 0 , 8 ] , [ 0 , 0 , 8 , 0 , 11 ] , [ 0 , 8 , 0 , 2 , 0 ] , [ 0 , 0 , 2 , 0 , 1 ] , [ 8 , 11 , 0 , 1 , 0 ] ] NEW_LINE print ( desopo ( graph ) ) NEW_LINE DEDENT
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_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 5 , 6 , 7 ] ; NEW_LINE X = 5 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( CountSubSet ( arr , n , X ) ) ; NEW_LINE DEDENT
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 calculate 2 ^ ( n - 1 ) as count ; if X is not present in a given set ; Driver code
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 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == X ) : NEW_LINE INDENT checkX = 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( checkX == 1 ) : NEW_LINE INDENT count = calculatePower ( 2 , n - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT count = 0 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 5 , 6 , 7 ] ; NEW_LINE X = 5 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( CountSubSet ( arr , n , X ) ) ; NEW_LINE DEDENT
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 to find the answer ; The amount of wood collected when cut is made at the mid ; If the current collected wood is equal to the required amount ; If it is more than the required amount then the cut needs to be made at a height higher than the current height ; Else made the cut at a lower height ; Driver code
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 height = sorted ( height ) NEW_LINE low = 0 NEW_LINE high = height [ n - 1 ] NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( ( high - low ) // 2 ) NEW_LINE collected = woodCollected ( height , n , mid ) NEW_LINE if ( collected == k ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( collected > k ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT height = [ 1 , 2 , 1 , 2 ] NEW_LINE n = len ( height ) NEW_LINE k = 2 NEW_LINE print ( collectKWood ( height , n , k ) ) NEW_LINE
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 current digit as present ; For every digit from 0 to 9 ; If the current digit is not present in st ; Driver code
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 ) : NEW_LINE INDENT if ( isDigit ( st [ i ] ) ) : NEW_LINE INDENT digit = ord ( st [ i ] ) - ord ( '0' ) NEW_LINE present [ digit ] = True NEW_LINE DEDENT DEDENT for i in range ( MAX ) : NEW_LINE INDENT if ( present [ i ] == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT st = " Geeks12345for69708" NEW_LINE le = len ( st ) NEW_LINE if ( allDigits ( st , le ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 been found ; The frequency of the element something other than 0 and 1 ; Driver code
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_LINE INDENT continue NEW_LINE DEDENT if ( frequency % 4 == 1 ) : NEW_LINE INDENT if ( foundModOne == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT foundModOne = True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 1 , 1 , 1 , 1 , 2 , 2 , 2 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE if ( isPlusPossible ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 elements to the vector v ; Procedure to build the segment tree ; Reached the leaf node of the segment tree ; Recursively call the buildTree on both the nodes of the tree ; Storing the final vector after merging the two of its sorted child vector ; Query procedure to get the answer for each query l and r are query range ; out of bound or no overlap ; Complete overlap Query range completely lies in the segment tree node range ; binary search to find index of k ; Partially overlap Query range partially lies in the segment tree node range ; Function to perform the queries ; Driver code ; 1 - based indexing ; Number of queries
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_LINE INDENT v . append ( v2 [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT for k in range ( i , len ( v1 ) ) : NEW_LINE INDENT v . append ( v1 [ k ] ) NEW_LINE DEDENT for k in range ( j , len ( v2 ) ) : NEW_LINE INDENT v . append ( v2 [ k ] ) NEW_LINE DEDENT return v NEW_LINE DEDENT def buildTree ( tree , arr , index , s , e ) : NEW_LINE INDENT if ( s == e ) : NEW_LINE INDENT tree [ index ] . append ( arr [ s ] ) NEW_LINE return NEW_LINE DEDENT mid = ( s + e ) // 2 NEW_LINE buildTree ( tree , arr , 2 * index , s , mid ) NEW_LINE buildTree ( tree , arr , 2 * index + 1 , mid + 1 , e ) NEW_LINE tree [ index ] = merge ( tree [ 2 * index ] , tree [ 2 * index + 1 ] ) NEW_LINE DEDENT def query ( tree , index , s , e , l , r , k ) : NEW_LINE INDENT if ( r < s or l > e ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( s >= l and e <= r ) : NEW_LINE INDENT return len ( tree [ index ] ) - ( lower_bound ( tree [ index ] , k ) ) NEW_LINE DEDENT mid = ( s + e ) // 2 NEW_LINE return ( query ( tree , 2 * index , s , mid , l , r , k ) + query ( tree , 2 * index + 1 , mid + 1 , e , l , r , k ) ) NEW_LINE DEDENT def performQueries ( L , R , K , n , q , tree ) : NEW_LINE INDENT for i in range ( q ) : NEW_LINE INDENT print ( query ( tree , 1 , 0 , n - 1 , L [ i ] - 1 , R [ i ] - 1 , K [ i ] ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 3 , 9 , 13 , 5 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE tree = [ [ ] for i in range ( 4 * n + 1 ) ] NEW_LINE buildTree ( tree , arr , 1 , 0 , n - 1 ) NEW_LINE L = [ 1 , 2 ] NEW_LINE R = [ 4 , 6 ] NEW_LINE K = [ 6 , 8 ] NEW_LINE q = len ( L ) NEW_LINE performQueries ( L , R , K , n , q , tree ) NEW_LINE DEDENT
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 ; 1 - based indexing
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 ] > x : NEW_LINE INDENT tree [ ind ] = arr [ low ] NEW_LINE DEDENT else : NEW_LINE INDENT tree [ ind ] = 0 NEW_LINE DEDENT return NEW_LINE DEDENT mid = ( high - low ) / 2 + low NEW_LINE mid = math . floor ( mid ) NEW_LINE mid = int ( mid ) NEW_LINE build_tree ( arr , tree , 2 * ind + 1 , low , mid , x ) NEW_LINE build_tree ( arr , tree , 2 * ind + 2 , mid + 1 , high , x ) NEW_LINE tree [ ind ] = combine ( tree [ 2 * ind + 1 ] , tree [ 2 * ind + 2 ] ) NEW_LINE DEDENT def query ( tree , ind , low , high , l , r ) : NEW_LINE INDENT mid = ( high - low ) / 2 + low NEW_LINE mid = math . floor ( mid ) NEW_LINE mid = int ( mid ) NEW_LINE if low > r or high < l : NEW_LINE INDENT return 0 NEW_LINE DEDENT if l <= low and r >= high : NEW_LINE INDENT return tree [ ind ] NEW_LINE DEDENT q1 = query ( tree , 2 * ind + 1 , low , mid , l , r ) NEW_LINE q2 = query ( tree , 2 * ind + 2 , mid + 1 , high , l , r ) NEW_LINE return combine ( q1 , q2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 3 , 9 , 13 , 5 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 6 NEW_LINE tree = [ [ ] for i in range ( 4 * n ) ] NEW_LINE l = 1 NEW_LINE r = 4 NEW_LINE build_tree ( arr , tree , 0 , 0 , n - 1 , k ) NEW_LINE print ( query ( tree , 0 , 0 , n - 1 , l - 1 , r - 1 ) ) NEW_LINE DEDENT
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_LINE DEDENT DEDENT return GCDSum ; NEW_LINE DEDENT def __gcd ( a , b ) : NEW_LINE INDENT return a if ( b == 0 ) else __gcd ( b , a % b ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; NEW_LINE a = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE totalSum = findGCDSum ( n , a ) ; NEW_LINE print ( totalSum ) ; NEW_LINE DEDENT
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 ; If the XOR of the remaining elements is equal to the current element ; If no such element is found ; Driver Code
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 arr = [ 8 , 2 , 4 , 15 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE if ( containsElement ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) 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 vertices that have indegree equal to zero ; Iterate till queue is not empty ; Push the front of queue to answer ; For all neighbours of u , decrement their indegree value ; If indegree of any vertex becomes zero and it is not marked then push it to queue ; Mark this vertex as visited ; Return the resultant topological order ; Function to return the winner between u and v ; Player who comes first wins ; Driver code ; Total number of players ; Build the graph add ( adj , x , y ) means x wins over y ; Resultant topological order in topotable ; Queries
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 = [ False for i in range ( n ) ] NEW_LINE q = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( indeg [ i ] == 0 ) : NEW_LINE INDENT q . append ( i ) NEW_LINE visited [ i ] = True NEW_LINE DEDENT DEDENT while ( len ( q ) != 0 ) : NEW_LINE INDENT u = q [ 0 ] NEW_LINE answer . append ( u ) NEW_LINE q . remove ( q [ 0 ] ) NEW_LINE for x in adj [ u ] : NEW_LINE INDENT indeg [ x ] -= 1 NEW_LINE if ( indeg [ x ] == 0 and visited [ x ] == False ) : NEW_LINE INDENT q . append ( x ) NEW_LINE visited [ x ] = True NEW_LINE DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT def who_wins ( topotable , u , v ) : NEW_LINE INDENT for x in topotable : NEW_LINE INDENT if ( x == u ) : NEW_LINE INDENT return u NEW_LINE DEDENT if ( x == v ) : NEW_LINE INDENT return v NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT adj = [ [ ] for i in range ( 10 ) ] NEW_LINE n = 7 NEW_LINE add ( adj , 0 , 1 ) NEW_LINE add ( adj , 0 , 2 ) NEW_LINE add ( adj , 0 , 3 ) NEW_LINE add ( adj , 1 , 5 ) NEW_LINE add ( adj , 2 , 5 ) NEW_LINE add ( adj , 3 , 4 ) NEW_LINE add ( adj , 4 , 5 ) NEW_LINE add ( adj , 6 , 0 ) NEW_LINE topotable = topo ( adj , n ) NEW_LINE print ( who_wins ( topotable , 3 , 5 ) ) NEW_LINE print ( who_wins ( topotable , 1 , 2 ) ) NEW_LINE DEDENT
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 to find the square root of n ; While the square root is not found ; If n is a perfect square ; Square root will lie in the interval i - 1 and i ; Driver code
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 INDENT return Square ( n , i , mid ) ; NEW_LINE DEDENT DEDENT def findSqrt ( n ) : NEW_LINE INDENT i = 1 ; NEW_LINE found = False ; NEW_LINE while ( found == False ) : NEW_LINE INDENT if ( i * i == n ) : NEW_LINE INDENT print ( i ) ; NEW_LINE found = True ; NEW_LINE DEDENT elif ( i * i > n ) : NEW_LINE INDENT res = Square ( n , i - 1 , i ) ; NEW_LINE print ( " { 0 : . 5f } " . format ( res ) ) NEW_LINE found = True NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 ; NEW_LINE findSqrt ( n ) ; NEW_LINE DEDENT
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_LINE DEDENT DEDENT prev_cnt = max ( prev_cnt , curr_cnt ) NEW_LINE max_len = prev_cnt NEW_LINE return max_len NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcd1111aabc " NEW_LINE K = '1' NEW_LINE print ( length_substring ( S , K ) ) NEW_LINE DEDENT
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 index of the array ; Driver code ; Function call
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 ( left_xor + right_xor > sum ) : NEW_LINE INDENT sum = left_xor + right_xor NEW_LINE index = i NEW_LINE DEDENT DEDENT return index + 1 NEW_LINE DEDENT arr = [ 1 , 4 , 6 , 3 , 8 , 13 , 34 , 2 , 21 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( Xor_Sum ( arr , n ) ) NEW_LINE
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 array at some index i ; PrefixXor [ i ] = Xor of all arr elements till i ' th ▁ index ▁ PrefixXor [ n - 1 ] ▁ ▁ ^ ▁ PrefixXor [ i ] ▁ = ▁ Xor ▁ of ▁ all ▁ elements ▁ ▁ from ▁ i + 1' th index to n - 1 'th index ; Return the index ; Driver code ; Function call
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 , PrefixXor , n ) ; NEW_LINE sum , index = 0 , 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( PrefixXor [ i ] + ( PrefixXor [ n - 1 ] ^ PrefixXor [ i ] ) > sum ) : NEW_LINE INDENT sum = PrefixXor [ i ] + ( PrefixXor [ n - 1 ] ^ PrefixXor [ i ] ) ; NEW_LINE index = i ; NEW_LINE DEDENT DEDENT return index + 1 ; NEW_LINE DEDENT arr = [ 1 , 4 , 6 , 3 , 8 , 13 , 34 , 2 , 21 , 10 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( Xor_Sum ( arr , n ) ) ; NEW_LINE
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 ; Return maximum color ; Function to build hash map with color ; To store color of each node ; For each number add a color number ; Assigning color ; Return hash map ; Driver code ; Build mapWithColor ; Print the maximum color
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 DEDENT else : NEW_LINE INDENT query = query // 2 NEW_LINE DEDENT DEDENT return maximum NEW_LINE DEDENT def buildMapWithColor ( arr , n ) : NEW_LINE INDENT mapWithColor = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mapWithColor [ arr [ i ] ] = i + 1 NEW_LINE DEDENT return mapWithColor NEW_LINE DEDENT arr = [ 3 , 2 , 1 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE k = 7 NEW_LINE mapWithColor = buildMapWithColor ( arr , n ) NEW_LINE print ( findColor ( mapWithColor , k ) ) NEW_LINE
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 character ; Check for the smallest character 's frequency ; Get the smallest character frequency ; Insert it in the vector ; Sort the count of all the frequency of the smallest character in every string ; Iterate for every in B ; Hash set every frequency 0 ; Count the frequency of every character ; Find the frequency of the smallest character ; Count the number of strings in A which has the frequency of the smaller character less than the frequency of the smaller character of the in B ; Store the answer ; Function to print the answer ; Get the answer ; Print the number of strings for every answer ; Driver code
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 DEDENT for j in range ( len ( s ) ) : NEW_LINE INDENT freq [ ord ( s [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for j in range ( MAX ) : NEW_LINE INDENT if ( freq [ j ] ) : NEW_LINE INDENT smallestFreq . append ( freq [ j ] ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT smallestFreq = sorted ( smallestFreq ) NEW_LINE ans = [ ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT s = b [ i ] NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT freq [ i ] = 0 NEW_LINE DEDENT for j in range ( len ( s ) ) : NEW_LINE INDENT freq [ ord ( s [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT frequency = 0 NEW_LINE for j in range ( MAX ) : NEW_LINE INDENT if ( freq [ j ] ) : NEW_LINE INDENT frequency = freq [ j ] NEW_LINE break NEW_LINE DEDENT DEDENT ind = lower_bound ( smallestFreq , frequency ) NEW_LINE ans . append ( ind ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def printAnswer ( a , b , n , m ) : NEW_LINE INDENT ans = findCount ( a , b , n , m ) NEW_LINE for it in ans : NEW_LINE INDENT print ( it , end = " ▁ " ) NEW_LINE DEDENT DEDENT A = [ " aaa " , " aa " , " bdc " ] NEW_LINE B = [ " cccch " , " cccd " ] NEW_LINE n = len ( A ) NEW_LINE m = len ( B ) NEW_LINE printAnswer ( A , B , n , m ) 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 ( " Leftmost ▁ node ▁ is ▁ " , min ) NEW_LINE print ( " Rightmost ▁ node ▁ is ▁ " , max ) NEW_LINE DEDENT preorder = [ 3 , 2 , 1 , 5 , 4 ] NEW_LINE n = len ( preorder ) NEW_LINE LeftRightNode ( preorder , n ) NEW_LINE
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 matrix using binary search ; If current row is equal to the given array then return the row number ; If arr [ ] is greater , ignore left half ; If arr [ ] is smaller , ignore right half ; No valid row found ; Driver code
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 , arr ) : NEW_LINE INDENT l = 0 ; r = m - 1 ; NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = ( l + r ) // 2 ; NEW_LINE temp = compareRow ( ar [ mid ] , arr ) ; NEW_LINE if ( temp == 0 ) : NEW_LINE INDENT return mid + 1 ; NEW_LINE DEDENT elif ( temp == 1 ) : NEW_LINE INDENT l = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT r = mid - 1 ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 0 , 0 , 1 , 0 ] , [ 10 , 9 , 22 , 23 ] , [ 40 , 40 , 40 , 40 ] , [ 43 , 44 , 55 , 68 ] , [ 81 , 73 , 100 , 132 ] , [ 100 , 75 , 125 , 133 ] ] ; NEW_LINE row = [ 10 , 9 , 22 , 23 ] ; NEW_LINE print ( binaryCheck ( mat , row ) ) ; NEW_LINE DEDENT
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 ; Function to find required value
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 ] > k or arr [ 0 ] < - 1 * k ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT arr = sorted ( arr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += n - upper_bound ( arr , arr [ i ] + k ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ - 1 , 4 , - 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE k = 0 NEW_LINE print ( findCnt ( arr , n , k ) ) NEW_LINE
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 ranges ; Subtract those ranges which are starting after R ; Subtract those ranges which are ending before L ; Driver Code
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 = sorted ( start ) NEW_LINE start = sorted ( end ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT L = type2 [ i ] [ 0 ] NEW_LINE R = type2 [ i ] [ 1 ] NEW_LINE ans -= ( len ( start ) - upper_bound ( start , R ) ) NEW_LINE ans -= ( upper_bound ( end , L - 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT type1 = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 4 , 5 ] , [ 6 , 7 ] ] NEW_LINE type2 = [ [ 1 , 5 ] , [ 2 , 3 ] , [ 4 , 7 ] , [ 5 , 7 ] ] NEW_LINE n = len ( type1 ) NEW_LINE m = len ( type2 ) NEW_LINE print ( FindIntersection ( type1 , n , type2 , m ) ) NEW_LINE
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 both a and b , both b and c , both c and a and then add which are divisible by a and b and c ; Function to find the nth term divisible by a , b or c by using binary search ; Set low to 1 and high to max ( a , b , c ) * n ; If the current term is less than n then we need to increase low to mid + 1 ; If current term is greater than equal to n then high = mid ; Driver code
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 ) + ( num // c ) - ( num // lcm ( a , b ) ) - ( num // lcm ( b , c ) ) - ( num // lcm ( a , c ) ) + ( num // lcm ( a , lcm ( b , c ) ) ) ) NEW_LINE DEDENT def findNthTerm ( a , b , c , n ) : NEW_LINE INDENT low = 1 NEW_LINE high = 10 ** 9 NEW_LINE mid = 0 NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( divTermCount ( a , b , c , mid ) < n ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT a = 2 NEW_LINE b = 3 NEW_LINE c = 5 NEW_LINE n = 10 NEW_LINE print ( findNthTerm ( a , b , c , n ) ) NEW_LINE
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 = max ( array ) Max subarray sum , considering subarray of length 1 ; Answer stores possible maximum sub array sum ; If mid is possible solution Put answer = mid ; ; Driver Code
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 DEDENT count += 1 NEW_LINE if ( count <= K ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def solve ( array , n , K ) : NEW_LINE INDENT end = 0 NEW_LINE for i in range ( n ) : NEW_LINE answer = 0 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE if ( check ( mid , array , n , K ) ) : NEW_LINE INDENT answer = mid NEW_LINE end = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT array = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( array ) NEW_LINE K = 3 NEW_LINE print ( solve ( array , n , K ) ) NEW_LINE DEDENT
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 AND of both the bitsets ; Find the count of 1 's ; Driver code
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 DEDENT bit3 = bit1 & bit2 ; NEW_LINE count = bin ( bit3 ) . count ( '1' ) ; NEW_LINE return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 4 , 7 , 2 , 3 ] ; NEW_LINE b = [ 2 , 11 , 7 , 4 , 15 , 20 , 24 ] ; NEW_LINE n = len ( a ) ; NEW_LINE m = len ( b ) ; NEW_LINE print ( count_common ( a , n , b , m ) ) ; NEW_LINE DEDENT
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 already present in the new array ; add a [ j ] at mid + 1. you can add it at mid ; if a [ j ] is lesser than b [ mid ] go right side ; means pos should be between start and mid - 1 ; else pos should be between mid + 1 and end ; if a [ j ] is the largest push it at last ; here max ( 0 , pos ) is used because sometimes pos can be negative as smallest duplicates can be present in the array ; Print the new generated sorted array ; Driver Code
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 = start + ( end - start ) // 2 NEW_LINE if b [ mid ] == a [ j ] : NEW_LINE INDENT b . insert ( max ( 0 , mid + 1 ) , a [ j ] ) NEW_LINE break NEW_LINE DEDENT elif b [ mid ] > a [ j ] : NEW_LINE INDENT pos = end = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT pos = start = mid + 1 NEW_LINE DEDENT if start > end : NEW_LINE INDENT pos = start NEW_LINE b . insert ( max ( 0 , pos ) , a [ j ] ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( b [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 5 , 4 , 9 , 8 ] NEW_LINE n = len ( a ) NEW_LINE createSorted ( a , n ) NEW_LINE DEDENT
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 contains every character at least k times ; To store the required maximum length ; Starting index of the sub - string ; Ending index of the sub - string ; If the frequency of every character of the current sub - string is at least k ; Update the maximum possible length ; Driver code
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 ] = 0 ; NEW_LINE DEDENT DEDENT def findlength ( string , n , k ) : NEW_LINE INDENT maxLen = 0 ; NEW_LINE freq = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT setZero ( freq ) ; NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT freq [ ord ( string [ j ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE if ( atLeastK ( freq , k ) ) : NEW_LINE INDENT maxLen = max ( maxLen , j - i + 1 ) ; NEW_LINE DEDENT DEDENT DEDENT return maxLen ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " xyxyyz " ; NEW_LINE n = len ( string ) ; NEW_LINE k = 2 ; NEW_LINE print ( findlength ( string , n , k ) ) ; NEW_LINE DEDENT
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 operations required to convert the given array to an increasing AP series with common difference as 1 ; Apply Binary Search ; If array can be generated with mid as the last element ; Current ans is mid ; Check whether the same can be achieved with even less operations ; Build the desired array ; Calculate the number of operations required ; Return the number of operations required ; Driver code
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 DEDENT DEDENT return True NEW_LINE DEDENT def minOperations ( arr , n ) : NEW_LINE INDENT start = arr [ n - 1 ] ; NEW_LINE end = max ( arr ) + n ; NEW_LINE max_arr = 0 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 ; NEW_LINE if ( check ( mid , n , arr ) ) : NEW_LINE INDENT max_arr = mid ; NEW_LINE end = mid - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT start = mid + 1 ; NEW_LINE DEDENT DEDENT desired = [ 0 ] * n ; NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT desired [ i ] = max_arr ; NEW_LINE max_arr -= 1 ; NEW_LINE DEDENT operations = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT operations += ( desired [ i ] - arr [ i ] ) ; NEW_LINE DEDENT return operations ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 4 , 5 , 5 , 7 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( minOperations ( arr , n ) ) ; NEW_LINE DEDENT
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 . next = ref_head NEW_LINE head = temp NEW_LINE DEDENT def countNode ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT s = set ( ) NEW_LINE s . add ( head . data ) NEW_LINE count = 0 NEW_LINE curr = head . next NEW_LINE while ( curr != None ) : NEW_LINE INDENT if ( curr . data in s ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT s . add ( curr . data ) NEW_LINE curr = curr . next NEW_LINE DEDENT return count NEW_LINE DEDENT insert ( head , 5 ) NEW_LINE insert ( head , 7 ) NEW_LINE insert ( head , 5 ) NEW_LINE insert ( head , 1 ) NEW_LINE insert ( head , 7 ) NEW_LINE print ( countNode ( head ) ) NEW_LINE
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 algorithm ; Current queue size ; Top - most element of queue ; Base case ; If we reach the destination i . e . index ( n - 1 ) ; Marking the cell visited ; Pushing the adjacent nodes i . e . indices reachable from the current index ; Driver code
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 ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( i == n - 1 ) : NEW_LINE INDENT return depth NEW_LINE DEDENT v [ i ] = 1 NEW_LINE if ( i + arr [ i ] < n ) : NEW_LINE INDENT q . append ( i + arr [ i ] ) NEW_LINE DEDENT if ( i - arr [ i ] >= 0 ) : NEW_LINE INDENT q . append ( i - arr [ i ] ) NEW_LINE DEDENT DEDENT depth += 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minSteps ( arr , n ) ) NEW_LINE DEDENT
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 both the arrays ; For every element of A [ ] apply binary search to find number of pairs where A wins ; B wins if A doesnot win ; Driver code
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 return ans NEW_LINE DEDENT def findwinner ( A , B , N , M ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT A [ i ] = divisorcount ( A [ i ] ) NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT B [ i ] = divisorcount ( B [ i ] ) NEW_LINE DEDENT A . sort ( ) NEW_LINE B . sort ( ) NEW_LINE winA = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT val = A [ i ] NEW_LINE start = 0 NEW_LINE end = M - 1 NEW_LINE index = - 1 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE if ( B [ mid ] <= val ) : NEW_LINE INDENT index = mid NEW_LINE start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT winA += ( index + 1 ) NEW_LINE DEDENT winB = N * M - winA NEW_LINE if ( winA > winB ) : NEW_LINE INDENT return " A " NEW_LINE DEDENT elif ( winB > winA ) : NEW_LINE INDENT return " B " NEW_LINE DEDENT return " Draw " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 4 , 12 , 24 ] NEW_LINE N = len ( A ) NEW_LINE B = [ 25 , 28 , 13 , 45 ] NEW_LINE M = len ( B ) NEW_LINE print ( findwinner ( A , B , N , M ) ) NEW_LINE 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 time ; Function to return the minimum time required ; Sort the two arrays ; Stores minimum time in which all the boxes can be transported ; Check for the minimum time in which all the boxes can be transported ; If it is possible to transport all the boxes in mid amount of time ; Driver code
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 ( temp == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def minTime ( box , truck , n , m ) : NEW_LINE INDENT box . sort ( ) ; NEW_LINE truck . sort ( ) ; NEW_LINE l = 0 NEW_LINE h = 2 * n NEW_LINE min_time = 0 NEW_LINE while ( l <= h ) : NEW_LINE INDENT mid = ( l + h ) // 2 NEW_LINE if ( isPossible ( box , truck , n , m , mid ) ) : NEW_LINE INDENT min_time = mid NEW_LINE h = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT return min_time NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT box = [ 10 , 2 , 16 , 19 ] NEW_LINE truck = [ 29 , 25 ] NEW_LINE n = len ( box ) NEW_LINE m = len ( truck ) NEW_LINE print ( minTime ( box , truck , n , m ) ) NEW_LINE DEDENT
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 range ( Q ) : NEW_LINE INDENT if ( Mark [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT count1 = [ 0 for i in range ( Q ) ] NEW_LINE if ( Mark [ 0 ] == 1 ) : NEW_LINE INDENT count1 [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , Q ) : NEW_LINE INDENT if ( Mark [ i ] == 1 ) : NEW_LINE INDENT count1 [ i ] = count1 [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT count1 [ i ] = count1 [ i - 1 ] NEW_LINE DEDENT DEDENT maxindex = 0 NEW_LINE maxcoverage = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT l = interval [ i ] [ 0 ] - 1 NEW_LINE r = interval [ i ] [ 1 ] - 1 NEW_LINE elem1 = 0 NEW_LINE if ( l != 0 ) : NEW_LINE INDENT elem1 = count1 [ r ] - count1 [ l - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT elem1 = count1 [ r ] NEW_LINE DEDENT if ( count - elem1 >= maxcoverage ) : NEW_LINE INDENT maxcoverage = count - elem1 NEW_LINE maxindex = i NEW_LINE DEDENT DEDENT print ( " Maximum ▁ Coverage ▁ is " , maxcoverage , " after ▁ removing ▁ interval ▁ at ▁ index " , maxindex ) NEW_LINE DEDENT interval = [ [ 1 , 4 ] , [ 4 , 5 ] , [ 5 , 6 ] , [ 6 , 7 ] , [ 3 , 5 ] ] NEW_LINE N = len ( interval ) NEW_LINE Q = 7 NEW_LINE solve ( interval , N , Q ) NEW_LINE
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 ; Returns the minimum maximum distance required to reach the end of the array in exactly k jumps ; Stores the answer ; Binary search to calculate the result ; Driver code
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 INDENT break NEW_LINE DEDENT prev = curr - 1 NEW_LINE DEDENT if ( curr != n ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( req <= k ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def minDistance ( arr , n , k ) : NEW_LINE INDENT l = 0 NEW_LINE h = arr [ n - 1 ] NEW_LINE ans = 0 NEW_LINE while ( l <= h ) : NEW_LINE INDENT m = ( l + h ) // 2 ; NEW_LINE if ( isPossible ( arr , n , m , k ) ) : NEW_LINE INDENT ans = m NEW_LINE h = m - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 15 , 36 , 43 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE print ( minDistance ( arr , n , k ) ) NEW_LINE
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 element will lie ; Find the position of the kth element in the interval in which it lies ; Driver code
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 INDENT m = ( l + h ) // 2 NEW_LINE if ( total [ m ] > k ) : NEW_LINE INDENT index = m NEW_LINE h = m - 1 NEW_LINE DEDENT elif ( total [ m ] < k ) : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT index = m NEW_LINE break NEW_LINE DEDENT DEDENT l = L [ index - 1 ] NEW_LINE h = R [ index - 1 ] NEW_LINE x = k - total [ index - 1 ] NEW_LINE while ( l <= h ) : NEW_LINE INDENT m = ( l + h ) // 2 NEW_LINE if ( ( m - L [ index - 1 ] ) + 1 == x ) : NEW_LINE INDENT return m NEW_LINE DEDENT elif ( ( m - L [ index - 1 ] ) + 1 > x ) : NEW_LINE INDENT h = m - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT DEDENT DEDENT L = [ 1 , 8 , 21 ] NEW_LINE R = [ 4 , 10 , 23 ] NEW_LINE n = len ( L ) NEW_LINE k = 6 NEW_LINE print ( getKthElement ( n , k , L , R ) ) NEW_LINE
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 - 1 NEW_LINE DEDENT elif ( ( a * m * m ) + ( b * m ) < ( k - c ) ) : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return m NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT a , b , c , k = 3 , 2 , 4 , 15 NEW_LINE print ( MinimumX ( a , b , c , k ) ) NEW_LINE
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 ; Stores the index of the largest number present in the array smaller than i ; Stores the index of the smallest number present in the array greater than i ; Find index of smallest number greater than i ; Find index of smallest number greater than i ; If there exists a number ; If no such number exists print no ; Driver code
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_LINE INDENT findex = 0 ; NEW_LINE lindex = 0 ; NEW_LINE l = 0 ; NEW_LINE r = n - 1 ; NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = ( l + r ) // 2 ; NEW_LINE if ( arr [ m ] < i ) : NEW_LINE INDENT findex = m ; NEW_LINE l = m + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 ; NEW_LINE DEDENT DEDENT l = 1 ; NEW_LINE r = n ; NEW_LINE flag = False ; NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = ( r + l ) // 2 ; NEW_LINE if ( arr [ m ] > i ) : NEW_LINE INDENT lindex = m ; NEW_LINE r = m - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 ; NEW_LINE DEDENT DEDENT if ( sum [ findex ] == sum [ n - 1 ] - sum [ lindex - 1 ] ) : NEW_LINE INDENT flag = True ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE IfExists ( arr , n ) ; NEW_LINE DEDENT
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 element ; Move left ; No missing element found ; Driver code
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 : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( arr [ mid ] - arr [ mid - 1 ] > 1 ) : NEW_LINE INDENT return arr [ mid ] - 1 NEW_LINE DEDENT else : NEW_LINE INDENT h = mid - 1 NEW_LINE DEDENT DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ - 9 , - 8 , - 7 , - 5 , - 4 , - 3 , - 2 , - 1 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMissing ( arr , n ) ) NEW_LINE
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 sequences ; Sum of the sequence starting from index i ; Update maximum ; Driver code
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 DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 4 , 7 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( maxSum ( arr , n , K ) ) NEW_LINE DEDENT
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 leftGreater and r ; If mid element is less than or equal to k update l ; Return the count of elements greater than k ; Driver code
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 DEDENT DEDENT return ( n - leftGreater ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 3 , 4 , 7 , 7 , 7 , 11 , 13 , 13 ] NEW_LINE n = len ( arr ) NEW_LINE k = 7 NEW_LINE print ( countGreater ( arr , n , k ) ) NEW_LINE DEDENT
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 operations can be performed on k without reducing it to <= 0 ; Perform operations ; Final check ; Driver code
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 >= 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT times = ( k - abs ( minimum ) ) // abs ( nVal ) NEW_LINE k = ( k - ( times * abs ( nVal ) ) ) NEW_LINE count = ( times * n ) NEW_LINE while ( k > 0 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT k = k + op [ i ] NEW_LINE count += 1 NEW_LINE if ( k <= 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT op = [ - 60 , 65 , - 1 , 14 , - 25 ] NEW_LINE n = len ( op ) NEW_LINE k = 100000 NEW_LINE print ( operations ( op , n , k ) ) NEW_LINE
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 value is greater than the mid value ; main function ; create the lookup table ; print the position of the array
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 += 1 NEW_LINE DEDENT DEDENT def binary ( arr , v ) : NEW_LINE INDENT index = lookup_table [ 0 ] - 1 NEW_LINE co = 0 NEW_LINE while lookup_table [ co ] != 0 : NEW_LINE INDENT if v == arr [ index ] : NEW_LINE INDENT return index NEW_LINE DEDENT elif v < arr [ index ] : NEW_LINE INDENT co += 1 NEW_LINE index -= lookup_table [ co ] NEW_LINE DEDENT else : NEW_LINE INDENT co += 1 NEW_LINE index += lookup_table [ co ] NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 3 , 5 , 6 , 7 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE create_table ( n ) NEW_LINE print ( " Position ▁ of ▁ 3 ▁ in ▁ array ▁ = ▁ " , binary ( arr , 3 ) ) NEW_LINE
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 = ( high + low ) // 2 ; NEW_LINE if ( countFactor ( 5 , mid ) < Y ) : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT N = mid ; NEW_LINE high = mid - 1 ; NEW_LINE DEDENT DEDENT return N ; NEW_LINE DEDENT Y = 10 ; NEW_LINE print ( findSmallestX ( Y ) ) ; NEW_LINE
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 NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return N NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 25 NEW_LINE print ( findMaxN ( X ) ) NEW_LINE DEDENT
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_LINE n = len ( a ) NEW_LINE k = 6 NEW_LINE index = findNumber ( a , n , k ) NEW_LINE if ( index != - 1 ) : NEW_LINE INDENT print ( index , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 , end = " " ) NEW_LINE DEDENT DEDENT
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 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT a = [ [ 1 , 3 ] , [ 4 , 7 ] , [ 8 , 11 ] ] NEW_LINE n = len ( a ) NEW_LINE k = 6 NEW_LINE index = findNumber ( a , n , k ) NEW_LINE if ( index != - 1 ) : NEW_LINE INDENT print ( index ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT
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 the value exists in the map ; Driver code ; prefix - Sum array ; Map to store the values of prefix - Sum ; Perform queries
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 DEDENT DEDENT def canDivide ( p_arr , n , q , l , r ) : NEW_LINE INDENT Sum = 0 NEW_LINE if ( l == 0 ) : NEW_LINE INDENT Sum = p_arr [ r ] NEW_LINE DEDENT else : NEW_LINE INDENT Sum = p_arr [ r ] - p_arr [ l - 1 ] NEW_LINE DEDENT if ( Sum % 2 == 1 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT beg = 0 NEW_LINE if ( l != 0 ) : NEW_LINE INDENT beg = p_arr [ l - 1 ] NEW_LINE DEDENT if ( beg + Sum // 2 in q . keys ( ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE p_arr = [ 0 for i in range ( n ) ] NEW_LINE prefixSum ( p_arr , arr , n ) NEW_LINE q = dict ( ) NEW_LINE hashPrefixSum ( p_arr , n , q ) NEW_LINE canDivide ( p_arr , n , q , 0 , 1 ) NEW_LINE canDivide ( p_arr , n , q , 1 , 3 ) NEW_LINE canDivide ( p_arr , n , q , 1 , 2 ) NEW_LINE
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 search on an array sorted in increasing order l and r represent the left and right index of the row to be searched ; Function to perform binary search on a particular column of the 2D array t and b represent top and bottom rows ; Function to perform binary search on an array sorted in decreasing order ; Function to perform binary search on a particular column of the 2D array ; Function to find the position of the number x ; Finding the ring ; To store row and column ; Edge case if n is odd ; Check which of the 4 sides , the number x lies in ; Printing the position ; Driver code
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 while l < r : NEW_LINE INDENT mid = ( l + r ) // 2 NEW_LINE if arr [ mid ] [ mid ] <= x : NEW_LINE INDENT if ( mid == ( n + 1 ) // 2 - 1 or arr [ mid + 1 ] [ mid + 1 ] > x ) : NEW_LINE INDENT return mid NEW_LINE DEDENT else : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT DEDENT return r NEW_LINE DEDENT def binarySearchRowInc ( arr , row , l , r , x ) : NEW_LINE INDENT while l <= r : NEW_LINE INDENT mid = ( l + r ) // 2 NEW_LINE if arr [ row ] [ mid ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ row ] [ mid ] < x : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def binarySearchColumnInc ( arr , col , t , b , x ) : NEW_LINE INDENT while t <= b : NEW_LINE INDENT mid = ( t + b ) // 2 NEW_LINE if arr [ mid ] [ col ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ mid ] [ col ] < x : NEW_LINE INDENT t = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT b = mid - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def binarySearchRowDec ( arr , row , l , r , x ) : NEW_LINE INDENT while l <= r : NEW_LINE INDENT mid = ( l + r ) // 2 NEW_LINE if arr [ row ] [ mid ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ row ] [ mid ] < x : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def binarySearchColumnDec ( arr , col , t , b , x ) : NEW_LINE INDENT while t <= b : NEW_LINE INDENT mid = ( t + b ) // 2 NEW_LINE if arr [ mid ] [ col ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ mid ] [ col ] < x : NEW_LINE INDENT b = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT t = mid + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def spiralBinary ( arr , x ) : NEW_LINE INDENT f1 = findRing ( arr , x ) NEW_LINE r , c = None , None NEW_LINE if f1 == - 1 : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT if n % 2 == 1 and f1 == ( n + 1 ) // 2 - 1 : NEW_LINE INDENT print ( f1 , f1 ) NEW_LINE return NEW_LINE DEDENT if x < arr [ f1 ] [ n - f1 - 1 ] : NEW_LINE INDENT c = binarySearchRowInc ( arr , f1 , f1 , n - f1 - 2 , x ) NEW_LINE r = f1 NEW_LINE DEDENT elif x < arr [ n - f1 - 1 ] [ n - f1 - 1 ] : NEW_LINE INDENT c = n - f1 - 1 NEW_LINE r = binarySearchColumnInc ( arr , n - f1 - 1 , f1 , n - f1 - 2 , x ) NEW_LINE DEDENT elif x < arr [ n - f1 - 1 ] [ f1 ] : NEW_LINE INDENT c = binarySearchRowDec ( arr , n - f1 - 1 , f1 + 1 , n - f1 - 1 , x ) NEW_LINE r = n - f1 - 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = binarySearchColumnDec ( arr , f1 , f1 + 1 , n - f1 - 1 , x ) NEW_LINE c = f1 NEW_LINE DEDENT if c == - 1 or r == - 1 : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " { 0 } ▁ { 1 } " . format ( r , c ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE arr = [ [ 1 , 2 , 3 , 4 ] , [ 12 , 13 , 14 , 5 ] , [ 11 , 16 , 15 , 6 ] , [ 10 , 9 , 8 , 7 ] ] NEW_LINE spiralBinary ( arr , 7 ) 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 can be traded for some gain ; If gain is more than the cost ; Return the total cost if gain < 0 ; Driver code
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_LINE INDENT gain -= 2 * cost [ i ] NEW_LINE DEDENT elif occurrences [ i ] > 1 : NEW_LINE INDENT gain += cost [ i ] * ( occurrences [ i ] - 1 ) NEW_LINE DEDENT DEDENT if gain >= 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT return gain * - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT cost = [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] NEW_LINE string = " geeksforgeeks " NEW_LINE print ( costToPanagram ( string , cost ) ) NEW_LINE DEDENT
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 ' ) + 1 NEW_LINE DEDENT score = score * m [ s ] NEW_LINE return score NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = [ " geeksforgeeks " , " algorithms " , " stack " ] NEW_LINE s = " algorithms " NEW_LINE n = len ( string ) NEW_LINE score = strScore ( string , s , n ) ; NEW_LINE print ( score ) NEW_LINE DEDENT
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 count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE k = 6 NEW_LINE print ( countSubArrays ( arr , n , k ) ) NEW_LINE DEDENT
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 ] ; Driver code
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 , mid + 1 , end ) NEW_LINE tree [ node ] = tree [ 2 * node ] | tree [ 2 * node + 1 ] NEW_LINE DEDENT def query ( node , start , end , l , r ) : NEW_LINE INDENT if start > end or start > r or end < l : NEW_LINE INDENT return 0 NEW_LINE DEDENT if start >= l and end <= r : NEW_LINE INDENT return tree [ node ] NEW_LINE DEDENT mid = ( start + end ) >> 1 NEW_LINE q1 = query ( 2 * node , start , mid , l , r ) NEW_LINE q2 = query ( 2 * node + 1 , mid + 1 , end , l , r ) NEW_LINE return q1 or q2 NEW_LINE DEDENT def countSubArrays ( arr , n , K ) : NEW_LINE INDENT build ( arr , 1 , 0 , n - 1 ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT bitwise_or = query ( 1 , 0 , n - 1 , i , j ) NEW_LINE if bitwise_or >= K : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE k = 6 NEW_LINE print ( countSubArrays ( arr , n , k ) ) NEW_LINE
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 ] >= K , then all subsequent subarrays will have OR >= K therefore reduce high to mid - 1 to find the minimal length subarray [ i . . mid ] having OR >= K ; Increase count with number of subarrays having OR >= K and starting with index i ; Driver code ; Build segment tree .
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 build ( arr , 2 * node + 1 , mid + 1 , end ) ; NEW_LINE tree [ node ] = tree [ 2 * node ] | tree [ 2 * node + 1 ] ; NEW_LINE DEDENT def query ( node , start , end , l , r ) : NEW_LINE INDENT if ( start > end or start > r or end < l ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( start >= l and end <= r ) : NEW_LINE INDENT return tree [ node ] ; NEW_LINE DEDENT mid = ( start + end ) >> 1 ; NEW_LINE q1 = query ( 2 * node , start , mid , l , r ) ; NEW_LINE q2 = query ( 2 * node + 1 , mid + 1 , end , l , r ) ; NEW_LINE return q1 | q2 ; NEW_LINE DEDENT def countSubArrays ( arr , n , K ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT low = i NEW_LINE high = n - 1 NEW_LINE index = 1000000000 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) >> 1 ; NEW_LINE if ( query ( 1 , 0 , n - 1 , i , mid ) >= K ) : NEW_LINE INDENT index = min ( index , mid ) ; NEW_LINE high = mid - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT DEDENT if ( index != 1000000000 ) : NEW_LINE INDENT count += n - index ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE build ( arr , 1 , 0 , n - 1 ) ; NEW_LINE k = 6 ; NEW_LINE print ( countSubArrays ( arr , n , k ) ) NEW_LINE DEDENT
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 pattern_int and all_ones ; If the pattern occurs in the last digits of n ; Right shift n by 1 bit ; Driver code
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 NEW_LINE power_two = power_two * 2 NEW_LINE i -= 1 NEW_LINE DEDENT count = 0 NEW_LINE while ( n != 0 and n >= pattern_int ) : NEW_LINE INDENT if ( ( n & all_ones ) == pattern_int ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT n = n >> 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 500 NEW_LINE pat = "10" NEW_LINE print ( countPattern ( n , pat ) ) NEW_LINE DEDENT
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 all distinct points ( Xi , Yi ) ; Hash xi coordinate ; Hash yi coordinate ; Hash the point ( xi , yi ) ; find pairs with same Xi ; calculate ( ( xFrequency ) C2 ) ; find pairs with same Yi ; calculate ( ( yFrequency ) C2 ) ; find pairs with same ( Xi , Yi ) ; calculate ( ( xyFrequency ) C2 ) ; Driver Code
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 ] NEW_LINE X [ xi ] += 1 NEW_LINE Y [ yi ] += 1 NEW_LINE XY [ tuple ( arr [ i ] ) ] += 1 NEW_LINE DEDENT xAns , yAns , xyAns = 0 , 0 , 0 NEW_LINE for xCoordinatePair in X : NEW_LINE INDENT xFrequency = X [ xCoordinatePair ] NEW_LINE sameXPairs = ( xFrequency * ( xFrequency - 1 ) ) // 2 NEW_LINE xAns += sameXPairs NEW_LINE DEDENT for yCoordinatePair in Y : NEW_LINE INDENT yFrequency = Y [ yCoordinatePair ] NEW_LINE sameYPairs = ( yFrequency * ( yFrequency - 1 ) ) // 2 NEW_LINE yAns += sameYPairs NEW_LINE DEDENT for XYPair in XY : NEW_LINE INDENT xyFrequency = XY [ XYPair ] NEW_LINE samePointPairs = ( xyFrequency * ( xyFrequency - 1 ) ) // 2 NEW_LINE xyAns += samePointPairs NEW_LINE DEDENT return ( xAns + yAns - xyAns ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 1 , 3 ] ] NEW_LINE n = len ( arr ) NEW_LINE print ( findManhattanEuclidPair ( arr , n ) ) NEW_LINE DEDENT
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 non - prime ; Compute primeUpto array ; Function to return the count of valid numbers ; Compute primeUpto array ; Check if the number is valid , try to reduce it ; ans is the minimum valid number ; Driver Code
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 for j in range ( i * 2 , MAX , i ) : NEW_LINE INDENT isPrime [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , MAX ) : NEW_LINE INDENT primeUpto [ i ] = primeUpto [ i - 1 ] NEW_LINE if isPrime [ i ] == 1 : NEW_LINE INDENT primeUpto [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT def countOfNumbers ( N , K ) : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE low , high , ans = 1 , N , 0 NEW_LINE while low <= high : NEW_LINE INDENT mid = ( low + high ) >> 1 NEW_LINE if mid - primeUpto [ mid ] >= K : NEW_LINE INDENT ans = mid NEW_LINE high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return ( N - ans + 1 ) if ans else 0 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N , K = 10 , 3 NEW_LINE print ( countOfNumbers ( N , K ) ) NEW_LINE DEDENT
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 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( minIndex ( arr , n ) ) NEW_LINE
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 greater than the given element ; Since arr [ i ] also exists in array , v [ it - 1 ] will be same as arr [ i ] . Let us check v [ it - 2 ] is also same as arr [ i ] . If true , then arr [ i ] exists twice in array , so ceiling is same same as arr [ i ] ; If next element is also same , then there are multiple occurrences , so print it ; Driver code
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 [ it - 2 ] == arr [ i ] : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT elif it <= n - 1 : NEW_LINE INDENT print ( v [ it ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 5 , 11 , 10 , 20 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE printPrevGreater ( arr , n ) NEW_LINE DEDENT
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 to given element ; If next element is also same , then there are multiple occurrences , so print it ; Otherwise print previous element ; Driver Code
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 , end = " ▁ " ) NEW_LINE DEDENT continue NEW_LINE DEDENT if v . count ( arr [ i ] ) > 0 : NEW_LINE INDENT it = v [ v . index ( arr [ i ] ) ] NEW_LINE DEDENT else : NEW_LINE INDENT it = v [ n - 1 ] NEW_LINE DEDENT if ( it != v [ n - 1 ] and v [ v . index ( it ) + 1 ] == arr [ i ] ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( v [ v . index ( it ) - 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 11 , 7 , 8 , 20 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE printPrevGreater ( arr , n ) NEW_LINE DEDENT
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 smallest value ; take new largest value ; Condition for secondary diagonal is mat [ n - 1 - i ] [ i ] take new smallest value ; take new largest value ; Declare and initialize 5 X5 matrix
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 INDENT if ( mat [ i ] [ i ] < principalMin ) : NEW_LINE INDENT principalMin = mat [ i ] [ i ] NEW_LINE DEDENT if ( mat [ i ] [ i ] > principalMax ) : NEW_LINE INDENT principalMax = mat [ i ] [ i ] NEW_LINE DEDENT if ( mat [ n - 1 - i ] [ i ] < secondaryMin ) : NEW_LINE INDENT secondaryMin = mat [ n - 1 - i ] [ i ] NEW_LINE DEDENT if ( mat [ n - 1 - i ] [ i ] > secondaryMax ) : NEW_LINE INDENT secondaryMax = mat [ n - 1 - i ] [ i ] NEW_LINE DEDENT DEDENT print ( " Principal ▁ Diagonal ▁ Smallest ▁ Element : ▁ " , principalMin ) NEW_LINE print ( " Principal ▁ Diagonal ▁ Greatest ▁ Element ▁ : ▁ " , principalMax ) NEW_LINE print ( " Secondary ▁ Diagonal ▁ Smallest ▁ Element : ▁ " , secondaryMin ) NEW_LINE print ( " Secondary ▁ Diagonal ▁ Greatest ▁ Element : ▁ " , secondaryMax ) NEW_LINE DEDENT matrix = [ [ 1 , 2 , 3 , 4 , - 10 ] , [ 5 , 6 , 7 , 8 , 6 ] , [ 1 , 2 , 11 , 3 , 4 ] , [ 5 , 6 , 70 , 5 , 8 ] , [ 4 , 9 , 7 , 1 , - 5 ] ] NEW_LINE diagonalsMinMax ( matrix ) NEW_LINE
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 swap 5 and 2. ; Cases like { 1 , 2 , 4 , 3 , 5 } ; Now check if array becomes sorted for cases like { 4 , 1 , 2 , 3 } ; Driver Code
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 DEDENT DEDENT if count > 2 : NEW_LINE INDENT return False NEW_LINE DEDENT if count == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT if count == 2 : NEW_LINE INDENT ( arr [ first - 1 ] , arr [ second ] ) = ( arr [ second ] , arr [ first - 1 ] ) NEW_LINE DEDENT elif count == 1 : NEW_LINE INDENT ( arr [ first - 1 ] , arr [ first ] ) = ( arr [ first ] , arr [ first - 1 ] ) NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] < arr [ i - 1 ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE if checkSorted ( n , arr ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ [ 2 , 4 , 6 , 8 ] , [ 1 , 3 , 5 , 7 ] , [ 8 , 6 , 4 , 2 ] , [ 7 , 5 , 3 , 1 ] ] NEW_LINE B = [ [ 2 , 3 , 6 , 8 ] , [ 1 , 3 , 5 , 2 ] , [ 8 , 1 , 4 , 2 ] , [ 3 , 5 , 4 , 1 ] ] NEW_LINE printIntersection ( A , B ) NEW_LINE DEDENT
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 of size max_val + 1. We can also use HashMap to store frequencies . We have used an array to keep remaining code simple . ; Case 1 : 0 , 0 , 0 ; Case 2 : 0 , x , x ; Case 3 : x , x , 2 * x ; Case 4 : x , y , x + y iterate through all pairs ( x , y ) ; Driver code
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 += ( freq [ 0 ] * ( freq [ 0 ] - 1 ) * ( freq [ 0 ] - 2 ) // 6 ) NEW_LINE for i in range ( 1 , max_val + 1 ) : NEW_LINE INDENT ans += ( freq [ 0 ] * freq [ i ] * ( freq [ i ] - 1 ) // 2 ) NEW_LINE DEDENT for i in range ( 1 , ( max_val + 1 ) // 2 ) : NEW_LINE INDENT ans += ( freq [ i ] * ( freq [ i ] - 1 ) // 2 * freq [ 2 * i ] ) NEW_LINE DEDENT for i in range ( 1 , max_val + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , max_val - i + 1 ) : NEW_LINE INDENT ans += freq [ i ] * freq [ j ] * freq [ i + j ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countWays ( arr , n ) ) NEW_LINE