text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Maximum GCD among all pairs ( i , j ) of first N natural numbers | Function to find the maximum GCD among all the pairs from first n natural numbers ; Return max GCD ; Driver code | def maxGCD ( n ) : NEW_LINE INDENT return ( n // 2 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE print ( maxGCD ( n ) ) ; NEW_LINE DEDENT |
Remove odd indexed characters from a given string | Function to remove the odd indexed characters from a given string ; Stores the resultant string ; If the current index is odd ; Skip the character ; Otherwise , append the character ; Return the modified string ; Driver Code ; Remove the characters which have odd index | def removeOddIndexCharacters ( s ) : NEW_LINE INDENT new_s = " " NEW_LINE i = 0 NEW_LINE while i < len ( s ) : NEW_LINE INDENT if ( i % 2 == 1 ) : NEW_LINE INDENT i += 1 NEW_LINE continue NEW_LINE DEDENT new_s += s [ i ] NEW_LINE i += 1 NEW_LINE DEDENT return new_s NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " abcdef " NEW_LINE str = removeOddIndexCharacters ( str ) NEW_LINE print ( str ) NEW_LINE DEDENT |
Longest subarray forming a Geometic Progression ( GP ) | Function to return the length of the longest subarray forming a GP in a sorted array ; Base Case ; Stores the length of GP and the common ratio ; Stores the maximum length of the GP ; Traverse the array ; Check if the common ratio is valid for GP ; If the current common ratio is equal to previous common ratio ; Increment the length of the GP ; Store the max length of GP ; Otherwise ; Update the common ratio ; Update the length of GP ; Store the max length of GP ; Update the length of GP ; Store the max length of GP ; Return the max length of GP ; Given array ; Length of the array ; Function call | def longestGP ( A , N ) : NEW_LINE INDENT if ( N < 2 ) : NEW_LINE INDENT return N NEW_LINE DEDENT length = 1 NEW_LINE common_ratio = 1 NEW_LINE maxlength = 1 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i + 1 ] % A [ i ] == 0 ) : NEW_LINE INDENT if ( A [ i + 1 ] // A [ i ] == common_ratio ) : NEW_LINE INDENT length = length + 1 NEW_LINE maxlength = max ( maxlength , length ) NEW_LINE DEDENT else : NEW_LINE INDENT common_ratio = A [ i + 1 ] // A [ i ] NEW_LINE length = 2 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT maxlength = max ( maxlength , length ) NEW_LINE length = 1 NEW_LINE DEDENT DEDENT maxlength = max ( maxlength , length ) NEW_LINE return maxlength NEW_LINE DEDENT arr = [ 1 , 2 , 4 , 7 , 14 , 28 , 56 , 89 ] NEW_LINE N = len ( arr ) NEW_LINE print ( longestGP ( arr , N ) ) NEW_LINE |
Maximum number of uncrossed lines between two given arrays | Function to count maximum number of uncrossed lines between the two given arrays ; Stores the length of lcs obtained upto every index ; Iterate over first array ; Iterate over second array ; Update value in dp table ; If both characters are equal ; Update the length of lcs ; If both characters are not equal ; Update the table ; Return the answer ; Driver Code ; Given array A [ ] and B [ ] ; Function Call | def uncrossedLines ( a , b , n , m ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( m + 1 ) ] for y 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 dp [ i ] [ j ] = 0 NEW_LINE DEDENT elif ( a [ i - 1 ] == b [ j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] [ m ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 3 , 9 , 2 ] NEW_LINE B = [ 3 , 2 , 9 ] NEW_LINE N = len ( A ) NEW_LINE M = len ( B ) NEW_LINE print ( uncrossedLines ( A , B , N , M ) ) NEW_LINE DEDENT |
Minimize flips required to make all shortest paths from top | Function to count the minimum number of flips required ; Dimensions of matrix ; Stores the count the flips ; Check if element is same or not ; Return the final count ; Given Matrix ; Given path as a string ; Function call | def minFlips ( mat , s ) : NEW_LINE INDENT N = len ( mat ) NEW_LINE M = len ( mat [ 0 ] ) NEW_LINE count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != ord ( s [ i + j ] ) - ord ( '0' ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT mat = [ [ 1 , 0 , 1 ] , [ 0 , 1 , 1 ] , [ 0 , 0 , 0 ] ] NEW_LINE s = "10001" NEW_LINE print ( minFlips ( mat , s ) ) NEW_LINE |
Generate a pair of integers from a range [ L , R ] whose LCM also lies within the range | Python3 implementation of the above approach ; Checking if any pair is possible or not in range ( l , r ) ; If not possible print ( - 1 ) ; Print LCM pair ; Driver Code ; Function call | def lcmpair ( l , r ) : NEW_LINE INDENT x = l NEW_LINE y = 2 * l NEW_LINE if ( y > r ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " X β = β { } β Y β = β { } " . format ( x , y ) ) NEW_LINE DEDENT DEDENT l = 13 NEW_LINE r = 69 NEW_LINE lcmpair ( l , r ) NEW_LINE |
Print all possible shortest chains to reach a target word | Python Program to implement the above approach ; Function to print all possible shortest sequences starting from start to target . ; Find words differing by a single character with word ; Find next word in dict by changing each element from ' a ' to 'z ; Function to get all the shortest possible sequences starting from ' start ' to 'target ; Store all the shortest path . ; Store visited words in list ; Queue used to find the shortest path ; Stores the distinct words from given list ; Stores whether the shortest path is found or not ; Explore the next level ; Find words differing by a single character ; Add words to the path . ; Found the target ; If already reached target ; Erase all visited words . ; Driver Code | from collections import deque NEW_LINE from typing import Deque , List , Set NEW_LINE def displaypath ( res : List [ List [ str ] ] ) : NEW_LINE INDENT for i in res : NEW_LINE INDENT print ( " [ β " , end = " " ) for j in i : print ( j , end = " , β " ) print ( " ] " ) NEW_LINE DEDENT DEDENT def addWord ( word : str , Dict : Set ) : NEW_LINE INDENT res : List [ str ] = [ ] NEW_LINE wrd = list ( word ) NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( len ( wrd ) ) : NEW_LINE INDENT s = wrd [ i ] NEW_LINE c = ' a ' NEW_LINE while c <= ' z ' : NEW_LINE INDENT wrd [ i ] = c NEW_LINE if ' ' . join ( wrd ) in Dict : NEW_LINE INDENT res . append ( ' ' . join ( wrd ) ) NEW_LINE DEDENT c = chr ( ord ( c ) + 1 ) NEW_LINE DEDENT wrd [ i ] = s NEW_LINE DEDENT return res NEW_LINE DEDENT ' NEW_LINE def findLadders ( Dictt : List [ str ] , beginWord : str , endWord : str ) : NEW_LINE INDENT res : List [ List [ str ] ] = [ ] NEW_LINE visit = set ( ) NEW_LINE q : Deque [ List [ str ] ] = deque ( ) NEW_LINE Dict = set ( ) NEW_LINE for i in Dictt : NEW_LINE INDENT Dict . add ( i ) NEW_LINE DEDENT q . append ( [ beginWord ] ) NEW_LINE flag = False NEW_LINE while q : NEW_LINE INDENT size = len ( q ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT cur = q [ 0 ] NEW_LINE q . popleft ( ) NEW_LINE newadd = [ ] NEW_LINE newadd = addWord ( cur [ - 1 ] , Dict ) NEW_LINE for j in range ( len ( newadd ) ) : NEW_LINE INDENT newline = cur . copy ( ) NEW_LINE newline . append ( newadd [ j ] ) NEW_LINE if ( newadd [ j ] == endWord ) : NEW_LINE INDENT flag = True NEW_LINE res . append ( newline ) NEW_LINE DEDENT visit . add ( newadd [ j ] ) NEW_LINE q . append ( newline ) NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT break NEW_LINE DEDENT for it in visit : NEW_LINE INDENT Dict . remove ( it ) NEW_LINE DEDENT visit . clear ( ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = [ " ted " , " tex " , " red " , " tax " , " tad " , " den " , " rex " , " pee " ] NEW_LINE beginWord = " red " NEW_LINE endWord = " tax " NEW_LINE res = findLadders ( string , beginWord , endWord ) NEW_LINE displaypath ( res ) NEW_LINE DEDENT |
Count non | Function to reverse a number ; Store the reverse of N ; Return reverse of N ; Function to get the count of non - palindromic numbers having same first and last digit ; Store the required count ; Traverse the array ; Store reverse of arr [ i ] ; Check for palindrome ; IF non - palindromic ; Check if first and last digits are equal ; Driver Code | def revNum ( N ) : NEW_LINE INDENT x = 0 NEW_LINE while ( N ) : NEW_LINE INDENT x = x * 10 + N % 10 NEW_LINE N = N // 10 NEW_LINE DEDENT return x NEW_LINE DEDENT def ctNonPalin ( arr , N ) : NEW_LINE INDENT Res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = revNum ( arr [ i ] ) NEW_LINE if ( x == arr [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT Res += ( arr [ i ] % 10 == N % 10 ) NEW_LINE DEDENT DEDENT return Res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 121 , 134 , 2342 , 4514 ] NEW_LINE N = len ( arr ) NEW_LINE print ( ctNonPalin ( arr , N ) ) NEW_LINE DEDENT |
Smallest subarray from a given Array with sum greater than or equal to K | Set 2 | Python3 program for the above approach ; Function to find the smallest subarray with sum greater than or equal target ; DP table to store the computed subproblems ; Initialize first column with 0 ; Initialize first row with 0 ; Check for invalid condition ; Fill up the dp table ; Print the minimum length ; Driver Code | import sys NEW_LINE def minlt ( arr , target , n ) : NEW_LINE INDENT dp = [ [ - 1 for _ in range ( target + 1 ) ] \ for _ in range ( len ( arr ) + 1 ) ] NEW_LINE for i in range ( len ( arr ) + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 0 NEW_LINE DEDENT for j in range ( target + 1 ) : NEW_LINE INDENT dp [ 0 ] [ j ] = sys . maxsize NEW_LINE DEDENT for i in range ( 1 , len ( arr ) + 1 ) : NEW_LINE INDENT for j in range ( 1 , target + 1 ) : NEW_LINE INDENT if arr [ i - 1 ] > j : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i - 1 ] [ j ] , \ 1 + dp [ i ] [ j - arr [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ - 1 ] [ - 1 ] NEW_LINE if dp [ - 1 ] [ - 1 ] == sys . maxsize : NEW_LINE INDENT return ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return dp [ - 1 ] [ - 1 ] NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 5 , 4 , 1 ] NEW_LINE target = 11 NEW_LINE n = len ( arr ) NEW_LINE print ( minlt ( arr , target , n ) ) NEW_LINE |
Minimum absolute difference of server loads | Function which returns the minimum difference of loads ; Compute the overall server load ; Stores the results of subproblems ; Fill the partition table in bottom up manner ; If i - th server is included ; If i - th server is excluded ; Server A load : total_sum - ans Server B load : ans Diff : abs ( total_sum - 2 * ans ) ; Driver Code ; Function Call | def minServerLoads ( n , servers ) : NEW_LINE INDENT totalLoad = sum ( servers ) NEW_LINE requiredLoad = totalLoad // 2 NEW_LINE dp = [ [ 0 for col in range ( requiredLoad + 1 ) ] for row in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , requiredLoad + 1 ) : NEW_LINE INDENT if servers [ i - 1 ] > j : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , servers [ i - 1 ] + dp [ i - 1 ] [ j - servers [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT return totalLoad - 2 * dp [ n ] [ requiredLoad ] NEW_LINE DEDENT N = 5 ; NEW_LINE servers = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE print ( minServerLoads ( N , servers ) ) NEW_LINE |
Length of longest subarray with positive product | Function to find the length of longest subarray whose product is positive ; Stores the length of current subarray with positive product ; Stores the length of current subarray with negative product ; Stores the length of the longest subarray with positive product ; Reset the value ; If current element is positive ; Increment the length of subarray with positive product ; If at least one element is present in the subarray with negative product ; Update res ; If current element is negative ; Increment the length of subarray with negative product ; If at least one element is present in the subarray with positive product ; Update res ; Driver Code | def maxLenSub ( arr , N ) : NEW_LINE INDENT Pos = 0 NEW_LINE Neg = 0 NEW_LINE res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT Pos = Neg = 0 NEW_LINE DEDENT elif ( arr [ i ] > 0 ) : NEW_LINE INDENT Pos += 1 NEW_LINE if ( Neg != 0 ) : NEW_LINE INDENT Neg += 1 NEW_LINE DEDENT res = max ( res , Pos ) NEW_LINE DEDENT else : NEW_LINE INDENT Pos , Neg = Neg , Pos NEW_LINE Neg += 1 NEW_LINE if ( Pos != 0 ) : NEW_LINE INDENT Pos += 1 NEW_LINE DEDENT res = max ( res , Pos ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 1 , - 2 , - 3 , 0 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maxLenSub ( arr , N ) ) NEW_LINE DEDENT |
Print all strings of maximum length from an array of strings | Python3 program to implement the above approach ; Function to find the length of the longest string from the given array of strings ; Traverse the array ; Stores the length of current string ; Update maximum length ; Return the maximum length ; Function to print the longest strings from the array ; Find the strings having length equals to lenn ; Print the resultant vector of strings ; Function to print all the longest strings from the array ; Find the length of longest string ; Find and print all the strings having length equals to max ; Driver Code | import sys NEW_LINE def maxLength ( arr ) : NEW_LINE INDENT lenn = - sys . maxsize - 1 NEW_LINE N = len ( arr ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT l = len ( arr [ i ] ) NEW_LINE if ( lenn < l ) : NEW_LINE INDENT lenn = l NEW_LINE DEDENT DEDENT return lenn NEW_LINE DEDENT def maxStrings ( arr , lenn ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE ans = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( lenn == len ( arr [ i ] ) ) : NEW_LINE INDENT ans . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def printStrings ( arr ) : NEW_LINE INDENT max = maxLength ( arr ) NEW_LINE maxStrings ( arr , max ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " aba " , " aa " , " ad " , " vcd " , " aba " ] NEW_LINE printStrings ( arr ) NEW_LINE DEDENT |
Minimize count of flips required such that no substring of 0 s have length exceeding K | Function to return minimum number of flips required ; Base Case ; Stores the count of minimum number of flips ; Stores the count of zeros in current sub ; If current character is 0 ; Continue ongoing sub ; Start a new sub ; If k consecutive zeroes are obtained ; End segment ; Return the result ; Driver Code ; Function call | def min_flips ( strr , k ) : NEW_LINE INDENT if ( len ( strr ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 0 NEW_LINE cnt_zeros = 0 NEW_LINE for ch in strr : NEW_LINE INDENT if ( ch == '0' ) : NEW_LINE INDENT cnt_zeros += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt_zeros = 0 NEW_LINE DEDENT if ( cnt_zeros == k ) : NEW_LINE INDENT ans += 1 NEW_LINE cnt_zeros = 0 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = "11100000011" NEW_LINE k = 3 NEW_LINE print ( min_flips ( strr , k ) ) NEW_LINE DEDENT |
Find all possible subarrays having product less than or equal to K | Function to return all possible subarrays having product less than or equal to K ; Store the required subarrays ; Stores the product of current subarray ; Stores the starting index of the current subarray ; Check for empty array ; Iterate over the array ; Calculate product ; If product exceeds K ; Reduce product ; Increase starting index of current subarray ; Stores the subarray elements ; Store the subarray elements ; Add the subarrays to the li ; Return the final li of subarrays ; Driver Code | def maxSubArray ( arr , n , K ) : NEW_LINE INDENT solution = [ ] NEW_LINE multi = 1 NEW_LINE start = 0 NEW_LINE if ( n <= 1 or K < 0 ) : NEW_LINE INDENT return solution NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT multi = multi * arr [ i ] NEW_LINE while ( multi > K ) : NEW_LINE INDENT multi = multi // arr [ start ] NEW_LINE start += 1 NEW_LINE DEDENT li = [ ] NEW_LINE j = i NEW_LINE while ( j >= start ) : NEW_LINE INDENT li . insert ( 0 , arr [ j ] ) NEW_LINE solution . append ( list ( li ) ) NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT return solution NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 7 , 1 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE K = 7 NEW_LINE v = maxSubArray ( arr , n , K ) NEW_LINE print ( v ) NEW_LINE DEDENT |
Count of collisions at a point ( X , Y ) | Function to find the count of possible pairs of collisions ; Stores the time at which points reach the origin ; Calculate time for each point ; Sort the times ; Counting total collisions ; Count of elements arriving at a given point at the same time ; Driver Code ; Given set of points with speed ; Function Call | def solve ( D , N , X , Y ) : NEW_LINE INDENT T = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = D [ i ] [ 0 ] NEW_LINE y = D [ i ] [ 1 ] NEW_LINE speed = D [ i ] [ 2 ] NEW_LINE time = ( ( x * x - X * X ) + ( y * y - Y * Y ) ) / ( speed * speed ) NEW_LINE T . append ( time ) NEW_LINE DEDENT T . sort ( ) NEW_LINE i = 0 NEW_LINE total = 0 NEW_LINE while i < len ( T ) - 1 : NEW_LINE INDENT count = 1 NEW_LINE while i < len ( T ) - 1 and T [ i ] == T [ i + 1 ] : NEW_LINE INDENT count += 1 NEW_LINE i += 1 NEW_LINE DEDENT total += ( count * ( count - 1 ) ) / 2 NEW_LINE i += 1 NEW_LINE DEDENT return total NEW_LINE DEDENT N = 5 NEW_LINE D = [ [ 5 , 12 , 1 ] , [ 16 , 63 , 5 ] , [ - 10 , 24 , 2 ] , [ 7 , 24 , 2 ] , [ - 24 , 7 , 2 ] ] NEW_LINE X = 0 NEW_LINE Y = 0 NEW_LINE print ( solve ( D , N , X , Y ) ) NEW_LINE |
Longest subarray forming an Arithmetic Progression ( AP ) | Function to return the length of longest subarray forming an AP ; Minimum possible length of required subarray is 2 ; Stores the length of the current subarray ; Stores the common difference of the current AP ; Stores the common difference of the previous AP ; If the common differences are found to be equal ; Continue the previous subarray ; Start a new subarray ; Update the length to store maximum length ; Update the length to store maximum length ; Return the length of the longest subarray ; Driver Code | def getMaxLength ( arr , N ) : NEW_LINE INDENT res = 2 NEW_LINE dist = 2 NEW_LINE curradj = ( arr [ 1 ] - arr [ 0 ] ) NEW_LINE prevadj = ( arr [ 1 ] - arr [ 0 ] ) NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT curradj = arr [ i ] - arr [ i - 1 ] NEW_LINE if ( curradj == prevadj ) : NEW_LINE INDENT dist += 1 NEW_LINE DEDENT else : NEW_LINE INDENT prevadj = curradj NEW_LINE res = max ( res , dist ) NEW_LINE dist = 2 NEW_LINE DEDENT DEDENT res = max ( res , dist ) NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 7 , 4 , 6 , 8 , 10 , 11 ] NEW_LINE N = len ( arr ) NEW_LINE print ( getMaxLength ( arr , N ) ) NEW_LINE DEDENT |
Minimize cost to empty a given string by removing characters alphabetically | Function to find the minimum cost required to remove each character of the string in alphabetical order ; Stores the frequency of characters of the string ; Iterate through the string ; Count the number of characters smaller than the present character ; If no smaller character precedes current character ; Increase the frequency of the current character ; Return the total cost ; Given string str ; Function call | def minSteps ( str , N ) : NEW_LINE INDENT cost = 0 NEW_LINE f = [ 0 ] * 26 NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr_ele = ord ( str [ i ] ) - ord ( ' a ' ) NEW_LINE smaller = 0 NEW_LINE for j in range ( curr_ele + 1 ) : NEW_LINE INDENT if ( f [ j ] ) : NEW_LINE INDENT smaller += f [ j ] NEW_LINE DEDENT DEDENT if ( smaller == 0 ) : NEW_LINE INDENT cost += ( i + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT cost += ( i - smaller + 1 ) NEW_LINE DEDENT f [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT return cost NEW_LINE DEDENT str = " abcab " NEW_LINE N = len ( str ) NEW_LINE print ( minSteps ( str , N ) ) NEW_LINE |
Count of Rectangles with area K made up of only 1 s from given Binary Arrays | Function to find the subarrays of all possible lengths made up of only 1 s ; Stores the frequency of the subarrays ; Check if the previous value was also 0 ; If the previous value was 1 ; Find the subarrays of each size from 1 to count ; If A [ ] is of the form ... .111 ; Function to find the count of all possible rectangles ; Size of each of the arrays ; Stores the count of subarrays of each size consisting of only 1 s from array A [ ] ; Stores the count of subarrays of each size consisting of only 1 s from array B [ ] ; Iterating over all subarrays consisting of only 1 s in A [ ] ; If i is a factor of K , then there is a subarray of size K / i in B [ ] ; Driver Code | def findSubarrays ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE freq = [ 0 ] * ( n + 1 ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT if ( count == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT value = count NEW_LINE for j in range ( 1 , count + 1 ) : NEW_LINE INDENT freq [ j ] += value NEW_LINE value -= 1 NEW_LINE DEDENT count = 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count > 0 ) : NEW_LINE INDENT value = count NEW_LINE for j in range ( 1 , count + 1 ) : NEW_LINE INDENT freq [ j ] += value NEW_LINE value -= 1 NEW_LINE DEDENT DEDENT return freq NEW_LINE DEDENT def countRectangles ( a , b , K ) : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE subA = [ ] NEW_LINE subA = findSubarrays ( a ) NEW_LINE subB = [ ] NEW_LINE subB = findSubarrays ( b ) NEW_LINE total = 0 NEW_LINE for i in range ( 1 , len ( subA ) ) : NEW_LINE INDENT if ( K % i == 0 and ( K // i ) <= m ) : NEW_LINE INDENT total = total + subA [ i ] * subB [ K // i ] NEW_LINE DEDENT DEDENT print ( total ) NEW_LINE DEDENT a = [ 0 , 0 , 1 , 1 ] NEW_LINE b = [ 1 , 0 , 1 ] NEW_LINE K = 2 NEW_LINE countRectangles ( a , b , K ) NEW_LINE |
Print Longest Bitonic subsequence ( Space Optimized Approach ) | Function to print the longest bitonic subsequence ; Function to generate the longest bitonic subsequence ; Store the lengths of LIS ending at every index ; Store the lengths of LDS ending at every index ; Compute LIS for all indices ; Compute LDS for all indices ; Find the index having maximum value of lis [ i ] + lds [ i ] + 1 ; Stores the count of elements in increasing order in Bitonic subsequence ; Store the increasing subsequence ; Sort the bitonic subsequence to arrange smaller elements at the beginning ; Stores the count of elements in decreasing order in Bitonic subsequence ; Print the longest bitonic sequence ; Driver code | def printRes ( res ) : NEW_LINE INDENT n = len ( res ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( res [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def printLBS ( arr , N ) : NEW_LINE INDENT lis = [ 0 ] * N NEW_LINE lds = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT lis [ i ] = lds [ i ] = 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if arr [ j ] < arr [ i ] : NEW_LINE INDENT if lis [ i ] < lis [ j ] + 1 : NEW_LINE INDENT lis [ i ] = lis [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( N - 1 , i , - 1 ) : NEW_LINE INDENT if arr [ j ] < arr [ i ] : NEW_LINE INDENT if lds [ i ] < lds [ j ] + 1 : NEW_LINE INDENT lds [ i ] = lds [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT MaxVal = arr [ 0 ] NEW_LINE inx = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if MaxVal < lis [ i ] + lds [ i ] - 1 : NEW_LINE INDENT MaxVal = lis [ i ] + lds [ i ] - 1 NEW_LINE inx = i NEW_LINE DEDENT DEDENT ct1 = lis [ inx ] NEW_LINE res = [ ] NEW_LINE i = inx NEW_LINE while i >= 0 and ct1 > 0 : NEW_LINE INDENT if lis [ i ] == ct1 : NEW_LINE INDENT res . append ( arr [ i ] ) NEW_LINE ct1 -= 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT res . reverse ( ) NEW_LINE ct2 = lds [ inx ] - 1 NEW_LINE i = inx NEW_LINE while i < N and ct2 > 0 : NEW_LINE INDENT if lds [ i ] == ct2 : NEW_LINE INDENT res . append ( arr [ i ] ) NEW_LINE ct2 -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT printRes ( res ) NEW_LINE DEDENT arr = [ 80 , 60 , 30 , 40 , 20 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE printLBS ( arr , N ) NEW_LINE |
Minimum possible value T such that at most D Partitions of the Array having at most sum T is possible | Function to check if the array can be partitioned into atmost d subarray with sum atmost T ; Initial partition ; Current sum ; If current sum exceeds T ; Create a new partition ; If count of partitions exceed d ; Function to find the minimum possible value of T ; Stores the maximum and total sum of elements ; Maximum element ; Sum of all elements ; Calculate median T ; If atmost D partitions possible ; Check for smaller T ; Otherwise ; Check for larger T ; Print the minimum T required ; Driver code ; Function call | def possible ( T , arr , n , d ) : NEW_LINE INDENT partition = 1 ; NEW_LINE total = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT total = total + arr [ i ] ; NEW_LINE if ( total > T ) : NEW_LINE INDENT partition = partition + 1 ; NEW_LINE total = arr [ i ] ; NEW_LINE if ( partition > d ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT DEDENT return True ; NEW_LINE DEDENT def calcT ( n , d , arr ) : NEW_LINE INDENT mx = - 1 ; sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT mx = max ( mx , arr [ i ] ) ; NEW_LINE sum = sum + arr [ i ] ; NEW_LINE DEDENT lb = mx ; NEW_LINE ub = sum ; NEW_LINE while ( lb < ub ) : NEW_LINE INDENT T_mid = lb + ( ub - lb ) // 2 ; NEW_LINE if ( possible ( T_mid , arr , n , d ) == True ) : NEW_LINE INDENT ub = T_mid ; NEW_LINE DEDENT else : NEW_LINE INDENT lb = T_mid + 1 ; NEW_LINE DEDENT DEDENT print ( lb ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT d = 2 ; NEW_LINE arr = [ 1 , 1 , 1 , 1 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE calcT ( n , d , arr ) ; NEW_LINE DEDENT |
Minimize splits to generate monotonous Substrings from given String | Function to return final result ; Initialize variable to keep track of ongoing sequence ; If current sequence is neither increasing nor decreasing ; If prev char is greater ; If prev char is same ; Otherwise ; If current sequence is Non - Decreasing ; If prev char is smaller ; If prev char is same ; Update ongoing ; Otherwise ; Update ongoing ; Increase count ; If current sequence is Non - Increasing ; If prev char is greater , then update ongoing with D ; If prev char is equal , then update current with D ; Otherwise , update ongoing with N and increment count ; Return count + 1 ; Driver code | def minReqSubstring ( s , n ) : NEW_LINE INDENT ongoing = ' N ' NEW_LINE count , l = 0 , len ( s ) NEW_LINE for i in range ( 1 , l ) : NEW_LINE INDENT if ongoing == ' N ' : NEW_LINE INDENT if s [ i ] < s [ i - 1 ] : NEW_LINE INDENT ongoing = ' D ' NEW_LINE DEDENT elif s [ i ] == s [ i - 1 ] : NEW_LINE INDENT ongoing = ' N ' NEW_LINE DEDENT else : NEW_LINE INDENT ongoing = ' I ' NEW_LINE DEDENT DEDENT elif ongoing == ' I ' : NEW_LINE INDENT if s [ i ] > s [ i - 1 ] : NEW_LINE INDENT ongoing = ' I ' NEW_LINE DEDENT elif s [ i ] == s [ i - 1 ] : NEW_LINE INDENT ongoing = ' I ' NEW_LINE DEDENT else : NEW_LINE INDENT ongoing = ' N ' NEW_LINE count += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if s [ i ] < s [ i - 1 ] : NEW_LINE INDENT ongoing = ' D ' NEW_LINE DEDENT elif s [ i ] == s [ i - 1 ] : NEW_LINE INDENT ongoing = ' D ' NEW_LINE DEDENT else : NEW_LINE INDENT ongoing = ' N ' NEW_LINE count += 1 NEW_LINE DEDENT DEDENT DEDENT return count + 1 NEW_LINE DEDENT S = " aeccdhba " NEW_LINE n = len ( S ) NEW_LINE print ( minReqSubstring ( S , n ) ) NEW_LINE |
Minimum decrements required such that sum of all adjacent pairs in an Array does not exceed K | Function to calculate the minimum number of operations required ; Stores the total number of operations ; Iterate over the array ; If the sum of pair of adjacent elements exceed k . ; If current element exceeds k ; Reduce arr [ i ] to k ; Update arr [ i + 1 ] accordingly ; Update answer ; Driver Code | def minimum_required_operations ( arr , n , k ) : NEW_LINE INDENT answer = 0 NEW_LINE mod = 10 ** 9 + 7 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if arr [ i ] + arr [ i + 1 ] > k : NEW_LINE INDENT if arr [ i ] > k : NEW_LINE INDENT answer += ( arr [ i ] - k ) NEW_LINE arr [ i ] = k NEW_LINE DEDENT answer += ( arr [ i ] + arr [ i + 1 ] ) - k NEW_LINE arr [ i + 1 ] = ( k - arr [ i ] ) NEW_LINE answer %= mod NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT a = [ 9 , 50 , 4 , 14 , 42 , 89 ] NEW_LINE k = 10 NEW_LINE print ( minimum_required_operations ( a , len ( a ) , k ) ) NEW_LINE |
Lexicographic smallest permutation of a String containing the second String as a Substring | Function to print the desired lexicographic smaller string ; Calculate length of the string ; Stores the frequencies of characters of string str1 ; Stores the frequencies of characters of string str2 ; Decrease the frequency of second string from that of of the first string ; To store the resultant string ; To find the index of first character of the string str2 ; Append the characters in lexicographical order ; Append all the current character ( i + ' a ' ) ; If we reach first character of string str2 append str2 ; Return the resultant string ; Driver code | def findSmallestString ( str1 , str2 ) : NEW_LINE INDENT freq1 = [ 0 ] * 26 NEW_LINE freq2 = [ 0 ] * 26 NEW_LINE n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT freq1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( n2 ) : NEW_LINE INDENT freq2 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT freq1 [ i ] -= freq2 [ i ] NEW_LINE DEDENT res = " " NEW_LINE minIndex = ord ( str2 [ 0 ] ) - ord ( ' a ' ) NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT for j in range ( freq1 [ i ] ) : NEW_LINE INDENT res += chr ( i + ord ( ' a ' ) ) NEW_LINE DEDENT if i == minIndex : NEW_LINE INDENT res += str2 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT str1 = " geeksforgeeksfor " NEW_LINE str2 = " for " NEW_LINE print ( findSmallestString ( str1 , str2 ) ) NEW_LINE |
Restore original String from given Encrypted String by the given operations | Function to decrypt and print the original strings ; If length is exceeded ; Reverse the string ; Driver Code | def decryptString ( s , N ) : NEW_LINE INDENT for i in range ( 0 , len ( s ) , 2 * N ) : NEW_LINE INDENT if ( i + N < len ( s ) ) : NEW_LINE INDENT end = s [ i + N ] NEW_LINE DEDENT if ( i + N > len ( s ) ) : NEW_LINE INDENT end = s [ - 1 ] NEW_LINE DEDENT if ( i == 0 ) : NEW_LINE INDENT s = s [ i + N - 1 : : - 1 ] + s [ i + N : ] NEW_LINE DEDENT else : NEW_LINE INDENT s = s [ : i ] + s [ i + N - 1 : i - 1 : - 1 ] + s [ i + N : ] NEW_LINE DEDENT DEDENT print ( s ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " ihTs β suohld β ebeas ! y " NEW_LINE N = 3 NEW_LINE decryptString ( s , N ) NEW_LINE DEDENT |
Determine the winner of a game of deleting Characters from a String | Function to find the winner of the game when both players play optimally ; Stores the frequency of all digit ; Stores the scores of player1 and player2 respectively ; Iterate to store frequencies ; Turn for the player1 ; Add score of player1 ; Add score of player2 ; Check if its a draw ; If score of player 1 is greater ; Otherwise ; Driver code | def determineWinner ( str ) : NEW_LINE INDENT A = [ 0 for i in range ( 9 ) ] ; NEW_LINE sum1 = 0 ; sum2 = 0 ; NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT A [ int ( str [ i ] ) ] += 1 ; NEW_LINE DEDENT for i in range ( 0 , 9 ) : NEW_LINE INDENT if ( i % 2 != 0 ) : NEW_LINE INDENT sum1 = sum1 + A [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT sum2 = sum2 + A [ i ] ; NEW_LINE DEDENT DEDENT if ( sum1 == sum2 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT elif ( sum1 > sum2 ) : NEW_LINE INDENT print ( " Player β 1" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Player β 2" ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "78787" ; NEW_LINE determineWinner ( str ) ; NEW_LINE DEDENT |
Generate a String from given Strings P and Q based on the given conditions | Function to generate a string S from string P and Q according to the given conditions ; Stores the frequencies ; Counts occurrences of each characters ; Reduce the count of the character which is also present in Q ; Stores the resultant string ; Index in freq [ ] to segregate the string ; Add Q to the resulting string ; Driver Code ; Function call | def manipulateStrings ( P , Q ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] ; NEW_LINE for i in range ( len ( P ) ) : NEW_LINE INDENT freq [ ord ( P [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( len ( Q ) ) : NEW_LINE INDENT freq [ ord ( Q [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE DEDENT sb = " " NEW_LINE pos = ord ( Q [ 0 ] ) - ord ( ' a ' ) NEW_LINE for i in range ( pos + 1 ) : NEW_LINE INDENT while freq [ i ] > 0 : NEW_LINE INDENT sb += chr ( ord ( ' a ' ) + i ) NEW_LINE freq [ i ] -= 1 NEW_LINE DEDENT DEDENT sb += Q NEW_LINE for i in range ( pos + 1 , 26 ) : NEW_LINE INDENT while freq [ i ] > 0 : NEW_LINE INDENT sb += chr ( ord ( ' a ' ) + i ) NEW_LINE freq [ i ] -= 1 NEW_LINE DEDENT DEDENT print ( sb ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT P = " geeksforgeeksfor " ; NEW_LINE Q = " for " ; NEW_LINE manipulateStrings ( P , Q ) ; NEW_LINE DEDENT |
Minimum moves required to type a word in QWERTY based keyboard | Function that calculates the moves required to prthe current String ; row1 has qwertyuiop , row2 has asdfghjkl , and row3 has zxcvbnm Store the row number of each character ; String length ; Initialise move to 1 ; Traverse the String ; If current row number is not equal to previous row then increment the moves ; Return the moves ; Driver Code ; Given String str ; Function Call | def numberMoves ( s ) : NEW_LINE INDENT row = [ 2 , 3 , 3 , 2 , 1 , 2 , 2 , 2 , 1 , 2 , 2 , 2 , 3 , 3 , 1 , 1 , 1 , 1 , 2 , 1 , 1 , 3 , 1 , 3 , 1 , 3 ] ; NEW_LINE n = len ( s ) ; NEW_LINE move = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE if ( row [ ord ( s [ i ] ) - ord ( ' a ' ) ] != row [ ord ( s [ i - 1 ] ) - ord ( ' a ' ) ] ) : NEW_LINE move += 1 ; NEW_LINE return move ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " geeksforgeeks " ; NEW_LINE print ( numberMoves ( str ) ) ; NEW_LINE DEDENT |
Count of distinct Strings possible by swapping prefixes of pairs of Strings from the Array | Python3 program to implement the above approach ; Function to count the distinct strings possible after swapping the prefixes between two possible strings of the array ; Stores the count of unique characters for each index ; Store current string ; Stores the total number of distinct strings possible ; Return the answer ; Driver Code | from collections import defaultdict NEW_LINE mod = 1000000007 NEW_LINE def countS ( string : list , n : int , m : int ) -> int : NEW_LINE INDENT counts = defaultdict ( lambda : set ( ) ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = string [ i ] NEW_LINE for j in range ( m ) : NEW_LINE INDENT counts [ j ] . add ( s [ j ] ) NEW_LINE DEDENT DEDENT result = 1 NEW_LINE for index in counts : NEW_LINE INDENT result = ( result * len ( counts [ index ] ) ) % mod NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = [ "112" , "211" ] NEW_LINE N = 2 NEW_LINE M = 3 NEW_LINE print ( countS ( string , N , M ) ) NEW_LINE DEDENT |
Longest Subarrays having each Array element as the maximum | Function to find the maximum length of Subarrays for each element of the array having it as the maximum ; Initialise the bounds ; Iterate to find greater element on the left ; If greater element is found ; Decrement left pointer ; If boundary is exceeded ; Iterate to find greater element on the right ; If greater element is found ; Increment right pointer ; if boundary is exceeded ; Length of longest subarray where arr [ i ] is the largest ; Print the answer ; Driver code | def solve ( n , arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT left = max ( i - 1 , 0 ) NEW_LINE right = min ( n - 1 , i + 1 ) NEW_LINE while left >= 0 : NEW_LINE INDENT if arr [ left ] > arr [ i ] : NEW_LINE INDENT left += 1 NEW_LINE break NEW_LINE DEDENT left -= 1 NEW_LINE DEDENT if left < 0 : NEW_LINE INDENT left += 1 NEW_LINE DEDENT while right < n : NEW_LINE INDENT if arr [ right ] > arr [ i ] : NEW_LINE INDENT right -= 1 NEW_LINE break NEW_LINE DEDENT right += 1 NEW_LINE DEDENT if right >= n : NEW_LINE INDENT right -= 1 NEW_LINE DEDENT ans = 1 + right - left NEW_LINE print ( ans , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 4 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE solve ( n , arr ) NEW_LINE |
Count of Substrings having Sum equal to their Length | Python3 program to implement the above approach ; Function to count the number of substrings with sum equal to length ; Stores the count of substrings ; Add character to sum ; Add count of substrings to result ; Increase count of subarrays ; Return count ; Driver code | from collections import defaultdict NEW_LINE def countSubstrings ( s , n ) : NEW_LINE INDENT count , sum = 0 , 0 NEW_LINE mp = defaultdict ( lambda : 0 ) NEW_LINE mp [ 0 ] += 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ord ( s [ i ] ) - ord ( '0' ) NEW_LINE count += mp [ sum - ( i + 1 ) ] NEW_LINE mp [ sum - ( i + 1 ) ] += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT str = '112112' NEW_LINE n = len ( str ) NEW_LINE print ( countSubstrings ( str , n ) ) NEW_LINE |
Count of ways to split an Array into three contiguous Subarrays having increasing Sum | Function to count the number of ways to split array into three contiguous subarrays of the required type ; Stores the prefix sums ; Stores the suffix sums ; Traverse the given array ; Updating curr_subarray_sum until it is less than prefix_sum [ s - 1 ] ; Increase count ; Decrease curr_subarray_sum by arr [ s [ ] ; Return count ; Driver code | def findCount ( arr , n ) : NEW_LINE INDENT prefix_sum = [ 0 for x in range ( n ) ] NEW_LINE prefix_sum [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i ] NEW_LINE DEDENT suffix_sum = [ 0 for x in range ( n ) ] NEW_LINE suffix_sum [ n - 1 ] = arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffix_sum [ i ] = suffix_sum [ i + 1 ] + arr [ i ] NEW_LINE DEDENT s = 1 NEW_LINE e = 1 NEW_LINE curr_subarray_sum = 0 NEW_LINE count = 0 NEW_LINE while ( s < n - 1 and e < n - 1 ) : NEW_LINE INDENT while ( e < n - 1 and curr_subarray_sum < prefix_sum [ s - 1 ] ) : NEW_LINE INDENT curr_subarray_sum += arr [ e ] NEW_LINE e += 1 NEW_LINE DEDENT if ( curr_subarray_sum <= suffix_sum [ e ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT curr_subarray_sum -= arr [ s ] NEW_LINE s += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT arr = [ 2 , 3 , 1 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findCount ( arr , n ) ) NEW_LINE |
Minimum number of operations required to maximize the Binary String | Function to find the number of operations required ; Count of 1 's ; Count of 0 's upto (cnt1)-th index ; Return the answer ; Driver Code | def minOperation ( s , n ) : NEW_LINE INDENT cnt1 = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ord ( s [ i ] ) == ord ( '1' ) ) : NEW_LINE INDENT cnt1 += 1 ; NEW_LINE DEDENT DEDENT cnt0 = 0 ; NEW_LINE for i in range ( 0 , cnt1 ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT cnt0 += 1 ; NEW_LINE DEDENT DEDENT return cnt0 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 8 ; NEW_LINE s = "01001011" ; NEW_LINE ans = minOperation ( s , n ) ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT |
Minimum number of operations required to maximize the Binary String | Function to find the number of operations required ; Swap 0 ' s β and β 1' s ; Return the answer ; Driver code | def minOperation ( s , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE i = 0 ; j = n - 1 ; NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( s [ i ] == '0' and s [ j ] == '1' ) : NEW_LINE INDENT ans += 1 ; NEW_LINE i += 1 ; NEW_LINE j -= 1 ; NEW_LINE continue ; NEW_LINE DEDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT if ( s [ j ] == '0' ) : NEW_LINE INDENT j -= 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 8 ; NEW_LINE s = "10100101" ; NEW_LINE print ( minOperation ( s , n ) ) ; NEW_LINE DEDENT |
Count of N digit Numbers having no pair of equal consecutive Digits | Function to count the number of N - digit numbers with no equal pair of consecutive digits ; Base Case ; Calculate the total count of valid ( i - 1 ) - digit numbers ; Update dp table ; Calculate the count of required N - digit numbers ; Driver Code | def count ( N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( 10 ) ; NEW_LINE return ; NEW_LINE DEDENT dp = [ [ 0 for i in range ( 10 ) ] for j in range ( N ) ] NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 ; NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT temp = 0 ; NEW_LINE for j in range ( 10 ) : NEW_LINE INDENT temp += dp [ i - 1 ] [ j ] ; NEW_LINE DEDENT for j in range ( 10 ) : NEW_LINE INDENT dp [ i ] [ j ] = temp - dp [ i - 1 ] [ j ] ; NEW_LINE DEDENT DEDENT ans = 0 ; NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT ans += dp [ N - 1 ] [ i ] ; NEW_LINE DEDENT print ( ans ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 ; NEW_LINE count ( N ) ; NEW_LINE DEDENT |
Count of N digit Numbers having no pair of equal consecutive Digits | Iterative Function to calculate ( x ^ y ) % mod in O ( log y ) ; Initialize result ; Update x if x >= mod ; If x is divisible by mod ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Function to count the number of N - digit numbers with no equal pair of consecutive digits ; Base Case ; Driver Code | def power ( x , y , mod ) : NEW_LINE INDENT res = 1 ; NEW_LINE x = x % mod ; NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) == 1 ) : NEW_LINE INDENT res = ( res * x ) % mod ; NEW_LINE DEDENT y = y >> 1 ; NEW_LINE x = ( x * x ) % mod ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def count ( N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( 10 ) ; NEW_LINE return ; NEW_LINE DEDENT print ( power ( 9 , N , 1000000007 ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 ; NEW_LINE count ( N ) ; NEW_LINE DEDENT |
Smallest String consisting of a String S exactly K times as a Substring | KMP algorithm ; Function to return the required string ; Finding the longest proper prefix which is also suffix ; ans string ; Update ans appending the substring K - 1 times ; Append the original string ; Returning min length string which contain exactly k substring of given string ; Driver code | def kmp ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE lps = [ None ] * n NEW_LINE lps [ 0 ] = 0 NEW_LINE i , Len = 1 , 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( s [ i ] == s [ Len ] ) : NEW_LINE INDENT Len += 1 NEW_LINE lps [ i ] = Len NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( Len != 0 ) : NEW_LINE INDENT Len = lps [ Len - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT lps [ i ] = 0 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT DEDENT return lps NEW_LINE DEDENT def findString ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE lps = kmp ( s ) NEW_LINE ans = " " NEW_LINE suff = s [ 0 : n - lps [ n - 1 ] : 1 ] NEW_LINE for i in range ( k - 1 ) : NEW_LINE INDENT ans += suff NEW_LINE DEDENT ans += s NEW_LINE return ans NEW_LINE DEDENT k = 3 NEW_LINE s = " geeksforgeeks " NEW_LINE print ( findString ( s , k ) ) NEW_LINE |
Check if an Array can be Sorted by picking only the corner Array elements | Function to check if an array can be sorted using given operations ; If sequence becomes increasing after an already non - decreasing to non - increasing pattern ; If a decreasing pattern is observed ; Driver Code | def check ( arr , n ) : NEW_LINE INDENT g = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] > 0 and g == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( arr [ i ] - arr [ i ] < 0 ) : NEW_LINE INDENT g = 1 NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 10 , 4 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE if ( check ( arr , n ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Queries to find the count of connected Non | Count of connected cells ; Function to return the representative of the Set to which x belongs ; If x is parent of itself ; x is representative of the Set ; Otherwise ; Path Compression ; Unites the set that includes x and the set that includes y ; Find the representatives ( or the root nodes ) for x an y ; If both are in the same set ; Decrement count ; If x ' s β rank β is β less β than β y ' s rank ; Otherwise ; Then move x under y ( doesn 't matter which one goes where) ; And increment the result tree 's rank by 1 ; Function to count the number of connected cells in the matrix ; Store result for queries ; Store representative of each element ; Initially , all elements are in their own set ; Stores the rank ( depth ) of each node ; If the grid [ x * m + y ] is already set , store the result ; Set grid [ x * m + y ] to 1 ; Increment count . ; Check for all adjacent cells to do a Union with neighbour 's set if neighbour is also 1 ; Store result . ; Driver Code | ctr = 0 NEW_LINE def find ( parent , x ) : NEW_LINE INDENT if ( parent [ x ] == x ) : NEW_LINE INDENT return x NEW_LINE DEDENT parent [ x ] = find ( parent , parent [ x ] ) NEW_LINE return parent [ x ] NEW_LINE DEDENT def setUnion ( parent , rank , x , y ) : NEW_LINE INDENT global ctr NEW_LINE parentx = find ( parent , x ) NEW_LINE parenty = find ( parent , y ) NEW_LINE if ( parenty == parentx ) : NEW_LINE INDENT return NEW_LINE DEDENT ctr -= 1 NEW_LINE if ( rank [ parentx ] < rank [ parenty ] ) : NEW_LINE INDENT parent [ parentx ] = parenty NEW_LINE DEDENT elif ( rank [ parentx ] > rank [ parenty ] ) : NEW_LINE INDENT parent [ parenty ] = parentx NEW_LINE DEDENT else : NEW_LINE INDENT parent [ parentx ] = parenty NEW_LINE rank [ parenty ] += 1 NEW_LINE DEDENT DEDENT def solve ( n , m , query ) : NEW_LINE INDENT global ctr NEW_LINE result = [ 0 ] * len ( query ) NEW_LINE parent = [ 0 ] * ( n * m ) NEW_LINE for i in range ( n * m ) : NEW_LINE INDENT parent [ i ] = i NEW_LINE DEDENT rank = [ 1 ] * ( n * m ) NEW_LINE grid = [ 0 ] * ( n * m ) NEW_LINE for i in range ( len ( query ) ) : NEW_LINE INDENT x = query [ i ] [ 0 ] NEW_LINE y = query [ i ] [ 1 ] NEW_LINE if ( grid [ m * x + y ] == 1 ) : NEW_LINE INDENT result [ i ] = ctr NEW_LINE continue NEW_LINE DEDENT grid [ m * x + y ] = 1 NEW_LINE ctr += 1 NEW_LINE if ( x > 0 and grid [ m * ( x - 1 ) + y ] == 1 ) : NEW_LINE INDENT setUnion ( parent , rank , m * x + y , m * ( x - 1 ) + y ) NEW_LINE DEDENT if ( y > 0 and grid [ m * ( x ) + y - 1 ] == 1 ) : NEW_LINE INDENT setUnion ( parent , rank , m * x + y , m * ( x ) + y - 1 ) NEW_LINE DEDENT if ( x < n - 1 and grid [ m * ( x + 1 ) + y ] == 1 ) : NEW_LINE INDENT setUnion ( parent , rank , m * x + y , m * ( x + 1 ) + y ) NEW_LINE DEDENT if ( y < m - 1 and grid [ m * ( x ) + y + 1 ] == 1 ) : NEW_LINE INDENT setUnion ( parent , rank , m * x + y , m * ( x ) + y + 1 ) NEW_LINE DEDENT result [ i ] = ctr NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE M = 3 NEW_LINE K = 4 NEW_LINE query = [ [ 0 , 0 ] , [ 1 , 1 ] , [ 1 , 0 ] , [ 1 , 2 ] ] NEW_LINE result = solve ( N , M , query ) NEW_LINE for i in range ( K ) : NEW_LINE INDENT print ( result [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT |
Minimum Sum of a pair at least K distance apart from an Array | Python3 program to implement the above approach ; Function to find the minimum sum of two elements that are atleast K distance apart ; Length of the array ; Find the suffix array ; Iterate in the array ; Update minimum sum ; Print the answer ; Driver Code | import sys NEW_LINE def findMinSum ( A , K ) : NEW_LINE INDENT n = len ( A ) ; NEW_LINE suffix_min = [ 0 ] * n ; NEW_LINE suffix_min [ n - 1 ] = A [ n - 1 ] ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffix_min [ i ] = min ( suffix_min [ i + 1 ] , A [ i ] ) ; NEW_LINE DEDENT min_sum = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i + K < n ) : NEW_LINE INDENT min_sum = min ( min_sum , A [ i ] + suffix_min [ i + K ] ) ; NEW_LINE DEDENT DEDENT print ( min_sum ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 , 6 ] ; NEW_LINE K = 2 ; NEW_LINE findMinSum ( A , K ) ; NEW_LINE DEDENT |
Maximum number of envelopes that can be put inside other bigger envelopes | Function that returns the maximum number of envelopes that can be inserted into another envelopes ; Number of envelopes ; Sort the envelopes in non - decreasing order ; Initialize dp [ ] array ; To store the result ; Loop through the array ; Find envelopes count for each envelope ; Store maximum envelopes count ; Return the result ; Driver Code ; Given the envelopes ; Function Call | def maxEnvelopes ( envelopes ) : NEW_LINE INDENT N = len ( envelopes ) NEW_LINE if ( N == 0 ) : NEW_LINE INDENT return N NEW_LINE DEDENT envelopes = sorted ( envelopes ) NEW_LINE dp = [ 0 ] * N NEW_LINE max_envelope = 1 NEW_LINE dp [ 0 ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( envelopes [ i ] [ 0 ] > envelopes [ j ] [ 0 ] and envelopes [ i ] [ 1 ] > envelopes [ j ] [ 1 ] and dp [ i ] < dp [ j ] + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ j ] + 1 NEW_LINE DEDENT DEDENT max_envelope = max ( max_envelope , dp [ i ] ) NEW_LINE DEDENT return max_envelope NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT envelopes = [ [ 4 , 3 ] , [ 5 , 3 ] , [ 5 , 6 ] , [ 1 , 2 ] ] NEW_LINE print ( maxEnvelopes ( envelopes ) ) NEW_LINE DEDENT |
Maximize difference between the Sum of the two halves of the Array after removal of N elements | Function to print the maximum difference possible between the two halves of the array ; Stores n maximum values from the start ; Insert first n elements ; Update sum of largest n elements from left ; For the remaining elements ; Obtain minimum value in the set ; Insert only if it is greater than minimum value ; Update sum from left ; Remove the minimum ; Insert the current element ; Clear the set ; Store n minimum elements from the end ; Insert the last n elements ; Update sum of smallest n elements from right ; For the remaining elements ; Obtain the minimum ; Insert only if it is smaller than maximum value ; Update sum from right ; Remove the minimum ; Insert the new element ; Compare the difference and store the maximum ; Return the maximum possible difference ; Driver code | def FindMaxDif ( a , m ) : NEW_LINE INDENT n = m // 3 NEW_LINE l = [ 0 ] * ( m + 5 ) NEW_LINE r = [ 0 ] * ( m + 5 ) NEW_LINE s = [ ] NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( i <= n ) : NEW_LINE INDENT l [ i ] = a [ i - 1 ] + l [ i - 1 ] NEW_LINE s . append ( a [ i - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT l [ i ] = l [ i - 1 ] NEW_LINE s . sort ( ) NEW_LINE d = s [ 0 ] NEW_LINE if ( a [ i - 1 ] > d ) : NEW_LINE INDENT l [ i ] -= d NEW_LINE l [ i ] += a [ i - 1 ] NEW_LINE s . remove ( d ) NEW_LINE s . append ( a [ i - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT s . clear ( ) NEW_LINE for i in range ( m , 0 , - 1 ) : NEW_LINE INDENT if ( i >= m - n + 1 ) : NEW_LINE INDENT r [ i ] = a [ i - 1 ] + r [ i + 1 ] NEW_LINE s . append ( a [ i - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT r [ i ] = r [ i + 1 ] NEW_LINE s . sort ( ) NEW_LINE d = s [ - 1 ] NEW_LINE if ( a [ i - 1 ] < d ) : NEW_LINE INDENT r [ i ] -= d NEW_LINE r [ i ] += a [ i - 1 ] NEW_LINE s . remove ( d ) NEW_LINE s . append ( a [ i - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT ans = - 9e18 NEW_LINE for i in range ( n , m - n + 1 ) : NEW_LINE INDENT ans = max ( ans , l [ i ] - r [ i + 1 ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT vtr = [ 3 , 1 , 4 , 1 , 5 , 9 ] NEW_LINE n = len ( vtr ) NEW_LINE print ( FindMaxDif ( vtr , n ) ) NEW_LINE |
Check if each element of an Array is the Sum of any two elements of another Array | Function to check if each element of B [ ] can be formed by adding two elements of array A [ ] ; Store each element of B [ ] ; Traverse all possible pairs of array ; If A [ i ] + A [ j ] is present in the set ; Remove A [ i ] + A [ j ] from the set ; If set is empty ; Otherwise ; Driver Code | def checkPossible ( A , B , n ) : NEW_LINE INDENT values = set ( [ ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT values . add ( B [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ( A [ i ] + A [ j ] ) in values ) : NEW_LINE INDENT values . remove ( A [ i ] + A [ j ] ) NEW_LINE if ( len ( values ) == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( len ( values ) == 0 ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE A = [ 3 , 5 , 1 , 4 , 2 ] NEW_LINE B = [ 3 , 4 , 5 , 6 , 7 ] NEW_LINE print ( checkPossible ( A , B , N ) ) NEW_LINE DEDENT |
Count of Array elements greater than or equal to twice the Median of K trailing Array elements | Python3 program to implement the above approach ; Function to find the count of array elements >= twice the median of K trailing array elements ; Stores frequencies ; Stores the array elements ; Count the frequencies of the array elements ; Iterating from d to n - 1 index means ( d + 1 ) th element to nth element ; To check the median ; Iterate over the frequencies of the elements ; Add the frequencies ; Check if the low_median value is obtained or not , if yes then do not change as it will be minimum ; Check if the high_median value is obtained or not , if yes then do not change it as it will be maximum ; Store 2 * median of K trailing elements ; If the current >= 2 * median ; Decrease the frequency for ( k - 1 ) - th element ; Increase the frequency of the current element ; Print the count ; Driver Code | import math NEW_LINE N = 200000 NEW_LINE V = 500 NEW_LINE def solve ( n , d , input1 ) : NEW_LINE INDENT a = [ 0 ] * N NEW_LINE cnt = [ 0 ] * ( V + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] = input1 [ i ] NEW_LINE DEDENT answer = 0 NEW_LINE for i in range ( d ) : NEW_LINE INDENT cnt [ a [ i ] ] += 1 NEW_LINE DEDENT for i in range ( d , n ) : NEW_LINE INDENT acc = 0 NEW_LINE low_median = - 1 NEW_LINE high_median = - 1 NEW_LINE for v in range ( V + 1 ) : NEW_LINE INDENT acc += cnt [ v ] NEW_LINE if ( low_median == - 1 and acc >= int ( math . floor ( ( d + 1 ) / 2.0 ) ) ) : NEW_LINE INDENT low_median = v NEW_LINE DEDENT if ( high_median == - 1 and acc >= int ( math . ceil ( ( d + 1 ) / 2.0 ) ) ) : NEW_LINE INDENT high_median = v NEW_LINE DEDENT DEDENT double_median = low_median + high_median NEW_LINE if ( a [ i ] >= double_median ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT cnt [ a [ i - d ] ] -= 1 NEW_LINE cnt [ a [ i ] ] += 1 NEW_LINE DEDENT print ( answer ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input1 = [ 1 , 2 , 2 , 4 , 5 ] NEW_LINE n = len ( input1 ) NEW_LINE k = 3 NEW_LINE solve ( n , k , input1 ) NEW_LINE DEDENT |
Smallest positive integer X satisfying the given equation | Python3 program to implement the above approach ; Function to find out the smallest positive integer for the equation ; Stores the minimum ; Iterate till K ; Check if n is divisible by i ; Return the answer ; Driver Code | import sys NEW_LINE def findMinSoln ( n , k ) : NEW_LINE INDENT minSoln = sys . maxsize ; NEW_LINE for i in range ( 1 , k ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT minSoln = min ( minSoln , ( n // i ) * k + i ) ; NEW_LINE DEDENT DEDENT return minSoln ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE k = 6 ; NEW_LINE print ( findMinSoln ( n , k ) ) ; NEW_LINE DEDENT |
Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree | Function to calculate and return the sum of arr [ 0. . index ] ; Traverse ancestors of BITree [ index ] ; Update the sum of current element of BIT to ans ; Update index to that of the parent node in getSum ( ) view by subtracting LSB ( Least Significant Bit ) ; Function to update the Binary Index Tree by replacing all ancestors of index by their respective sum with val ; Traverse all ancestors and sum with ' val ' . ; Add ' val ' to current node of BIT ; Update index to that of the parent node in updateBit ( ) view by adding LSB ( Least Significant Bit ) ; Function to construct the Binary Indexed Tree for the given array ; Initialize the Binary Indexed Tree ; Store the actual values in BITree [ ] using update ( ) ; Function to obtain and return the index of lower_bound of k ; Store the Binary Indexed Tree ; Solve each query in Q ; Update the values of all ancestors of idx ; Driver Code | def getSum ( BITree , index ) : NEW_LINE INDENT ans = 0 NEW_LINE index += 1 NEW_LINE while ( index > 0 ) : NEW_LINE INDENT ans += BITree [ index ] NEW_LINE index -= index & ( - index ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def updateBIT ( BITree , n , index , val ) : NEW_LINE INDENT index = index + 1 NEW_LINE while ( index <= n ) : NEW_LINE INDENT BITree [ index ] += val NEW_LINE index += index & ( - index ) NEW_LINE DEDENT DEDENT def constructBITree ( arr , n ) : NEW_LINE INDENT BITree = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT BITree [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT updateBIT ( BITree , n , i , arr [ i ] ) NEW_LINE DEDENT return BITree NEW_LINE DEDENT def getLowerBound ( BITree , arr , n , k ) : NEW_LINE INDENT lb = - 1 NEW_LINE l = 0 NEW_LINE r = n - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = l + ( r - l ) // 2 NEW_LINE if ( getSum ( BITree , mid ) >= k ) : NEW_LINE INDENT r = mid - 1 NEW_LINE lb = mid NEW_LINE DEDENT else : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT return lb NEW_LINE DEDENT def performQueries ( A , n , q ) : NEW_LINE INDENT BITree = constructBITree ( A , n ) NEW_LINE for i in range ( len ( q ) ) : NEW_LINE INDENT id = q [ i ] [ 0 ] NEW_LINE if ( id == 1 ) : NEW_LINE INDENT idx = q [ i ] [ 1 ] NEW_LINE val = q [ i ] [ 2 ] NEW_LINE A [ idx ] += val NEW_LINE updateBIT ( BITree , n , idx , val ) NEW_LINE DEDENT else : NEW_LINE INDENT k = q [ i ] [ 1 ] NEW_LINE lb = getLowerBound ( BITree , A , n , k ) NEW_LINE print ( lb ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , 3 , 5 , 8 ] NEW_LINE n = len ( A ) NEW_LINE q = [ [ 1 , 0 , 2 ] , [ 2 , 5 , 0 ] , [ 1 , 3 , 5 ] ] NEW_LINE performQueries ( A , n , q ) NEW_LINE DEDENT |
Minimum number of leaves required to be removed from a Tree to satisfy the given condition | Stores the count of safe nodes ; Function to perform DFS on the Tree to obtain the count of vertices that are not required to be deleted ; Update cost to reach the vertex ; If the vertex does not satisfy the condition ; Otherwise ; Traverse its subtree ; Driver Code ; Stores the Tree ; Perform DFS ; Print the number of nodes to be deleted | cnt = 0 NEW_LINE def dfs ( val , cost , tr , u , s ) : NEW_LINE INDENT global cnt NEW_LINE s = s + cost [ u ] NEW_LINE if ( s < 0 ) : NEW_LINE INDENT s = 0 NEW_LINE DEDENT if ( s > val [ u ] ) : NEW_LINE INDENT return NEW_LINE DEDENT cnt += 1 NEW_LINE for i in range ( 0 , len ( tr [ u ] ) ) : NEW_LINE INDENT dfs ( val , cost , tr , tr [ u ] [ i ] , s ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 9 NEW_LINE val = [ 88 , 22 , 83 , 14 , 95 , 91 , 98 , 53 , 11 ] NEW_LINE cost = [ - 1 , 24 , - 8 , 67 , 64 , 65 , 12 , - 80 , 8 ] NEW_LINE tr = [ [ ] for i in range ( n + 1 ) ] NEW_LINE tr [ 0 ] . append ( 3 ) NEW_LINE tr [ 0 ] . append ( 4 ) NEW_LINE tr [ 4 ] . append ( 6 ) NEW_LINE tr [ 6 ] . append ( 2 ) NEW_LINE tr [ 2 ] . append ( 1 ) NEW_LINE tr [ 2 ] . append ( 8 ) NEW_LINE tr [ 8 ] . append ( 5 ) NEW_LINE tr [ 5 ] . append ( 7 ) NEW_LINE dfs ( val , cost , tr , 0 , 0 ) NEW_LINE print ( n - cnt ) NEW_LINE DEDENT |
Check if an Array is made up of Subarrays of continuous repetitions of every distinct element | Function to check if the array is made up of subarrays of repetitions ; Base Case ; Stores the size of current subarray ; If a different element is encountered ; If the previous subarray was a single element ; Reset to new subarray ; Increase size of subarray ; If last element differed from the second last element ; Driver code | def ContinuousElements ( a , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT curr = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] != a [ i - 1 ] ) : NEW_LINE if ( curr == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT curr = 0 NEW_LINE curr += 1 NEW_LINE if ( curr == 1 ) : NEW_LINE return False NEW_LINE return True NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 1 , 2 , 2 , 1 , 3 , 3 ] NEW_LINE n = len ( a ) NEW_LINE if ( ContinuousElements ( a , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Size of all connected non | Python3 program to implement the above approach ; Function to find size of all the islands from the given matrix ; Initialize a queue for the BFS traversal ; Iterate until the queue is empty ; Top element of queue ; Pop the element Q . pop ( ) ; ; Check for boundaries ; Check if current element is 0 ; Check if current element is 1 ; Mark the cell visited ; Incrementing the size ; Traverse all neighbors ; Return the answer ; Function to prsize of each connections ; Stores the size of each connected non - empty ; Check if the cell is non - empty ; Function call ; Print the answer ; Driver Code | from collections import deque NEW_LINE def BFS ( mat , row , col ) : NEW_LINE INDENT area = 0 NEW_LINE Q = deque ( ) NEW_LINE Q . append ( [ row , col ] ) NEW_LINE while ( len ( Q ) > 0 ) : NEW_LINE INDENT it = Q . popleft ( ) NEW_LINE r , c = it [ 0 ] , it [ 1 ] NEW_LINE if ( r < 0 or c < 0 or r > 4 or c > 4 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( mat [ r ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( mat [ r ] == 1 ) : NEW_LINE INDENT mat [ r ] = 0 NEW_LINE area += 1 NEW_LINE DEDENT Q . append ( [ r + 1 , c ] ) NEW_LINE Q . append ( [ r - 1 , c ] ) NEW_LINE Q . append ( [ r , c + 1 ] ) NEW_LINE Q . append ( [ r , c - 1 ] ) NEW_LINE DEDENT return area NEW_LINE DEDENT def sizeOfConnections ( mat ) : NEW_LINE INDENT result = [ ] NEW_LINE for row in range ( 5 ) : NEW_LINE INDENT for col in range ( 5 ) : NEW_LINE INDENT if ( mat [ row ] [ col ] == 1 ) : NEW_LINE INDENT area = BFS ( mat , row , col ) ; NEW_LINE result . append ( area ) NEW_LINE DEDENT DEDENT DEDENT for val in result : NEW_LINE INDENT print ( val , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 1 , 0 , 0 , 0 ] , [ 1 , 1 , 0 , 1 , 1 ] , [ 1 , 0 , 0 , 1 , 1 ] , [ 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 1 , 1 , 1 ] ] NEW_LINE sizeOfConnections ( mat ) NEW_LINE DEDENT |
Find a pair in Array with second largest product | Function to find second largest product pair in arr [ 0. . n - 1 ] ; No pair exits ; Sort the array ; Initialize smallest element of the array ; Initialize largest element of the array ; Prsecond largest product pair ; Driver Code ; Given array ; Function Call | def maxProduct ( arr , N ) : NEW_LINE INDENT if ( N < 3 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT arr . sort ( ) ; NEW_LINE smallest1 = arr [ 0 ] ; NEW_LINE smallest3 = arr [ 2 ] ; NEW_LINE largest1 = arr [ N - 1 ] ; NEW_LINE largest3 = arr [ N - 3 ] ; NEW_LINE if ( smallest1 * smallest3 >= largest1 * largest3 ) : NEW_LINE INDENT print ( smallest1 , " β " , smallest3 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( largest1 , " β " , largest3 ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 2 , 67 , 45 , 160 , 78 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE maxProduct ( arr , N ) ; NEW_LINE DEDENT |
Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | Function to find the maximum subarray length of ones ; Stores the length , starting index and ending index of the subarrays ; S : starting index of the sub - array ; Traverse only continuous 1 s ; Calculate length of the sub - array ; v [ i ] [ 0 ] : Length of subarray v [ i ] [ 1 ] : Starting Index of subarray v [ i ] [ 2 ] : Ending Index of subarray ; If no such sub - array exists ; Traversing through the subarrays ; Update maximum length ; v [ i + 1 ] [ 1 ] - v [ i ] [ 2 ] - 1 : Count of zeros between the two sub - arrays ; Update length of both subarrays to the maximum ; Update length of both subarrays - 1 to the maximum ; Check if the last subarray has the maximum length ; Driver Code | def maxLen ( A , N ) : NEW_LINE INDENT v = [ ] NEW_LINE i = 0 NEW_LINE while i < N : NEW_LINE INDENT if ( A [ i ] == 1 ) : NEW_LINE INDENT s = i NEW_LINE while ( i < N and A [ i ] == 1 ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT le = i - s NEW_LINE v . append ( [ le , s , i - 1 ] ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( len ( v ) == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( len ( v ) - 1 ) : NEW_LINE INDENT ans = max ( ans , v [ i ] [ 0 ] ) NEW_LINE if ( v [ i + 1 ] [ 1 ] - v [ i ] [ 2 ] - 1 == 2 ) : NEW_LINE INDENT ans = max ( ans , v [ i ] [ 0 ] + v [ i + 1 ] [ 0 ] ) NEW_LINE DEDENT if ( v [ i + 1 ] [ 1 ] - v [ i ] [ 2 ] - 1 == 1 ) : NEW_LINE INDENT ans = max ( ans , v [ i ] [ 0 ] + v [ i + 1 ] [ 0 ] - 1 ) NEW_LINE DEDENT DEDENT ans = max ( v [ len ( v ) - 1 ] [ 0 ] , ans ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 0 , 1 , 0 , 0 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maxLen ( arr , N ) ) NEW_LINE DEDENT |
Detect cycle in Directed Graph using Topological Sort | Python3 program to implement the above approach ; Stack to store the visited vertices in the Topological Sort ; Store Topological Order ; Adjacency list to store edges ; To ensure visited vertex ; Function to perform DFS ; Set the vertex as visited ; Visit connected vertices ; Push into the stack on complete visit of vertex ; Function to check and return if a cycle exists or not ; Stores the position of vertex in topological order ; Pop all elements from stack ; Push element to get Topological Order ; Pop from the stack ; If parent vertex does not appear first ; Cycle exists ; Return false if cycle does not exist ; Function to add edges from u to v ; Driver Code ; Insert edges ; If cycle exist | t = 0 NEW_LINE n = 0 NEW_LINE m = 0 NEW_LINE a = 0 NEW_LINE s = [ ] NEW_LINE tsort = [ ] NEW_LINE adj = [ [ ] for i in range ( 100001 ) ] NEW_LINE visited = [ False for i in range ( 100001 ) ] NEW_LINE def dfs ( u ) : NEW_LINE INDENT visited [ u ] = 1 NEW_LINE for it in adj [ u ] : NEW_LINE INDENT if ( visited [ it ] == 0 ) : NEW_LINE INDENT dfs ( it ) NEW_LINE DEDENT DEDENT s . append ( u ) NEW_LINE DEDENT def check_cycle ( ) : NEW_LINE INDENT pos = dict ( ) NEW_LINE ind = 0 NEW_LINE while ( len ( s ) != 0 ) : NEW_LINE INDENT pos [ s [ - 1 ] ] = ind NEW_LINE tsort . append ( s [ - 1 ] ) NEW_LINE ind += 1 NEW_LINE s . pop ( ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for it in adj [ i ] : NEW_LINE INDENT first = 0 if i not in pos else pos [ i ] NEW_LINE second = 0 if it not in pos else pos [ it ] NEW_LINE if ( first > second ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT def addEdge ( u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE m = 5 NEW_LINE addEdge ( 0 , 1 ) NEW_LINE addEdge ( 0 , 2 ) NEW_LINE addEdge ( 1 , 2 ) NEW_LINE addEdge ( 2 , 0 ) NEW_LINE addEdge ( 2 , 3 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( visited [ i ] == False ) : NEW_LINE INDENT dfs ( i ) NEW_LINE DEDENT DEDENT if ( check_cycle ( ) ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT DEDENT |
Rearrange an Array such that Sum of same | Function to rearrange the array such that no same - indexed subset have sum equal to that in the original array ; Initialize a vector ; Iterate the array ; Sort the vector ; Shift of elements to the index of its next cyclic element ; Print the answer ; Driver Code | def printNewArray ( a , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT v . append ( ( a [ i ] , i ) ) NEW_LINE DEDENT v . sort ( ) NEW_LINE ans = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans [ v [ ( i + 1 ) % n ] [ 1 ] ] = v [ i ] [ 0 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 4 , 1 , 2 , 5 , 3 ] NEW_LINE n = len ( a ) NEW_LINE printNewArray ( a , n ) NEW_LINE DEDENT |
Minimize count of array elements to be removed to maximize difference between any pair up to K | Python3 program to implement the above approach ; Function to count the number of elements to be removed from the array based on the given condition ; Sort the array ; Initialize the variable ; Iterate for all possible pairs ; Check the difference between the numbers ; Update the minimum removals ; Return the answer ; Driver Code | import sys NEW_LINE def min_remove ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if ( arr [ j ] - arr [ i ] <= k ) : NEW_LINE INDENT ans = min ( ans , n - j + i - 1 ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k = 3 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( min_remove ( arr , n , k ) ) NEW_LINE DEDENT |
Reduce a given Binary Array to a single element by removal of Triplets | Function to check if it is possible to reduce the array to a single element ; Stores frequency of 0 's ; Stores frequency of 1 's ; Condition for array to be reduced ; Otherwise ; Driver Code | def solve ( arr , n ) : NEW_LINE INDENT countzeroes = 0 ; NEW_LINE countones = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT countzeroes += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT countones += 1 ; NEW_LINE DEDENT DEDENT if ( abs ( countzeroes - countones ) == 1 ) : 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 = [ 0 , 1 , 0 , 0 , 1 , 1 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE solve ( arr , n ) ; NEW_LINE DEDENT |
Nearest smaller character to a character K from a Sorted Array | Function to return the nearest smaller character ; Stores the nearest smaller character ; Iterate till starts cross end ; Find the mid element ; Check if K is found ; Check if current character is less than K ; Increment the start ; Otherwise ; Increment end ; Return the character ; Driver code | def bs ( a , n , ele ) : NEW_LINE INDENT start = 0 NEW_LINE end = n - 1 NEW_LINE ch = ' @ ' NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = start + ( end - start ) // 2 ; NEW_LINE if ( ar [ mid ] == ele ) : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT elif ( ar [ mid ] < ele ) : NEW_LINE INDENT ch = ar [ mid ] NEW_LINE start = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 ; NEW_LINE DEDENT DEDENT return ch NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ar = [ ' e ' , ' g ' , ' t ' , ' y ' ] NEW_LINE n = len ( ar ) NEW_LINE K = ' u ' ; NEW_LINE ch = bs ( ar , n , K ) ; NEW_LINE if ( ch == ' @ ' ) : NEW_LINE INDENT print ( ' - 1' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ch ) NEW_LINE DEDENT DEDENT |
Largest possible Subset from an Array such that no element is K times any other element in the Subset | Function to find the maximum size of the required subset ; Size of the array ; Sort the array ; Stores which index is included or excluded ; Stores the indices of array elements ; Count of pairs ; Iterate through all the element ; If element is included ; Check if a [ i ] * k is present in the array or not ; Increase count of pair ; Exclude the pair ; Driver Code | def findMaxLen ( a , k ) : NEW_LINE INDENT n = len ( a ) NEW_LINE a . sort ( ) NEW_LINE vis = [ 0 ] * n NEW_LINE mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ a [ i ] ] = i NEW_LINE DEDENT c = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( vis [ i ] == False ) : NEW_LINE INDENT check = a [ i ] * k NEW_LINE if ( check in mp . keys ( ) ) : NEW_LINE INDENT c += 1 NEW_LINE vis [ mp [ check ] ] = True NEW_LINE DEDENT DEDENT DEDENT return n - c NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 3 NEW_LINE arr = [ 1 , 4 , 3 , 2 ] NEW_LINE print ( findMaxLen ( arr , K ) ) NEW_LINE DEDENT |
Minimize length of prefix of string S containing all characters of another string T | Python3 program for the above approach ; Base Case - if T is empty , it matches 0 length prefix ; Convert strings to lower case for uniformity ; Update dictCount to the letter count of T ; If new character is found , initialize its entry , and increase nUnique ; Increase count of ch ; Iterate from 0 to N ; i - th character ; Skip if ch not in targetStr ; Decrease Count ; If the count of ch reaches 0 , we do not need more ch , and can decrease nUnique ; If nUnique reaches 0 , we have found required prefix ; Otherwise ; Driver Code | def getPrefixLength ( srcStr , targetStr ) : NEW_LINE INDENT if ( len ( targetStr ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT srcStr = srcStr . lower ( ) NEW_LINE targetStr = targetStr . lower ( ) NEW_LINE dictCount = dict ( [ ] ) NEW_LINE nUnique = 0 NEW_LINE for ch in targetStr : NEW_LINE INDENT if ( ch not in dictCount ) : NEW_LINE INDENT nUnique += 1 NEW_LINE dictCount [ ch ] = 0 NEW_LINE DEDENT dictCount [ ch ] += 1 NEW_LINE DEDENT for i in range ( len ( srcStr ) ) : NEW_LINE INDENT ch = srcStr [ i ] NEW_LINE if ( ch not in dictCount ) : NEW_LINE INDENT continue NEW_LINE DEDENT dictCount [ ch ] -= 1 NEW_LINE if ( dictCount [ ch ] == 0 ) : NEW_LINE INDENT nUnique -= 1 NEW_LINE DEDENT if ( nUnique == 0 ) : NEW_LINE INDENT return ( i + 1 ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " MarvoloGaunt " NEW_LINE T = " Tom " NEW_LINE print ( getPrefixLength ( S , T ) ) NEW_LINE DEDENT |
Minimize length of Substrings containing at least one common Character | Function to check and return if substrings of length mid has a common character a ; Length of the string ; Initialise the first occurrence of character a ; Check that distance b / w the current and previous occurrence of character a is less than or equal to mid ; If distance exceeds mid ; Function to check for all the alphabets , if substrings of length mid have a character common ; Check for all 26 alphabets ; Check that char i + a is common in all the substrings of length mid ; If no characters is common ; Function to calculate and return the minm length of substrings ; Initialise low and high ; Perform binary search ; Update mid ; Check if one common character is present in the length of the mid ; Returns the minimum length that contain one common character ; Function to check if all characters are distinct ; Driver Code | def check ( st , mid , a ) : NEW_LINE INDENT n = len ( st ) NEW_LINE previous = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( st [ i ] == chr ( a ) ) : NEW_LINE INDENT if ( i - previous > mid ) : NEW_LINE INDENT return False NEW_LINE DEDENT previous = i NEW_LINE DEDENT DEDENT if ( i - previous > mid ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT def possible ( st , mid ) : NEW_LINE INDENT for i in range ( 26 ) : NEW_LINE INDENT if ( check ( st , mid , i + ord ( ' a ' ) ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def findMinLength ( st ) : NEW_LINE INDENT low = 1 NEW_LINE high = len ( st ) NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( possible ( st , mid ) ) : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return high + 1 NEW_LINE DEDENT def ifAllDistinct ( st ) : NEW_LINE INDENT s = [ ] NEW_LINE for c in st : NEW_LINE INDENT s . append ( c ) NEW_LINE DEDENT return len ( set ( s ) ) == len ( st ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " geeksforgeeks " NEW_LINE if ( ifAllDistinct ( st ) ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( findMinLength ( st ) ) NEW_LINE DEDENT DEDENT |
Maximize product of absolute index difference with K | Function returns maximum possible value of k ; Pointer i make sure that A [ i ] will result in max k ; Stores maximum possible k ; Possible value of k for current pair ( A [ i ] and A [ j ] ) ; If current value exceeds k ; Update the value of k ; Update pointer i ; Return the maxm possible k ; Driver Code | def solve ( A , N ) : NEW_LINE INDENT i = 0 NEW_LINE k = 0 NEW_LINE for j in range ( 1 , N ) : NEW_LINE INDENT tempK = ( min ( A [ i ] , A [ j ] ) // ( j - i ) ) NEW_LINE if ( tempK > k ) : NEW_LINE INDENT k = tempK NEW_LINE DEDENT if ( A [ j ] >= A [ i ] // ( j - i ) ) : NEW_LINE INDENT i = j NEW_LINE DEDENT DEDENT return k NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 10 , 5 , 12 , 15 , 8 ] NEW_LINE N = len ( A ) ; NEW_LINE print ( solve ( A , N ) ) NEW_LINE DEDENT |
Split Array into min number of subsets with difference between each pair greater than 1 | Function to Split the array into minimum number of subsets with difference strictly > 1 ; Sort the array ; Traverse through the sorted array ; Check the pairs of elements with difference 1 ; If we find even a single pair with difference equal to 1 , then 2 partitions else only 1 partition ; Print the count of partitions ; Driver Code ; Given array ; Size of the array ; Function call | def split ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE count = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] == 1 ) : NEW_LINE INDENT count = 2 NEW_LINE break NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE split ( arr , n ) NEW_LINE DEDENT |
Check if a Palindromic String can be formed by concatenating Substrings of two given Strings | Function to check if a palindromic string can be formed from the substring of given strings ; Boolean array to mark presence of characters ; Check if any of the character of str2 is already marked ; If a common character is found ; If no common character is found ; Driver code | def check ( str1 , str2 ) : NEW_LINE INDENT mark = [ False for i in range ( 26 ) ] NEW_LINE n = len ( str1 ) NEW_LINE m = len ( str2 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mark [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT if ( mark [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " abca " NEW_LINE str2 = " efad " NEW_LINE if ( check ( str1 , str2 ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Generate K co | Python3 implementation of the above approach ; Function prints the required pairs ; First co - prime pair ; As a pair ( 1 n ) has already been Printed ; If i is a factor of N ; Since ( i , i ) won 't form a coprime pair ; Driver Code | from math import sqrt NEW_LINE def FindPairs ( n , k ) : NEW_LINE INDENT print ( 1 , n ) NEW_LINE k -= 1 NEW_LINE for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT print ( 1 , i ) NEW_LINE k -= 1 NEW_LINE if ( k == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( i != n // i ) : NEW_LINE INDENT print ( 1 , n // i ) NEW_LINE k -= 1 NEW_LINE DEDENT if ( k == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 100 NEW_LINE K = 5 NEW_LINE FindPairs ( N , K ) NEW_LINE DEDENT |
Count of subarrays which forms a permutation from given Array elements | Function returns the required count ; Store the indices of the elements present in A [ ] . ; Store the maximum and minimum index of the elements from 1 to i . ; Update maxi and mini , to store minimum and maximum index for permutation of elements from 1 to i + 1 ; If difference between maxi and mini is equal to i ; Increase count ; Return final count ; Driver Code | def PermuteTheArray ( A , n ) : NEW_LINE INDENT arr = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ A [ i ] - 1 ] = i NEW_LINE DEDENT mini = n NEW_LINE maxi = 0 NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mini = min ( mini , arr [ i ] ) NEW_LINE maxi = max ( maxi , arr [ i ] ) NEW_LINE if ( maxi - mini == i ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 4 , 5 , 1 , 3 , 2 , 6 ] NEW_LINE print ( PermuteTheArray ( A , 6 ) ) NEW_LINE DEDENT |
Find Second largest element in an array | Set 2 | Function to find the largest element in the array arr [ ] ; Base Condition ; Initialize an empty list ; Divide the array into two equal length subarrays and recursively find the largest among the two ; Store length of compared1 [ ] in the first index ; Store the maximum element ; Return compared1 which contains the maximum element ; Store length of compared2 [ ] in the first index ; Store the maximum element ; Return compared2 [ ] which contains the maximum element ; Function to print the second largest element in the array arr [ ] ; Find the largest element in arr [ ] ; Find the second largest element in arr [ ] ; Print the second largest element ; Driver Code | def findLargest ( beg , end , arr , n ) : NEW_LINE INDENT if ( beg == end ) : NEW_LINE INDENT compared = [ 0 ] * n NEW_LINE compared [ 0 ] = 1 NEW_LINE compared [ 1 ] = arr [ beg ] NEW_LINE return compared NEW_LINE DEDENT compared1 = findLargest ( beg , ( beg + end ) // 2 , arr , n ) NEW_LINE compared2 = findLargest ( ( beg + end ) // 2 + 1 , end , arr , n ) NEW_LINE if ( compared1 [ 1 ] > compared2 [ 1 ] ) : NEW_LINE INDENT k = compared1 [ 0 ] + 1 NEW_LINE compared1 [ 0 ] = k NEW_LINE compared1 [ k ] = compared2 [ 1 ] NEW_LINE return compared1 NEW_LINE DEDENT else : NEW_LINE INDENT k = compared2 [ 0 ] + 1 NEW_LINE compared2 [ 0 ] = k NEW_LINE compared2 [ k ] = compared1 [ 1 ] NEW_LINE return compared2 NEW_LINE DEDENT DEDENT def findSecondLargest ( end , arr ) : NEW_LINE INDENT compared1 = findLargest ( 0 , end - 1 , arr , end ) NEW_LINE compared2 = findLargest ( 2 , compared1 [ 0 ] + 2 , compared1 , compared1 [ 0 ] ) NEW_LINE print ( compared2 [ 1 ] ) NEW_LINE DEDENT N = 10 NEW_LINE arr = [ 20 , 1990 , 12 , 1110 , 1 , 59 , 12 , 15 , 120 , 1110 ] NEW_LINE findSecondLargest ( N , arr ) NEW_LINE |
Count of Reverse Bitonic Substrings in a given String | Function to calculate the number of reverse bitonic substrings ; Stores the count ; All possible lengths of substrings ; Starting poof a substring ; Ending poof a substring ; Condition for reverse bitonic substrings of length 1 ; Check for decreasing sequence ; If end of substring is reache ; For increasing sequence ; If end of substring is reached ; Return the number of bitonic substrings ; Driver Code | def CountsubString ( strr , n ) : NEW_LINE INDENT c = 0 NEW_LINE for len in range ( n + 1 ) : NEW_LINE INDENT for i in range ( n - len ) : NEW_LINE INDENT j = i + len - 1 NEW_LINE temp = strr [ i ] NEW_LINE f = 0 NEW_LINE if ( j == i ) : NEW_LINE INDENT c += 1 NEW_LINE continue NEW_LINE DEDENT k = i + 1 NEW_LINE while ( k <= j and temp > strr [ k ] ) : NEW_LINE INDENT temp = strr [ k ] NEW_LINE k += 1 NEW_LINE DEDENT if ( k > j ) : NEW_LINE INDENT c += 1 NEW_LINE f = 2 NEW_LINE DEDENT while ( k <= j and f != 2 and temp < strr [ k ] ) : NEW_LINE INDENT temp = strr [ k ] NEW_LINE k += 1 NEW_LINE DEDENT if ( k > j and f != 2 ) : NEW_LINE INDENT c += 1 NEW_LINE f = 0 NEW_LINE DEDENT DEDENT DEDENT return c NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " bade " NEW_LINE print ( CountsubString ( strr , len ( strr ) ) ) NEW_LINE DEDENT |
Maximum subsequence sum from a given array which is a perfect square | Python3 program to implement the above approach ; If sum is 0 , then answer is true ; If sum is not 0 and arr [ ] is empty , then answer is false ; Fill the subset table in bottom up manner ; Function to find the sum ; Find sum of all values ; Return the value ; ; Driver Code | import math NEW_LINE def isSubsetSum ( arr , n , sum ) : NEW_LINE INDENT subset = [ [ True for x in range ( sum + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT subset [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , sum + 1 ) : NEW_LINE INDENT subset [ 0 ] [ i ] = False NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , sum + 1 ) : NEW_LINE INDENT if ( j < arr [ i - 1 ] ) : NEW_LINE INDENT subset [ i ] [ j ] = subset [ i - 1 ] [ j ] NEW_LINE DEDENT if ( j >= arr [ i - 1 ] ) : NEW_LINE INDENT subset [ i ] [ j ] = ( subset [ i - 1 ] [ j ] or subset [ i - 1 ] [ j - arr [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT return subset [ n ] [ sum ] NEW_LINE DEDENT def findSum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT val = int ( math . sqrt ( sum ) ) NEW_LINE for i in range ( val , - 1 , - 1 ) : NEW_LINE INDENT if ( isSubsetSum ( arr , n , i * i ) ) : NEW_LINE INDENT return i * i NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findSum ( arr , n ) ) NEW_LINE DEDENT |
Smallest subarray whose product leaves remainder K when divided by size of the array | Function to find the subarray of minimum length ; Initialize the minimum subarray size to N + 1 ; Generate all possible subarray ; Initialize the product ; Find the product ; Return the minimum size of subarray ; Driver code ; Given array | def findsubArray ( arr , N , K ) : NEW_LINE INDENT res = N + 1 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT curr_prad = 1 NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT curr_prad = curr_prad * arr [ j ] NEW_LINE if ( curr_prad % N == K and res > ( j - i + 1 ) ) : NEW_LINE INDENT res = min ( res , j - i + 1 ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if res == N + 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return res NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE K = 1 NEW_LINE answer = findsubArray ( arr , N , K ) NEW_LINE if ( answer != 0 ) : NEW_LINE INDENT print ( answer ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT |
Count of array elements whose order of deletion precedes order of insertion | Python3 Program to implement the above approach ; Function returns maximum number of required elements ; Insert the elements of array B in the queue and set ; Stores the answer ; If A [ i ] is already processed ; Until we find A [ i ] in the queue ; Remove elements from the queue ; Increment the count ; Remove the current element A [ i ] from the queue and set . ; Return total count ; Driver code | import queue NEW_LINE def maximumCount ( A , B , n ) : NEW_LINE INDENT q = queue . Queue ( ) NEW_LINE s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( B [ i ] ) NEW_LINE q . put ( B [ i ] ) NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( A [ i ] not in s ) : NEW_LINE INDENT continue NEW_LINE DEDENT while ( q . qsize ( ) > 0 and q . queue [ 0 ] != A [ i ] ) : NEW_LINE INDENT s . remove ( q . queue [ 0 ] ) ; NEW_LINE q . get ( ) NEW_LINE count += 1 NEW_LINE DEDENT if ( A [ i ] == q . queue [ 0 ] ) : NEW_LINE INDENT q . get ( ) NEW_LINE s . remove ( A [ i ] ) NEW_LINE DEDENT if ( q . qsize ( ) == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT N = 4 NEW_LINE A = [ 1 , 2 , 3 , 4 ] NEW_LINE B = [ 1 , 2 , 4 , 3 ] NEW_LINE maximumCount ( A , B , N ) NEW_LINE |
Check if a Matrix is Bitonic or not | Python3 program to check if a matrix is Bitonic or not ; Function to check if an array is Bitonic or not ; Check for increasing sequence ; Check for decreasing sequence ; Function to check whether given matrix is bitonic or not ; Check row wise ; Check column wise ; Generate an array consisting of elements of current column ; Driver Code | N = 3 NEW_LINE M = 3 NEW_LINE def checkBitonic ( arr , n ) : NEW_LINE INDENT i , j , f = 0 , 0 , 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT f = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( i == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] < arr [ j - 1 ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT if ( f == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def check ( arr ) : NEW_LINE INDENT f = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( not checkBitonic ( arr [ i ] , M ) ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE return NEW_LINE DEDENT DEDENT i = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT temp = [ 0 ] * N NEW_LINE for j in range ( N ) : NEW_LINE INDENT temp [ j ] = arr [ j ] [ i ] NEW_LINE DEDENT if ( not checkBitonic ( temp , N ) ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " YES " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = [ [ 1 , 2 , 3 ] , [ 3 , 4 , 5 ] , [ 2 , 6 , 4 ] ] NEW_LINE check ( m ) NEW_LINE DEDENT |
Maximum possible GCD for a pair of integers with product N | Python3 program to implement the above approach ; Function to return the maximum GCD ; To find all divisors of N ; If i is a factor ; Store the pair of factors ; Store the maximum GCD ; Return the maximum GCD ; Driver Code | import sys NEW_LINE import math NEW_LINE def getMaxGcd ( N ) : NEW_LINE INDENT maxGcd = - sys . maxsize - 1 NEW_LINE for i in range ( 1 , int ( math . sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT A = i NEW_LINE B = N // i NEW_LINE maxGcd = max ( maxGcd , math . gcd ( A , B ) ) NEW_LINE DEDENT DEDENT return maxGcd NEW_LINE DEDENT N = 18 NEW_LINE print ( getMaxGcd ( N ) ) NEW_LINE |
Maximum of minimum difference of all pairs from subsequences of given size | Function to check a subsequence can be formed with min difference mid ; If a subsequence of size B with min diff = mid is possible return true else false ; Function to find the maximum of all minimum difference of pairs possible among the subsequence ; Sort the Array ; Stores the boundaries of the search space ; Store the answer ; Binary Search ; If subsequence can be formed with min diff mid and size B ; Right half ; Left half ; Driver code | def can_place ( A , n , B , mid ) : NEW_LINE INDENT count = 1 NEW_LINE last_position = A [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( A [ i ] - last_position >= mid ) : NEW_LINE INDENT last_position = A [ i ] NEW_LINE count = count + 1 NEW_LINE if ( count == B ) : NEW_LINE INDENT return bool ( True ) NEW_LINE DEDENT DEDENT DEDENT return bool ( False ) NEW_LINE DEDENT def find_min_difference ( A , n , B ) : NEW_LINE INDENT A . sort ( ) NEW_LINE s = 0 NEW_LINE e = A [ n - 1 ] - A [ 0 ] NEW_LINE ans = 0 NEW_LINE while ( s <= e ) : NEW_LINE INDENT mid = ( int ) ( ( s + e ) / 2 ) NEW_LINE if ( can_place ( A , n , B , mid ) ) : NEW_LINE INDENT ans = mid NEW_LINE s = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT e = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A = [ 1 , 2 , 3 , 5 ] NEW_LINE n = len ( A ) NEW_LINE B = 3 NEW_LINE min_difference = find_min_difference ( A , n , B ) NEW_LINE print ( min_difference ) NEW_LINE |
Count of triplets in an Array such that A [ i ] * A [ j ] = A [ k ] and i < j < k | Python3 program for the above approach ; Returns total number of valid triplets possible ; Stores the count ; Map to store frequency of array elements ; Increment the frequency of A [ j + 1 ] as it can be a valid A [ k ] ; If target exists in the map ; Return the final count ; Driver code | from collections import defaultdict NEW_LINE def countTriplets ( A , N ) : NEW_LINE INDENT ans = 0 NEW_LINE map = defaultdict ( lambda : 0 ) NEW_LINE for j in range ( N - 2 , 0 , - 1 ) : NEW_LINE INDENT map [ A [ j + 1 ] ] += 1 NEW_LINE for i in range ( j ) : NEW_LINE INDENT target = A [ i ] * A [ j ] NEW_LINE if ( target in map . keys ( ) ) : NEW_LINE INDENT ans += map [ target ] NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE A = [ 2 , 3 , 4 , 6 , 12 ] NEW_LINE print ( countTriplets ( A , N ) ) NEW_LINE DEDENT |
Missing vertex among N axis | Python3 program for the above approach ; Driver code ; Number of rectangles ; Stores the coordinates ; Insert the coordinates | from collections import defaultdict NEW_LINE def MissingPoint ( V , N ) : NEW_LINE INDENT mp = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( len ( V ) ) : NEW_LINE INDENT mp [ V [ i ] [ 0 ] ] += 1 NEW_LINE DEDENT for it in mp . keys ( ) : NEW_LINE INDENT if ( mp [ it ] % 2 == 1 ) : NEW_LINE INDENT x = it NEW_LINE break NEW_LINE DEDENT DEDENT del mp NEW_LINE mp = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( len ( V ) ) : NEW_LINE INDENT mp [ V [ i ] [ 1 ] ] += 1 NEW_LINE DEDENT for it in mp . keys ( ) : NEW_LINE INDENT if ( mp [ it ] % 2 == 1 ) : NEW_LINE INDENT y = it NEW_LINE break NEW_LINE DEDENT DEDENT print ( x , y ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE V = [ ] NEW_LINE V . append ( [ 1 , 1 ] ) NEW_LINE V . append ( [ 1 , 2 ] ) NEW_LINE V . append ( [ 4 , 6 ] ) NEW_LINE V . append ( [ 2 , 1 ] ) NEW_LINE V . append ( [ 9 , 6 ] ) NEW_LINE V . append ( [ 9 , 3 ] ) NEW_LINE V . append ( [ 4 , 3 ] ) NEW_LINE MissingPoint ( V , N ) NEW_LINE DEDENT |
Longest alternating subsequence with maximum sum | Set 2 | Function to check the sign of the element ; Function to calculate and return the maximum sum of longest alternating subsequence ; Iterate through the array ; Stores the first element of a sequence of same sign ; Traverse until an element with opposite sign is encountered ; Update the maximum ; Update the maximum sum ; Update i ; Return the maximum sum ; Driver Code | def sign ( x ) : NEW_LINE INDENT if ( x > 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT def findMaxSum ( arr , size ) : NEW_LINE INDENT max_sum = 0 NEW_LINE i = 0 NEW_LINE while i < size : NEW_LINE INDENT pres = arr [ i ] NEW_LINE j = i NEW_LINE while ( j < size and ( sign ( arr [ i ] ) == sign ( arr [ j ] ) ) ) : NEW_LINE INDENT pres = max ( pres , arr [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT max_sum = max_sum + pres NEW_LINE i = j - 1 NEW_LINE i += 1 NEW_LINE DEDENT return max_sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 2 , 8 , 3 , 8 , - 4 , - 15 , 5 , - 2 , - 3 , 1 ] NEW_LINE size = len ( arr ) NEW_LINE print ( findMaxSum ( arr , size ) ) NEW_LINE DEDENT |
Check if an array can be split into subsets of K consecutive elements | Python3 program to implement the above approach ; Function to check if a given array can be split into subsets of K consecutive elements ; Stores the frequencies of array elements ; Traverse the map ; Check if all its occurrences can be grouped into K subsets ; Traverse next K elements ; If the element is not present in the array ; If it cannot be split into required number of subsets ; Driver Code | from collections import defaultdict NEW_LINE def groupInKConsecutive ( arr , K ) : NEW_LINE INDENT count = defaultdict ( int ) NEW_LINE for h in arr : NEW_LINE INDENT count [ h ] += 1 NEW_LINE DEDENT for key , value in count . items ( ) : NEW_LINE INDENT cur = key NEW_LINE n = value NEW_LINE if ( n > 0 ) : NEW_LINE INDENT for i in range ( 1 , K ) : NEW_LINE INDENT if ( ( cur + i ) not in count ) : NEW_LINE INDENT return False NEW_LINE DEDENT count [ cur + i ] -= n NEW_LINE if ( count [ cur + i ] < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 6 , 2 , 3 , 4 , 7 , 8 ] NEW_LINE k = 3 NEW_LINE if ( groupInKConsecutive ( arr , k ) ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT DEDENT |
Count of substrings of a given Binary string with all characters same | Function to count number of sub - strings of a given binary string that contains only 1 ; Iterate untill L and R cross each other ; Check if reached the end of string ; Check if encountered '1' then extend window ; Check if encountered '0' then add number of strings of current window and change the values for both l and r ; Return the answer ; Function to flip the bits of string ; Function to count number of sub - strings of a given binary string that contains only 0 s & 1 s ; count of substring which contains only 1 s ; Flip the character of string s 0 to 1 and 1 to 0 to count the substring with consecutive 0 s ; count of substring which contains only 0 s ; Driver Code ; Given string str ; Function Call | def countSubAllOnes ( s ) : NEW_LINE INDENT l , r , ans = 0 , 0 , 0 NEW_LINE while ( l <= r ) : NEW_LINE INDENT if ( r == len ( s ) ) : NEW_LINE INDENT ans += ( ( r - l ) * ( r - l + 1 ) ) // 2 NEW_LINE break NEW_LINE DEDENT if ( s [ r ] == '1' ) : NEW_LINE INDENT r += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( ( r - l ) * ( r - l + 1 ) ) // 2 NEW_LINE l = r + 1 NEW_LINE r += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def flip ( s ) : NEW_LINE INDENT arr = list ( s ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( arr [ i ] == '1' ) : NEW_LINE INDENT arr [ i ] = '0' NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = '1' NEW_LINE DEDENT DEDENT s = ' ' . join ( arr ) NEW_LINE return s NEW_LINE DEDENT def countSubAllZerosOnes ( s ) : NEW_LINE INDENT only_1s = countSubAllOnes ( s ) NEW_LINE s = flip ( s ) NEW_LINE only_0s = countSubAllOnes ( s ) NEW_LINE return only_0s + only_1s NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "011" NEW_LINE print ( countSubAllZerosOnes ( s ) ) NEW_LINE DEDENT |
Count of primes in a given range that can be expressed as sum of perfect squares | Function to check if a prime number satisfies the condition to be expressed as sum of two perfect squares ; Function to check if a number is prime or not ; Corner cases ; Function to return the count of primes in the range which can be expressed as the sum of two squares ; If i is a prime ; If i can be expressed as the sum of two squares ; Return the count ; Driver code | def sumsquare ( p ) : NEW_LINE INDENT return ( p - 1 ) % 4 == 0 NEW_LINE DEDENT 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 i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( ( n % i == 0 ) or ( n % ( i + 2 ) == 0 ) ) : NEW_LINE return False NEW_LINE i += 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def countOfPrimes ( L , R ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( isprime ( i ) ) : NEW_LINE if sumsquare ( i ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 5 NEW_LINE R = 41 NEW_LINE print ( countOfPrimes ( L , R ) ) NEW_LINE DEDENT |
Count of array elements which are greater than all elements on its left | Function to return the count of array elements with all elements to its left smaller than it ; Stores the count ; Stores the maximum ; Iterate over the array ; If an element greater than maximum is obtained ; Increase count ; Update maximum ; Driver Code | def count_elements ( arr ) : NEW_LINE INDENT count = 1 NEW_LINE max = arr [ 0 ] NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT if arr [ i ] > max : NEW_LINE INDENT count += 1 NEW_LINE max = arr [ i ] NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 2 , 1 , 4 , 6 , 3 ] NEW_LINE print ( count_elements ( arr ) ) NEW_LINE |
Count of bitonic substrings from the given string | Function to find all the bitonic sub strings ; Pick starting po ; Iterate till length of the string ; Pick ending pofor string ; Substring from i to j is obtained ; Substrings of length 1 ; Increase count ; For increasing sequence ; Check for strictly increasing ; Increase count ; Check for decreasing sequence ; Increase count ; Print the result ; Given string ; Function Call | def subString ( str , n ) : NEW_LINE INDENT c = 0 ; NEW_LINE for len in range ( 1 , n + 1 ) : NEW_LINE INDENT for i in range ( 0 , n - len + 1 ) : NEW_LINE INDENT j = i + len - 1 ; NEW_LINE temp = str [ i ] NEW_LINE f = 0 ; NEW_LINE if ( j == i ) : NEW_LINE INDENT c += 1 NEW_LINE continue ; NEW_LINE DEDENT k = i + 1 ; NEW_LINE while ( k <= j and temp < str [ k ] ) : NEW_LINE INDENT temp = str [ k ] ; NEW_LINE k += 1 ; NEW_LINE f = 2 ; NEW_LINE DEDENT if ( k > j ) : NEW_LINE INDENT c += 1 ; NEW_LINE f = 2 ; NEW_LINE DEDENT while ( k <= j and temp > str [ k ] and f != 2 ) : NEW_LINE INDENT k += 1 ; NEW_LINE f = 0 ; NEW_LINE DEDENT if ( k > j and f != 2 ) : NEW_LINE INDENT c += 1 ; NEW_LINE f = 0 ; NEW_LINE DEDENT DEDENT DEDENT print ( c ) NEW_LINE DEDENT str = " bade " ; NEW_LINE subString ( str , len ( str ) ) NEW_LINE |
Check if ceil of number divided by power of two exist in sorted array | Function to find there exist a number or not in the array ; Loop to check if there exist a number by divided by power of 2 ; Binary Search ; Condition to check the number is found in the array or not ; Otherwise divide the number by increasing the one more power of 2 ; Driver Code | def findNumberDivByPowerofTwo ( ar , k , n ) : NEW_LINE INDENT found = - 1 NEW_LINE m = k NEW_LINE while ( m > 0 ) : NEW_LINE INDENT l = 0 NEW_LINE r = n - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = ( l + r ) // 2 NEW_LINE if ( ar [ mid ] == m ) : NEW_LINE INDENT found = m NEW_LINE break NEW_LINE DEDENT elif ( ar [ mid ] > m ) : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT elif ( ar [ mid ] < m ) : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT DEDENT if ( found != - 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT m = m // 2 NEW_LINE DEDENT return found NEW_LINE DEDENT arr = [ 3 , 5 , 7 , 8 , 10 ] NEW_LINE k = 4 NEW_LINE n = 5 NEW_LINE print ( findNumberDivByPowerofTwo ( arr , k , n ) ) NEW_LINE |
Largest subset having with sum less than equal to sum of respective indices | Function to find the length of the longest subset ; Stores the sum of differences between elements and their respective index ; Stores the size of the subset ; Iterate over the array ; If an element which is smaller than or equal to its index is encountered ; Increase count and sum ; Store the difference with index of the remaining elements ; Sort the differences in increasing order ; Include the differences while sum remains positive or ; Return the size ; Driver code ; Function calling | def findSubset ( a , n ) : NEW_LINE INDENT sum = 0 NEW_LINE cnt = 0 NEW_LINE v = [ ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( a [ i - 1 ] - i <= 0 ) : NEW_LINE INDENT sum += a [ i - 1 ] - i NEW_LINE cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( a [ i - 1 ] - i ) NEW_LINE DEDENT DEDENT v . sort ( ) NEW_LINE ptr = 0 NEW_LINE while ( ptr < len ( v ) and sum + v [ ptr ] <= 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE ptr += 1 NEW_LINE sum += v [ ptr ] NEW_LINE DEDENT return cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 1 , 6 , 7 , 8 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findSubset ( arr , n ) ) NEW_LINE DEDENT |
Queries for count of array elements with values in given range with updates | Python3 code for queries for number of elements that lie in range [ l , r ] ( with updates ) ; Function to set arr [ index ] = x ; Function to get count of elements that lie in range [ l , r ] ; Traverse array ; If element lies in the range [ L , R ] ; Increase count ; Function to solve each query ; Driver Code | from typing import Generic , List , TypeVar NEW_LINE T = TypeVar ( ' T ' ) NEW_LINE V = TypeVar ( ' V ' ) NEW_LINE class Pair ( Generic [ V , T ] ) : NEW_LINE INDENT def __init__ ( self , first : V , second : T ) -> None : NEW_LINE INDENT self . first = first NEW_LINE self . second = second NEW_LINE DEDENT DEDENT def setElement ( arr : List [ int ] , n : int , index : int , x : int ) -> None : NEW_LINE INDENT arr [ index ] = x NEW_LINE DEDENT def getCount ( arr : List [ int ] , n : int , l : int , r : int ) -> int : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] >= l and arr [ i ] <= r ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def SolveQuery ( arr : List [ int ] , n : int , Q : List [ Pair [ int , Pair [ int , int ] ] ] ) : NEW_LINE INDENT x = 0 NEW_LINE for i in range ( len ( Q ) ) : NEW_LINE INDENT if ( Q [ i ] . first == 1 ) : NEW_LINE INDENT x = getCount ( arr , n , Q [ i ] . second . first , Q [ i ] . second . second ) NEW_LINE print ( x , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT setElement ( arr , n , Q [ i ] . second . first , Q [ i ] . second . second ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 3 , 4 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE Q = [ Pair ( 1 , Pair ( 3 , 5 ) ) , Pair ( 1 , Pair ( 2 , 4 ) ) , Pair ( 1 , Pair ( 1 , 2 ) ) , Pair ( 2 , Pair ( 1 , 7 ) ) , Pair ( 1 , Pair ( 1 , 2 ) ) ] NEW_LINE SolveQuery ( arr , n , Q ) NEW_LINE DEDENT |
Construct a sequence from given frequencies of N consecutive integers with unit adjacent difference | Function generates the sequence ; Map to store the frequency of numbers ; Sum of all frequencies ; Try all possibilities for the starting element ; If the frequency of current element is non - zero ; vector to store the answer ; Copy of the map for every possible starting element ; Decrement the frequency ; Push the starting element to the vector ; The last element inserted is i ; Try to fill the rest of the positions if possible ; If the frequency of last - 1 is non - zero ; Decrement the frequency of last - 1 ; Insert it into the sequence ; Update last number added to sequence ; Break from the inner loop ; If the size of the sequence vector is equal to sum of total frequqncies ; Return sequence ; If no such sequence if found return empty sequence ; Function Call to print the sequence ; The required sequence ; If the size of sequence if zero it means no such sequence was found ; Otherwise print the sequence ; Driver Code ; Frequency of all elements from 0 to n - 1 ; Number of elements whose frequencies are given ; Function Call | def generateSequence ( freq , n ) : NEW_LINE INDENT m = { } NEW_LINE total = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ i ] = freq [ i ] NEW_LINE total += freq [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( m [ i ] ) : NEW_LINE INDENT sequence = [ ] NEW_LINE mcopy = { } NEW_LINE for j in m : NEW_LINE INDENT mcopy [ j ] = m [ j ] NEW_LINE DEDENT mcopy [ i ] -= 1 NEW_LINE sequence . append ( i ) NEW_LINE last = i NEW_LINE for j in range ( total - 1 ) : NEW_LINE INDENT if ( ( last - 1 ) in mcopy and mcopy [ last - 1 ] > 0 ) : NEW_LINE INDENT mcopy [ last - 1 ] -= 1 NEW_LINE sequence . append ( last - 1 ) NEW_LINE last -= 1 NEW_LINE DEDENT elif ( mcopy [ last + 1 ] ) : NEW_LINE INDENT mcopy [ last + 1 ] -= 1 NEW_LINE sequence . append ( last + 1 ) NEW_LINE last += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( len ( sequence ) == total ) : NEW_LINE INDENT return sequence NEW_LINE DEDENT DEDENT DEDENT return [ ] NEW_LINE DEDENT def PrintSequence ( freq , n ) : NEW_LINE INDENT sequence = generateSequence ( freq , n ) NEW_LINE if ( len ( sequence ) == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( len ( sequence ) ) : NEW_LINE INDENT print ( sequence [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT freq = [ 2 , 2 , 2 , 3 , 1 ] NEW_LINE N = 5 NEW_LINE PrintSequence ( freq , N ) NEW_LINE DEDENT |
Minimum distance between any most frequent and least frequent element of an array | Python3 implementation of the approach ; Function to find the minimum distance between any two most and least frequent element ; Initialize sets to store the least and the most frequent elements ; Initialize variables to store max and min frequency ; Initialize HashMap to store frequency of each element ; Loop through the array ; Store the count of each element ; Store the least and most frequent elements in the respective sets ; Store count of current element ; If count is equal to max count ; Store in max set ; If count is greater then max count ; Empty max set ; Update max count ; Store in max set ; If count is equal to min count ; Store in min set ; If count is less then max count ; Empty min set ; Update min count ; Store in min set ; Initialize a variable to store the minimum distance ; Initialize a variable to store the last index of least frequent element ; Traverse array ; If least frequent element ; Update last index of least frequent element ; If most frequent element ; Update minimum distance ; Traverse array from the end ; If least frequent element ; Update last index of least frequent element ; If most frequent element ; Update minimum distance ; Print the minimum distance ; Driver Code ; Given array ; Function Call | import sys NEW_LINE def getMinimumDistance ( a , n ) : NEW_LINE INDENT min_set = { } NEW_LINE max_set = { } NEW_LINE max , min = 0 , sys . maxsize + 1 NEW_LINE frequency = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT frequency [ a [ i ] ] = frequency . get ( a [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT count = frequency [ a [ i ] ] NEW_LINE if ( count == max ) : NEW_LINE INDENT max_set [ a [ i ] ] = 1 NEW_LINE DEDENT elif ( count > max ) : NEW_LINE INDENT max_set . clear ( ) NEW_LINE max = count NEW_LINE max_set [ a [ i ] ] = 1 NEW_LINE DEDENT if ( count == min ) : NEW_LINE INDENT min_set [ a [ i ] ] = 1 NEW_LINE DEDENT elif ( count < min ) : NEW_LINE INDENT min_set . clear ( ) NEW_LINE min = count NEW_LINE min_set [ a [ i ] ] = 1 NEW_LINE DEDENT DEDENT min_dist = sys . maxsize + 1 NEW_LINE last_min_found = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] in min_set ) : NEW_LINE INDENT last_min_found = i NEW_LINE DEDENT if ( ( a [ i ] in max_set ) and last_min_found != - 1 ) : NEW_LINE INDENT if i - last_min_found < min_dist : NEW_LINE INDENT min_dist = i - last_min_found NEW_LINE DEDENT DEDENT DEDENT last_min_found = - 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] in min_set ) : NEW_LINE INDENT last_min_found = i ; NEW_LINE DEDENT if ( ( a [ i ] in max_set ) and last_min_found != - 1 ) : NEW_LINE INDENT if min_dist > last_min_found - i : NEW_LINE INDENT min_dist = last_min_found - i NEW_LINE DEDENT DEDENT DEDENT print ( min_dist ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 3 , 2 , 3 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE getMinimumDistance ( arr , N ) NEW_LINE DEDENT |
Construct a string that has exactly K subsequences from given string | Python3 program for the above approach ; Function that computes the string s ; Length of the given string str ; List that stores all the prime factors of given k ; Find the prime factors ; Initialize the count of each character position as 1 ; Loop until the list becomes empty ; Increase the character count by multiplying it with the prime factor ; If we reach end then again start from beginning ; store output ; Print the string ; Driver code ; Given String ; Function Call | import math NEW_LINE def printSubsequenceString ( st , k ) : NEW_LINE INDENT n = len ( st ) NEW_LINE factors = [ ] NEW_LINE sqt = ( int ( math . sqrt ( k ) ) ) NEW_LINE for i in range ( 2 , sqt + 1 ) : NEW_LINE INDENT while ( k % i == 0 ) : NEW_LINE INDENT factors . append ( i ) NEW_LINE k //= i NEW_LINE DEDENT DEDENT if ( k > 1 ) : NEW_LINE INDENT factors . append ( k ) NEW_LINE DEDENT count = [ 1 ] * n NEW_LINE index = 0 NEW_LINE while ( len ( factors ) > 0 ) : NEW_LINE INDENT count [ index ] *= factors [ - 1 ] NEW_LINE factors . pop ( ) NEW_LINE index += 1 NEW_LINE if ( index == n ) : NEW_LINE INDENT index = 0 NEW_LINE DEDENT DEDENT s = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( count [ i ] > 0 ) : NEW_LINE INDENT s += st [ i ] NEW_LINE count [ i ] -= 1 NEW_LINE DEDENT DEDENT print ( s ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " code " NEW_LINE k = 20 NEW_LINE printSubsequenceString ( st , k ) NEW_LINE DEDENT |
Replace each element of Array with it 's corresponding rank | Function to assign rank to array elements ; Copy input array into newArray ; Sort newArray [ ] in ascending order ; Dictionary to store the rank of the array element ; Update rank of element ; Assign ranks to elements ; Driver Code ; Given array arr [ ] ; Function call ; Print the array elements | def changeArr ( input1 ) : NEW_LINE INDENT newArray = input1 . copy ( ) NEW_LINE newArray . sort ( ) NEW_LINE ranks = { } NEW_LINE rank = 1 NEW_LINE for index in range ( len ( newArray ) ) : NEW_LINE INDENT element = newArray [ index ] ; NEW_LINE if element not in ranks : NEW_LINE INDENT ranks [ element ] = rank NEW_LINE rank += 1 NEW_LINE DEDENT DEDENT for index in range ( len ( input1 ) ) : NEW_LINE INDENT element = input1 [ index ] NEW_LINE input1 [ index ] = ranks [ input1 [ index ] ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 100 , 2 , 70 , 2 ] NEW_LINE changeArr ( arr ) NEW_LINE print ( arr ) NEW_LINE DEDENT |
Find pairs in array whose sum does not exist in Array | Function to print all pairs with sum not present in the array ; Corner Case ; Stores the distinct array elements ; Generate all possible pairs ; Calculate sum of current pair ; Check if the sum exists in the HashSet or not ; Driver Code | def findPair ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT hashMap = [ ] NEW_LINE for k in arr : NEW_LINE INDENT hashMap . append ( k ) NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT sum = arr [ i ] + arr [ j ] NEW_LINE if sum not in hashMap : NEW_LINE INDENT print ( " ( " , arr [ i ] , " , β " , arr [ j ] , " ) " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 2 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE findPair ( arr , n ) NEW_LINE DEDENT |
Largest subset with M as smallest missing number | Function to find and return the length of the longest subset whose smallest missing value is M ; Initialize a set ; If array element is not equal to M ; Insert into set ; Increment frequency ; Stores minimum missing number ; Iterate to find the minimum missing integer ; If minimum obtained is less than M ; Update answer ; Return answer ; Driver Code | def findLengthOfMaxSubset ( arr , n , m ) : NEW_LINE INDENT s = [ ] ; NEW_LINE answer = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT tmp = arr [ i ] ; NEW_LINE if ( tmp != m ) : NEW_LINE INDENT s . append ( tmp ) ; NEW_LINE answer += 1 ; NEW_LINE DEDENT DEDENT min = 1 ; NEW_LINE while ( s . count ( min ) ) : NEW_LINE INDENT min += 1 ; NEW_LINE DEDENT if ( min != m ) : NEW_LINE INDENT answer = - 1 ; NEW_LINE DEDENT return answer ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE M = 3 ; NEW_LINE print ( findLengthOfMaxSubset ( arr , N , M ) ) ; NEW_LINE DEDENT |
Count of submatrix with sum X in a given Matrix | Size of a column ; Function to find the count of submatrix whose sum is X ; Copying arr to dp and making it indexed 1 ; Precalculate and store the sum of all rectangles with upper left corner at ( 0 , 0 ) ; ; Calculating sum in a 2d grid ; Stores the answer ; Minimum length of square ; Maximum length of square ; Flag to set if sub - square with sum X is found ; Calculate lower right index if upper right corner is at { i , j } ; Calculate the sum of elements in the submatrix with upper left column { i , j } and lower right column at { ni , nj } ; ; If sum X is found ; If sum > X , then size of the square with sum X must be less than mid ; If sum < X , then size of the square with sum X must be greater than mid ; If found , increment count by 1 ; ; Driver Code ; Given matrix arr [ ] [ ] ; Function call | m = 5 NEW_LINE def countSubsquare ( arr , n , X ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( m + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT dp [ i + 1 ] [ j + 1 ] = arr [ i ] [ j ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] += ( dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] - dp [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT cnt = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT lo = 1 NEW_LINE hi = min ( n - i , m - j ) + 1 NEW_LINE found = False NEW_LINE while ( lo <= hi ) : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE ni = i + mid - 1 NEW_LINE nj = j + mid - 1 NEW_LINE sum = ( dp [ ni ] [ nj ] - dp [ ni ] [ j - 1 ] - dp [ i - 1 ] [ nj ] + dp [ i - 1 ] [ j - 1 ] ) NEW_LINE if ( sum >= X ) : NEW_LINE INDENT if ( sum == X ) : NEW_LINE INDENT found = True NEW_LINE DEDENT hi = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT DEDENT if ( found == True ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N , X = 4 , 10 NEW_LINE arr = [ [ 2 , 4 , 3 , 2 , 10 ] , [ 3 , 1 , 1 , 1 , 5 ] , [ 1 , 1 , 2 , 1 , 4 ] , [ 2 , 1 , 1 , 1 , 3 ] ] NEW_LINE print ( countSubsquare ( arr , N , X ) ) NEW_LINE DEDENT |
Check if two arrays can be made equal by reversing any subarray once | Function to check whether two arrays can be made equal by reversing a sub - array only once ; Integer variable for storing the required starting and ending indices in the array ; Finding the smallest index for which A [ i ] != B [ i ] i . e the starting index of the unequal sub - array ; Finding the largest index for which A [ i ] != B [ i ] i . e the ending index of the unequal sub - array ; Reversing the sub - array A [ start ] , A [ start + 1 ] . . A [ end ] ; Checking whether on reversing the sub - array A [ start ] ... A [ end ] makes the arrays equal ; If any element of the two arrays is unequal print No and return ; Print Yes if arrays are equal after reversing the sub - array ; Driver code | def checkArray ( A , B , N ) : NEW_LINE INDENT start = 0 NEW_LINE end = N - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] ) : NEW_LINE INDENT start = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] ) : NEW_LINE INDENT end = i NEW_LINE break NEW_LINE DEDENT DEDENT A [ start : end + 1 ] = reversed ( A [ start : end + 1 ] ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " Yes " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 3 , 2 , 4 ] NEW_LINE B = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( A ) NEW_LINE checkArray ( A , B , N ) NEW_LINE DEDENT |
Count of substrings having all distinct characters | Function to count total number of valid substrings ; Stores the count of substrings ; Stores the frequency of characters ; Initialised both pointers to beginning of the string ; If all characters in substring from index i to j are distinct ; Increment count of j - th character ; Add all substring ending at j and starting at any index between i and j to the answer ; Increment 2 nd pointer ; If some characters are repeated or j pointer has reached to end ; Decrement count of j - th character ; Increment first pointer ; Return the final count of substrings ; Driver code | def countSub ( Str ) : NEW_LINE INDENT n = len ( Str ) NEW_LINE ans = 0 NEW_LINE cnt = 26 * [ 0 ] NEW_LINE i , j = 0 , 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( j < n and ( cnt [ ord ( Str [ j ] ) - ord ( ' a ' ) ] == 0 ) ) : NEW_LINE INDENT cnt [ ord ( Str [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE ans += ( j - i + 1 ) NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt [ ord ( Str [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT Str = " gffg " NEW_LINE print ( countSub ( Str ) ) NEW_LINE |
Find largest factor of N such that N / F is less than K | Function to find the largest factor of N which is less than or equal to K ; Initialise the variable to store the largest factor of N <= K ; Loop to find all factors of N ; Check if j is a factor of N or not ; Check if j <= K If yes , then store the larger value between ans and j in ans ; Check if N / j <= K If yes , then store the larger value between ans and j in ans ; Since max value is always stored in ans , the maximum value divisible by N less than or equal to K will be returned . ; Driver Code ; Given N and K ; Function call | def solve ( n , k ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( j * j > n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT if ( n % j == 0 ) : NEW_LINE INDENT if ( j <= k ) : NEW_LINE INDENT ans = max ( ans , j ) ; NEW_LINE DEDENT if ( n // j <= k ) : NEW_LINE INDENT ans = max ( ans , n // j ) ; NEW_LINE DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 ; K = 7 ; NEW_LINE print ( ( N // solve ( N , K ) ) ) ; NEW_LINE DEDENT |
Maximum sum subarray of size range [ L , R ] | Python3 program to find maximum sum subarray of size between L and R . ; Function to find maximum sum subarray of size between L and R ; Calculating prefix sum ; Maintain 0 for initial values of i upto R Once i = R , then we need to erase that 0 from our multiset as our first index of subarray cannot be 0 anymore . ; We maintain flag to counter if that initial 0 was erased from set or not . ; Erase 0 from multiset once i = b ; Insert pre [ i - L ] ; Find minimum value in multiset . ; Erase pre [ i - R ] ; Driver code | import sys NEW_LINE def max_sum_subarray ( arr , L , R ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE pre = n * [ 0 ] NEW_LINE pre [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + arr [ i ] NEW_LINE DEDENT s1 = [ ] NEW_LINE s1 . append ( 0 ) NEW_LINE ans = - sys . maxsize - 1 NEW_LINE ans = max ( ans , pre [ L - 1 ] ) NEW_LINE flag = 0 NEW_LINE for i in range ( L , n ) : NEW_LINE INDENT if ( i - R >= 0 ) : NEW_LINE INDENT if ( flag == 0 ) : NEW_LINE INDENT s1 . remove ( 0 ) NEW_LINE flag = 1 NEW_LINE DEDENT DEDENT if ( i - L >= 0 ) : NEW_LINE INDENT s1 . append ( pre [ i - L ] ) NEW_LINE DEDENT ans = max ( ans , pre [ i ] - s1 [ 0 ] ) NEW_LINE if ( i - R >= 0 ) : NEW_LINE INDENT s1 . remove ( pre [ i - R ] ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 1 NEW_LINE R = 3 NEW_LINE arr = [ 1 , 2 , 2 , 1 ] NEW_LINE max_sum_subarray ( arr , L , R ) NEW_LINE DEDENT |
Count of ways to select K consecutive empty cells from a given Matrix | Function to Traverse the matrix row wise ; Initialize ans ; Traverse row wise ; Initialize no of consecutive empty cells ; Check if blocked cell is encountered then reset countcons to 0 ; Check if empty cell is encountered , then increment countcons ; Check if number of empty consecutive cells is greater or equal to K , increment the ans ; Return the count ; Function to Traverse the matrix column wise ; Initialize ans ; Traverse column wise ; Initialize no of consecutive empty cells ; Check if blocked cell is encountered then reset countcons to 0 ; Check if empty cell is encountered , increment countcons ; Check if number of empty consecutive cells is greater than or equal to K , increment the ans ; Return the count ; Driver Code ; If k = 1 only traverse row wise ; Traverse both row and column wise | def rowWise ( v , n , m , k ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT countcons = 0 NEW_LINE for j in range ( m ) : NEW_LINE INDENT if ( v [ i ] [ j ] == '1' ) : NEW_LINE INDENT countcons = 0 NEW_LINE DEDENT else : NEW_LINE INDENT countcons += 1 NEW_LINE DEDENT if ( countcons >= k ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT def colWise ( v , n , m , k ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT countcons = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( v [ j ] [ i ] == '1' ) : NEW_LINE INDENT countcons = 0 NEW_LINE DEDENT else : NEW_LINE INDENT countcons += 1 NEW_LINE DEDENT if ( countcons >= k ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE m = 3 NEW_LINE k = 1 NEW_LINE v = [ [ '0' , '0' , '0' ] , [ '0' , '0' , '0' ] , [ '0' , '0' , '0' ] ] NEW_LINE if ( k == 1 ) : NEW_LINE INDENT print ( rowWise ( v , n , m , k ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( colWise ( v , n , m , k ) + rowWise ( v , n , m , k ) ) NEW_LINE DEDENT DEDENT |
Check if the count of inversions of two given types on an Array are equal or not | Python3 program to implement the above approach ; Function to check if the count of inversion of two types are same or not ; If maximum value is found to be greater than a [ j ] , then that pair of indices ( i , j ) will add extra value to inversion of Type 1 ; Update max ; Driver code | import sys NEW_LINE def solve ( a , n ) : NEW_LINE INDENT mx = - sys . maxsize - 1 NEW_LINE for j in range ( 1 , n ) : NEW_LINE INDENT if ( mx > a [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT mx = max ( mx , a [ j - 1 ] ) NEW_LINE DEDENT return True NEW_LINE DEDENT a = [ 1 , 0 , 2 ] NEW_LINE n = len ( a ) NEW_LINE possible = solve ( a , n ) NEW_LINE if ( possible != 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
How to validate an IP address using ReGex | Python3 program to validate IP address using Regex ; Function for Validating IP ; Regex expression for validating IPv4 ; Regex expression for validating IPv6 ; Checking if it is a valid IPv4 addresses ; Checking if it is a valid IPv6 addresses ; Return Invalid ; IP addresses to validate | import re NEW_LINE def Validate_It ( IP ) : NEW_LINE INDENT regex = " ( ( [ 0-9 ] β [ 1-9 ] [ 0-9 ] β 1[0-9 ] [ 0-9 ] β " \ "2[0-4 ] [ 0-9 ] β 25[0-5 ] ) \\ . ) { 3 } " " ( [0-9 ] β [ 1-9 ] [ 0-9 ] β 1[0-9 ] [ 0-9 ] β " \ "2[0-4 ] [ 0-9 ] β 25[0-5 ] ) " NEW_LINE regex1 = " ( ( ( [0-9a - fA - F ] ) { 1,4 } ) \\ : ) { 7 } " p = re . compile ( regex ) NEW_LINE p1 = re . compile ( regex1 ) NEW_LINE if ( re . search ( p , IP ) ) : NEW_LINE INDENT return " Valid β IPv4" NEW_LINE DEDENT elif ( re . search ( p1 , IP ) ) : NEW_LINE INDENT return " Valid β IPv6" NEW_LINE DEDENT return " Invalid β IP " NEW_LINE DEDENT IP = "203.120.223.13" NEW_LINE print ( Validate_It ( IP ) ) NEW_LINE IP = " fffe : 3465 : efab : 23fe : 2235:6565 : aaab : 0001" NEW_LINE print ( Validate_It ( IP ) ) NEW_LINE IP = "2F33:12a0:3Ea0:0302" NEW_LINE print ( Validate_It ( IP ) ) NEW_LINE |
Count of prime factors of N to be added at each step to convert N to M | Array to store shortest prime factor of every integer ; Function to precompute shortest prime factors ; Function to append distinct prime factors of every integer into a set ; Store distinct prime factors ; Function to return minimum steps using BFS ; Queue of pairs to store the current number and distance from root . ; Set to store distinct prime factors ; Run BFS ; Find out the prime factors of newNum ; Iterate over every prime factor of newNum . ; If M is obtained ; Return number of operations ; If M is exceeded ; Otherwise ; Update and store the new number obtained by prime factor ; If M cannot be obtained ; Driver code | spf = [ - 1 for i in range ( 100009 ) ] ; NEW_LINE def sieve ( ) : NEW_LINE INDENT i = 2 NEW_LINE while ( i * i <= 100006 ) : NEW_LINE INDENT for j in range ( i , 100006 , i ) : NEW_LINE INDENT if ( spf [ j ] == - 1 ) : NEW_LINE INDENT spf [ j ] = i ; NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def findPrimeFactors ( s , n ) : NEW_LINE INDENT while ( n > 1 ) : NEW_LINE INDENT s . add ( spf [ n ] ) ; NEW_LINE n //= spf [ n ] ; NEW_LINE DEDENT return s ; NEW_LINE DEDENT def MinimumSteps ( n , m ) : NEW_LINE INDENT q = [ ] NEW_LINE s = set ( ) NEW_LINE q . append ( [ n , 0 ] ) NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT newNum = q [ 0 ] [ 0 ] NEW_LINE distance = q [ 0 ] [ 1 ] NEW_LINE q . pop ( 0 ) ; NEW_LINE k = findPrimeFactors ( s , newNum ) ; NEW_LINE for i in k : NEW_LINE INDENT if ( newNum == m ) : NEW_LINE INDENT return distance ; NEW_LINE DEDENT elif ( newNum > m ) : NEW_LINE INDENT break ; NEW_LINE DEDENT else : NEW_LINE INDENT q . append ( [ newNum + i , distance + 1 ] ) ; NEW_LINE DEDENT DEDENT DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE M = 16 ; NEW_LINE sieve ( ) ; NEW_LINE print ( MinimumSteps ( N , M ) ) NEW_LINE DEDENT |
Count of elements which is product of a pair or an element square | Python3 program to implement the above approach ; Stores all factors a number ; Function to calculate and store in a vector ; Function to return the count of array elements which are a product of two array elements ; Copy elements into a a duplicate array ; Sort the duplicate array ; Store the count of elements ; If the factors are not calculated already ; Traverse its factors ; If a pair of factors is found ; Driver Code | import math NEW_LINE v = [ [ ] for i in range ( 100000 ) ] NEW_LINE def div ( n ) : NEW_LINE INDENT global v NEW_LINE for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT v [ n ] . append ( i ) NEW_LINE DEDENT DEDENT DEDENT def prodof2elements ( arr , n ) : NEW_LINE INDENT arr2 = arr . copy ( ) NEW_LINE arr2 . sort ( ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( len ( v [ arr [ i ] ] ) == 0 ) : NEW_LINE INDENT div ( arr [ i ] ) NEW_LINE DEDENT for j in v [ arr [ i ] ] : NEW_LINE INDENT if j in arr2 : NEW_LINE INDENT if int ( arr [ i ] / j ) in arr2 : NEW_LINE INDENT ans += 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 1 , 8 , 4 , 32 , 18 ] NEW_LINE N = len ( arr ) NEW_LINE print ( prodof2elements ( arr , N ) ) NEW_LINE |
Largest subarray with frequency of all elements same | Function to find maximum subarray size ; Generating all subarray i -> starting index j -> end index ; Map 1 to hash frequency of all elements in subarray ; Map 2 to hash frequency of all frequencies of elements ; Finding previous frequency of arr [ j ] in map 1 ; Increasing frequency of arr [ j ] by 1 ; Check if previous frequency is present in map 2 ; Delete previous frequency if hash is equal to 1 ; Decrement the hash of previous frequency ; Incrementing hash of new frequency in map 2 ; Check if map2 size is 1 and updating answer ; Return the maximum size of subarray ; Given array arr [ ] ; Function Call | def max_subarray_size ( N , arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT map1 = { } NEW_LINE map2 = { } NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT if ( arr [ j ] not in map1 ) : NEW_LINE INDENT ele_count = 0 NEW_LINE DEDENT else : NEW_LINE INDENT ele_count = map1 [ arr [ j ] ] NEW_LINE DEDENT if arr [ j ] in map1 : NEW_LINE INDENT map1 [ arr [ j ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT map1 [ arr [ j ] ] = 1 NEW_LINE DEDENT if ( ele_count in map2 ) : NEW_LINE INDENT if ( map2 [ ele_count ] == 1 ) : NEW_LINE INDENT del map2 [ ele_count ] NEW_LINE DEDENT else : NEW_LINE INDENT map2 [ ele_count ] -= 1 NEW_LINE DEDENT DEDENT if ele_count + 1 in map2 : NEW_LINE INDENT map2 [ ele_count + 1 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT map2 [ ele_count + 1 ] = 1 NEW_LINE DEDENT if ( len ( map2 ) == 1 ) : NEW_LINE INDENT ans = max ( ans , j - i + 1 ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 5 , 6 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( max_subarray_size ( N , arr ) ) NEW_LINE |
Longest substring consisting of vowels using Binary Search | Function to check if a character is vowel or not ; 0 - a 1 - b 2 - c and so on 25 - z ; Function to check if any substring of length k exists which contains only vowels ; Applying sliding window to get all substrings of length K ; Remove the occurence of ( i - k + 1 ) th character ; Function to perform Binary Search ; Doing binary search on the lengths ; Driver Code | def vowel ( vo ) : NEW_LINE INDENT if ( vo == 0 or vo == 4 or vo == 8 or vo == 14 or vo == 20 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def check ( s , k ) : NEW_LINE INDENT cnt = [ 0 ] * 26 NEW_LINE for i in range ( k - 1 ) : NEW_LINE INDENT cnt [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( k - 1 , len ( s ) ) : NEW_LINE INDENT cnt [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE flag1 = 0 NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT if ( vowel ( j ) == False and cnt [ j ] > 0 ) : NEW_LINE INDENT flag1 = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag1 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT cnt [ ord ( s [ i - k + 1 ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE DEDENT return False NEW_LINE DEDENT def longestSubstring ( s ) : NEW_LINE INDENT l = 1 NEW_LINE r = len ( s ) NEW_LINE maxi = 0 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = ( l + r ) // 2 NEW_LINE if ( check ( s , mid ) ) : NEW_LINE INDENT l = mid + 1 NEW_LINE maxi = max ( maxi , mid ) NEW_LINE DEDENT else : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT DEDENT return maxi NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " sedrewaefhoiu " NEW_LINE print ( longestSubstring ( s ) ) NEW_LINE DEDENT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.