text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Count number of triangles possible for the given sides range | Function to count the number of possible triangles for the given sides ranges ; Iterate for every possible of x ; Range of y is [ b , c ] From this range First we will find the number of x + y greater than d ; For x + y greater than d we can choose all z fr... | def count_triangles ( a , b , c , d ) : NEW_LINE INDENT ans = 0 NEW_LINE for x in range ( a , b + 1 ) : NEW_LINE INDENT num_greater_than_d = ( max ( d , c + x ) - max ( d , b + x - 1 ) ) NEW_LINE ans = ( ans + num_greater_than_d * ( d - c + 1 ) ) NEW_LINE r = min ( max ( c , c + x ) , d ) - c ; NEW_LINE l = min ( max (... |
Minimum number of swaps required to make the string K periodic | Python3 code to find the minimum number of swaps required to make the string K periodic ; Mark all allowed characters as true ; Initialize the freq array to 0 ; Increase the frequency of each character ; Total number of periods of size K in the string ; C... | def minFlip ( s , n , k , a , p ) : NEW_LINE INDENT allowed = [ 0 ] * 26 NEW_LINE for i in range ( p ) : NEW_LINE INDENT allowed [ ord ( a [ i ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT freq = [ [ 0 for x in range ( 26 ) ] for y in range ( k ) ] NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( 26 ) : ... |
Minimum number of colors required to color a Circular Array | Function that finds minimum number of colors required ; To check that if all the elements are same or not ; To check if only one adjacent exist ; Traverse the array ; If adjacent elements found different means all are not same ; If two adjacent elements foun... | def colorRequired ( arr , n ) : NEW_LINE INDENT all_same = True NEW_LINE one_adjacent_same = False NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i + 1 ] ) : NEW_LINE INDENT all_same = False NEW_LINE DEDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT one_adjacent_same = True NEW_LIN... |
Maximize the sum of sum of the Array by removing end elements | Function to find the maximum sum of sum ; Compute the sum of whole array ; Traverse and remove the minimum value from an end to maximum the sum value ; If the left end element is smaller than right end ; Remove the left end element ; If the right end eleme... | def maxRemainingSum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT i = 0 NEW_LINE j = n - 1 NEW_LINE result = 0 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( arr [ i ] < arr [ j ] ) : NEW_LINE INDENT sum -= arr [ i ] NEW_LINE i += 1 NEW_LINE DEDE... |
Split a number as sum of K numbers which are not divisible by K | Function to split into K parts and print them ; Print 1 K - 1 times ; Print N - K + 1 ; Print 1 K - 2 times ; Print 2 and N - K ; Driver code | def printKParts ( N , K ) : NEW_LINE INDENT if ( N % K == 0 ) : NEW_LINE INDENT for i in range ( 1 , K ) : NEW_LINE INDENT print ( "1 , β " ) ; NEW_LINE DEDENT print ( N - ( K - 1 ) , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( K == 2 ) : NEW_LINE INDENT print ( " Not β Possible " , end = " " ) ; NEW_LINE... |
Make the intervals non | Function to assign the intervals to two different processors ; Loop to pair the interval with their indices ; sorting the interval by their startb times ; Loop to iterate over the intervals with their start time ; Condition to check if there is a possible solution ; form = ''.join(form) ; Drive... | def assignIntervals ( interval , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT interval [ i ] . append ( i ) NEW_LINE DEDENT interval . sort ( key = lambda x : x [ 0 ] ) NEW_LINE firstEndTime = - 1 NEW_LINE secondEndTime = - 1 NEW_LINE fin = ' ' NEW_LINE flag = False NEW_LINE for i in range ( n ) : NEW_L... |
Minimum operation required to make a balanced sequence | Python3 implementation of the approach ; Function to return the minimum operations required ; Condition where we got only one closing bracket instead of 2 , here we have to add one more closing bracket to make the sequence balanced ; Add closing bracket that cost... | from queue import LifoQueue NEW_LINE def minOperations ( s , len ) : NEW_LINE INDENT operationCnt = 0 ; NEW_LINE st = LifoQueue ( ) ; NEW_LINE cntClosing = 0 ; NEW_LINE for i in range ( 0 , len ) : NEW_LINE INDENT if ( s [ i ] == ' { ' ) : NEW_LINE INDENT if ( cntClosing > 0 ) : NEW_LINE INDENT operationCnt += 1 ; NEW_... |
Longest subsequence with different adjacent characters | Function to find the longest Subsequence with different adjacent character ; Length of the string s ; Previously picked character ; If the current character is different from the previous then include this character and update previous character ; Driver Code ; F... | def longestSubsequence ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE answer = 0 ; NEW_LINE prev = ' - ' ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( prev != s [ i ] ) : NEW_LINE INDENT prev = s [ i ] ; NEW_LINE answer += 1 ; NEW_LINE DEDENT DEDENT return answer ; NEW_LINE DEDENT str = " ababa " ; NEW_L... |
Length of longest subarray of length at least 2 with maximum GCD | Function to calculate GCD of two numbers ; Function to find maximum size subarray having maximum GCD ; Base case ; Let the maximum GCD be 1 initially ; Loop through array to find maximum GCD of subarray with size 2 ; Traverse the array ; Is a multiple o... | def gcd ( a , b ) : NEW_LINE INDENT if b == 0 : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def maxGcdSubarray ( arr , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT k = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT k = max ( k , gcd ( arr [ i ] ... |
Split N powers of 2 into two subsets such that their difference of sum is minimum | Python3 program to find the minimum difference possible by splitting all powers of 2 up to N into two sets of equal size ; Store the largest ; Form two separate groups ; Initialize the sum for two groups as 0 ; Insert 2 ^ n in the first... | def MinDiff ( n ) : NEW_LINE INDENT val = 2 ** n NEW_LINE sep = n // 2 NEW_LINE grp1 = 0 NEW_LINE grp2 = 0 NEW_LINE grp1 = grp1 + val NEW_LINE for i in range ( 1 , sep ) : NEW_LINE INDENT grp1 = grp1 + 2 ** i NEW_LINE DEDENT for i in range ( sep , n ) : NEW_LINE INDENT grp2 = grp2 + 2 ** i NEW_LINE DEDENT print ( abs (... |
Count elements in first Array with absolute difference greater than K with an element in second Array | Function to count the such elements ; Store count of required elements in arr1 ; Initialise the smallest and the largest value from the second array arr2 [ ] ; Find the smallest and the largest element in arr2 ; Chec... | def countDist ( arr1 , n , arr2 , m , k ) : NEW_LINE INDENT count = 0 NEW_LINE smallest = arr2 [ 0 ] NEW_LINE largest = arr2 [ 0 ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT smallest = max ( smallest , arr2 [ i ] ) NEW_LINE largest = min ( largest , arr1 [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDE... |
Make sum of all subarrays of length K equal by only inserting elements | Function that prints another array whose all subarray of length k have an equal sum ; Store all distinct elements in the unordered map ; Condition if the number of distinct elements is greater than k ; Push all distinct elements in a vector ; Push... | def MakeArray ( a , n , k ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in a : NEW_LINE INDENT if i not in mp : NEW_LINE INDENT mp [ a [ i ] ] = 1 NEW_LINE DEDENT DEDENT if ( len ( mp ) > k ) : NEW_LINE print ( " Not β possible " ) NEW_LINE return NEW_LINE ans = [ ] NEW_LINE for i in mp : NEW_LINE INDENT ans . appen... |
Longest substring with atmost K characters from the given set of characters | Function to find the longest substring in the string which contains atmost K characters from the given set of characters ; Base Condition ; Count for Characters from set in substring ; Two pointers ; Loop to iterate until right pointer is not... | def maxNormalSubstring ( P , Q , K , N ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 0 NEW_LINE left = 0 NEW_LINE right = 0 NEW_LINE ans = 0 NEW_LINE while ( right < N ) : NEW_LINE INDENT while ( right < N and count <= K ) : NEW_LINE INDENT if ( P [ right ] in Q ) : NEW_LINE INDEN... |
Find the minimum value of the given expression over all pairs of the array | Python3 program to find the minimum value of the given expression over all pairs of the array ; Function to find the minimum value of the expression ; Iterate over all the pairs and find the minimum value ; Driver code | import sys NEW_LINE def MinimumValue ( a , n ) : NEW_LINE INDENT answer = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n , 1 ) : NEW_LINE INDENT answer = min ( answer , ( ( a [ i ] & a [ j ] ) ^ ( a [ i ] a [ j ] ) ) ) NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __n... |
Number of substrings with length divisible by the number of 1 's in it | Function return count of such substring ; Mark 1 at those indices where '1' appears ; Take prefix sum ; Iterate through all the substrings ; Driver Code | def countOfSubstrings ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE prefix_sum = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT prefix_sum [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , n , 1 ) : NEW_LINE INDENT prefix_sum [ i ] += prefix_sum [... |
Find the number of elements X such that X + K also exists in the array | Function to return the count of element x such that x + k also lies in this array ; Key in map will store elements and value will store the frequency of the elements ; Find if i . first + K is present in this map or not ; If we find i . first or k... | def count_element ( N , K , arr ) : 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 answer = 0 NEW_LINE for i in mp : NEW_LINE INDENT if i + K in mp : NEW_LINE INDENT answer += mp [ i ] NEW_LINE DEDENT DEDENT return answer N... |
Find the size of largest group where groups are according to the xor of digits | Function to find out xor of digit ; Calculate xor digitwise ; Return xor ; Function to find the size of largest group ; Hash map for counting frequency ; Counting freq of each element ; Find the maximum ; Initialise N | def digit_xor ( x ) : NEW_LINE INDENT xorr = 0 NEW_LINE while ( x != 0 ) : NEW_LINE INDENT xorr ^= x % 10 NEW_LINE x = x // 10 NEW_LINE DEDENT return xorr NEW_LINE DEDENT def find_count ( n ) : NEW_LINE INDENT mpp = { } NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if digit_xor ( i ) in mpp : NEW_LINE INDENT ... |
Count of largest sized groups while grouping according to product of digits | Function to find out product of digit ; calculate product ; return the product of digits ; Function to find the count ; hash map for counting frequency ; counting freq of each element ; find the maximum ; count the number of groups having siz... | def digit_prod ( x ) : NEW_LINE INDENT prod = 1 NEW_LINE while ( x ) : NEW_LINE INDENT prod = prod * ( x % 10 ) NEW_LINE x = x // 10 NEW_LINE DEDENT return prod NEW_LINE DEDENT def find_count ( n ) : NEW_LINE INDENT mpp = { } NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT x = digit_prod ( i ) NEW_LINE if x in ... |
Count of subarrays having exactly K prime numbers | Python3 program for the above approach ; A utility function to check if the number n is prime or not ; Base Cases ; Check to skip middle five numbers in below loop ; If n is divisible by i & i + 2 then it is not prime ; Function to find number of subarrays with sum ex... | from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 5 , int ( sqrt ( n ) ) + 1 , 6 ) : N... |
Count the elements having frequency equals to its value | Function to find the count ; Hash map for counting frequency ; Counting freq of each element ; Check if value equals to frequency and increment the count ; Driver code ; Function call | def find_maxm ( arr , n ) : NEW_LINE INDENT mpp = { } NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] in mpp : NEW_LINE INDENT mpp [ arr [ i ] ] = mpp [ arr [ i ] ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT mpp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for key in mpp : NEW_LINE INDENT ... |
Find the Number of Permutations that satisfy the given condition in an array | Function to calculate x ^ y recursively ; Function to return the number of permutations that satisfy the given condition in an array ; If there is only one element then only one permutation is available ; Sort the array for calculating the n... | def pow ( x , y ) : NEW_LINE INDENT if ( y == 1 ) : NEW_LINE INDENT return x NEW_LINE DEDENT if ( y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT temp = pow ( x , y // 2 ) NEW_LINE temp *= temp NEW_LINE if ( y & 1 ) : NEW_LINE INDENT temp *= x NEW_LINE DEDENT return temp NEW_LINE DEDENT def noOfPermutations ( a , n... |
Length of the Smallest Subarray that must be removed in order to Maximise the GCD | Function to find the length of the smallest subarray that must be removed in order to maximise the GCD ; Store the maximum possible GCD of the resulting subarray ; Two pointers initially pointing to the first and last element respective... | def GetMinSubarrayLength ( a , n ) : NEW_LINE INDENT ans = max ( a [ 0 ] , a [ n - 1 ] ) NEW_LINE lo = 0 NEW_LINE hi = n - 1 NEW_LINE while ( lo < n and a [ lo ] % ans == 0 ) : NEW_LINE INDENT lo += 1 NEW_LINE DEDENT while ( hi > lo and a [ hi ] % ans == 0 ) : NEW_LINE INDENT hi -= 1 NEW_LINE DEDENT return ( hi - lo + ... |
Maximize the number of indices such that element is greater than element to its left | Function to find the maximum pairs such that arr [ i + 1 ] > arr [ i ] ; To store the frequency of the element in arr [ ] ; Store the frequency in map M ; To find the maximum frequency store in map M ; Print the maximum number of pos... | def countPairs ( arr , N ) : NEW_LINE INDENT M = dict . fromkeys ( arr , 0 ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT M [ arr [ i ] ] += 1 ; NEW_LINE DEDENT maxFreq = 0 ; NEW_LINE for it in M . values ( ) : NEW_LINE INDENT maxFreq = max ( maxFreq , it ) ; NEW_LINE DEDENT print ( N - maxFreq ) ; NEW_LINE DEDENT... |
Find minimum value of the expression by choosing K elements from given array | Function to find the minimum possible of the expression by choosing exactly K ( ? N ) integers form given array arr ; Sorting the array for least k element selection ; Select first k elements from sorted array ; Return value of solved expres... | def minimumValue ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE answer = 0 ; NEW_LINE for i in range ( k ) : NEW_LINE INDENT answer += arr [ i ] * arr [ i ] ; NEW_LINE DEDENT return answer * ( 2 * k - 2 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 21 , 5 , 3 , 8 ] ; NEW... |
Transform N to Minimum possible value | Python3 program to transform N to the minimum value ; Initialising the answer ; Function to find the digitsum ; Iterate over all digits and add them ; Return the digit su , ; Function to transform N to the minimum value ; If the final value is lesser than least value ; If final v... | import sys ; NEW_LINE min_val = sys . maxsize ; NEW_LINE min_steps = 0 ; NEW_LINE def sumOfDigits ( n ) : NEW_LINE INDENT s = str ( n ) ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT sum += ( ord ( s [ i ] ) - ord ( '0' ) ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def Transform ( n ,... |
Remove all 1 s from the adjacent left of 0 s in a Binary Array | Function to find the maximum number of 1 's before 0 ; Traverse the array ; If value is 1 ; If consecutive 1 followed by 0 , then update the maxCnt ; Print the maximum consecutive 1 's followed by 0 ; Driver Code ; Function Call ; Function Call | def noOfMoves ( arr , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE maxCnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( cnt != 0 ) : NEW_LINE INDENT maxCnt = max ( maxCnt , cnt ) NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT DEDENT p... |
Check if given coins can be used to pay a value of S | Function to check if it is possible to pay a value ; Loop to add the value of coin A ; Condition to check if it is possible to pay a value of S ; Driver Code | def knowPair ( a , b , n , s , m ) : NEW_LINE INDENT i = 0 NEW_LINE rem = 0 NEW_LINE count_b = 0 NEW_LINE flag = 0 NEW_LINE while ( i <= a ) : NEW_LINE INDENT rem = s - ( n * i ) NEW_LINE count_b = rem // m NEW_LINE if ( rem % m == 0 and count_b <= b ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT i... |
Sum of all numbers in the given range which are divisible by M | Function to find the sum of numbers divisible by M in the given range ; Variable to store the sum ; Running a loop from A to B and check if a number is divisible by i . ; If the number is divisible , then add it to sum ; Return the sum ; Driver code ; A a... | def sumDivisibles ( A , B , M ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( A , B + 1 ) : NEW_LINE INDENT if ( i % M == 0 ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 6 NEW_LINE B = 15 NEW_LINE M = 3 NEW_LINE print ( sumDivi... |
Sum of all numbers in the given range which are divisible by M | Function to find the largest number smaller than or equal to N that is divisible by K ; Finding the remainder when N is divided by K ; If the remainder is 0 , then the number itself is divisible by K ; Else , then the difference between N and remainder is... | def findSmallNum ( N , K ) : NEW_LINE INDENT rem = N % K NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT return N NEW_LINE DEDENT else : NEW_LINE INDENT return N - rem NEW_LINE DEDENT DEDENT def findLargeNum ( N , K ) : NEW_LINE INDENT rem = ( N + K ) % K NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT return N NEW_LINE DEDENT e... |
Count of all unique substrings with non | Function to count all unique distinct character substrings ; Hashmap to store all substrings ; Iterate over all the substrings ; Boolean array to maintain all characters encountered so far ; Variable to maintain the subtill current position ; Get the position of the character i... | def distinctSubstring ( P , N ) : NEW_LINE INDENT S = dict ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq = [ False ] * 26 NEW_LINE s = " " NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT pos = ord ( P [ j ] ) - ord ( ' a ' ) NEW_LINE if ( freq [ pos ] == True ) : NEW_LINE INDENT break NEW_LINE DEDENT fre... |
Sum of all subarrays of size K | Function to find the sum of all subarrays of size K ; Loop to consider every subarray of size K ; Initialize sum = 0 ; Calculate sum of all elements of current subarray ; Prsum of each subarray ; Driver Code ; Function Call | def calcSum ( arr , n , k ) : NEW_LINE INDENT for i in range ( n - k + 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( i , k + i ) : NEW_LINE INDENT sum += arr [ j ] NEW_LINE DEDENT print ( sum , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LIN... |
Sum of all subarrays of size K | Function to find the sum of all subarrays of size K ; Initialize sum = 0 ; Consider first subarray of size k Store the sum of elements ; Print the current sum ; Consider every subarray of size k Remove first element and add current element to the window ; Add the element which enters in... | def calcSum ( arr , n , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT print ( sum , end = " β " ) NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT sum = ( sum - arr [ i - k ] ) + arr [ i ] NEW_LINE print ( sum , end = " β " ) NEW_LINE DEDENT DEDENT if ... |
Number of indices pair such that element pair sum from first Array is greater than second Array | Python 3 program to find the number of indices pair such that pair sum from first Array is greater than second Array ; Function to get the number of pairs of indices { i , j } in the given two arrays A and B such that A [ ... | import bisect NEW_LINE def getPairs ( A , B , n ) : NEW_LINE INDENT D = [ 0 ] * ( n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT D [ i ] = A [ i ] - B [ i ] NEW_LINE DEDENT D . sort ( ) NEW_LINE total = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( D [ i ] > 0 ) : NEW_LINE INDENT total += ... |
Number of pairs such that their HCF and LCM is equal | Function to return HCF of two numbers ; Function to return LCM of two numbers ; Returns the number of valid pairs ; Traversing the array . For each array element , checking if it follow the condition ; Driver function | 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 countPairs ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in ra... |
Number of pairs such that their HCF and LCM is equal | Python 3 program to count number of pairs such that their hcf and lcm are equal ; Function to count number of pairs such that their hcf and lcm are equal ; Store frequencies of array elements ; Count of pairs ( arr [ i ] , arr [ j ] ) where arr [ i ] = arr [ j ] ; ... | from collections import defaultdict NEW_LINE def countPairs ( a , n ) : NEW_LINE INDENT frequency = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT frequency [ a [ i ] ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for x in frequency . keys ( ) : NEW_LINE INDENT f = frequency [ x ] NEW_LINE count += f * ... |
Find the maximum possible value of last element of the Array | Function to find the maximum possible value of last element of the array ; Traverse for all element ; Find the distance ; If moves less than distance then we can not move this number to end ; How many number we can move to end ; Take the minimum of both of ... | def maxValue ( arr , n , moves ) : NEW_LINE INDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT distance = n - 1 - i NEW_LINE if ( moves < distance ) : NEW_LINE INDENT break NEW_LINE DEDENT can_take = moves // distance NEW_LINE take = min ( arr [ i ] , can_take ) NEW_LIN... |
Minimum number of Factorials whose sum is equal to N | Array to calculate all factorials less than or equal to N Since there can be only 14 factorials till 10 ^ 10 Hence the maximum size of fact [ ] is 14 ; Store the actual size of fact [ ] ; Function to precompute factorials till N ; Precomputing factorials ; Function... | fact = [ 0 ] * 14 NEW_LINE size = 1 NEW_LINE def preCompute ( N ) : NEW_LINE INDENT global size NEW_LINE fact [ 0 ] = 1 NEW_LINE i = 1 NEW_LINE while fact [ i - 1 ] <= N : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE size += 1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT def findMin ( N ) : NEW_LINE INDENT preCom... |
Longest increasing sub | Function to find the LCS ; Loop to create frequency array ; Driver code | def findLCS ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT return len ( mp ) NEW_LINE DEDENT n = 3 NEW_LINE arr = [ 3 , 2 , 1 ] NEW_LINE p... |
Path with maximum product in 2 | Python Program to find maximum product path from ( 0 , 0 ) to ( N - 1 , M - 1 ) ; Function to find maximum product ; It will store the maximum product till a given cell . ; It will store the minimum product till a given cell ( for - ve elements ) ; If we are at topmost or leftmost , jus... | import sys NEW_LINE N = 3 ; NEW_LINE M = 3 ; NEW_LINE def maxProductPath ( arr ) : NEW_LINE INDENT maxPath = [ [ 0 for i in range ( M ) ] for j in range ( N ) ] ; NEW_LINE minPath = [ [ 0 for i in range ( M ) ] for j in range ( N ) ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDE... |
Vertical and Horizontal retrieval ( MRT ) on Tapes | Python3 program to print Vertical filling ; 2D matrix for vertical insertion on tapes ; It is used for checking whether tape is full or not ; It is used for calculating total retrieval time ; It is used for calculating mean retrieval time ; It is used for calculating... | import numpy as np NEW_LINE def vertical_Fill ( records , tape , m , n ) : NEW_LINE INDENT v = np . zeros ( ( m , n ) ) ; NEW_LINE sum = 0 ; NEW_LINE Retrieval_Time = 0 ; NEW_LINE Mrt = None ; NEW_LINE z = 0 ; j = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT sum = 0 ; NEW_L... |
Minimum number of subsequences required to convert one string to another | Python3 program to find the Minimum number of subsequences required to convert one to another ; Function to find the no of subsequences ; Push the values of indexes of each character ; Find the next index available in the array ; If Character is... | from bisect import bisect as upper_bound NEW_LINE def minSubsequnces ( A , B ) : NEW_LINE INDENT v = [ [ ] for i in range ( 26 ) ] NEW_LINE minIndex = - 1 NEW_LINE cnt = 1 NEW_LINE j = 0 NEW_LINE flag = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT p = ord ( A [ i ] ) - 97 NEW_LINE v [ p ] . append ( i ) NE... |
Find two equal subsequences of maximum length with at least one different index | Python implementation of the approach ; Function to return the required length of the subsequences ; To store the result ; To store the last visited position of lowercase letters ; Initialisation of frequency array to - 1 to indicate no c... | MAX = 26 ; NEW_LINE def maxLength ( str , len ) : NEW_LINE INDENT res = 0 ; NEW_LINE lastPos = [ 0 ] * MAX ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT lastPos [ i ] = - 1 ; NEW_LINE DEDENT for i in range ( len ) : NEW_LINE INDENT C = ord ( str [ i ] ) - ord ( ' a ' ) ; NEW_LINE if ( lastPos [ C ] != - 1 ) : NEW... |
Maximum profit by selling N items at two markets | Python3 implementation of the approach ; Max profit will be saved here ; loop to check all possible combinations of sales ; the sum of the profit after the sale for products 0 to i in market A ; the sum of the profit after the sale for products i to n in market B ; Rep... | def maxProfit ( a , b , n ) : NEW_LINE INDENT maxP = - 1 NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT sumA = sum ( a [ : i ] ) NEW_LINE sumB = sum ( b [ i : ] ) NEW_LINE maxP = max ( maxP , sumA + sumB ) NEW_LINE DEDENT return maxP NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 3... |
Partitions possible such that the minimum element divides all the other elements of the partition | Python3 implementation of the approach ; Function to return the count partitions possible from the given array such that the minimum element of any partition divides all the other elements of that partition ; Initialize ... | import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def countPartitions ( A , N ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT min_elem = min ( A ) ; NEW_LINE if ( min_elem == INT_MAX ) : NEW_LINE INDENT break ; NEW_LINE DEDENT count += 1 ; NEW_LINE for i in range ( N ) : NEW_LINE IN... |
Minimum number of swaps to make two binary string equal | Function to calculate min swaps to make binary strings equal ; Count of zero 's ; Count of one 's ; As discussed above ; Driver code | def minSwaps ( s1 , s2 ) : NEW_LINE INDENT c0 = 0 ; c1 = 0 ; NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( s1 [ i ] == '0' and s2 [ i ] == '1' ) : NEW_LINE INDENT c0 += 1 ; NEW_LINE DEDENT elif ( s1 [ i ] == '1' and s2 [ i ] == '0' ) : NEW_LINE INDENT c1 += 1 ; NEW_LINE DEDENT DEDENT ans = c0 // 2 + c1 ... |
Minimum changes required to make all element in an array equal | Function to count of minimum changes required to make all elements equal ; Store the count of each element as key - value pair in Dictionary ; Traverse through the Dictionary and find the maximum occurring element ; Return count of all element minus count... | def minChanges ( arr , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT maxElem = 0 NEW_LINE for x in mp : NEW_LINE INDENT maxElem =... |
Minimum operations to make two numbers equal | Python3 implementation of the above approach ; Function to find the minimum no . of operations ; find the maximum of two and store it in p ; increase it until it is achievable from given n and m ; Here value added to n and m will be S ( n ) = p - n + p - m ; check whether ... | from math import sqrt , floor NEW_LINE def minOperations ( n , m ) : NEW_LINE INDENT a = 0 ; k = 1 ; NEW_LINE p = max ( n , m ) ; NEW_LINE while ( n != m ) : NEW_LINE INDENT s = float ( p - n + p - m ) ; NEW_LINE q = ( - 1 + sqrt ( 8 * s + 1 ) ) / 2 ; NEW_LINE if ( q - floor ( q ) == 0 ) : NEW_LINE INDENT a = q ; NEW_L... |
Count of subarrays with sum at least K | Function to return the number of subarrays with sum atleast k ; To store the right index and the current sum ; To store the number of sub - arrays ; For all left indexes ; Get elements till current sum is less than k ; No such subarray is possible ; Add all possible subarrays ; ... | def k_sum ( a , n , k ) : NEW_LINE INDENT r , sum = 0 , 0 ; NEW_LINE ans = 0 ; NEW_LINE for l in range ( n ) : NEW_LINE INDENT while ( sum < k ) : NEW_LINE INDENT if ( r == n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT else : NEW_LINE INDENT sum += a [ r ] ; NEW_LINE r += 1 ; NEW_LINE DEDENT DEDENT if ( sum < k ) : NEW... |
Find if a crest is present in the index range [ L , R ] of the given array | Function that returns true if the array contains a crest in the index range [ L , R ] ; To keep track of elements which satisfy the Property ; Property is satisfied for the current element ; Cumulative Sum ; If a crest is present in the given ... | def hasCrest ( arr , n , L , R ) : NEW_LINE INDENT present = [ 0 ] * n ; NEW_LINE for i in range ( 1 , n - 2 + 1 ) : NEW_LINE INDENT if ( ( arr [ i ] <= arr [ i + 1 ] ) and ( arr [ i ] <= arr [ i - 1 ] ) ) : NEW_LINE INDENT present [ i ] = 1 ; NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT present [ ... |
Maximum Sum of Products of two arrays by toggling adjacent bits | Python3 program to find the maximum SoP of two arrays by toggling adjacent bits in the second array ; Function to return Max Sum ; intialParity and finalParity are 0 if total no . of 1 's is even else 1 ; minPositive and maxNegative will store smallest p... | import sys NEW_LINE def maxSum ( arr1 , arr2 , n ) : NEW_LINE INDENT initialParity , finalParity = 0 , 0 NEW_LINE sum = 0 NEW_LINE minPositive = sys . maxsize NEW_LINE maxNegative = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT initialParity += arr2 [ i ] ; NEW_LINE if ( arr1 [ i ] >= 0 ) : NEW_LI... |
Minimum number to be added to all digits of X to make X > Y | Function to check if X is lexicographically larger Y ; It is lexicographically larger ; Utility function to check minimum value of d ; If X is already larger do not need to add anything ; Adding d to all elements of X ; If X is larger now print d ; else prin... | def IsLarger ( X , Y , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( X [ i ] < Y [ i ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def solve ( X , Y , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE if ( IsLarger ( X , Y , n ) ) : NEW_LINE INDENT ans = 0 ; NEW_LI... |
Maximum possible Bitwise OR of the two numbers from the range [ L , R ] | Function to return the maximum bitwise OR of any pair from the given range ; Converting L to its binary representation ; Converting R to its binary representation ; In order to make the number of bits of L and R same ; Push 0 to the MSB ; When it... | def max_bitwise_or ( L , R ) : NEW_LINE INDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE v3 = [ ] NEW_LINE z = 0 NEW_LINE i = 0 NEW_LINE ans = 0 NEW_LINE cnt = 1 NEW_LINE while ( L > 0 ) : NEW_LINE INDENT v1 . append ( L % 2 ) NEW_LINE L = L // 2 NEW_LINE DEDENT while ( R > 0 ) : NEW_LINE INDENT v2 . append ( R % 2 ) NEW_LIN... |
Find the minimum value of X for an expression | Function to calculate value of X ; Check for both possibilities ; Driver Code | def valueofX ( ar , n ) : NEW_LINE INDENT summ = sum ( ar ) NEW_LINE if ( summ % n == 0 ) : NEW_LINE INDENT return summ // n NEW_LINE DEDENT else : NEW_LINE INDENT A = summ // n NEW_LINE B = summ // n + 1 NEW_LINE ValueA = 0 NEW_LINE ValueB = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ValueA += ( ar [ i ] - A ) ... |
Minimum length String with Sum of the alphabetical values of the characters equal to N | Function to find the minimum length ; Function to find the minimum length String ; Driver code | def minLength ( n ) : NEW_LINE INDENT ans = n // 26 NEW_LINE if ( n % 26 != 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def minString ( n ) : NEW_LINE INDENT ans = n // 26 NEW_LINE res = " " NEW_LINE while ( ans ) : NEW_LINE INDENT res = res + " z " NEW_LINE ans -= 1 NEW_LINE DEDENT if ( n... |
Minimum halls required for class scheduling | Python3 implementation of the approach ; Function to return the minimum number of halls required ; Array to store the number of lectures ongoing at time t ; For every lecture increment start point s decrement ( end point + 1 ) ; Perform prefix sum and update the ans to maxi... | MAX = 100001 NEW_LINE def minHalls ( lectures , n ) : NEW_LINE INDENT prefix_sum = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix_sum [ lectures [ i ] [ 0 ] ] += 1 ; NEW_LINE prefix_sum [ lectures [ i ] [ 1 ] + 1 ] -= 1 ; NEW_LINE DEDENT ans = prefix_sum [ 0 ] ; NEW_LINE for i in range ( 1 , MAX )... |
Find the minimum capacity of the train required to hold the passengers | Function to return the minimum capacity required ; To store the minimum capacity ; To store the current capacity of the train ; For every station ; Add the number of people entering the train and subtract the number of people exiting the train to ... | def minCapacity ( enter , exit , n ) : NEW_LINE INDENT minCap = 0 ; NEW_LINE currCap = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT currCap = currCap + enter [ i ] - exit [ i ] ; NEW_LINE minCap = max ( minCap , currCap ) ; NEW_LINE DEDENT return minCap ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LIN... |
Count of numbers in the range [ L , R ] which satisfy the given conditions | Python3 implementation of the approach ; Maximum possible valid number ; To store all the required number from the range [ 1 , MAX ] ; Function that returns true if x satisfies the given conditions ; To store the digits of x ; If current digit... | from collections import deque NEW_LINE MAX = 543210 NEW_LINE ans = [ ] NEW_LINE def isValidNum ( x ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( len ( x ) ) : NEW_LINE INDENT if ( ord ( x [ i ] ) - ord ( '0' ) in mp . keys ( ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( ord ( x [ i ] ) - ord (... |
Find permutation with maximum remainder Sum | Function to find the permutation ; Put n at the first index 1 ; Put all the numbers from 2 to n sequentially ; Driver code ; Display the permutation | def Findpermutation ( n ) : NEW_LINE INDENT a = [ 0 ] * ( n + 1 ) ; NEW_LINE a [ 1 ] = n ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT a [ i ] = i - 1 ; NEW_LINE DEDENT return a ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 8 ; NEW_LINE v = Findpermutation ( n ) ; NEW_LINE for i in... |
Lexicographically smallest string of length N and sum K | Function to return the lexicographically smallest string of length n that satisfies the given condition ; Iteration from the last position in the array ; If k is a positive integer ; ' z ' needs to be inserted ; Add the required character ; Driver code | def lexo_small ( n , k ) : NEW_LINE INDENT arr = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr += ' a ' ; NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT k -= i ; NEW_LINE if ( k >= 0 ) : NEW_LINE INDENT if ( k >= 26 ) : NEW_LINE INDENT arr = arr [ : i ] + ' z ' + arr [ i + 1 : ] ; NE... |
Check if string can be rearranged so that every Odd length Substring is Palindrome | Function to check is it possible to rearrange the string such that every odd length substring is palindrome ; Length of the string ; To count number of distinct character in string ; To count frequency of each character ; Inserting int... | def IsPossible ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE count = set ( ) ; NEW_LINE map = dict . fromkeys ( s , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT count . add ( s [ i ] ) ; NEW_LINE map [ s [ i ] ] += 1 ; NEW_LINE DEDENT if ( len ( count ) == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT... |
Minimum element left from the array after performing given operations | Function to return the minimum possible value of the last element left after performing the given operations ; Driver code | def getMin ( arr , n ) : NEW_LINE INDENT minVal = min ( arr ) ; NEW_LINE return minVal ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 3 , 1 , 6 , 9 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( getMin ( arr , n ) ) ; NEW_LINE DEDENT |
Largest substring with same Characters | Function to find largest sub with same characters ; Traverse the string ; If character is same as previous increment temp value ; Return the required answer ; Driver code ; Function call | def Substring ( s ) : NEW_LINE INDENT ans , temp = 1 , 1 NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == s [ i - 1 ] ) : NEW_LINE INDENT temp += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans = max ( ans , temp ) NEW_LINE temp = 1 NEW_LINE DEDENT DEDENT ans = max ( ans , temp ) NEW_LINE return... |
Number of balanced parenthesis substrings | Function to find number of balanced parenthesis sub strings ; To store required answer ; Vector to stores the number of balanced brackets at each depth . ; d stores checks the depth of our sequence For example level of ( ) is 1 and that of ( ( ) ) is 2. ; If open bracket incr... | def Balanced_Substring ( s , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE arr = [ 0 ] * ( int ( n / 2 ) + 1 ) ; NEW_LINE d = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT d += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( d == 1 ) : NEW_LINE INDENT j = 2 NEW_LINE while ( j ... |
Count ways to divide circle using N non | Function to calculate x ^ y % mod efficiently ; Initialize the answer ; If power is odd ; Update the answer ; Square the base and half the exponent ; Return the value ; Function to calculate ncr % mod efficiently ; Initialize the answer ; Calculate ncr in O ( r ) ; Multiply wit... | def power ( x , y , mod ) : NEW_LINE INDENT res = 1 NEW_LINE while ( y ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % mod NEW_LINE DEDENT x = ( x * x ) % mod NEW_LINE y = ( y >> 1 ) NEW_LINE DEDENT return ( res % mod ) NEW_LINE DEDENT def ncr ( n , r , mod ) : NEW_LINE INDENT res = 1 NEW_LINE fo... |
Longest Subarray having strictly positive XOR | Function to return the length of the longest sub - array having positive XOR ; To store the XOR of all the elements ; To check if all the elements of the array are 0 s ; Take XOR of all the elements ; If any positive value is found the make the checkallzero false ; If com... | def StrictlyPositiveXor ( A , N ) : NEW_LINE INDENT allxor = 0 ; NEW_LINE checkallzero = True ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT allxor ^= A [ i ] ; NEW_LINE if ( A [ i ] > 0 ) : NEW_LINE INDENT checkallzero = False ; NEW_LINE DEDENT DEDENT if ( allxor != 0 ) : NEW_LINE INDENT return N ; NEW_LINE DEDENT ... |
Find minimum length sub | Python3 implementation of the approach ; Function to return the minimum length of a sub - array which contains 0 , 1 , 2 , 3 , 4 as a sub - sequence ; To store the indices where 0 , 1 , 2 , 3 and 4 are present ; To store if there exist a valid prefix of sequence in array ; Base Case ; If curre... | MAX_INT = 1000000 NEW_LINE def solve ( Array , N ) : NEW_LINE INDENT pos = [ [ ] for i in range ( 5 ) ] NEW_LINE pref = [ 0 for i in range ( 5 ) ] NEW_LINE if ( Array [ 0 ] == 0 ) : NEW_LINE INDENT pref [ 0 ] = 1 NEW_LINE pos [ 0 ] . append ( 0 ) NEW_LINE DEDENT ans = MAX_INT NEW_LINE for i in range ( N ) : NEW_LINE IN... |
Find optimal weights which can be used to weigh all the weights in the range [ 1 , X ] | Function to find the optimal weights ; Number of weights required ; Finding the value of required powers of 3 ; Optimal Weights are powers of 3 ; Driver code | def findWeights ( X ) : NEW_LINE INDENT sum = 0 NEW_LINE power = 0 NEW_LINE while ( sum < X ) : NEW_LINE INDENT sum = pow ( 3 , power + 1 ) - 1 NEW_LINE sum //= 2 NEW_LINE power += 1 NEW_LINE DEDENT ans = 1 NEW_LINE for i in range ( 1 , power + 1 ) : NEW_LINE INDENT print ( ans , end = " β " ) NEW_LINE ans = ans * 3 NE... |
Order of indices which is lexicographically smallest and sum of elements is <= X | Python3 implementation of the approach ; Function to return the chosen indices ; Maximum indices chosen ; Try to replace the first element in ans by i , making the order lexicographically smaller ; If no further replacement possible retu... | import sys ; NEW_LINE def solve ( X , A ) : NEW_LINE INDENT minimum = sys . maxsize ; NEW_LINE ind = - 1 ; NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] < minimum ) : NEW_LINE INDENT minimum = A [ i ] ; NEW_LINE ind = i ; NEW_LINE DEDENT DEDENT maxIndChosen = X // minimum ; NEW_LINE ans = [ ] ; N... |
Find if a binary matrix exists with given row and column sums | Function to check if matrix exists ; Store sum of rowsums , max of row sum number of non zero row sums ; Store sum of column sums , max of column sum number of non zero column sums ; Check condition 1 , 2 , 3 ; Driver Code | def matrix_exist ( row , column , r , c ) : NEW_LINE INDENT row_sum = 0 NEW_LINE column_sum = 0 NEW_LINE row_max = - 1 NEW_LINE column_max = - 1 NEW_LINE row_non_zero = 0 NEW_LINE column_non_zero = 0 NEW_LINE for i in range ( r ) : NEW_LINE INDENT row_sum += row [ i ] NEW_LINE row_max = max ( row_max , row [ i ] ) NEW_... |
Length of longest sub | Function to find maximum distance between unequal elements ; Calculate maxMean ; Iterate over array and calculate largest subarray with all elements greater or equal to maxMean ; Driver code | def longestSubarray ( arr , n ) : NEW_LINE INDENT maxMean = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT maxMean = max ( maxMean , ( arr [ i ] + arr [ i - 1 ] ) // 2 ) ; NEW_LINE DEDENT ans = 0 ; NEW_LINE subarrayLength = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] >= maxMean ) : NEW_L... |
Maximum distance between two unequal elements | Function to return the maximum distance between two unequal elements ; If first and last elements are unequal they are maximum distance apart ; Fix first element as one of the elements and start traversing from the right ; Break for the first unequal element ; To store th... | def maxDistance ( arr , n ) : NEW_LINE INDENT if ( arr [ 0 ] != arr [ n - 1 ] ) : NEW_LINE INDENT return ( n - 1 ) ; NEW_LINE DEDENT i = n - 1 ; NEW_LINE while ( i > 0 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ 0 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT i -= 1 ; NEW_LINE DEDENT distFirst = - 1 if ( i == 0 ) else ... |
Minimum number of pairs required to make two strings same | Python3 implementation of the approach ; Function which will check if there is a path between a and b by using BFS ; Function to return the minimum number of pairs ; To store the count of pairs ; Iterating through the strings ; Check if we can add an edge in t... | from collections import defaultdict , deque NEW_LINE def Check_Path ( a , b , G ) : NEW_LINE INDENT visited = defaultdict ( bool ) NEW_LINE queue = deque ( ) NEW_LINE queue . append ( a ) NEW_LINE visited [ a ] = True NEW_LINE while queue : NEW_LINE INDENT n = queue . popleft ( ) NEW_LINE if n == b : NEW_LINE INDENT re... |
Generate an array of K elements such that sum of elements is N and the condition a [ i ] < a [ i + 1 ] <= 2 * a [ i ] is met | Set 2 | Function that print the desired array which satisfies the given conditions ; If the lowest filling condition is void , then it is not possible to generate the required array ; Increase ... | def solve ( n , k ) : NEW_LINE INDENT mini = 0 NEW_LINE x1 = 1 NEW_LINE a = [ 0 for i in range ( k ) ] NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT mini += x1 NEW_LINE a [ i - 1 ] = x1 NEW_LINE x1 += 1 NEW_LINE DEDENT if ( n < mini ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE return NEW_LINE DED... |
Minimizing array sum by applying XOR operation on all elements of the array | Python3 implementation of the approach ; Function to return the minimized sum ; To store the frequency of bit in every element ; Finding element X ; Taking XOR of elements and finding sum ; Driver code | MAX = 25 ; NEW_LINE def getMinSum ( arr , n ) : NEW_LINE INDENT bits_count = [ 0 ] * MAX NEW_LINE max_bit = 0 ; sum = 0 ; ans = 0 ; NEW_LINE for d in range ( n ) : NEW_LINE INDENT e = arr [ d ] ; f = 0 ; NEW_LINE while ( e > 0 ) : NEW_LINE INDENT rem = e % 2 ; NEW_LINE e = e // 2 ; NEW_LINE if ( rem == 1 ) : NEW_LINE I... |
Maximum money that can be withdrawn in two steps | Function to return the maximum coins we can get ; Update elements such that X > Y ; Take from the maximum ; Refill ; Again , take the maximum ; Driver code | def maxCoins ( X , Y ) : NEW_LINE INDENT if ( X < Y ) : NEW_LINE INDENT X , Y = Y , X ; NEW_LINE DEDENT coins = X ; NEW_LINE X -= 1 ; NEW_LINE coins += max ( X , Y ) ; NEW_LINE return coins ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 7 ; Y = 5 ; NEW_LINE print ( maxCoins ( X , Y ) ) ; NEW_LI... |
Minimum value of X to make all array elements equal by either decreasing or increasing by X | Function that returns the minimum value of X ; Declare a set ; Iterate in the array element and insert them into the set ; If unique elements is 1 ; Unique elements is 2 ; Get both el2 and el1 ; Check if they are even ; If the... | def findMinimumX ( a , n ) : NEW_LINE INDENT st = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT st . add ( a [ i ] ) NEW_LINE DEDENT if ( len ( st ) == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( len ( st ) == 2 ) : NEW_LINE INDENT st = list ( st ) NEW_LINE el1 = st [ 0 ] NEW_LINE el2 = st [ 1 ] NEW_L... |
Maximum elements which can be crossed using given units of a and b | Function to find the number of elements crossed ; Keep a copy of a ; Iterate in the binary array ; If no a and b left to use ; If there is no a ; use b and increase a by 1 if arr [ i ] is 1 ; simply use b ; Use a if theres no b ; Increase a and use b ... | def findElementsCrossed ( arr , a , b , n ) : NEW_LINE INDENT aa = a NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a == 0 and b == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT elif ( a == 0 ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT b -= 1 NEW_LINE a = min ( aa , a + 1 ) NEW_LINE... |
Move all zeros to start and ones to end in an Array of random integers | Utility function to print the contents of an array ; Function that pushes all the zeros to the start and ones to the end of an array ; To store the count of elements which are not equal to 1 ; Traverse the array and calculate count of elements whi... | def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def pushBinaryToBorder ( arr , n ) : NEW_LINE INDENT count1 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != 1 ) : NEW_LINE INDENT arr [ count1 ] = arr [ i ] NE... |
Count the pairs of vowels in the given string | Function that return true if character ch is a vowel ; Function to return the count of adjacent vowel pairs in the given string ; If current character and the character after it are both vowels ; Driver code | def isVowel ( ch ) : NEW_LINE INDENT if ch in [ ' a ' , ' e ' , ' i ' , ' o ' , ' u ' ] : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def vowelPairs ( s , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( isVowel ( s [ i ] )... |
Minimum possible final health of the last monster in a game | Function to return the gcd of two numbers ; Function to return the minimum possible health for the monster ; gcd of first and second element ; gcd for all subsequent elements ; 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 solve ( health , n ) : NEW_LINE INDENT currentgcd = gcd ( health [ 0 ] , health [ 1 ] ) NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT currentgcd = gcd ( currentgcd , health [ i... |
Divide array into increasing and decreasing subsequence without changing the order | Function to print strictly increasing and strictly decreasing sequence if possible ; Arrays to store strictly increasing and decreasing sequence ; Initializing last element of both sequence ; Iterating through the array ; If current el... | def Find_Sequence ( array , n ) : NEW_LINE INDENT inc_arr , dec_arr = [ ] , [ ] NEW_LINE inc , dec = - 1 , 1e7 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if inc < array [ i ] < dec : NEW_LINE INDENT if array [ i ] < array [ i + 1 ] : NEW_LINE INDENT inc = array [ i ] NEW_LINE inc_arr . append ( array [ i ] ) NEW_L... |
Find the sum of digits of a number at even and odd places | Function to return the reverse of a number ; Function to find the sum of the odd and even positioned digits in a number ; If c is even number then it means digit extracted is at even place ; Driver code | def reverse ( n ) : NEW_LINE INDENT rev = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT rev = ( rev * 10 ) + ( n % 10 ) NEW_LINE n //= 10 NEW_LINE DEDENT return rev NEW_LINE DEDENT def getSum ( n ) : NEW_LINE INDENT n = reverse ( n ) NEW_LINE sumOdd = 0 NEW_LINE sumEven = 0 NEW_LINE c = 1 NEW_LINE while ( n != 0 ) : NE... |
Find the sum of digits of a number at even and odd places | Function to find the sum of the odd and even positioned digits in a number ; If n is odd then the last digit will be odd positioned ; To store the respective sums ; While there are digits left process ; If current digit is odd positioned ; Even positioned digi... | def getSum ( n ) : NEW_LINE INDENT if ( n % 2 == 1 ) : NEW_LINE INDENT isOdd = True NEW_LINE DEDENT else : NEW_LINE INDENT isOdd = False NEW_LINE DEDENT sumOdd = 0 NEW_LINE sumEven = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( isOdd ) : NEW_LINE INDENT sumOdd += n % 10 NEW_LINE DEDENT else : NEW_LINE INDENT sumE... |
Count the number of currency notes needed | Function to return the amount of notes with value A required ; If possible ; Driver code | def bankNotes ( A , B , S , N ) : NEW_LINE INDENT numerator = S - ( B * N ) NEW_LINE denominator = A - B NEW_LINE if ( numerator % denominator == 0 ) : NEW_LINE INDENT return ( numerator // denominator ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT A , B , S , N = 1 , 2 , 7 , 5 NEW_LINE print ( bankNotes ( A , B , S , N ... |
Length of the longest substring with no consecutive same letters | Function to return the length of the required sub - string ; Get the length of the string ; Iterate in the string ; Check for not consecutive ; If cnt greater than maxi ; Re - initialize ; Check after iteration is complete ; Driver code | def longestSubstring ( s ) : NEW_LINE INDENT cnt = 1 ; NEW_LINE maxi = 1 ; NEW_LINE n = len ( s ) ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] != s [ i - 1 ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT maxi = max ( cnt , maxi ) ; NEW_LINE cnt = 1 ; NEW_LINE DEDENT DEDENT ... |
Minimum number of changes such that elements are first Negative and then Positive | Function to return the count of minimum operations required ; To store the count of negative integers on the right of the current index ( inclusive ) ; Find the count of negative integers on the right ; If current element is negative ; ... | def Minimum_Operations ( a , n ) : NEW_LINE INDENT np = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT np [ i ] = np [ i + 1 ] NEW_LINE if ( a [ i ] <= 0 ) : NEW_LINE INDENT np [ i ] += 1 NEW_LINE DEDENT DEDENT pos = 0 NEW_LINE ans = n NEW_LINE for i in range ( n - 1 ) : ... |
Sum of elements in an array whose difference with the mean of another array is less than k | Function for finding sum of elements whose diff with mean is not more than k ; Find the mean of second array ; Find sum of elements from array1 whose difference with mean is not more than k ; Return result ; Driver code | def findSumofEle ( arr1 , m , arr2 , n , k ) : NEW_LINE INDENT arraySum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT arraySum += arr2 [ i ] NEW_LINE DEDENT mean = arraySum / n NEW_LINE sumOfElements = 0 NEW_LINE difference = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT difference = arr1 [ i ] - mean NEW_LIN... |
Find n positive integers that satisfy the given equations | Function to find n positive integers that satisfy the given conditions ; To store n positive integers ; Place N - 1 one 's ; If can not place ( y - ( n - 1 ) ) as the Nth integer ; Place Nth integer ; To store the sum of squares of N integers ; If it is less t... | def findIntegers ( n , x , y ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT ans . append ( 1 ) NEW_LINE DEDENT if ( y - ( n - 1 ) <= 0 ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE return NEW_LINE DEDENT ans . append ( y - ( n - 1 ) ) NEW_LINE store = 0 NEW_LINE for i in r... |
Find the minimum number of steps to reach M from N | Function to find a minimum number of steps to reach M from N ; Continue till m is greater than n ; If m is odd ; add one ; divide m by 2 ; Return the required answer ; Driver code | def Minsteps ( n , m ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( m > n ) : NEW_LINE INDENT if ( m & 1 ) : NEW_LINE INDENT m += 1 NEW_LINE ans += 1 NEW_LINE DEDENT m //= 2 NEW_LINE ans += 1 NEW_LINE DEDENT return ans + n - m NEW_LINE DEDENT n = 4 NEW_LINE m = 6 NEW_LINE print ( Minsteps ( n , m ) ) NEW_LINE |
Find the number of jumps to reach X in the number line from zero | Utility function to calculate sum of numbers from 1 to x ; Function to find the number of jumps to reach X in the number line from zero ; First make number positive Answer will be same either it is Positive or negative ; To store the required answer ; C... | def getsum ( x ) : NEW_LINE INDENT return int ( ( x * ( x + 1 ) ) / 2 ) NEW_LINE DEDENT def countJumps ( n ) : NEW_LINE INDENT n = abs ( n ) NEW_LINE ans = 0 NEW_LINE while ( getsum ( ans ) < n or ( getsum ( ans ) - n ) & 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ mai... |
Maximum number of candies that can be bought | Function to return the maximum candies that can be bought ; Buy all the candies of the last type ; Starting from second last ; Amount of candies of the current type that can be bought ; Add candies of current type that can be bought ; Update the previous bought amount ; Dr... | def maxCandies ( arr , n ) : NEW_LINE INDENT prevBought = arr [ n - 1 ] ; NEW_LINE candies = prevBought ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT x = min ( prevBought - 1 , arr [ i ] ) ; NEW_LINE if ( x >= 0 ) : NEW_LINE INDENT candies += x ; NEW_LINE prevBought = x ; NEW_LINE DEDENT DEDENT retu... |
Replace all elements by difference of sums of positive and negative numbers after that element | Function to print the array elements ; Function to replace all elements with absolute difference of absolute sums of positive and negative elements ; Calculate absolute sums of positive and negative elements in range i + 1 ... | def printArray ( N , arr ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT print ( " " , β end β = β " " ) NEW_LINE DEDENT def replacedArray ( N , arr ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT pos_sum = 0 NEW_LINE neg_sum = 0 NEW_LINE for j in ... |
Minimum cuts required to convert a palindromic string to a different palindromic string | Function to check if string is palindrome or not ; Function to check if it is possible to get result by making just one cut ; Appending last element in front ; Removing last element ; Checking whether string s2 is palindrome and d... | def isPalindrome ( s ) : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] != s [ len ( s ) - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return true NEW_LINE DEDENT def ans ( s ) : NEW_LINE INDENT s2 = s NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT s2 = s2 [ len... |
Minimum cuts required to convert a palindromic string to a different palindromic string | Recursive function to find minimum number of cuts if length of string is even ; If length is odd then return 2 ; To check if half of palindromic string is itself a palindrome ; If not then return 1 ; Else call function with half p... | def solveEven ( s ) : NEW_LINE INDENT if len ( s ) % 2 == 1 : NEW_LINE INDENT return 2 NEW_LINE DEDENT ls = s [ 0 : len ( s ) // 2 ] NEW_LINE rs = s [ len ( s ) // 2 : len ( s ) ] NEW_LINE if ls != rs : NEW_LINE INDENT return 1 NEW_LINE DEDENT return solveEven ( ls ) NEW_LINE DEDENT def solveOdd ( s ) : NEW_LINE INDENT... |
Minimum changes required such that the string satisfies the given condition | Function to return the minimum changes required ; To store the count of minimum changes , number of ones and the number of zeroes ; First character has to be '1 ; If condition fails changes need to be made ; Return the required count ; Driver... | def minChanges ( str , n ) : NEW_LINE INDENT count , zeros , ones = 0 , 0 , 0 NEW_LINE DEDENT ' NEW_LINE INDENT if ( ord ( str [ 0 ] ) != ord ( '1' ) ) : NEW_LINE INDENT count += 1 NEW_LINE ones += 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( ord ( str [ i ] ) == ord ( '0' ) ) : NEW_LINE INDENT zer... |
Count possible moves in the given direction in a grid | Function to return the count of possible steps in a single direction ; It can cover infinite steps ; We are approaching towards X = N ; We are approaching towards X = 1 ; Function to return the count of steps ; Take the minimum of both moves independently ; Update... | def steps ( cur , x , n ) : NEW_LINE INDENT if x == 0 : NEW_LINE INDENT return float ( ' inf ' ) NEW_LINE DEDENT elif x > 0 : NEW_LINE INDENT return abs ( ( n - cur ) // x ) NEW_LINE DEDENT else : NEW_LINE INDENT return abs ( int ( ( cur - 1 ) / x ) ) NEW_LINE DEDENT DEDENT def countSteps ( curx , cury , n , m , moves ... |
Minimum number of elements that should be removed to make the array good | Function to return the minimum number of elements that must be removed to make the given array good ; Count frequency of each element ; For each element check if there exists another element that makes a valid pair ; If does not exist then incre... | def minimumRemoval ( n , a ) : NEW_LINE INDENT c = dict . fromkeys ( a , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT c [ a [ i ] ] += 1 ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT ok = False ; NEW_LINE for j in range ( 31 ) : NEW_LINE INDENT x = ( 1 << j ) - a [ i ] ; NEW_LINE ... |
Minimum elements to be removed such that sum of adjacent elements is always odd | Returns the minimum number of eliminations ; Stores the previous element ; Stores the new value ; Check if the previous and current values are of same parity ; Previous value is now the current value ; Return the counter variable ; Driver... | def min_elimination ( n , arr ) : NEW_LINE INDENT count = 0 NEW_LINE prev_val = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT curr_val = arr [ i ] ; NEW_LINE if ( curr_val % 2 == prev_val % 2 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT prev_val = curr_val NEW_LINE DEDENT return count NEW_LINE ... |
Count all possible N digit numbers that satisfy the given condition | Function to return the count of required numbers ; If N is odd then return 0 ; Driver Code | def getCount ( N ) : NEW_LINE INDENT if ( N % 2 == 1 ) : NEW_LINE INDENT return "0" NEW_LINE DEDENT result = "9" NEW_LINE for i in range ( 1 , N // 2 ) : NEW_LINE INDENT result = result + "0" NEW_LINE DEDENT return result NEW_LINE DEDENT N = 4 NEW_LINE print ( getCount ( N ) ) NEW_LINE |
Maximum number of teams that can be formed with given persons | Function that returns true if it possible to form a team with the given n and m ; 1 person of Type1 and 2 persons of Type2 can be chosen ; 1 person of Type2 and 2 persons of Type1 can be chosen ; Cannot from a team ; Function to return the maximum number o... | def canFormTeam ( n , m ) : NEW_LINE INDENT if ( n >= 1 and m >= 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( m >= 1 and n >= 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def maxTeams ( n , m ) : NEW_LINE INDENT count = 0 NEW_LINE while ( canFormTeam ( n , m ) ) : NEW_LINE IN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.