text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Append digits to the end of duplicate strings to make all strings in an array unique | Function to replace duplicate strings by alphanumeric strings to make all strings in the array unique ; Store the frequency of strings ; Iterate over the array ; For the first occurrence , update the frequency count ; Otherwise ; Append frequency count to end of the string ; Print the modified array ; Driver Code ; Function Call | def replaceDuplicates ( names ) : NEW_LINE INDENT hash = { } NEW_LINE for i in range ( 0 , len ( names ) ) : NEW_LINE INDENT if names [ i ] not in hash : NEW_LINE INDENT hash [ names [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = hash [ names [ i ] ] NEW_LINE hash [ names [ i ] ] += 1 NEW_LINE names [ i ] += str ( count ) NEW_LINE DEDENT DEDENT for i in range ( 0 , len ( names ) ) : NEW_LINE INDENT print ( names [ i ] , end = ' β ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = [ " aa " , " bb " , " cc " , " bb " , " aa " , " aa " , " aa " ] NEW_LINE replaceDuplicates ( str1 ) NEW_LINE DEDENT |
Minimum cost of flipping characters required to convert Binary String to 0 s only | Function to find the minimum cost to convert given string to 0 s only ; Length of string ; Stores the index of leftmost '1' in str ; Update the index of leftmost '1' in str ; Stores the index of rightmost '1' in str ; Update the index of rightmost '1' in str ; If str does not contain any '1' s ; No changes required ; Stores minimum cost ; Iterating through str form left_1 to right_1 ; Stores length of consecutive 0 s ; Calculate length of consecutive 0 s ; If a substring of 0 s exists ; Update minimum cost ; Printing the minimum cost ; Driver Code | def convert_to_allzeroes ( st , a , b ) : NEW_LINE INDENT length = len ( st ) NEW_LINE left_1 = 0 NEW_LINE i = 0 NEW_LINE while ( i < length and st [ i ] == '0' ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT left_1 = i NEW_LINE right_1 = 0 NEW_LINE i = length - 1 NEW_LINE while ( i >= 0 and st [ i ] == '0' ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT right_1 = i NEW_LINE if ( left_1 == length and right_1 == - 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT cost = a NEW_LINE for i in range ( left_1 , right_1 + 1 ) : NEW_LINE INDENT zeroes = 0 NEW_LINE while ( i < length and st [ i ] == '0' ) : NEW_LINE INDENT zeroes += 1 NEW_LINE i += 1 NEW_LINE DEDENT if ( zeroes ) : NEW_LINE INDENT cost += min ( zeroes * b , a ) NEW_LINE DEDENT DEDENT print ( cost ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "01101110" NEW_LINE A = 5 NEW_LINE B = 1 NEW_LINE convert_to_allzeroes ( st , A , B ) NEW_LINE DEDENT |
Minimum distance to visit given K points on X | Python3 program to implement the above approach ; Function to find the minimum distance travelled to visit K point ; Stores minimum distance travelled to visit K point ; Stores distance travelled to visit points ; Traverse the array arr [ ] ; If arr [ i ] and arr [ i + K - 1 ] are positive ; Update dist ; Update dist ; Update res ; Driver Code ; Initial the array | import sys NEW_LINE def MinDistK ( arr , N , K ) : NEW_LINE INDENT res = sys . maxsize NEW_LINE dist = 0 NEW_LINE for i in range ( N - K + 1 ) : NEW_LINE INDENT if ( arr [ i ] >= 0 and arr [ i + K - 1 ] >= 0 ) : NEW_LINE INDENT dist = max ( arr [ i ] , arr [ i + K - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dist = ( abs ( arr [ i ] ) + abs ( arr [ i + K - 1 ] ) + min ( abs ( arr [ i ] ) , abs ( arr [ i + K - 1 ] ) ) ) NEW_LINE DEDENT res = min ( res , dist ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 3 NEW_LINE arr = [ - 30 , - 10 , 10 , 20 , 50 ] NEW_LINE N = len ( arr ) NEW_LINE print ( MinDistK ( arr , N , K ) ) NEW_LINE DEDENT |
Maximize the minimum array element by M subarray increments of size S | Function to return index of minimum element in the array ; Initialize a [ 0 ] as minValue ; Traverse the array ; If a [ i ] < existing minValue ; Return the minimum index ; Function that maximize the minimum element of array after incrementing subarray of size S by 1 , M times ; Iterating through the array for M times ; Find minimum element index ; Increment the minimum value ; Storing the left index and right index ; Incrementing S - 1 minimum elements to the left and right of minValue ; Reached extreme left ; Reached extreme right ; Left value is minimum ; Right value is minimum ; Find the minValue in A [ ] after M operations ; Return the minimum value ; Driver Code ; Function Call | def min ( a , n ) : NEW_LINE INDENT minIndex = 0 NEW_LINE minValue = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] < minValue ) : NEW_LINE INDENT minValue = a [ i ] NEW_LINE minIndex = i NEW_LINE DEDENT DEDENT return minIndex NEW_LINE DEDENT def maximizeMin ( A , N , S , M ) : NEW_LINE INDENT minIndex , left , right = 0 , 0 , 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT minIndex = min ( A , N ) NEW_LINE A [ minIndex ] += 1 NEW_LINE left = minIndex - 1 NEW_LINE right = minIndex + 1 NEW_LINE for j in range ( S - 1 ) : NEW_LINE INDENT if ( left == - 1 ) : NEW_LINE INDENT A [ right ] += 1 NEW_LINE right += 1 NEW_LINE DEDENT elif ( right == N ) : NEW_LINE INDENT A [ left ] += 1 NEW_LINE left -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( A [ left ] < A [ right ] ) : NEW_LINE INDENT A [ left ] += 1 NEW_LINE left -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT A [ right ] += 1 NEW_LINE right += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT minIndex = min ( A , N ) NEW_LINE return A [ minIndex ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE S = 2 NEW_LINE M = 3 NEW_LINE print ( maximizeMin ( arr , N , S , M ) ) NEW_LINE DEDENT |
Sum of nodes in the path from root to N | Python3 program for the above approach ; Function to find sum of all nodes from root to N ; If N is equal to 1 ; If N is equal to 2 or 3 ; Stores the number of nodes at ( i + 1 ) - th level ; Stores the number of nodes ; Stores if the current level is even or odd ; If level is odd ; If level is even ; If level with node N is reached ; Push into vector ; Compute prefix sums of count of nodes in each level ; Stores the level in which node N s present ; Stores the required sum ; Add temp to the sum ; Driver Code ; Function Call | from bisect import bisect_left , bisect NEW_LINE def sumOfPathNodes ( N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( N == 2 or N == 3 ) : NEW_LINE INDENT return N + 1 NEW_LINE DEDENT arr = [ ] NEW_LINE arr . append ( 1 ) NEW_LINE k = 1 NEW_LINE flag = True NEW_LINE while ( k < N ) : NEW_LINE INDENT if ( flag == True ) : NEW_LINE INDENT k *= 2 NEW_LINE flag = False NEW_LINE DEDENT else : NEW_LINE INDENT k *= 4 NEW_LINE flag = True NEW_LINE DEDENT if ( k > N ) : NEW_LINE INDENT break NEW_LINE DEDENT arr . append ( k ) NEW_LINE DEDENT lenn = len ( arr ) NEW_LINE prefix = [ 0 ] * ( lenn ) NEW_LINE prefix [ 0 ] = 1 NEW_LINE for i in range ( 1 , lenn ) : NEW_LINE INDENT prefix [ i ] = arr [ i ] + prefix [ i - 1 ] NEW_LINE DEDENT it = bisect_left ( prefix , N ) NEW_LINE ind = it NEW_LINE final_ans = 0 NEW_LINE temp = N NEW_LINE while ( ind > 1 ) : NEW_LINE INDENT val = temp - prefix [ ind - 1 ] NEW_LINE if ( ind % 2 != 0 ) : NEW_LINE INDENT temp = prefix [ ind - 2 ] + ( val + 1 ) // 2 NEW_LINE DEDENT else : NEW_LINE INDENT temp = prefix [ ind - 2 ] + ( val + 3 ) // 4 NEW_LINE DEDENT ind -= 1 NEW_LINE final_ans += temp NEW_LINE DEDENT final_ans += ( N + 1 ) NEW_LINE return final_ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 13 NEW_LINE print ( sumOfPathNodes ( N ) ) NEW_LINE DEDENT |
Check if given point lies in range of any of the given towers | Python3 program to implement the above approach ; Function to check if the point ( X , Y ) exists in the towers network - range or not ; Traverse the array arr [ ] ; Stores distance of the point ( X , Y ) from i - th tower ; If dist lies within the range of the i - th tower ; If the point ( X , Y ) does not lie in the range of any of the towers ; Driver Code ; If point ( X , Y ) lies in the range of any of the towers ; Otherwise | from math import sqrt NEW_LINE def checkPointRange ( arr , X , Y , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT dist = sqrt ( ( arr [ i ] [ 0 ] - X ) * ( arr [ i ] [ 0 ] - X ) + ( arr [ i ] [ 1 ] - Y ) * ( arr [ i ] [ 1 ] - Y ) ) NEW_LINE if ( dist <= arr [ i ] [ 2 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 1 , 3 ] , [ 10 , 10 , 3 ] , [ 15 , 15 , 15 ] ] NEW_LINE X = 5 NEW_LINE Y = 5 NEW_LINE N = len ( arr ) NEW_LINE if ( checkPointRange ( arr , X , Y , N ) ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT DEDENT |
Find the winner of the Game of removing odd or replacing even array elements | Function to evaluate the winner of the game ; Stores count of odd array elements ; Stores count of even array elements ; Traverse the array ; If array element is odd ; Otherwise ; If count of even is zero ; If count of odd is even ; If count of odd is odd ; If count of odd is odd and count of even is one ; Otherwise ; Driver code | def findWinner ( arr , N ) : NEW_LINE INDENT odd = 0 NEW_LINE even = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even += 1 NEW_LINE DEDENT DEDENT if ( even == 0 ) : NEW_LINE INDENT if ( odd % 2 == 0 ) : NEW_LINE INDENT print ( " Player β 2" ) NEW_LINE DEDENT elif ( odd % 2 == 1 ) : NEW_LINE INDENT print ( " Player β 1" ) NEW_LINE DEDENT DEDENT elif ( even == 1 and odd % 2 == 1 ) : NEW_LINE INDENT print ( " Player β 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 1 , 9 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE findWinner ( arr , N ) NEW_LINE DEDENT |
Rearrange array to maximize count of local minima | Function to rearrange array elements to maximize count of local minima in the array ; Sort the array in ascending order ; Stores index of left pointer ; Stores index of right pointer ; Traverse the array elements ; if right is less than N ; Print array element ; Update right ; Print array element ; Update left ; Driver Code | def rearrangeArrMaxcntMinima ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE left = 0 NEW_LINE right = N // 2 NEW_LINE while ( left < N // 2 or right < N ) : NEW_LINE INDENT if ( right < N ) : NEW_LINE INDENT print ( arr [ right ] , end = " β " ) NEW_LINE right += 1 NEW_LINE DEDENT if ( left < N // 2 ) : NEW_LINE INDENT print ( arr [ left ] , end = " β " ) NEW_LINE left += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE rearrangeArrMaxcntMinima ( arr , N ) NEW_LINE DEDENT |
Minimum jumps required to make a group of persons sit together | Python3 program for the above approach ; Function to find the minimum jumps required to make the whole group sit adjacently ; Store the indexes ; Stores the count of occupants ; Length of the string ; Traverse the seats ; If current place is occupied ; Push the current position in the vector ; Base Case : ; The index of the median element ; The value of the median element ; Traverse the position [ ] ; Update the ans ; Return the final count ; Driver Code ; Given arrange of seats ; Function Call | MOD = 10 ** 9 + 7 NEW_LINE def minJumps ( seats ) : NEW_LINE INDENT position = [ ] NEW_LINE count = 0 NEW_LINE lenn = len ( seats ) NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( seats [ i ] == ' x ' ) : NEW_LINE INDENT position . append ( i - count ) NEW_LINE count += 1 NEW_LINE DEDENT DEDENT if ( count == lenn or count == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT med_index = ( count - 1 ) // 2 NEW_LINE med_val = position [ med_index ] NEW_LINE ans = 0 NEW_LINE for i in range ( len ( position ) ) : NEW_LINE INDENT ans = ( ans % MOD + abs ( position [ i ] - med_val ) % MOD ) % MOD NEW_LINE DEDENT return ans % MOD NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " . . . . x . . xx . . . x . . " NEW_LINE print ( minJumps ( S ) ) NEW_LINE DEDENT |
Count pairs whose product contains single distinct prime factor | Function to find a single distinct prime factor of N ; Stores distinct prime factors of N ; Calculate prime factor of N ; Calculate distinct prime factor ; Insert i into disPrimeFact ; Update N ; If N is not equal to 1 ; Insert N into disPrimeFact ; If N contains a single distinct prime factor ; Return single distinct prime factor of N ; If N contains more than one distinct prime factor ; Function to count pairs in the array whose product contains only single distinct prime factor ; Stores count of 1 s in the array ; mp [ i ] : Stores count of array elements whose distinct prime factor is only i ; Traverse the array arr [ ] ; If current element is 1 ; Store distinct prime factor of arr [ i ] ; If arr [ i ] contains more than one prime factor ; If arr [ i ] contains a single prime factor ; Stores the count of pairs whose product of elements contains only a single distinct prime factor ; Traverse the map mp [ ] ; Stores count of array elements whose prime factor is ( it . first ) ; Update res ; Driver Code | def singlePrimeFactor ( N ) : NEW_LINE INDENT disPrimeFact = { } NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT while ( N % i == 0 ) : NEW_LINE INDENT disPrimeFact [ i ] = 1 NEW_LINE N //= i NEW_LINE DEDENT DEDENT if ( N != 1 ) : NEW_LINE INDENT disPrimeFact [ N ] = 1 NEW_LINE DEDENT if ( len ( disPrimeFact ) == 1 ) : NEW_LINE INDENT return list ( disPrimeFact . keys ( ) ) [ 0 ] NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def cntsingleFactorPair ( arr , N ) : NEW_LINE INDENT countOf1 = 0 NEW_LINE mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT countOf1 += 1 NEW_LINE continue NEW_LINE DEDENT factorValue = singlePrimeFactor ( arr [ i ] ) NEW_LINE if ( factorValue == - 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT mp [ factorValue ] = mp . get ( factorValue , 0 ) + 1 NEW_LINE DEDENT DEDENT res = 0 NEW_LINE for it in mp : NEW_LINE INDENT X = mp [ it ] NEW_LINE res += countOf1 * X + ( X * ( X - 1 ) ) // 2 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( cntsingleFactorPair ( arr , N ) ) NEW_LINE DEDENT |
Minimize replacements or swapping of same indexed characters required to make two given strings palindromic | Function to find minimum operations to make both the strings palindromic ; Stores index of the left pointer ; Stores index of the right pointer ; Stores count of minimum operations to make both the strings palindromic ; if str1 [ i ] equal to str1 [ j ] and str2 [ i ] not equal to str2 [ j ] ; Update cntOp ; If str1 [ i ] not equal to str1 [ j ] and str2 [ i ] equal to str2 [ j ] ; Update cntOp ; If str1 [ i ] is not equal to str1 [ j ] and str2 [ i ] is not equal to str2 [ j ] ; If str1 [ i ] is equal to str2 [ j ] and str2 [ i ] is equal to str1 [ j ] ; Update cntOp ; Update cntOp ; Update i and j ; Driver Code ; Stores length of str1 | def MincntBothPalin ( str1 , str2 , N ) : NEW_LINE INDENT i = 0 NEW_LINE j = N - 1 NEW_LINE cntOp = 0 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( str1 [ i ] == str1 [ j ] and str2 [ i ] != str2 [ j ] ) : NEW_LINE INDENT cntOp += 1 NEW_LINE DEDENT elif ( str1 [ i ] != str1 [ j ] and str2 [ i ] == str2 [ j ] ) : NEW_LINE INDENT cntOp += 1 NEW_LINE DEDENT elif ( str1 [ i ] != str1 [ j ] and str2 [ i ] != str2 [ j ] ) : NEW_LINE INDENT if ( str1 [ i ] == str2 [ j ] and str2 [ i ] == str1 [ j ] ) : NEW_LINE INDENT cntOp += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntOp += 2 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return cntOp NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " dbba " NEW_LINE str2 = " abcd " NEW_LINE N = len ( str1 ) NEW_LINE print ( MincntBothPalin ( str1 , str2 , N ) ) NEW_LINE DEDENT |
Find an integral solution of the non | Python3 program to implement the above approach ; Function to find the value of power ( X , N ) ; Stores the value of ( X ^ N ) ; Calculate the value of power ( x , N ) ; If N is odd ; Update res ; Update x ; Update N ; Function to find the value of X and Y that satisfy the condition ; Base Case ; Stores maximum possible of X ; Update xMax ; Stores maximum possible of Y ; Update yMax ; Iterate over all possible values of X ; Iterate over all possible values of Y ; Stores value of 2 ^ i ; Stores value of 5 ^ j ; If the pair ( i , j ) satisfy the equation ; If no solution exists ; Driver Code | from math import log2 NEW_LINE def power ( x , N ) : NEW_LINE INDENT res = 1 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N & 1 ) : NEW_LINE INDENT res = ( res * x ) NEW_LINE DEDENT x = ( x * x ) NEW_LINE N = N >> 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def findValX_Y ( N ) : NEW_LINE INDENT if ( N <= 1 ) : NEW_LINE print ( - 1 ) NEW_LINE return NEW_LINE xMax = 0 NEW_LINE xMax = int ( log2 ( N ) ) NEW_LINE yMax = 0 NEW_LINE yMax = int ( log2 ( N ) / log2 ( 5.0 ) ) NEW_LINE for i in range ( 1 , xMax + 1 ) : NEW_LINE INDENT for j in range ( 1 , yMax + 1 ) : NEW_LINE INDENT a = power ( 2 , i ) NEW_LINE b = power ( 5 , j ) NEW_LINE if ( a + b == N ) : NEW_LINE INDENT print ( i , j ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 129 NEW_LINE findValX_Y ( N ) NEW_LINE DEDENT |
Count pairs from two arrays with difference exceeding K | set 2 | Python3 program for the above approach ; Function to count pairs that satisfy the given conditions ; Stores the count of pairs ; If v1 [ ] is smaller than v2 [ ] ; Sort the array v1 [ ] ; Traverse the array v2 [ ] ; Returns the address of the first number which is >= v2 [ j ] - k ; Increase the count by all numbers less than v2 [ j ] - k ; Otherwise ; Sort the array v2 [ ] ; Traverse the array v1 [ ] ; Returns the address of the first number which is > v1 [ i ] + k ; Increase the count by all numbers greater than v1 [ i ] + k ; Return the total count of pairs ; Driver Code | from bisect import bisect_left , bisect_right NEW_LINE def countPairs ( v1 , v2 , n , m , k ) : NEW_LINE INDENT count = 0 NEW_LINE if ( n <= m ) : NEW_LINE INDENT v1 = sorted ( v1 ) NEW_LINE for j in range ( m ) : NEW_LINE INDENT index = bisect_left ( v1 , v2 [ j ] - k ) NEW_LINE count += index NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT v2 = sorted ( v2 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT index = bisect_right ( v2 , v1 [ i ] + k ) NEW_LINE count += m - index NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 9 , 1 , 8 ] NEW_LINE brr = [ 10 , 12 , 7 , 4 , 2 , 3 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE M = len ( brr ) NEW_LINE print ( countPairs ( arr , brr , N , M , K ) ) NEW_LINE DEDENT |
Maximum sum subarray of size K with sum less than X | Function to calculate maximum sum among all subarrays of size K with the sum less than X ; Initialize sum_K to 0 ; Calculate sum of first K elements ; If sum_K is less than X ; Initialize MaxSum with sum_K ; Iterate over the array from ( K + 1 ) - th index ; Subtract the first element from the previous K elements and add the next element ; If sum_K is less than X ; Update the Max_Sum ; Driver Code ; Size of Array ; Function Call | def maxSumSubarr ( A , N , K , X ) : NEW_LINE INDENT sum_K = 0 NEW_LINE for i in range ( 0 , K ) : NEW_LINE INDENT sum_K += A [ i ] NEW_LINE DEDENT Max_Sum = 0 NEW_LINE if ( sum_K < X ) : NEW_LINE INDENT Max_Sum = sum_K NEW_LINE DEDENT for i in range ( K , N ) : NEW_LINE INDENT sum_K -= ( A [ i - K ] - A [ i ] ) NEW_LINE if ( sum_K < X ) : NEW_LINE INDENT Max_Sum = max ( Max_Sum , sum_K ) NEW_LINE DEDENT DEDENT print ( Max_Sum ) NEW_LINE DEDENT arr = [ - 5 , 8 , 7 , 2 , 10 , 1 , 20 , - 4 , 6 , 9 ] NEW_LINE K = 5 NEW_LINE X = 30 NEW_LINE N = len ( arr ) NEW_LINE maxSumSubarr ( arr , N , K , X ) NEW_LINE |
Rearrange array to make sum of all subarrays starting from first index non | Function to rearrange the array such that sum of all elements of subarrays from the 1 st index is non - zero ; Initialize sum of subarrays ; Sum of all elements of array ; If sum is 0 , the required array could never be formed ; If sum is non zero , array might be formed ; Sort array in ascending order ; When current subarray sum becomes 0 replace it with the largest element ; Swap Operation ; If largest element is same as element to be replaced , then rearrangement impossible ; If b = 1 , then rearrangement is not possible . Hence check with reverse configuration ; Sort array in descending order ; When current subarray sum becomes 0 replace it with the smallest element ; Swap Operation ; If smallest element is same as element to be replaced , then rearrangement impossible ; If neither of the configurations worked then pr " - 1" ; Otherwise , print the formed rearrangement ; Driver Code ; Given array ; Size of array ; Function Call | def rearrangeArray ( a , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT sum = 0 NEW_LINE b = 0 NEW_LINE a = sorted ( a ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( sum == 0 ) : NEW_LINE INDENT if ( a [ i ] != a [ N - 1 ] ) : NEW_LINE INDENT sum -= a [ i ] NEW_LINE a [ i ] , a [ N - 1 ] = a [ N - 1 ] , a [ i ] NEW_LINE sum += a [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT b = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( b == 1 ) : NEW_LINE INDENT b = 0 NEW_LINE sum = 0 NEW_LINE a = sorted ( a ) NEW_LINE a = a [ : : - 1 ] NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( sum == 0 ) : NEW_LINE INDENT if ( a [ i ] != a [ 0 ] ) : NEW_LINE INDENT sum -= a [ i ] NEW_LINE a [ i ] , a [ 0 ] = a [ 0 ] , a [ i ] NEW_LINE sum += a [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT b = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( b == 1 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , - 1 , 2 , 4 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE rearrangeArray ( arr , N ) NEW_LINE DEDENT |
Length of smallest subarray to be removed to make sum of remaining elements divisible by K | Python3 program for the above approach ; Function to find the length of the smallest subarray to be removed such that sum of elements is divisible by K ; Stores the remainder of each arr [ i ] when divided by K ; Stores total sum of elements ; K has been added to each arr [ i ] to handle - ve integers ; Update the total sum ; Remainder when total_sum is divided by K ; If given array is already divisible by K ; Stores curr_remainder and the most recent index at which curr_remainder has occurred ; Stores required answer ; Add current element to curr_sum and take mod ; Update current remainder index ; If mod already exists in map the subarray exists ; If not possible ; Print the result ; Given array arr [ ] ; Size of array ; Given K ; Function Call | import sys NEW_LINE def removeSmallestSubarray ( arr , n , k ) : NEW_LINE INDENT mod_arr = [ 0 ] * n NEW_LINE total_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mod_arr [ i ] = ( arr [ i ] + k ) % k NEW_LINE total_sum += arr [ i ] NEW_LINE DEDENT target_remainder = total_sum % k NEW_LINE if ( target_remainder == 0 ) : NEW_LINE INDENT print ( "0" ) NEW_LINE return NEW_LINE DEDENT map1 = { } NEW_LINE map1 [ 0 ] = - 1 NEW_LINE curr_remainder = 0 NEW_LINE res = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_remainder = ( curr_remainder + arr [ i ] + k ) % k NEW_LINE map1 [ curr_remainder ] = i NEW_LINE mod = ( curr_remainder - target_remainder + k ) % k NEW_LINE if ( mod in map1 . keys ( ) ) : NEW_LINE INDENT res = min ( res , i - map1 [ mod ] ) NEW_LINE DEDENT DEDENT if ( res == sys . maxsize or res == n ) : NEW_LINE INDENT res = - 1 NEW_LINE DEDENT print ( res ) NEW_LINE DEDENT arr = [ 3 , 1 , 4 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE K = 6 NEW_LINE removeSmallestSubarray ( arr , N , K ) NEW_LINE |
Queries to flip characters of a binary string in given range | Function to find the binary by performing all the given queries ; Stores length of the string ; prefixCnt [ i ] : Stores number of times strr [ i ] toggled by performing all the queries ; Update prefixCnt [ Q [ i ] [ 0 ] ] ; Update prefixCnt [ Q [ i ] [ 1 ] + 1 ] ; Calculate prefix sum of prefixCnt [ i ] ; Traverse prefixCnt [ ] array ; If ith element toggled odd number of times ; Toggled i - th element of binary string ; Driver Code | def toggleQuery ( strr , Q , M ) : NEW_LINE INDENT strr = [ i for i in strr ] NEW_LINE N = len ( strr ) NEW_LINE prefixCnt = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT prefixCnt [ Q [ i ] [ 0 ] ] += 1 NEW_LINE prefixCnt [ Q [ i ] [ 1 ] + 1 ] -= 1 NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT prefixCnt [ i ] += prefixCnt [ i - 1 ] NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( prefixCnt [ i ] % 2 ) : NEW_LINE INDENT strr [ i ] = ( chr ( ord ( '1' ) - ord ( strr [ i ] ) + ord ( '0' ) ) ) NEW_LINE DEDENT DEDENT return " " . join ( strr ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = "101010" ; NEW_LINE Q = [ [ 0 , 1 ] , [ 2 , 5 ] , [ 2 , 3 ] , [ 1 , 4 ] , [ 0 , 5 ] ] NEW_LINE M = len ( Q ) NEW_LINE print ( toggleQuery ( strr , Q , M ) ) NEW_LINE DEDENT |
Maximum length possible by cutting N given woods into at least K pieces | Function to check if it is possible to cut woods into K pieces of length len ; Stores count of pieces having length equal to K ; Traverse wood [ ] array ; Update count ; Function to find the maximum value of L ; Stores minimum possible of L ; Stores maximum possible value of L ; Apply binary search over the range [ left , right ] ; Stores mid value of left and right ; If it is possible to cut woods into K pieces having length of each piece equal to mid ; Update left ; Update right ; Driver Code | def isValid ( wood , N , len , K ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT count += wood [ i ] // len NEW_LINE DEDENT return ( count >= K ) NEW_LINE DEDENT def findMaxLen ( wood , N , K ) : NEW_LINE INDENT left = 1 NEW_LINE right = max ( wood ) NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = left + ( right - left ) // 2 NEW_LINE if ( isValid ( wood , N , mid , K ) ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT DEDENT return right NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT wood = [ 5 , 9 , 7 ] NEW_LINE N = len ( wood ) NEW_LINE K = 4 NEW_LINE print ( findMaxLen ( wood , N , K ) ) NEW_LINE DEDENT |
Count quadruplets with sum K from given array | Function to return the number of quadruplets with the given sum ; Initialize answer ; All possible first elements ; All possible second elements ; All possible third elements ; All possible fourth elements ; Increment counter by 1 if quadruplet sum is S ; Return the final count ; Driver Code ; Given array arr [ ] ; Given sum S ; Function Call | def countSum ( a , n , sum ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n - 3 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 2 ) : NEW_LINE INDENT for k in range ( j + 1 , n - 1 ) : NEW_LINE INDENT for l in range ( k + 1 , n ) : NEW_LINE INDENT if ( a [ i ] + a [ j ] + a [ k ] + a [ l ] == sum ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 5 , 3 , 1 , 2 , 4 ] NEW_LINE S = 13 NEW_LINE N = len ( arr ) NEW_LINE print ( countSum ( arr , N , S ) ) NEW_LINE DEDENT |
Minimum adjacent swaps to group similar characters together | Function to find minimum adjacent swaps required to make all the same character adjacent ; Initialize answer ; Create a 2D array of size 26 ; Traverse the string ; Get character ; Append the current index in the corresponding vector ; Traverse each character from a to z ; Add difference of adjacent index ; Return answer ; Driver Code ; Given string ; Size of string ; Function Call | def minSwaps ( S , n ) : NEW_LINE INDENT swaps = 0 NEW_LINE arr = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT pos = ord ( S [ i ] ) - ord ( ' a ' ) NEW_LINE arr [ pos ] . append ( i ) NEW_LINE DEDENT for ch in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT pos = ch - ord ( ' a ' ) NEW_LINE for i in range ( 1 , len ( arr [ pos ] ) ) : NEW_LINE INDENT swaps += abs ( arr [ pos ] [ i ] - arr [ pos ] [ i - 1 ] - 1 ) NEW_LINE DEDENT DEDENT return swaps NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abbccabbcc " NEW_LINE N = len ( S ) NEW_LINE print ( minSwaps ( S , N ) ) NEW_LINE DEDENT |
Construct a graph which does not contain any pair of adjacent nodes with same value | Function that prints the edges of the generated graph ; First print connections stored in store [ ] ; Check if there is more than one occurrence of 1 st unique element ; Print all other occurrence of 1 st unique element with second unique element ; Function to construct the graph such that the every adjacent nodes have different value ; Stores pair of edges formed ; Stores first unique occurrence ; Check for the second unique occurrence ; Store indices of 2 nd unique occurrence ; To check if arr has only 1 unique element or not ; Store the connections of all unique elements with Node 1 ; If value at node ( i + 1 ) is same as value at Node 1 then store its indices ; If count is zero then it 's not possible to construct the graph ; If more than 1 unique element is present ; Print the edges ; Driver Code ; Given array having node values ; Function Call | def printConnections ( store , ind , ind1 ) : NEW_LINE INDENT for pr in store : NEW_LINE INDENT print ( pr [ 0 ] , pr [ 1 ] ) NEW_LINE DEDENT if ( len ( ind ) != 0 ) : NEW_LINE INDENT for x in ind : NEW_LINE INDENT print ( ind1 , x + 1 ) NEW_LINE DEDENT DEDENT DEDENT def constructGraph ( arr , N ) : NEW_LINE INDENT ind = [ ] NEW_LINE store = [ ] NEW_LINE x = arr [ 0 ] NEW_LINE count , ind1 = 0 , 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] != x ) : NEW_LINE INDENT ind1 = i + 1 NEW_LINE count += 1 NEW_LINE store . append ( [ 1 , i + 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT ind . append ( i ) NEW_LINE DEDENT DEDENT if count == 0 : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Possible " ) NEW_LINE printConnections ( store , ind , ind1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE arr = [ ' a ' , ' b ' , ' a ' , ' b ' , ' c ' ] NEW_LINE constructGraph ( arr , N ) NEW_LINE DEDENT |
Minimum substring flips required to convert given binary string to another | Function that finds the minimum number of operations required such that string A and B are the same ; Stores the count of steps ; Stores the last index whose bits are not same ; Iterate until both string are unequal ; Check till end of string to find rightmost unequals bit ; Update the last index ; Flipping characters up to the last index ; Flip the bit ; Increasing steps by one ; Print the count of steps ; Driver Code ; Given strings A and B ; Function Call | def findMinimumOperations ( a , b ) : NEW_LINE INDENT step = 0 NEW_LINE last_index = 0 NEW_LINE while ( a != b ) : NEW_LINE INDENT a = [ i for i in a ] NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT if ( a [ i ] != b [ i ] ) : NEW_LINE INDENT last_index = i NEW_LINE DEDENT DEDENT for i in range ( last_index + 1 ) : NEW_LINE INDENT if ( a [ i ] == '0' ) : NEW_LINE INDENT a [ i ] = '1' NEW_LINE DEDENT else : NEW_LINE INDENT a [ i ] = '0' NEW_LINE DEDENT DEDENT a = " " . join ( a ) NEW_LINE step += 1 NEW_LINE DEDENT print ( step ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = "101010" NEW_LINE B = "110011" NEW_LINE findMinimumOperations ( A , B ) NEW_LINE DEDENT |
Count all disjoint pairs having absolute difference at least K from a given array | Function to check if it is possible to form M pairs with abs diff at least K ; Traverse the array over [ 0 , M ] ; If valid index ; Return 1 ; Function to count distinct pairs with absolute difference atleasr K ; Stores the count of all possible pairs ; Initialize left and right ; Sort the array ; Perform Binary Search ; Find the value of mid ; Check valid index ; Update ans ; Print the answer ; Driver Code ; Given array arr [ ] ; Given difference K ; Size of the array ; Function call | def isValid ( arr , n , m , d ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT if ( abs ( arr [ n - m + i ] - arr [ i ] ) < d ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def countPairs ( arr , N , K ) : NEW_LINE INDENT ans = 0 NEW_LINE left = 0 NEW_LINE right = N // 2 + 1 NEW_LINE arr . sort ( reverse = False ) NEW_LINE while ( left < right ) : NEW_LINE INDENT mid = ( left + right ) // 2 NEW_LINE if ( isValid ( arr , N , mid , K ) ) : NEW_LINE INDENT ans = mid NEW_LINE left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT DEDENT print ( ans , end = " " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 3 , 5 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE countPairs ( arr , N , K ) NEW_LINE DEDENT |
Minimum common element in subarrays of all possible lengths | Function to find maximum distance between every two element ; Stores index of last occurence of each array element ; Initialize temp [ ] with - 1 ; Traverse the array ; If array element has not occurred previously ; Update index in temp ; Otherwise ; Compare temp [ a [ i ] ] with distance from its previous occurence and store the maximum ; Compare temp [ i ] with distance of its last occurence from the end of the array and store the maximum ; Function to find the minimum common element in subarrays of all possible lengths ; Function call to find a the maximum distance between every pair of repetition ; Initialize ans [ ] to - 1 ; Check if subarray of length temp [ i ] contains i as one of the common elements ; Find the minimum of all common elements ; Driver Code | def max_distance ( a , temp , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT temp [ i ] = - 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] not in mp ) : NEW_LINE INDENT temp [ a [ i ] ] = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp [ a [ i ] ] = max ( temp [ a [ i ] ] , i - mp [ a [ i ] ] ) NEW_LINE DEDENT mp [ a [ i ] ] = i NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( temp [ i ] != - 1 ) : NEW_LINE INDENT temp [ i ] = max ( temp [ i ] , n - mp [ i ] ) NEW_LINE DEDENT DEDENT DEDENT def min_comm_ele ( a , ans , temp , n ) : NEW_LINE INDENT max_distance ( a , temp , n ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans [ i ] = - 1 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( ans [ temp [ i ] ] == - 1 ) : NEW_LINE INDENT ans [ temp [ i ] ] = i NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i > 1 and ans [ i - 1 ] != - 1 ) : NEW_LINE INDENT if ( ans [ i ] == - 1 ) : NEW_LINE INDENT ans [ i ] = ans [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT ans [ i ] = min ( ans [ i ] , ans [ i - 1 ] ) NEW_LINE DEDENT DEDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE a = [ 1 , 3 , 4 , 5 , 6 , 7 ] NEW_LINE temp = [ 0 ] * 100 NEW_LINE ans = [ 0 ] * 100 NEW_LINE min_comm_ele ( a , ans , temp , N ) NEW_LINE DEDENT |
Find a triplet in an array such that arr [ i ] arr [ k ] and i < j < k | Function to find a triplet that satisfy the conditions ; Traverse the given array ; Stores current element ; Stores element just before the current element ; Stores element just after the current element ; Check the given conditions ; Print a triplet ; If no triplet found ; Driver Code | def FindTrip ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N - 1 ) : NEW_LINE INDENT p = arr [ i - 1 ] NEW_LINE q = arr [ i ] NEW_LINE r = arr [ i + 1 ] NEW_LINE if ( p < q and q > r ) : NEW_LINE INDENT print ( i - 1 , i , i + 1 ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 4 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE FindTrip ( arr , N ) NEW_LINE DEDENT |
Count subarrays having each distinct element occurring at least twice | Python3 program to implement the above approach ; Function to get the count of subarrays having each element occurring at least twice ; Stores count of subarrays having each distinct element occurring at least twice ; Stores count of unique elements in a subarray ; Store frequency of each element of a subarray ; Traverse the given array ; Count frequency and check conditions for each subarray ; Update frequency ; Check if frequency of arr [ j ] equal to 1 ; Update Count of unique elements ; Update count of unique elements ; If each element of subarray occurs at least twice ; Update cntSub ; Remove all elements from the subarray ; Update cntUnique ; Driver code | from collections import defaultdict NEW_LINE def cntSubarrays ( arr , N ) : NEW_LINE INDENT cntSub = 0 NEW_LINE cntUnique = 0 NEW_LINE cntFreq = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i , N ) : NEW_LINE INDENT cntFreq [ arr [ j ] ] += 1 NEW_LINE if ( cntFreq [ arr [ j ] ] == 1 ) : NEW_LINE INDENT cntUnique += 1 NEW_LINE DEDENT elif ( cntFreq [ arr [ j ] ] == 2 ) : NEW_LINE INDENT cntUnique -= 1 NEW_LINE DEDENT if ( cntUnique == 0 ) : NEW_LINE INDENT cntSub += 1 NEW_LINE DEDENT DEDENT cntFreq . clear ( ) NEW_LINE cntUnique = 0 NEW_LINE DEDENT return cntSub NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( cntSubarrays ( arr , N ) ) NEW_LINE DEDENT |
Check if permutation of a given string can be made palindromic by removing at most K characters | Function to check if the satisfies the given conditions or not ; Stores length of given string ; Stores frequency of each character of str ; Update frequency of current character ; Stores count of distinct character whose frequency is odd ; Traverse the cntFreq [ ] array . ; If frequency of character i is odd ; Update cntOddFreq ; If count of distinct character having odd frequency is <= K + 1 ; Driver Code ; If str satisfy the given conditions | def checkPalinK ( str , K ) : NEW_LINE INDENT N = len ( str ) NEW_LINE cntFreq = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cntFreq [ ord ( str [ i ] ) ] += 1 NEW_LINE DEDENT cntOddFreq = 0 NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT if ( cntFreq [ i ] % 2 == 1 ) : NEW_LINE INDENT cntOddFreq += 1 NEW_LINE DEDENT DEDENT if ( cntOddFreq <= ( K + 1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE K = 2 NEW_LINE if ( checkPalinK ( str , K ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Maximum number of elements that can be removed such that MEX of the given array remains unchanged | Function to find the maximum number of elements that can be removed ; Initialize hash [ ] with 0 s ; Initialize MEX ; Set hash [ i ] = 1 , if i is present in arr [ ] ; Find MEX from the hash ; Print the maximum numbers that can be removed ; Driver Code ; Given array ; Size of the array ; Function Call | def countRemovableElem ( arr , N ) : NEW_LINE INDENT hash = [ 0 ] * ( N + 1 ) NEW_LINE mex = N + 1 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] <= N ) : NEW_LINE INDENT hash [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( hash [ i ] == 0 ) : NEW_LINE INDENT mex = i NEW_LINE break NEW_LINE DEDENT DEDENT print ( N - ( mex - 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 1 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE countRemovableElem ( arr , N ) NEW_LINE DEDENT |
Print all positions of a given string having count of smaller characters equal on both sides | Function to find indexes of the given that satisfy the condition ; Stores length of given string ; Stores frequency of each character of strr ; Update frequency of current character ; cntLeftFreq [ i ] Stores frequency of characters present on the left side of index i . ; Traverse the given string ; Stores count of smaller characters on left side of i . ; Stores count of smaller characters on Right side of i . ; Traverse smaller characters on left side of index i . ; Update cntLeft ; Update cntRight ; Update cntLeftFreq [ strr [ i ] ] ; If count of smaller elements on both sides equal ; Print current index ; Driver Code | def printIndexes ( strr ) : NEW_LINE INDENT N = len ( strr ) NEW_LINE cntFreq = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cntFreq [ ord ( strr [ i ] ) ] += 1 NEW_LINE DEDENT cntLeftFreq = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cntLeft = 0 NEW_LINE cntRight = 0 NEW_LINE for j in range ( ord ( strr [ i ] ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT cntLeft += cntLeftFreq [ j ] NEW_LINE cntRight += ( cntFreq [ j ] - cntLeftFreq [ j ] ) NEW_LINE DEDENT cntLeftFreq [ ord ( strr [ i ] ) ] += 1 NEW_LINE if ( cntLeft == cntRight and cntLeft != 0 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " aabacdabbb " NEW_LINE printIndexes ( strr ) NEW_LINE DEDENT |
Count three | Function to count three - digit numbers having difference x with its reverse ; If x is not multiple of 99 ; No solution exists ; Generate all possible pairs of digits [ 1 , 9 ] ; If any pair is obtained with difference x / 99 ; Increase count ; Return the count ; Driver Code | def Count_Number ( x ) : NEW_LINE INDENT ans = 0 ; NEW_LINE if ( x % 99 != 0 ) : NEW_LINE INDENT ans = - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT diff = x / 99 ; NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT for j in range ( 1 , 10 ) : NEW_LINE INDENT if ( ( i - j ) == diff ) : NEW_LINE INDENT ans += 10 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 792 ; NEW_LINE print ( Count_Number ( x ) ) ; NEW_LINE DEDENT |
Check if a point having maximum X and Y coordinates exists or not | Python3 program for the above approach ; Initialize INF as inifnity ; Function to return the pohaving maximum X and Y coordinates ; Base Case ; Stores if valid poexists ; If poarr [ i ] is valid ; Check for the same point ; Check for a valid point ; If current pois the required point ; Otherwise ; Function to find the required point ; Stores the powith maximum X and Y - coordinates ; If no required poexists ; Driver Code ; Given array of points ; Function Call | import sys NEW_LINE INF = sys . maxsize ; NEW_LINE def findMaxPoint ( arr , i , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return [ INF , INF ] NEW_LINE DEDENT flag = True ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( j == i ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( arr [ j ] [ 0 ] >= arr [ i ] [ 0 ] or arr [ j ] [ 1 ] >= arr [ i ] [ 1 ] ) : NEW_LINE INDENT flag = False ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT return arr [ i ] ; NEW_LINE DEDENT return findMaxPoint ( arr , i + 1 , n ) ; NEW_LINE DEDENT def findMaxPoints ( arr , n ) : NEW_LINE INDENT ans = findMaxPoint ( arr , 0 , n ) ; NEW_LINE if ( ans [ 0 ] == INF ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " ( " , ans [ 0 ] , " β " , ans [ 1 ] , " ) " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 2 ] , [ 2 , 1 ] , [ 3 , 4 ] , [ 4 , 3 ] , [ 5 , 5 ] ] ; NEW_LINE N = len ( arr ) ; NEW_LINE findMaxPoints ( arr , N ) ; NEW_LINE DEDENT |
Check if a point having maximum X and Y coordinates exists or not | Python3 program for the above approach ; Function to find the pohaving max X and Y coordinates ; Initialize maxX and maxY ; Length of the given array ; Get maximum X & Y coordinates ; Check if the required point i . e . , ( maxX , maxY ) is present ; If powith maximum X and Y coordinates is present ; If no such poexists ; Driver Code ; Given array of points ; Pranswer | import sys ; NEW_LINE def findMaxPoint ( arr ) : NEW_LINE INDENT maxX = - sys . maxsize ; NEW_LINE maxY = - sys . maxsize ; NEW_LINE n = len ( arr ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxX = max ( maxX , arr [ i ] [ 0 ] ) ; NEW_LINE maxY = max ( maxY , arr [ i ] [ 1 ] ) ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( maxX == arr [ i ] [ 0 ] and maxY == arr [ i ] [ 1 ] ) : NEW_LINE INDENT print ( " ( " , maxX , " , β " , maxY , " ) " ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT print ( - 1 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 2 ] , [ 2 , 1 ] , [ 3 , 4 ] , [ 4 , 3 ] , [ 5 , 5 ] ] ; NEW_LINE findMaxPoint ( arr ) ; NEW_LINE DEDENT |
Search insert position of K in a sorted array | Function to find insert position of K ; Traverse the array ; If K is found ; If arr [ i ] exceeds K ; If all array elements are smaller ; Driver Code | def find_index ( arr , n , K ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] == K : NEW_LINE INDENT return i NEW_LINE DEDENT elif arr [ i ] > K : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return n NEW_LINE DEDENT arr = [ 1 , 3 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( find_index ( arr , n , K ) ) NEW_LINE |
Count subarrays for every array element in which they are the minimum | Set 2 | Function to calculate total number of sub - arrays for each element where that element is occurring as the minimum element ; Map for storing the number of sub - arrays for each element ; Traverse over all possible subarrays ; Minimum in each subarray ; Print result ; Driver Code ; Function Call | def minSubarray ( arr , N ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT mini = 10 ** 9 NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT mini = min ( mini , arr [ j ] ) NEW_LINE m [ mini ] = m . get ( mini , 0 ) + 1 NEW_LINE DEDENT DEDENT for i in arr : NEW_LINE INDENT print ( m [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE minSubarray ( arr , N ) NEW_LINE DEDENT |
Count subarrays for every array element in which they are the minimum | Set 2 | Function to count subarrays for each element where it is the minimum ; For the length of strictly larger numbers on the left of A [ i ] ; Storing x in result [ i ] ; For the length of strictly larger numbers on the right of A [ i ] ; Store x * y in result array ; Print the result ; Driver Code ; Function Call | def minSubarray ( arr , N ) : NEW_LINE INDENT result = [ 0 ] * N NEW_LINE l = [ ] NEW_LINE r = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT count = 1 ; NEW_LINE while ( len ( l ) != 0 and l [ - 1 ] [ 0 ] > arr [ i ] ) : NEW_LINE INDENT count += l [ - 1 ] [ 1 ] NEW_LINE l . pop ( ) NEW_LINE DEDENT l . append ( [ arr [ i ] , count ] ) NEW_LINE result [ i ] = count ; NEW_LINE DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT count = 1 ; NEW_LINE while ( len ( r ) != 0 and r [ - 1 ] [ 0 ] >= arr [ i ] ) : NEW_LINE INDENT count += r [ - 1 ] [ 1 ] NEW_LINE r . pop ( ) ; NEW_LINE DEDENT r . append ( [ arr [ i ] , count ] ) ; NEW_LINE result [ i ] *= count NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( result [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE minSubarray ( arr , N ) NEW_LINE DEDENT |
Count Full Prime numbers in a given range | Function to check if a number is prime or not ; If a divisor of n exists ; Function to check if a number is Full Prime or not ; If n is not a prime ; Otherwise ; Extract digit ; If any digit of n is non - prime ; Function to prcount of Full Primes in a range [ L , R ] ; Stores count of full primes ; Check if i is full prime ; Driver Code ; Stores count of full primes | def isPrime ( num ) : NEW_LINE INDENT if ( num <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , num + 1 ) : NEW_LINE INDENT if i * i > num : NEW_LINE INDENT break NEW_LINE DEDENT if ( num % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isFulPrime ( n ) : NEW_LINE INDENT if ( not isPrime ( n ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT rem = n % 10 NEW_LINE if ( not ( rem == 2 or rem == 3 or rem == 5 or rem == 7 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = n // 10 NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def countFulPrime ( L , R ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( ( i % 2 ) != 0 and isFulPrime ( i ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 1 NEW_LINE R = 100 NEW_LINE ans = 0 NEW_LINE if ( L < 3 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT print ( ans + countFulPrime ( L , R ) ) NEW_LINE DEDENT |
Print alternate elements of an array | Function to print Alternate elements of the given array ; Print elements at odd positions ; If currIndex stores even index or odd position ; Driver Code | def printAlter ( arr , N ) : NEW_LINE INDENT for currIndex in range ( 0 , N ) : NEW_LINE INDENT if ( currIndex % 2 == 0 ) : NEW_LINE INDENT print ( arr [ currIndex ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE printAlter ( arr , N ) NEW_LINE DEDENT |
Minimize deletions in a Binary String to remove all subsequences of the form "0101" | Function to find minimum characters to be removed such that no subsequence of the form "0101" exists in the string ; Stores the partial sums ; Calculate partial sums ; Setting endpoints and deleting characters indices . ; Return count of deleted characters ; Driver Code | def findmin ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE maximum = 0 NEW_LINE incr = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT incr [ i + 1 ] = incr [ i ] NEW_LINE if ( s [ i ] == '0' ) : NEW_LINE INDENT incr [ i + 1 ] = incr [ i + 1 ] + 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , n + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT maximum = max ( maximum , incr [ i ] + j - i + 1 - ( incr [ j + 1 ] - incr [ i ] ) + incr [ n ] - incr [ j + 1 ] ) NEW_LINE DEDENT DEDENT return n - maximum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "0110100110" NEW_LINE minimum = findmin ( S ) NEW_LINE print ( minimum ) NEW_LINE DEDENT |
Length of longest subarray with product equal to a power of 2 | Function to check whether a number is power of 2 or not ; Function to find maximum length subarray having product of element as a perfect power of 2 ; Stores current subarray length ; Stores maximum subarray length ; Traverse the given array ; If arr [ i ] is power of 2 ; Increment max_length ; Update max_len_subarray ; Otherwise ; Prthe maximum length ; Driver Code ; Given arr ; Function Call | def isPower ( x ) : NEW_LINE INDENT if ( x != 0 and ( x & ( x - 1 ) ) == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def maximumlength ( arr , N ) : NEW_LINE INDENT max_length = 0 ; NEW_LINE max_len_subarray = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( isPower ( arr [ i ] ) ) : NEW_LINE INDENT max_length += 1 ; NEW_LINE max_len_subarray = max ( max_length , max_len_subarray ) ; NEW_LINE DEDENT else : NEW_LINE INDENT max_length = 0 ; NEW_LINE DEDENT DEDENT print ( max_len_subarray ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 5 , 4 , 6 , 8 , 8 , 2 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE maximumlength ( arr , N ) ; NEW_LINE DEDENT |
Length of smallest subarray to be removed such that the remaining array is sorted | Python3 program for the above approach ; Find the length of the shortest subarray ; To store the result ; Calculate the possible length of the sorted subarray from left ; Array is sorted ; Calculate the possible length of the sorted subarray from left ; Update the result ; Calculate the possible length in the middle we can delete and update the result ; Update the result ; Return the result ; Driver Code ; Function Call | import sys NEW_LINE def findLengthOfShortestSubarray ( arr ) : NEW_LINE INDENT minlength = sys . maxsize NEW_LINE left = 0 NEW_LINE right = len ( arr ) - 1 NEW_LINE while left < right and arr [ left + 1 ] >= arr [ left ] : NEW_LINE INDENT left += 1 NEW_LINE DEDENT if left == len ( arr ) - 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT while right > left and arr [ right - 1 ] <= arr [ right ] : NEW_LINE INDENT right -= 1 NEW_LINE DEDENT minlength = min ( len ( arr ) - left - 1 , right ) NEW_LINE j = right NEW_LINE for i in range ( left + 1 ) : NEW_LINE INDENT if arr [ i ] <= arr [ j ] : NEW_LINE INDENT minlength = min ( minlength , j - i - 1 ) NEW_LINE DEDENT elif j < len ( arr ) - 1 : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return minlength NEW_LINE DEDENT arr = [ 6 , 3 , 10 , 11 , 15 , 20 , 13 , 3 , 18 , 12 ] NEW_LINE print ( findLengthOfShortestSubarray ( arr ) ) NEW_LINE |
Smallest number to be subtracted to convert given number to a palindrome | Function to evaluate minimum subtraction required to make a number palindrome ; Counts number of subtractions required ; Run a loop till N >= 0 ; Store the current number ; Store reverse of current number ; Reverse the number ; Check if N is palindrome ; Increment the counter ; Reduce the number by 1 ; Print the result ; Driver Code ; Function call | def minSub ( N ) : NEW_LINE INDENT count = 0 NEW_LINE while ( N >= 0 ) : NEW_LINE INDENT num = N NEW_LINE rev = 0 NEW_LINE while ( num != 0 ) : NEW_LINE INDENT digit = num % 10 NEW_LINE rev = ( rev * 10 ) + digit NEW_LINE num = num // 10 NEW_LINE DEDENT if ( N == rev ) : NEW_LINE INDENT break NEW_LINE DEDENT count += 1 NEW_LINE N -= 1 NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3456 NEW_LINE minSub ( N ) NEW_LINE DEDENT |
Count subarrays of atleast size 3 forming a Geometric Progression ( GP ) | Function to count all the subarrays of size at least 3 forming GP ; If array size is less than 3 ; Stores the count of subarray ; Stores the count of subarray for each iteration ; Traverse the array ; Check if L [ i ] forms GP ; Otherwise , update count to 0 ; Update the final count ; Return the final count ; Driver Code ; Given array arr [ ] ; Function Call | def numberOfGP ( L , N ) : NEW_LINE INDENT if ( N <= 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 0 NEW_LINE res = 0 NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT if ( L [ i - 1 ] * L [ i - 1 ] == L [ i ] * L [ i - 2 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = 0 NEW_LINE DEDENT res += count NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 8 , 16 , 24 ] NEW_LINE N = len ( arr ) NEW_LINE print ( numberOfGP ( arr , N ) ) NEW_LINE DEDENT |
Count even length subarrays having bitwise XOR equal to 0 | Function to count the number of even - length subarrays having Bitwise XOR equal to 0 ; Stores the count of required subarrays ; Stores prefix - XOR of arr [ i , i + 1 , ... N - 1 ] ; Traverse the array ; Calculate the prefix - XOR of current subarray ; Check if XOR of the current subarray is 0 and length is even ; Driver Code | def cntSubarr ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE prefixXor = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT prefixXor = arr [ i ] NEW_LINE for j in range ( i + 1 , N ) : NEW_LINE INDENT prefixXor ^= arr [ j ] NEW_LINE if ( prefixXor == 0 and ( j - i + 1 ) % 2 == 0 ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 2 , 3 , 3 , 6 , 7 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE print ( cntSubarr ( arr , N ) ) NEW_LINE DEDENT |
Count even length subarrays having bitwise XOR equal to 0 | Python3 program to implement the above approach ; Function to get the count of even length subarrays having bitwise xor 0 ; Stores prefix - xor of the given array ; Stores prefix - xor at even index of the array . ; Stores prefix - xor at odd index of the array . ; Stores count of subarrays that satisfy the condition ; length from 0 index to odd index is even ; Traverse the array . ; Take prefix - xor ; If index is odd ; Calculate pairs ; Increment prefix - xor at odd index ; Calculate pairs ; Increment prefix - xor at odd index ; Driver Code | M = 1000000 ; NEW_LINE def cntSubXor ( arr , N ) : NEW_LINE INDENT prefixXor = 0 ; NEW_LINE Even = [ 0 ] * M ; NEW_LINE Odd = [ 0 ] * M ; NEW_LINE cntSub = 0 ; NEW_LINE Odd [ 0 ] = 1 ; NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT prefixXor ^= arr [ i ] ; NEW_LINE if ( i % 2 == 1 ) : NEW_LINE INDENT cntSub += Odd [ prefixXor ] ; NEW_LINE Odd [ prefixXor ] += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT cntSub += Even [ prefixXor ] ; NEW_LINE Even [ prefixXor ] += 1 ; NEW_LINE DEDENT DEDENT return cntSub ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 2 , 3 , 3 , 6 , 7 , 8 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( cntSubXor ( arr , N ) ) ; NEW_LINE DEDENT |
Maximize sum of array elements removed by performing the given operations | Function to find the maximum sum of the array arr [ ] where each element can be reduced to at most min [ i ] ; Stores the pair of arr [ i ] & min [ i ] ; Sorting vector of pairs ; Traverse the vector of pairs ; Add to the value of S ; Update K ; Driver Code ; Given array arr [ ] , min [ ] ; Given K ; Function Call ; Print the value of S | def findMaxSum ( arr , n , min , k , S ) : NEW_LINE INDENT A = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT A . append ( ( arr [ i ] , min [ i ] ) ) NEW_LINE DEDENT A = sorted ( A ) NEW_LINE A = A [ : : - 1 ] NEW_LINE K = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT S += max ( A [ i ] [ 0 ] - K , A [ i ] [ 1 ] ) NEW_LINE K += k NEW_LINE DEDENT return S NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr , min = [ ] , [ ] NEW_LINE arr = [ 3 , 5 , 2 , 1 ] NEW_LINE min = [ 3 , 2 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE S = 0 NEW_LINE S = findMaxSum ( arr , N , min , K , S ) NEW_LINE print ( S ) NEW_LINE DEDENT |
Length of smallest substring of a given string which contains another string as subsequence | Python3 program to implement the above approach ; Function to find the length of smallest substring of a having string b as a subsequence ; Stores the characters present in string b ; Find index of characters of a that are also present in string b ; If character is present in string b ; Store the index of character ; Flag is used to check if substring is possible ; Assume that substring is possible ; Stores first and last indices of the substring respectively ; For first character of string b ; If the first character of b is not present in a ; If the first character of b is present in a ; Remove the index from map ; Update indices of the substring ; For the remaining characters of b ; If index possible for current character ; If no index is possible ; If no more substring is possible ; Update the minimum length of substring ; Return the result ; Driver Code ; Given two string | import sys NEW_LINE def minLength ( a , b ) : NEW_LINE INDENT Char = { } NEW_LINE for i in range ( len ( b ) ) : NEW_LINE INDENT Char [ b [ i ] ] = Char . get ( b [ i ] , 0 ) + 1 NEW_LINE DEDENT CharacterIndex = { } NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT x = a [ i ] NEW_LINE if ( x in Char ) : NEW_LINE INDENT CharacterIndex [ x ] = CharacterIndex . get ( x , [ ] ) NEW_LINE CharacterIndex [ x ] . append ( i ) NEW_LINE DEDENT DEDENT l = sys . maxsize NEW_LINE while ( True ) : NEW_LINE INDENT flag = 1 NEW_LINE firstVar = 0 NEW_LINE lastVar = 0 NEW_LINE for i in range ( len ( b ) ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT if ( b [ i ] not in CharacterIndex ) : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT x = CharacterIndex [ b [ i ] ] [ 0 ] NEW_LINE CharacterIndex [ b [ i ] ] . remove ( CharacterIndex [ b [ i ] ] [ 0 ] ) NEW_LINE firstVar = x NEW_LINE lastVar = x NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT elementFound = 0 NEW_LINE for e in CharacterIndex [ b [ i ] ] : NEW_LINE INDENT if ( e > lastVar ) : NEW_LINE INDENT elementFound = 1 NEW_LINE lastVar = e NEW_LINE break NEW_LINE DEDENT DEDENT if ( elementFound == 0 ) : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT l = min ( l , abs ( lastVar - firstVar ) + 1 ) NEW_LINE DEDENT return l NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = " abcdefababaef " NEW_LINE b = " abf " NEW_LINE l = minLength ( a , b ) NEW_LINE if ( l != sys . maxsize ) : NEW_LINE INDENT print ( l ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Impossible " ) NEW_LINE DEDENT DEDENT |
Count smaller primes on the right of each array element | Function to check if a number is prime or not ; Function to find the count of smaller primes on the right of each array element ; Stores the count of smaller primes ; If A [ j ] <= A [ i ] and A [ j ] is prime ; Increase count ; Print the count for the current element ; Driver Code ; Function call | def is_prime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if i * i > n : NEW_LINE INDENT break NEW_LINE DEDENT if ( n % i == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def countSmallerPrimes ( ar , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( ar [ j ] <= ar [ i ] and is_prime ( ar [ j ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ar = [ 43 , 3 , 5 , 7 , 2 , 41 ] NEW_LINE N = len ( ar ) NEW_LINE countSmallerPrimes ( ar , N ) NEW_LINE DEDENT |
Check if a string is concatenation of another given string | Function to check if a is concatenation of another string ; Stores the length of str2 ; Stores the length of str1 ; If M is not multiple of N ; Traverse both the strings ; If str1 is not concatenation of str2 ; Driver Code | def checkConcat ( str1 , str2 ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE M = len ( str2 ) NEW_LINE if ( N % M != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ i % M ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " abcabcabc " NEW_LINE str2 = " abc " NEW_LINE if ( checkConcat ( str1 , str2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Minimize length of string by replacing K pairs of distinct adjacent characters | Function to minimize the length of the by replacing distinct pairs of adjacent characters ; Stores the length of the given string ; Stores the index of the given string ; Traverse the given string ; If two adjacent haracters are distinct ; If all characters are equal ; If all characters are distinct ; Driver Code | def MinLen ( str , K ) : NEW_LINE INDENT N = len ( str ) NEW_LINE i = 0 NEW_LINE while ( i < N - 1 ) : NEW_LINE INDENT if ( str [ i ] != str [ i + 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( i == N - 1 ) : NEW_LINE INDENT return N NEW_LINE DEDENT return max ( 1 , N - K ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " aabc " NEW_LINE K = 1 NEW_LINE print ( MinLen ( str , K ) ) NEW_LINE DEDENT |
Length of smallest sequence having sum X and product Y | Python3 program for the above approach ; Function for checking valid or not ; Function for checking boundary of binary search ; Function to calculate the minimum sequence size using binary search ; Initialize high and low ; Base case ; Print - 1 if a sequence cannot be generated ; Otherwise ; Iterate until difference between high and low exceeds 1 ; Calculate mid ; Reset values of high and low accordingly ; Print the answer ; Driver Code ; Function call | from math import floor , exp NEW_LINE def temp ( n , x ) : NEW_LINE INDENT return pow ( x * 1 / n , n ) NEW_LINE DEDENT def check ( n , y , x ) : NEW_LINE INDENT v = temp ( n , x ) NEW_LINE return ( v >= y ) NEW_LINE DEDENT def find ( x , y ) : NEW_LINE INDENT high = floor ( x / exp ( 1.0 ) ) NEW_LINE low = 1 NEW_LINE if ( x == y ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT elif ( not check ( high , y , x ) ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT while ( high - low > 1 ) : NEW_LINE INDENT mid = ( high + low ) // 2 NEW_LINE if ( check ( mid , y , x ) ) : NEW_LINE INDENT high = mid NEW_LINE DEDENT else : NEW_LINE INDENT low = mid NEW_LINE DEDENT DEDENT print ( high ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 9 NEW_LINE y = 8 NEW_LINE find ( x , y ) NEW_LINE DEDENT |
Print the middle nodes of each level of a Binary Tree | Structure Node of Binary Tree ; Function to create a new node ; Return the created node ; Function that performs the DFS traversal on Tree to store all the nodes at each level in map M ; Base Case ; Push the current level node ; Left Recursion ; Right Recursion ; Function that print all the middle nodes for each level in Binary Tree ; Stores all node in each level ; Perform DFS traversal ; Traverse the map M ; Get the size of vector ; For odd number of elements ; Print ( M / 2 ) th Element ; Otherwise ; Print ( M / 2 ) th and ( M / 2 + 1 ) th Element ; Driver Code ; Given Tree ; Function Call | class node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newnode ( d ) : NEW_LINE INDENT temp = node ( d ) NEW_LINE return temp NEW_LINE DEDENT def dfs ( root , l , M ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if l not in M : NEW_LINE INDENT M [ l ] = [ ] NEW_LINE DEDENT M [ l ] . append ( root . data ) NEW_LINE dfs ( root . left , l + 1 , M ) NEW_LINE dfs ( root . right , l + 1 , M ) NEW_LINE DEDENT def printMidNodes ( root ) : NEW_LINE INDENT M = dict ( ) NEW_LINE dfs ( root , 0 , M ) NEW_LINE for it in M . values ( ) : NEW_LINE INDENT size = len ( it ) NEW_LINE if ( size & 1 ) : NEW_LINE INDENT print ( it [ ( size - 1 ) // 2 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( str ( it [ ( size - 1 ) // 2 ] ) + ' β ' + str ( it [ ( size - 1 ) // 2 + 1 ] ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = newnode ( 1 ) NEW_LINE root . left = newnode ( 2 ) NEW_LINE root . right = newnode ( 3 ) NEW_LINE root . left . left = newnode ( 4 ) NEW_LINE root . left . right = newnode ( 5 ) NEW_LINE root . left . right . left = newnode ( 11 ) NEW_LINE root . left . right . right = newnode ( 6 ) NEW_LINE root . left . right . right . left = newnode ( 7 ) NEW_LINE root . left . right . right . right = newnode ( 9 ) NEW_LINE root . right . left = newnode ( 10 ) NEW_LINE root . right . right = newnode ( 8 ) NEW_LINE printMidNodes ( root ) NEW_LINE DEDENT |
Smallest array that can be obtained by replacing adjacent pairs with their products | Function to minimize the size of array by performing given operations ; If all array elements are not same ; If all array elements are same ; Driver Code ; Function call | def minLength ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ 0 ] != arr [ i ] ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return N NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 1 , 3 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minLength ( arr , N ) ) NEW_LINE DEDENT |
Subarrays whose sum is a perfect square | Python3 program to implement the above approach ; Function to print the start and end indices of all subarrays whose sum is a perfect square ; Stores the current subarray sum ; Update current subarray sum ; Stores the square root of currSubSum ; Check if currSubSum is a perfect square or not ; Driver Code | import math NEW_LINE def PrintIndexes ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT currSubSum = 0 NEW_LINE for j in range ( i , N , 1 ) : NEW_LINE INDENT currSubSum += arr [ j ] NEW_LINE sq = int ( math . sqrt ( currSubSum ) ) NEW_LINE if ( sq * sq == currSubSum ) : NEW_LINE INDENT print ( " ( " , i , " , " , j , " ) " , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT arr = [ 65 , 79 , 81 ] NEW_LINE N = len ( arr ) NEW_LINE PrintIndexes ( arr , N ) NEW_LINE |
Count positions in Binary Matrix having equal count of set bits in corresponding row and column | Function to return the count of indices in from the given binary matrix having equal count of set bits in its row and column ; Stores count of set bits in corresponding column and row ; Traverse matrix ; Since 1 contains a set bit ; Update count of set bits for current row and col ; Stores the count of required indices ; Traverse matrix ; If current row and column has equal count of set bits ; Return count of required position ; Driver Code | def countPosition ( mat ) : NEW_LINE INDENT n = len ( mat ) NEW_LINE m = len ( mat [ 0 ] ) NEW_LINE row = [ 0 ] * n NEW_LINE col = [ 0 ] * m NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT col [ j ] += 1 NEW_LINE row [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( row [ i ] == col [ j ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT mat = [ [ 0 , 1 ] , [ 1 , 1 ] ] NEW_LINE print ( countPosition ( mat ) ) NEW_LINE |
Maximum value at each level in an N | Function to find the maximum value at each level of N - ary tree ; Stores the adjacency list ; Create the adjacency list ; Perform level order traversal of nodes at each level ; Push the root node ; Iterate until queue is empty ; Get the size of queue ; Iterate for : all the nodes in the queue currently ; Dequeue an node from queue ; Enqueue the children of dequeued node ; Print the result ; Driver Code ; Number of nodes ; Edges of the N - ary tree ; Given cost ; Function Call | def maxAtLevel ( N , M , Value , Edges ) : NEW_LINE INDENT adj = [ [ ] for i in range ( N ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT u = Edges [ i ] [ 0 ] NEW_LINE v = Edges [ i ] [ 1 ] NEW_LINE adj [ u ] . append ( v ) NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( 0 ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT count = len ( q ) NEW_LINE maxVal = 0 NEW_LINE while ( count ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . remove ( q [ 0 ] ) NEW_LINE maxVal = max ( maxVal , Value [ temp ] ) NEW_LINE for i in range ( len ( adj [ temp ] ) ) : NEW_LINE INDENT q . append ( adj [ temp ] [ i ] ) NEW_LINE DEDENT count -= 1 NEW_LINE DEDENT print ( maxVal , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE Edges = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 0 , 3 ] , [ 1 , 4 ] , [ 1 , 5 ] , [ 3 , 6 ] , [ 6 , 7 ] , [ 6 , 8 ] , [ 6 , 9 ] ] NEW_LINE Value = [ 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 6 , 12 , 7 ] NEW_LINE maxAtLevel ( N , N - 1 , Value , Edges ) NEW_LINE DEDENT |
Rearrange array to maximize count of triplets ( i , j , k ) such that arr [ i ] > arr [ j ] < arr [ k ] and i < j < k | Function to rearrange the array to maximize the count of triplets ; Sort the given array ; Stores the permutations of the given array ; Stores the index of the given array ; Place the first half of the given array ; Place the last half of the given array ; Stores the count of triplets ; Check the given conditions ; Driver Code | def ctTriplets ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE temp = [ 0 ] * N NEW_LINE index = 0 NEW_LINE for i in range ( 1 , N , 2 ) : NEW_LINE INDENT temp [ i ] = arr [ index ] NEW_LINE index += 1 NEW_LINE DEDENT for i in range ( 0 , N , 2 ) : NEW_LINE INDENT temp [ i ] = arr [ index ] NEW_LINE index += 1 NEW_LINE DEDENT ct = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i > 0 and i + 1 < N ) : NEW_LINE INDENT if ( temp [ i ] < temp [ i + 1 ] and temp [ i ] < temp [ i - 1 ] ) : NEW_LINE INDENT ct += 1 NEW_LINE DEDENT DEDENT DEDENT print ( " Count β of β triplets : " , ct ) NEW_LINE print ( " Array : " , end = " " ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( temp [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE ctTriplets ( arr , N ) NEW_LINE |
Rearrange array to make it non | Python3 program for above approach ; Function to check if the array can be made non - decreasing ; Iterate till N ; Find the minimum element ; Sort the array ; Iterate till N ; Check if the element is at its correct position ; Return the answer ; Driver Code ; Print the answer | import sys NEW_LINE def check ( a , n ) : NEW_LINE INDENT b = [ None ] * n NEW_LINE minElement = sys . maxsize NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT b [ i ] = a [ i ] NEW_LINE minElement = min ( minElement , a [ i ] ) NEW_LINE DEDENT b . sort ( ) NEW_LINE k = 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( ( a [ i ] != b [ i ] ) and ( a [ i ] % minElement != 0 ) ) : NEW_LINE INDENT k = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if k == 1 : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 4 , 3 , 6 , 6 , 2 , 9 ] NEW_LINE n = len ( a ) NEW_LINE if check ( a , n ) == True : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Count 1 s in binary matrix having remaining indices of its row and column filled with 0 s | Function to count required 1 s from the given matrix ; Stores the dimensions of the mat ; Calculate sum of rows ; Calculate sum of columns ; Stores required count of 1 s ; If current cell is 1 and sum of row and column is 1 ; Increment count of 1 s ; Return the final count ; Driver Code ; Given matrix ; Function call | def numSpecial ( mat ) : NEW_LINE INDENT m = len ( mat ) NEW_LINE n = len ( mat [ 0 ] ) NEW_LINE rows = [ 0 ] * m NEW_LINE cols = [ 0 ] * n NEW_LINE i , j = 0 , 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT rows [ i ] = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT rows [ i ] += mat [ i ] [ j ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT cols [ i ] = 0 NEW_LINE for j in range ( m ) : NEW_LINE INDENT cols [ i ] += mat [ j ] [ i ] NEW_LINE DEDENT DEDENT cnt = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 and rows [ i ] == 1 and cols [ j ] == 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 0 , 0 ] , [ 0 , 0 , 1 ] , [ 0 , 0 , 0 ] ] NEW_LINE print ( numSpecial ( mat ) ) NEW_LINE DEDENT |
Find all matrix elements which are minimum in their row and maximum in their column | Python3 program for the above approach ; Functionto find all the matrix elements which are minimum in its row and maximum in its column ; Initialize unordered set ; Traverse the matrix ; Update the minimum element of current row ; Insert the minimum element of the row ; Update the maximum element of current column ; Checking if it is already present in the unordered_set or not ; Driver Code ; Function call ; If no such matrix element is found | import sys NEW_LINE def minmaxNumbers ( matrix , res ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 0 , len ( matrix ) , 1 ) : NEW_LINE INDENT minr = sys . maxsize NEW_LINE for j in range ( 0 , len ( matrix [ i ] ) , 1 ) : NEW_LINE INDENT minr = min ( minr , matrix [ i ] [ j ] ) NEW_LINE DEDENT s . add ( minr ) NEW_LINE DEDENT for j in range ( 0 , len ( matrix [ 0 ] ) , 1 ) : NEW_LINE INDENT maxc = - sys . maxsize - 1 NEW_LINE for i in range ( 0 , len ( matrix ) , 1 ) : NEW_LINE INDENT maxc = max ( maxc , matrix [ i ] [ j ] ) NEW_LINE DEDENT if ( maxc in s ) : NEW_LINE INDENT res . append ( maxc ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 10 , 4 ] , [ 9 , 3 , 8 ] , [ 15 , 16 , 17 ] ] NEW_LINE ans = [ ] NEW_LINE minmaxNumbers ( mat , ans ) NEW_LINE if ( len ( ans ) == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] ) NEW_LINE DEDENT DEDENT |
Node whose removal minimizes the maximum size forest from an N | Python3 program to implement the above approach ; Function to create the graph ; Function to traverse the graph and find the minimum of maximum size forest after removing a Node ; Traversing every child subtree except the parent Node ; Traverse all subtrees ; Update the maximum size of forests ; Update the minimum of maximum size of forests obtained ; Condition to find the minimum of maximum size forest ; Update and store the corresponding Node ; Driver Code | mini = 105 ; NEW_LINE ans = 0 ; NEW_LINE n = 0 ; NEW_LINE g = [ ] ; NEW_LINE size = [ 0 ] * 100 ; NEW_LINE def create_graph ( ) : NEW_LINE INDENT g [ 1 ] . append ( 2 ) ; NEW_LINE g [ 2 ] . append ( 1 ) ; NEW_LINE g [ 1 ] . append ( 3 ) ; NEW_LINE g [ 3 ] . append ( 1 ) ; NEW_LINE g [ 1 ] . append ( 4 ) ; NEW_LINE g [ 4 ] . append ( 1 ) ; NEW_LINE g [ 2 ] . append ( 5 ) ; NEW_LINE g [ 5 ] . append ( 2 ) ; NEW_LINE g [ 2 ] . append ( 6 ) ; NEW_LINE g [ 6 ] . append ( 2 ) ; NEW_LINE DEDENT def dfs ( Node , parent ) : NEW_LINE INDENT size [ Node ] = 1 ; NEW_LINE mx = 0 ; NEW_LINE global mini NEW_LINE global ans NEW_LINE for y in g [ Node ] : NEW_LINE INDENT if ( y == parent ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT dfs ( y , Node ) ; NEW_LINE size [ Node ] += size [ y ] ; NEW_LINE mx = max ( mx , size [ y ] ) ; NEW_LINE DEDENT mx = max ( mx , n - size [ Node ] ) ; NEW_LINE if ( mx < mini ) : NEW_LINE INDENT mini = mx ; NEW_LINE ans = Node ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 ; NEW_LINE for i in range ( 100 ) : NEW_LINE INDENT g . append ( [ ] ) NEW_LINE DEDENT create_graph ( ) ; NEW_LINE dfs ( 1 , - 1 ) ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT |
Smallest prefix to be deleted such that remaining array can be rearranged to form a sorted array | Function to find the minimum length of prefix required to be deleted ; Stores index to be returned ; Iterate until previous element is <= current index ; Decrementing index ; Return index ; Driver code ; Given arr ; Function call | def findMinLength ( arr ) : NEW_LINE INDENT index = len ( arr ) - 1 ; NEW_LINE while ( index > 0 and arr [ index ] >= arr [ index - 1 ] ) : NEW_LINE INDENT index -= 1 ; NEW_LINE DEDENT return index ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 8 , 5 , 0 , - 1 , - 1 , 0 , 1 , 2 , 3 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findMinLength ( arr ) ) ; NEW_LINE DEDENT |
Count array elements exceeding sum of preceding K elements | Function to count array elements exceeding sum of preceding K elements ; Iterate over the array ; Update prefix sum ; Check if arr [ K ] > arr [ 0 ] + . . + arr [ K - 1 ] ; Increment count ; Check if arr [ i ] > arr [ i - K - 1 ] + . . + arr [ i - 1 ] ; Increment count ; Driver Code ; Given array | def countPrecedingK ( a , n , K ) : NEW_LINE INDENT prefix = [ 0 ] * n NEW_LINE prefix [ 0 ] = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + a [ i ] NEW_LINE DEDENT ctr = 0 NEW_LINE if ( prefix [ K - 1 ] < a [ K ] ) : NEW_LINE INDENT ctr += 1 NEW_LINE DEDENT for i in range ( K + 1 , n ) : NEW_LINE INDENT if ( prefix [ i - 1 ] - prefix [ i - K - 1 ] < a [ i ] ) : NEW_LINE INDENT ctr += 1 NEW_LINE DEDENT DEDENT return ctr NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 8 , 10 , - 2 , 7 , 5 , 5 , 9 , 15 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( countPrecedingK ( arr , N , K ) ) NEW_LINE DEDENT |
Count minimum moves required to convert A to B | Function to find minimum number of moves to obtained B from A ; Stores the minimum number of moves ; Absolute difference ; K is in range [ 0 , 10 ] ; Print the required moves ; Driver Code | def convertBfromA ( a , b ) : NEW_LINE INDENT moves = 0 NEW_LINE x = abs ( a - b ) NEW_LINE for i in range ( 10 , 0 , - 1 ) : NEW_LINE INDENT moves += x // i NEW_LINE x = x % i NEW_LINE DEDENT print ( moves , end = " β " ) NEW_LINE DEDENT A = 188 NEW_LINE B = 4 NEW_LINE convertBfromA ( A , B ) NEW_LINE |
Count N digits numbers with sum divisible by K | Function to count the N digit numbers whose sum is divisible by K ; Base case ; If already computed subproblem occurred ; Store the count of N digit numbers whoe sum is divisible by K ; Check if the number does not contain any leading 0. ; Recurrence relation ; Driver code ; Stores the values of overlapping subproblems | def countNum ( N , sum , K , st , dp ) : NEW_LINE INDENT if ( N == 0 and sum == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( N < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ N ] [ sum ] [ st ] != - 1 ) : NEW_LINE INDENT return dp [ N ] [ sum ] [ st ] NEW_LINE DEDENT res = 0 NEW_LINE start = 1 NEW_LINE if ( st == 1 ) : NEW_LINE INDENT start = 0 NEW_LINE DEDENT else : NEW_LINE INDENT start = 1 NEW_LINE DEDENT for i in range ( start , 10 ) : NEW_LINE INDENT min = 0 NEW_LINE if ( ( st i ) > 0 ) : NEW_LINE INDENT min = 1 NEW_LINE DEDENT else : NEW_LINE INDENT min = 0 NEW_LINE DEDENT res += countNum ( N - 1 , ( sum + i ) % K , K , min , dp ) NEW_LINE dp [ N ] [ sum ] [ st ] = res NEW_LINE DEDENT return dp [ N ] [ sum ] [ st ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE K = 7 NEW_LINE M = 100 NEW_LINE dp = [ [ [ - 1 for i in range ( 2 ) ] for j in range ( M ) ] for j in range ( M ) ] NEW_LINE print ( countNum ( N , 0 , K , 0 , dp ) ) NEW_LINE DEDENT |
Minimize Nth term of an Arithmetic progression ( AP ) | Python3 program to implement the above approach ; Function to find the smallest Nth term of an AP possible ; Stores the smallest Nth term ; Check if common difference of AP is an integer ; Store the common difference ; Store the First Term of that AP ; Store the Nth term of that AP ; Check if all elements of an AP are positive ; Return the least Nth term obtained ; Driver Code | import sys NEW_LINE def smallestNth ( A , B , N ) : NEW_LINE INDENT res = sys . maxsize NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( N , i , - 1 ) : NEW_LINE INDENT if ( ( B - A ) % ( j - i ) == 0 ) : NEW_LINE INDENT D = ( B - A ) // ( j - i ) NEW_LINE FirstTerm = A - ( i - 1 ) * D NEW_LINE NthTerm = FirstTerm + ( N - 1 ) * D NEW_LINE if ( FirstTerm > 0 ) : NEW_LINE INDENT res = min ( res , NthTerm ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE A = 1 NEW_LINE B = 6 NEW_LINE print ( smallestNth ( A , B , N ) ) NEW_LINE DEDENT |
Subarray of size K with prime sum | Generate all prime numbers in the range [ 1 , 1000000 ] ; Set all numbers as prime initially ; Mark 0 and 1 as non - prime ; If current element is prime ; Mark all its multiples as non - prime ; Function to prthe subarray whose sum of elements is prime ; Store the current subarray of size K ; Calculate the sum of first K elements ; Check if currSum is prime ; Store the start and last index of subarray of size K ; Iterate over remaining array ; Check if currSum ; Driver Code | def sieve ( prime ) : NEW_LINE INDENT for i in range ( 1000000 ) : NEW_LINE INDENT prime [ i ] = True NEW_LINE DEDENT prime [ 0 ] = prime [ 1 ] = False NEW_LINE for i in range ( 2 , 1000 + 1 ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , 1000000 , i ) : NEW_LINE INDENT prime [ j ] = False NEW_LINE DEDENT DEDENT DEDENT return prime NEW_LINE DEDENT def subPrimeSum ( N , K , arr , prime ) : NEW_LINE INDENT currSum = 0 NEW_LINE for i in range ( 0 , K ) : NEW_LINE INDENT currSum += arr [ i ] NEW_LINE DEDENT if ( prime [ currSum ] ) : NEW_LINE INDENT for i in range ( K ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT return NEW_LINE DEDENT st = 1 NEW_LINE en = K NEW_LINE while ( en < N ) : NEW_LINE INDENT currSum += arr [ en ] - arr [ st - 1 ] NEW_LINE if ( prime [ currSum ] ) : NEW_LINE INDENT for i in range ( st , en + 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT return NEW_LINE DEDENT en += 1 NEW_LINE st += 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 20 , 7 , 5 , 4 , 3 , 11 , 99 , 87 , 23 , 45 ] NEW_LINE K = 4 NEW_LINE N = len ( arr ) NEW_LINE prime = [ False ] * 1000000 NEW_LINE prime = sieve ( prime ) NEW_LINE subPrimeSum ( N , K , arr , prime ) NEW_LINE DEDENT |
Minimum characters required to be removed to sort binary string in ascending order | Function to find the minimum count of characters to be removed to make the string sorted in ascending order ; Length of given string ; Stores the first occurrence of '1 ; Stores the last occurrence of '0 ; Traverse the string to find the first occurrence of '1 ; Traverse the string to find the last occurrence of '0 ; Return 0 if the str have only one type of character ; Initialize count1 and count0 to count '1' s before lastIdx0 and '0' s after firstIdx1 ; Traverse the string to count0 ; Traverse the string to count1 ; Return the minimum of count0 and count1 ; Given string str ; Function call | def minDeletion ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE DEDENT ' NEW_LINE INDENT firstIdx1 = - 1 NEW_LINE DEDENT ' NEW_LINE INDENT lastIdx0 = - 1 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT firstIdx1 = i NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT lastIdx0 = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( firstIdx1 == - 1 or lastIdx0 == - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count1 = 0 NEW_LINE count0 = 0 NEW_LINE for i in range ( 0 , lastIdx0 ) : NEW_LINE INDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT DEDENT for i in range ( firstIdx1 + 1 , n ) : NEW_LINE INDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT count0 += 1 NEW_LINE DEDENT DEDENT return min ( count0 , count1 ) NEW_LINE DEDENT str = "1000101" NEW_LINE print ( minDeletion ( str ) ) NEW_LINE |
Maximum score assigned to a subsequence of numerically consecutive and distinct array elements | Function to find the maximum score with unique element in the subset ; Base Case ; Check if the previously picked element differs by 1 from the current element ; Calculate score by including the current element ; Calculate score by excluding the current element ; Return maximum of the two possibilities ; Driver Code ; Given arrays ; Function call | def maximumSum ( a , b , n , index , lastpicked ) : NEW_LINE INDENT if ( index == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT option1 = 0 NEW_LINE option2 = 0 NEW_LINE if ( lastpicked == - 1 or a [ lastpicked ] != a [ index ] ) : NEW_LINE INDENT option1 = b [ index ] + maximumSum ( a , b , n , index + 1 , index ) NEW_LINE DEDENT option2 = maximumSum ( a , b , n , index + 1 , lastpicked ) NEW_LINE return max ( option1 , option2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 3 , 3 , 1 ] NEW_LINE brr = [ - 1 , 2 , 10 , 20 , - 10 , - 9 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maximumSum ( arr , brr , N , 0 , - 1 ) ) NEW_LINE DEDENT |
Replace every element in a circular array by sum of next K elements | Function to print required resultant array ; Reverse the array ; Traverse the range ; Store prefix sum ; Find the prefix sum ; Store the answer ; Calculate the answers ; Count of remaining elements ; Add the sum of all elements y times ; Add the remaining elements ; Update ans [ i ] ; If array is reversed print ans in reverse ; Driver Code ; Given array arr ; Given K ; Function | def sumOfKElements ( arr , n , k ) : NEW_LINE INDENT rev = False ; NEW_LINE if ( k < 0 ) : NEW_LINE INDENT rev = True ; NEW_LINE k *= - 1 ; NEW_LINE l = 0 ; NEW_LINE r = n - 1 ; NEW_LINE while ( l < r ) : NEW_LINE INDENT tmp = arr [ l ] ; NEW_LINE arr [ l ] = arr [ r ] ; NEW_LINE arr [ r ] = tmp ; NEW_LINE l += 1 ; NEW_LINE r -= 1 ; NEW_LINE DEDENT DEDENT dp = [ 0 ] * n ; NEW_LINE dp [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] += dp [ i - 1 ] + arr [ i ] ; NEW_LINE DEDENT ans = [ 0 ] * n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i + k < n ) : NEW_LINE INDENT ans [ i ] = dp [ i + k ] - dp [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT x = k - ( n - 1 - i ) ; NEW_LINE y = x // n ; NEW_LINE rem = x % n ; NEW_LINE ans [ i ] = ( dp [ n - 1 ] - dp [ i ] + y * dp [ n - 1 ] + ( dp [ rem - 1 ] if rem - 1 >= 0 else 0 ) ) ; NEW_LINE DEDENT DEDENT if ( rev ) : NEW_LINE INDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , - 5 , 11 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 3 ; NEW_LINE sumOfKElements ( arr , N , K ) ; NEW_LINE DEDENT |
Count subarrays for every array element in which they are the minimum | Function to find the boundary of every element within which it is minimum ; Perform Binary Search ; Find mid m ; Update l ; Update r ; Inserting the index ; Function to required count subarrays ; Stores the indices of element ; Initialize the output array ; Left boundary , till the element is smallest ; Right boundary , till the element is smallest ; Calculate the number of subarrays based on its boundary ; Adding cnt to the ans ; Driver Code ; Given array arr [ ] ; Function Call | def binaryInsert ( boundary , i ) : NEW_LINE INDENT l = 0 NEW_LINE r = len ( boundary ) - 1 NEW_LINE while l <= r : NEW_LINE INDENT m = ( l + r ) // 2 NEW_LINE if boundary [ m ] < i : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE DEDENT DEDENT boundary . insert ( l , i ) NEW_LINE return l NEW_LINE DEDENT def countingSubarray ( arr , n ) : NEW_LINE INDENT index = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT index [ arr [ i ] ] = i NEW_LINE DEDENT boundary = [ - 1 , n ] NEW_LINE arr . sort ( ) NEW_LINE ans = [ 0 for i in range ( n ) ] NEW_LINE for num in arr : NEW_LINE INDENT i = binaryInsert ( boundary , index [ num ] ) NEW_LINE l = boundary [ i ] - boundary [ i - 1 ] - 1 NEW_LINE r = boundary [ i + 1 ] - boundary [ i ] - 1 NEW_LINE cnt = l + r + l * r + 1 NEW_LINE ans [ index [ num ] ] += cnt NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 5 NEW_LINE arr = [ 3 , 2 , 4 , 1 , 5 ] NEW_LINE print ( countingSubarray ( arr , N ) ) NEW_LINE |
Check if digit cube limit of an integer arrives at fixed point or a limit cycle | Define the limit ; Function to get the sum of cube of digits of a number ; Convert to string to get sum of the cubes of its digits ; Return sum ; Function to check if the number arrives at a fixed point or a cycle ; Stores the values obtained ; Insert N to set s ; Get the next number using F ( N ) ; Check if the next number is repeated or not ; Function to check if digit cube limit of an integer arrives at fixed point or in a limit cycle ; N is a non negative integer ; Function Call ; If the value received is greater than limit ; If the value received is an Armstrong number ; Driver Code ; Function Call | LIMIT = 1000000000 NEW_LINE def F ( N : int ) -> int : NEW_LINE INDENT string = str ( N ) NEW_LINE sum = 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT val = int ( ord ( string [ i ] ) - ord ( '0' ) ) NEW_LINE sum += val * val * val NEW_LINE DEDENT return sum NEW_LINE DEDENT def findDestination ( N : int ) -> int : NEW_LINE INDENT s = set ( ) NEW_LINE prev = N NEW_LINE next = 0 NEW_LINE s . add ( N ) NEW_LINE while ( N <= LIMIT ) : NEW_LINE INDENT next = F ( N ) NEW_LINE if next in s : NEW_LINE INDENT return next NEW_LINE DEDENT prev = next NEW_LINE s . add ( prev ) NEW_LINE N = next NEW_LINE DEDENT return next NEW_LINE DEDENT def digitCubeLimit ( N : int ) -> int : NEW_LINE INDENT if ( N < 0 ) : NEW_LINE INDENT print ( " N β cannot β be β negative " ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = findDestination ( N ) NEW_LINE if ( ans > LIMIT ) : NEW_LINE INDENT print ( " Limit β exceeded " ) NEW_LINE DEDENT elif ( ans == F ( ans ) ) : NEW_LINE INDENT print ( " { } β reaches β to β a β fixed β point : β { } " . format ( N , ans ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " { } β reaches β to β a β limit β cycle : β { } " . format ( N , ans ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE digitCubeLimit ( N ) NEW_LINE DEDENT |
Count quadruples ( i , j , k , l ) in an array such that i < j < k < l and arr [ i ] = arr [ k ] and arr [ j ] = arr [ l ] | Function to count total number of required tuples ; Initialize unordered map ; Find the pairs ( j , l ) such that arr [ j ] = arr [ l ] and j < l ; Elements are equal ; Update the count ; Add the frequency of arr [ l ] to val ; Update the frequency of element arr [ j ] ; Return the answer ; Driver code ; Given array arr [ ] ; Function call | def countTuples ( arr , N ) : NEW_LINE INDENT ans = 0 NEW_LINE val = 0 NEW_LINE freq = { } NEW_LINE for j in range ( N - 2 ) : NEW_LINE INDENT val = 0 NEW_LINE for l in range ( j + 1 , N ) : NEW_LINE INDENT if ( arr [ j ] == arr [ l ] ) : NEW_LINE INDENT ans += val NEW_LINE DEDENT if arr [ l ] in freq : NEW_LINE INDENT val += freq [ arr [ l ] ] NEW_LINE DEDENT DEDENT freq [ arr [ j ] ] = freq . get ( arr [ j ] , 0 ) + 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 2 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countTuples ( arr , N ) ) NEW_LINE DEDENT |
Minimize subarray increments / decrements required to reduce all array elements to 0 | Python3 program of the above approach ; Function to count the minimum number of operations required ; Traverse the array ; If array element is negative ; Update minimum negative ; Update maximum position ; Return minOp ; Driver code | import sys NEW_LINE def minOperation ( arr ) : NEW_LINE INDENT minOp = sys . maxsize NEW_LINE minNeg = 0 NEW_LINE maxPos = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT if ( arr [ i ] < minNeg ) : NEW_LINE INDENT minNeg = arr [ i ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if arr [ i ] > maxPos : NEW_LINE INDENT maxPos = arr [ i ] NEW_LINE DEDENT DEDENT DEDENT return abs ( minNeg ) + maxPos NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 4 , 1 ] NEW_LINE print ( minOperation ( arr ) ) NEW_LINE DEDENT |
Pair of integers having least GCD among all given pairs having GCD exceeding K | Function to calculate the GCD of two numbers ; Function to print the pair having a gcd value just greater than the given integer ; Initialize variables ; Iterate until low less than equal to high ; Calculate mid ; Reducing the search space ; Print the answer ; Driver Code ; Given array and K ; Function call | def GCD ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return GCD ( b , a % b ) NEW_LINE DEDENT def GcdPair ( arr , k ) : NEW_LINE INDENT lo = 0 NEW_LINE hi = len ( arr ) - 1 NEW_LINE ans = [ - 1 , 0 ] NEW_LINE while ( lo <= hi ) : NEW_LINE INDENT mid = lo + ( hi - lo ) // 2 NEW_LINE if ( GCD ( arr [ mid ] [ 0 ] , arr [ mid ] [ 1 ] ) > k ) : NEW_LINE INDENT ans = arr [ mid ] NEW_LINE hi = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT DEDENT if ( len ( ans ) == - 1 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " ( " , ans [ 0 ] , " , " , ans [ 1 ] , " ) " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 3 , 6 ] , [ 15 , 30 ] , [ 25 , 75 ] , [ 30 , 120 ] ] NEW_LINE K = 16 NEW_LINE GcdPair ( arr , K ) NEW_LINE DEDENT |
Check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array | Python3 implementation of the above approach ; Function to check if it is possible to sort array or not ; Store the smallest element ; Copy the original array ; Iterate over the given array ; Update smallest element ; Copy elements of arr to array B ; Sort original array ; Iterate over the given array ; If the i - th element is not in its sorted place ; Not possible to swap ; Driver Code ; Given array ; Function Call | import sys NEW_LINE def isPossible ( arr , N ) : NEW_LINE INDENT mn = sys . maxsize ; NEW_LINE B = [ 0 ] * N ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT mn = min ( mn , arr [ i ] ) ; NEW_LINE B [ i ] = arr [ i ] ; NEW_LINE DEDENT arr . sort ( ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] != B [ i ] ) : NEW_LINE INDENT if ( B [ i ] % mn != 0 ) : NEW_LINE INDENT print ( " No " ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT DEDENT print ( " Yes " ) ; NEW_LINE return ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 ; NEW_LINE arr = [ 4 , 3 , 6 , 6 , 2 , 9 ] ; NEW_LINE isPossible ( arr , N ) ; NEW_LINE DEDENT |
Check if every vertex triplet in graph contains two vertices connected to third vertex | Function to add edge into the graph ; Finding the maximum and minimum values in each component ; Function for checking whether the given graph is valid or not ; Checking for intersecting intervals ; If intersection is found ; Graph is not valid ; Function for the DFS Traversal ; Traversing for every vertex ; Storing maximum and minimum values of each component ; Driver code | def addEdge ( adj , u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE return adj NEW_LINE DEDENT def DFSUtil ( u , adj , visited , componentMin , componentMax ) : NEW_LINE INDENT visited [ u ] = True NEW_LINE componentMax = max ( componentMax , u ) NEW_LINE componentMin = min ( componentMin , u ) NEW_LINE for i in range ( len ( adj [ u ] ) ) : NEW_LINE INDENT if ( visited [ adj [ u ] [ i ] ] == False ) : NEW_LINE INDENT visited , componentMax , componentMin = DFSUtil ( adj [ u ] [ i ] , adj , visited , componentMin , componentMax ) NEW_LINE DEDENT DEDENT return visited , componentMax , componentMin NEW_LINE DEDENT def isValid ( v ) : NEW_LINE INDENT MAX = - 1 NEW_LINE ans = False NEW_LINE for i in v : NEW_LINE INDENT if len ( i ) != 2 : NEW_LINE INDENT continue NEW_LINE DEDENT if ( i [ 0 ] <= MAX ) : NEW_LINE INDENT ans = True NEW_LINE DEDENT MAX = max ( MAX , i [ 1 ] ) NEW_LINE DEDENT return ( True if ans == False else False ) NEW_LINE DEDENT def DFS ( adj , V ) : NEW_LINE INDENT v = [ [ ] ] NEW_LINE visited = [ False for i in range ( V + 1 ) ] NEW_LINE for u in range ( 1 , V + 1 ) : NEW_LINE INDENT if ( visited [ u ] == False ) : NEW_LINE INDENT componentMax = u NEW_LINE componentMin = u NEW_LINE visited , componentMax , componentMin = DFSUtil ( u , adj , visited , componentMin , componentMax ) NEW_LINE v . append ( [ componentMin , componentMax ] ) NEW_LINE DEDENT DEDENT check = isValid ( v ) NEW_LINE if ( check ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT return NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE K = 3 NEW_LINE adj = [ [ ] for i in range ( N + 1 ) ] NEW_LINE adj = addEdge ( adj , 1 , 2 ) NEW_LINE adj = addEdge ( adj , 2 , 3 ) NEW_LINE adj = addEdge ( adj , 3 , 4 ) NEW_LINE DFS ( adj , N ) NEW_LINE DEDENT |
Check if all array elements are present in a given stack or not | Function to check if all array elements is present in the stack ; Store the frequency of array elements ; Loop while the elements in the stack is not empty ; Condition to check if the element is present in the stack ; Driver Code | def checkArrInStack ( s , arr ) : NEW_LINE INDENT freq = { } NEW_LINE for ele in arr : NEW_LINE INDENT freq [ ele ] = freq . get ( ele , 0 ) + 1 NEW_LINE DEDENT while s : NEW_LINE INDENT poppedEle = s . pop ( ) NEW_LINE if poppedEle in freq : NEW_LINE freq [ poppedEle ] -= 1 NEW_LINE if not freq [ poppedEle ] : NEW_LINE INDENT del freq [ poppedEle ] NEW_LINE DEDENT DEDENT if not freq : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = [ 10 , 20 , 30 , 40 , 50 ] NEW_LINE arr = [ 20 , 30 ] NEW_LINE if checkArrInStack ( s , arr ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Length of longest substring to be deleted to make a string equal to another string | Function to prthe length of longest substring to be deleted ; Stores the length of string ; Store the position of previous matched character of str1 ; Store the position of first occurrence of str2 in str1 ; Find the position of the first occurrence of str2 ; Store the index of str1 ; If both characters not matched ; Store the length of the longest deleted substring ; Store the position of last occurrence of str2 in str1 ; If both characters not matched ; Update res ; Update res . ; Given string ; Function call | def longDelSub ( str1 , str2 ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE M = len ( str2 ) NEW_LINE prev_pos = 0 NEW_LINE pos = [ 0 ] * M NEW_LINE for i in range ( M ) : NEW_LINE INDENT index = prev_pos NEW_LINE while ( index < N and str1 [ index ] != str2 [ i ] ) : NEW_LINE INDENT index += 1 NEW_LINE DEDENT pos [ i ] = index NEW_LINE prev_pos = index + 1 NEW_LINE DEDENT res = N - prev_pos NEW_LINE prev_pos = N - 1 NEW_LINE for i in range ( M - 1 , - 1 , - 1 ) : NEW_LINE INDENT index = prev_pos NEW_LINE while ( index >= 0 and str1 [ index ] != str2 [ i ] ) : NEW_LINE INDENT index -= 1 NEW_LINE DEDENT if ( i != 0 ) : NEW_LINE INDENT res = max ( res , index - pos [ i - 1 ] - 1 ) NEW_LINE DEDENT prev_pos = index - 1 NEW_LINE DEDENT res = max ( res , prev_pos + 1 ) NEW_LINE return res NEW_LINE DEDENT str1 = " GeeksforGeeks " NEW_LINE str2 = " forks " NEW_LINE print ( longDelSub ( str1 , str2 ) ) NEW_LINE |
Maximized partitions of a string such that each character of the string appears in one substring | Function to print all the substrings ; Stores the substrings ; Stores last index of characters of string s ; Find the last position of each character in the string ; Update the last index ; Iterate the given string ; Get the last index of s [ i ] ; Extend the current partition characters last pos ; If the current pos of character equals the min pos then the end of partition ; Add the respective character to the string ; Store the partition 's len and reset variables ; Update the minp and str ; Input string ; Function call | def print_substring ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE str = " " NEW_LINE ans = [ ] NEW_LINE if ( n == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT last_pos = [ - 1 ] * 26 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( last_pos [ ord ( s [ i ] ) - ord ( ' a ' ) ] == - 1 ) : NEW_LINE INDENT last_pos [ ord ( s [ i ] ) - ord ( ' a ' ) ] = i NEW_LINE DEDENT DEDENT minp = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT lp = last_pos [ ord ( s [ i ] ) - ord ( ' a ' ) ] NEW_LINE minp = max ( minp , lp ) NEW_LINE if ( i == minp ) : NEW_LINE INDENT str += s [ i ] NEW_LINE print ( str , end = " β " ) NEW_LINE minp = - 1 NEW_LINE str = " " NEW_LINE DEDENT else : NEW_LINE INDENT str += s [ i ] NEW_LINE DEDENT DEDENT DEDENT S = " ababcbacadefegdehijhklij " NEW_LINE print_substring ( S ) NEW_LINE |
Lengths of maximized partitions of a string such that each character of the string appears in one substring | Function to find the length of all partitions oof a string such that each characters occurs in a single substring ; Stores last index of string s ; Find the last position of each letter in the string ; Update the last index ; Iterate the given string ; Get the last index of s [ i ] ; Extend the current partition characters last pos ; Increase len of partition ; if the current pos of character equals the min pos then the end of partition ; Store the length ; Print all the partition lengths ; Given string str ; Function call | def partitionString ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = [ ] NEW_LINE if ( n == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT last_pos = [ - 1 ] * 26 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( last_pos [ ord ( s [ i ] ) - ord ( ' a ' ) ] == - 1 ) : NEW_LINE INDENT last_pos [ ord ( s [ i ] ) - ord ( ' a ' ) ] = i NEW_LINE DEDENT DEDENT minp = - 1 NEW_LINE plen = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT lp = last_pos [ ord ( s [ i ] ) - ord ( ' a ' ) ] NEW_LINE minp = max ( minp , lp ) NEW_LINE plen += 1 NEW_LINE if ( i == minp ) : NEW_LINE INDENT ans . append ( plen ) NEW_LINE minp = - 1 NEW_LINE plen = 0 NEW_LINE DEDENT DEDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT str = " acbbcc " NEW_LINE partitionString ( str ) NEW_LINE |
Find the maximum occurring character after performing the given operations | Function to find the maximum occurring character ; Initialize count of zero and one ; Iterate over the given string ; Count the zeros ; Count the ones ; Iterate over the given string ; Check if character is * then continue ; Check if first character after * is X ; Add all * to the frequency of X ; Set prev to the i - th character ; Check if first character after * is Y ; Set prev to the i - th character ; Check if prev character is 1 and current character is 0 ; Half of the * will be converted to 0 ; Half of the * will be converted to 1 ; Check if prev and current are 1 ; All * will get converted to 1 ; No * can be replaced by either 0 or 1 ; Prev becomes the ith character ; Check if prev and current are 0 ; All * will get converted to 0 ; If frequency of 0 is more ; If frequency of 1 is more ; Given string ; Function call | def solve ( S ) : NEW_LINE INDENT count_0 = 0 NEW_LINE count_1 = 0 NEW_LINE prev = - 1 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT count_0 += 1 NEW_LINE DEDENT elif ( S [ i ] == '1' ) : NEW_LINE INDENT count_1 += 1 NEW_LINE DEDENT DEDENT for i in range ( len ( S ) ) : NEW_LINE INDENT if ( S [ i ] == ' * ' ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( S [ i ] == '0' and prev == - 1 ) : NEW_LINE INDENT count_0 = count_0 + i NEW_LINE prev = i NEW_LINE DEDENT elif ( S [ i ] == '1' and prev == - 1 ) : NEW_LINE INDENT prev = i NEW_LINE DEDENT elif ( S [ prev ] == '1' and S [ i ] == '0' ) : NEW_LINE INDENT count_0 = count_0 + ( i - prev - 1 ) / 2 NEW_LINE count_1 = count_1 + ( i - prev - 1 ) // 2 NEW_LINE prev = i NEW_LINE DEDENT elif ( S [ prev ] == '1' and S [ i ] == '1' ) : NEW_LINE INDENT count_1 = count_1 + ( i - prev - 1 ) NEW_LINE prev = i NEW_LINE DEDENT elif ( S [ prev ] == '0' and S [ i ] == '1' ) : NEW_LINE INDENT prev = i NEW_LINE DEDENT elif ( S [ prev ] == '0' and S [ i ] == '0' ) : NEW_LINE INDENT count_0 = count_0 + ( i - prev - 1 ) NEW_LINE prev = i NEW_LINE DEDENT DEDENT if ( count_0 > count_1 ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT elif ( count_1 > count_0 ) : NEW_LINE INDENT print ( "1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT str = " * *0 * * 1 * * *0" NEW_LINE solve ( str ) NEW_LINE |
Arithmetic Progression containing X and Y with least possible first term | Python3 program for the approach ; Function that finds the minimum positive first term including X with given common difference and the number of terms ; Stores the first term ; Initialize the low and high ; Perform binary search ; Find the mid ; Check if first term is greater than 0 ; Store the possible first term ; Search between mid + 1 to high ; Search between low to mid - 1 ; Return the minimum first term ; Function that finds the Arithmetic Progression with minimum possible first term containing X and Y ; Considering X to be smaller than Y always ; Stores the max common difference ; Stores the minimum first term and the corresponding common difference of the resultant AP ; Iterate over all the common difference ; Check if X and Y is included for current common difference ; Store the possible common difference ; Number of terms from X to Y with diff1 common difference ; Number of terms from X to Y with diff2 common difference ; Find the corresponding first terms with diff1 and diff2 ; Store the minimum first term and the corresponding common difference ; Print the resultant AP ; Driver Code ; Given length of AP and the two terms ; Function call | import sys NEW_LINE def minFirstTerm ( X , diff , N ) : NEW_LINE INDENT first_term_1 = sys . maxsize NEW_LINE low = 0 NEW_LINE high = N NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( X - mid * diff > 0 ) : NEW_LINE INDENT first_term_1 = X - mid * diff NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return first_term_1 NEW_LINE DEDENT def printAP ( N , X , Y ) : NEW_LINE INDENT if ( X > Y ) : NEW_LINE INDENT X = X + Y NEW_LINE Y = X - Y NEW_LINE X = X - Y NEW_LINE DEDENT maxDiff = Y - X NEW_LINE first_term = sys . maxsize NEW_LINE diff = 0 NEW_LINE for i in range ( 1 , maxDiff + 1 ) : NEW_LINE INDENT if i * i > maxDiff : NEW_LINE INDENT break NEW_LINE DEDENT if ( maxDiff % i == 0 ) : NEW_LINE INDENT diff1 = i NEW_LINE diff2 = maxDiff // diff1 NEW_LINE terms1 = diff2 + 1 NEW_LINE terms2 = diff1 + 1 NEW_LINE first_term1 = minFirstTerm ( X , diff1 , N - terms1 ) NEW_LINE first_term2 = minFirstTerm ( X , diff2 , N - terms2 ) NEW_LINE if ( first_term1 < first_term ) : NEW_LINE INDENT first_term = first_term1 NEW_LINE diff = diff1 NEW_LINE DEDENT if ( first_term2 < first_term ) : NEW_LINE INDENT first_term = first_term2 NEW_LINE diff = diff2 NEW_LINE DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( first_term , end = " β " ) NEW_LINE first_term += diff NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE X = 10 NEW_LINE Y = 15 NEW_LINE printAP ( N , X , Y ) NEW_LINE DEDENT |
Check if a number can be represented as sum of two consecutive perfect cubes | Function to check if a number can be expressed as the sum of cubes of two consecutive numbers ; Driver Code | def isCubeSum ( n ) : NEW_LINE INDENT for i in range ( 1 , int ( pow ( n , 1 / 3 ) ) + 1 ) : NEW_LINE INDENT if ( i * i * i + ( i + 1 ) * ( i + 1 ) * ( i + 1 ) == n ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 35 ; NEW_LINE if ( isCubeSum ( n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Check if a number can be represented as sum of two consecutive perfect cubes | Function to check that a number is the sum of cubes of 2 consecutive numbers or not ; Condition to check if a number is the sum of cubes of 2 consecutive numbers or not ; Driver Code ; Function call | def isSumCube ( N ) : NEW_LINE INDENT a = int ( pow ( N , 1 / 3 ) ) NEW_LINE b = a - 1 NEW_LINE ans = ( ( a * a * a + b * b * b ) == N ) NEW_LINE return ans NEW_LINE DEDENT i = 35 NEW_LINE if ( isSumCube ( i ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Maximize sum of remaining elements after every removal of the array half with greater sum | Function to find the maximum sum ; Base case len of array is 1 ; Stores the final result ; Traverse the array ; Store left prefix sum ; Store right prefix sum ; Compare the left and right ; If both are equal apply the optimal method ; Update with minimum ; Return the final ans ; Function to print maximum sum ; Dicitionary to store prefix sums ; Traversing the array ; Add prefix sum of the array ; Drivers Code ; Function Call | def maxweight ( s , e , pre ) : NEW_LINE INDENT if s == e : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( s , e ) : NEW_LINE INDENT left = pre [ i ] - pre [ s - 1 ] NEW_LINE right = pre [ e ] - pre [ i ] NEW_LINE if left < right : NEW_LINE INDENT ans = max ( ans , left + maxweight ( s , i , pre ) ) NEW_LINE DEDENT if left == right : NEW_LINE INDENT ans = max ( ans , left + maxweight ( s , i , pre ) , right + maxweight ( i + 1 , e , pre ) ) NEW_LINE DEDENT if left > right : NEW_LINE INDENT ans = max ( ans , right + maxweight ( i + 1 , e , pre ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def maxSum ( arr ) : NEW_LINE INDENT pre = { - 1 : 0 , 0 : arr [ 0 ] } NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + arr [ i ] NEW_LINE DEDENT print ( maxweight ( 0 , len ( arr ) - 1 , pre ) ) NEW_LINE DEDENT arr = [ 6 , 2 , 3 , 4 , 5 , 5 ] NEW_LINE maxSum ( arr ) NEW_LINE |
Maximum time in HH : MM : SS format that can be represented by given six digits | Function to return the maximum possible time in 24 - Hours format that can be represented by array elements ; Stores the frequency of the array elements ; Maximum possible time ; Iterate to minimum possible time ; Conditions to reduce the the time iteratively ; If all required digits are present in the Map ; Retrieve Original Count ; If seconds is reduced to 0 ; If minutes is reduced to 0 ; Driver Code | def largestTimeFromDigits ( A ) : NEW_LINE INDENT mp1 = { } NEW_LINE mp2 = { } NEW_LINE for x in A : NEW_LINE INDENT mp1 [ x ] = mp1 . get ( x , 0 ) + 1 NEW_LINE DEDENT mp2 = mp1 . copy ( ) NEW_LINE hr = 23 NEW_LINE m = 59 NEW_LINE s = 59 NEW_LINE while ( hr >= 0 ) : NEW_LINE INDENT h0 = hr // 10 NEW_LINE h1 = hr % 10 NEW_LINE m0 = m // 10 NEW_LINE m1 = m % 10 NEW_LINE s0 = s // 10 NEW_LINE s1 = s % 10 NEW_LINE p = 0 NEW_LINE arr = [ h0 , h1 , m0 , m1 , s0 , s1 ] NEW_LINE for it in arr : NEW_LINE INDENT if ( it in mp1 and mp1 . get ( it ) > 0 ) : NEW_LINE INDENT mp1 [ it ] = mp1 . get ( it ) - 1 NEW_LINE DEDENT else : NEW_LINE INDENT p = 1 NEW_LINE DEDENT DEDENT if ( p == 0 ) : NEW_LINE INDENT s = " " NEW_LINE s = ( str ( h0 ) + str ( h1 ) ) NEW_LINE s += ( ' : ' + str ( m0 ) + str ( m1 ) ) NEW_LINE s += ( ' : ' + str ( s0 ) + str ( s1 ) ) NEW_LINE return s NEW_LINE DEDENT mp1 = mp2 . copy ( ) NEW_LINE if ( s == 0 ) : NEW_LINE INDENT s = 59 NEW_LINE m -= 1 NEW_LINE DEDENT elif ( m < 0 ) : NEW_LINE INDENT m = 59 NEW_LINE hr -= 1 NEW_LINE DEDENT if ( s > 0 ) : NEW_LINE INDENT s -= 1 NEW_LINE DEDENT DEDENT return " - 1" NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT v = [ 0 , 2 , 1 , 9 , 3 , 2 ] NEW_LINE print ( largestTimeFromDigits ( v ) ) NEW_LINE DEDENT |
Minimum size substring to be removed to make a given string palindromic | Function to find palindromic prefix of maximum length ; Finding palindromic prefix of maximum length ; Checking if curr substring is palindrome or not . ; Condition to check if the prefix is a palindrome ; if no palindrome exist ; Function to find the maximum size palindrome such that after removing minimum size substring ; Finding prefix and suffix of same length ; Matching the ranges ; Case 1 : Length is even and whole string is palindrome ; Case 2 : Length is odd and whole string is palindrome ; Adding that mid character ; Add prefix or suffix of the remaining string or suffix , whichever is longer ; Reverse the remaining string to find the palindromic suffix ; Driver Code | def palindromePrefix ( S ) : NEW_LINE INDENT n = len ( S ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT curr = S [ 0 : i + 1 ] NEW_LINE l = 0 NEW_LINE r = len ( curr ) - 1 NEW_LINE is_palindrome = 1 NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( curr [ l ] != curr [ r ] ) : NEW_LINE INDENT is_palindrome = 0 NEW_LINE break NEW_LINE DEDENT l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT if ( is_palindrome ) : NEW_LINE INDENT return curr NEW_LINE DEDENT DEDENT return " " NEW_LINE DEDENT def maxPalindrome ( S ) : NEW_LINE INDENT n = len ( S ) NEW_LINE if ( n <= 1 ) : NEW_LINE INDENT return S NEW_LINE DEDENT pre = " " NEW_LINE suff = " " NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE while ( S [ i ] == S [ j ] and i < j ) : NEW_LINE INDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT i -= 1 NEW_LINE j += 1 NEW_LINE pre = S [ 0 : i + 1 ] NEW_LINE suff = S [ j : ] NEW_LINE if ( j - i == 1 ) : NEW_LINE INDENT return pre + suff NEW_LINE DEDENT if ( j - i == 2 ) : NEW_LINE INDENT mid_char = S [ i + 1 : i + 2 ] NEW_LINE return pre + mid_char + suff NEW_LINE DEDENT rem_str = S [ i + 1 : j ] NEW_LINE pre_of_rem_str = palindromePrefix ( rem_str ) NEW_LINE list1 = list ( rem_str ) NEW_LINE list1 . reverse ( ) NEW_LINE rem_str = ' ' . join ( list1 ) NEW_LINE suff_of_rem_str = palindromePrefix ( rem_str ) NEW_LINE if ( len ( pre_of_rem_str ) >= len ( suff_of_rem_str ) ) : NEW_LINE INDENT return ( pre + pre_of_rem_str + suff ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( pre + suff_of_rem_str + suff ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geeksforskeeg " NEW_LINE print ( maxPalindrome ( S ) ) NEW_LINE DEDENT |
Count numbers from a given range that contains a given number as the suffix | Python3 program of the above approach ; Function to count the number ends with given number in range ; Find number of digits in A ; Find the power of 10 ; Incrementing the A ; Driver Code ; Function call | from math import log10 NEW_LINE def countNumEnds ( A , L , R ) : NEW_LINE INDENT count = 0 NEW_LINE digits = int ( log10 ( A ) + 1 ) NEW_LINE temp = int ( pow ( 10 , digits ) ) NEW_LINE cycle = temp NEW_LINE while ( temp <= R ) : NEW_LINE INDENT if ( temp >= L ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT temp += cycle NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT A = 2 NEW_LINE L = 2 NEW_LINE R = 20 NEW_LINE countNumEnds ( A , L , R ) NEW_LINE |
Minimize replacement of characters to its nearest alphabet to make a string palindromic | Function to find the minimum number of operations required to convert th given string into palindrome ; Iterate till half of the string ; Find the absolute difference between the characters ; Adding the minimum difference of the two result ; Return the result ; Given string ; Function call | def minOperations ( s ) : NEW_LINE INDENT length = len ( s ) NEW_LINE result = 0 NEW_LINE for i in range ( length // 2 ) : NEW_LINE INDENT D1 = ( ord ( max ( s [ i ] , s [ length - 1 - i ] ) ) - ord ( min ( s [ i ] , s [ length - 1 - i ] ) ) ) NEW_LINE D2 = 26 - D1 NEW_LINE result += min ( D1 , D2 ) NEW_LINE DEDENT return result NEW_LINE DEDENT s = " abccdb " NEW_LINE print ( minOperations ( s ) ) NEW_LINE |
Check if all the pairs of an array are coprime with each other | Function to store and check the factors ; Check if factors are equal ; Check if the factor is already present ; Insert the factor in set ; Check if the factor is already present ; Insert the factors in set ; Function to check if all the pairs of array elements are coprime with each other ; Check if factors of A [ i ] haven 't occurred previously ; Driver code | def findFactor ( value , factors ) : NEW_LINE INDENT factors . add ( value ) NEW_LINE i = 2 NEW_LINE while ( i * i <= value ) : NEW_LINE if value % i == 0 : NEW_LINE INDENT if value // i == i : NEW_LINE if i in factors : NEW_LINE INDENT return bool ( True ) NEW_LINE DEDENT else : NEW_LINE INDENT factors . add ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( i in factors ) or NEW_LINE ( ( value // i ) in factors ) : NEW_LINE return bool ( True ) NEW_LINE else : NEW_LINE factors . add ( i ) NEW_LINE factors . add ( value // i ) NEW_LINE DEDENT DEDENT i += 1 NEW_LINE return bool ( False ) NEW_LINE DEDENT def allCoprime ( A , n ) : NEW_LINE INDENT all_coprime = bool ( True ) NEW_LINE factors = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if A [ i ] == 1 : NEW_LINE INDENT continue NEW_LINE DEDENT if findFactor ( A [ i ] , factors ) : NEW_LINE all_coprime = bool ( False ) NEW_LINE break NEW_LINE DEDENT return bool ( all_coprime ) NEW_LINE DEDENT A = [ 3 , 5 , 11 , 7 , 19 ] NEW_LINE arr_size = len ( A ) NEW_LINE if ( allCoprime ( A , arr_size ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Count subsequences which contains both the maximum and minimum array element | Function to calculate the count of subsequences ; Find the maximum from the array ; Find the minimum from the array ; If array contains only one distinct element ; Find the count of maximum ; Find the count of minimum ; Finding the result with given condition ; Driver Code ; Function call | def countSubSequence ( arr , n ) : NEW_LINE INDENT maximum = max ( arr ) NEW_LINE minimum = min ( arr ) NEW_LINE if maximum == minimum : NEW_LINE INDENT return pow ( 2 , n ) - 1 NEW_LINE DEDENT i = arr . count ( maximum ) NEW_LINE j = arr . count ( minimum ) NEW_LINE res = ( pow ( 2 , i ) - 1 ) * ( pow ( 2 , j ) - 1 ) * pow ( 2 , n - i - j ) NEW_LINE return res NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countSubSequence ( arr , n ) ) NEW_LINE |
Minimize elements to be added to a given array such that it contains another given array as its subsequence | Function that finds the minimum number of the element must be added to make A as a subsequence in B ; Base Case ; dp [ i ] [ j ] indicates the length of LCS of A of length i & B of length j ; If there are no elements either in A or B then the length of lcs is 0 ; If the element present at ith and jth index of A and B are equal then include in LCS ; If they are not equal then take the max ; Return difference of length of A and lcs of A and B ; Driver Code ; Given Sequence A and B ; Function Call | def transformSubsequence ( n , m , A , B ) : NEW_LINE INDENT if B is None or len ( B ) == 0 : NEW_LINE INDENT return n NEW_LINE DEDENT dp = [ [ 0 for col in range ( m + 1 ) ] for row 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 n - dp [ n ] [ m ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE M = 6 NEW_LINE A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE B = [ 2 , 5 , 6 , 4 , 9 , 12 ] NEW_LINE print ( transformSubsequence ( N , M , A , B ) ) NEW_LINE DEDENT |
Check if the sum of a subarray within a given range is a perfect square or not | Function to calculate the square root of the sum of a subarray in a given range ; Calculate the sum of array elements within a given range ; Finding the square root ; If a perfect square is found ; Reduce the search space if the value is greater than sum ; Reduce the search space if the value if smaller than sum ; Driver Code ; Given Array ; Given range ; Function call | def checkForPerfectSquare ( arr , i , j ) : NEW_LINE INDENT mid , sum = 0 , 0 NEW_LINE for m in range ( i , j + 1 ) : NEW_LINE INDENT sum += arr [ m ] NEW_LINE DEDENT low = 0 NEW_LINE high = sum // 2 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( mid * mid == sum ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( mid * mid > sum ) : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 19 , 33 , 48 , 90 , 100 ] NEW_LINE L = 1 NEW_LINE R = 3 NEW_LINE print ( checkForPerfectSquare ( arr , L , R ) ) NEW_LINE DEDENT |
Count of subarrays forming an Arithmetic Progression ( AP ) | Function to find the total count of subarrays ; Iterate over each subarray ; Difference between first two terms of subarray ; Iterate over the subarray from i to j ; Check if the difference of all adjacent elements is same ; Driver Code ; Given array ; Function call | def calcSubarray ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT flag = True NEW_LINE comm_diff = A [ i + 1 ] - A [ i ] NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT if ( A [ k + 1 ] - A [ k ] == comm_diff ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 8 , 7 , 4 , 1 , 0 ] NEW_LINE N = len ( A ) NEW_LINE print ( calcSubarray ( A , N ) ) NEW_LINE DEDENT |
Largest Sum Contiguous Subarray having unique elements | Function to calculate required maximum subarray sum ; Initialize two pointers ; Stores the unique elements ; Insert the first element ; Current max sum ; Global maximum sum ; Update sum & increment j ; Add the current element ; Update sum and increment i and remove arr [ i ] from set ; Remove the element from start position ; Return the maximum sum ; Driver Code ; Given array arr [ ] ; Function call ; Print the maximum sum | def maxSumSubarray ( arr ) : NEW_LINE INDENT i = 0 NEW_LINE j = 1 NEW_LINE set = { } NEW_LINE set [ arr [ 0 ] ] = 1 NEW_LINE sum = arr [ 0 ] NEW_LINE maxsum = sum NEW_LINE while ( i < len ( arr ) - 1 and j < len ( arr ) ) : NEW_LINE INDENT if arr [ j ] not in set : NEW_LINE INDENT sum = sum + arr [ j ] NEW_LINE maxsum = max ( sum , maxsum ) NEW_LINE set [ arr [ j ] ] = 1 NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum -= arr [ i ] NEW_LINE del set [ arr [ i ] ] NEW_LINE i += 1 NEW_LINE DEDENT DEDENT return maxsum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 1 , 5 ] NEW_LINE ans = maxSumSubarray ( arr ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Count of numbers having only one unset bit in a range [ L , R ] | Python3 program for the above approach ; Function to count numbers in the range [ l , r ] having exactly one unset bit ; Stores the required count ; Iterate over the range ; Calculate number of bits ; Calculate number of set bits ; If count of unset bits is 1 ; Increment answer ; Return the answer ; Driver Code ; Function call | from math import log2 NEW_LINE def count_numbers ( L , R ) : NEW_LINE INDENT ans = 0 NEW_LINE for n in range ( L , R + 1 ) : NEW_LINE INDENT no_of_bits = int ( log2 ( n ) + 1 ) NEW_LINE no_of_set_bits = bin ( n ) . count ( '1' ) NEW_LINE if ( no_of_bits - no_of_set_bits == 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 4 NEW_LINE R = 9 NEW_LINE print ( count_numbers ( L , R ) ) NEW_LINE DEDENT |
Count of numbers having only one unset bit in a range [ L , R ] | Python3 program for the above approach ; Function to count numbers in the range [ L , R ] having exactly one unset bit ; Stores the count elements having one zero in binary ; Stores the maximum number of bits needed to represent number ; Loop over for zero bit position ; Number having zero_bit as unset and remaining bits set ; Sets all bits before zero_bit ; Set the bit at position j ; Set the bit position at j ; If cur is in the range [ L , R ] , then increment ans ; Return ans ; Driver Code ; Function Call | import math NEW_LINE def count_numbers ( L , R ) : NEW_LINE INDENT ans = 0 ; NEW_LINE LogR = ( int ) ( math . log ( R ) + 1 ) ; NEW_LINE for zero_bit in range ( LogR ) : NEW_LINE INDENT cur = 0 ; NEW_LINE for j in range ( zero_bit ) : NEW_LINE INDENT cur |= ( 1 << j ) ; NEW_LINE DEDENT for j in range ( zero_bit + 1 , LogR ) : NEW_LINE INDENT cur |= ( 1 << j ) ; NEW_LINE if ( cur >= L and cur <= R ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 4 ; NEW_LINE R = 9 ; NEW_LINE print ( count_numbers ( L , R ) ) ; NEW_LINE DEDENT |
Sum of all distances between occurrences of same characters in a given string | Function to calculate the sum of distances between occurrences of same characters in a string ; If similar characters are found ; Add the difference of their positions ; Return the answer ; Driver Code | def findSum ( s ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT sum += ( j - i ) NEW_LINE DEDENT DEDENT DEDENT return sum NEW_LINE DEDENT s = " ttt " NEW_LINE print ( findSum ( s ) ) NEW_LINE |
Count array elements that can be represented as sum of at least two consecutive array elements | Function to find the number of array elements that can be represented as the sum of two or more consecutive array elements ; Stores the frequencies of array elements ; Stores required count ; Update frequency of each array element ; Find sum of all subarrays ; Increment ans by cnt [ sum ] ; Reset cnt [ sum ] by 0 ; Return ans ; Driver Code ; Given array ; Function call | def countElements ( a , n ) : NEW_LINE INDENT cnt = [ 0 ] * ( n + 1 ) NEW_LINE ans = 0 NEW_LINE for k in a : NEW_LINE INDENT cnt [ k ] += 1 NEW_LINE DEDENT for l in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for r in range ( l , n ) : NEW_LINE INDENT sum += a [ r ] NEW_LINE if ( l == r ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( sum <= n ) : NEW_LINE INDENT ans += cnt [ sum ] NEW_LINE cnt [ sum ] = 0 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 1 , 1 , 1 , 1 ] NEW_LINE print ( countElements ( a , len ( a ) ) ) NEW_LINE DEDENT |
Maximum GCD among all pairs ( i , j ) of first N natural numbers | Python3 program for the above approach ; Function to find maximum gcd of all pairs possible from first n natural numbers ; Stores maximum gcd ; Iterate over all possible pairs ; Update maximum GCD ; Driver Code | def __gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT else : NEW_LINE INDENT return __gcd ( b , a % b ) ; NEW_LINE DEDENT DEDENT def maxGCD ( n ) : NEW_LINE INDENT maxHcf = - 2391734235435 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n + 1 ) : NEW_LINE INDENT maxHcf = max ( maxHcf , __gcd ( i , j ) ) ; NEW_LINE DEDENT DEDENT return maxHcf ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE print ( maxGCD ( n ) ) ; NEW_LINE DEDENT |
Subsets and Splits