text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Count number of triangles possible for the given sides range | Function to count the number of possible triangles for the given sides ranges ; Iterate for every possible of x ; Range of y is [ b , c ] From this range First we will find the number of x + y greater than d ; For x + y greater than d we can choose all z from [ c , d ] Total permutation will be ; Now we will find the number of x + y in between the [ c , d ] ; [ l , r ] will be the range from total [ c , d ] x + y belongs For any r such that r = x + y We can choose z , in the range [ c , d ] only less than r , Thus total permutation be ; Driver Code
def count_triangles ( a , b , c , d ) : NEW_LINE INDENT ans = 0 NEW_LINE for x in range ( a , b + 1 ) : NEW_LINE INDENT num_greater_than_d = ( max ( d , c + x ) - max ( d , b + x - 1 ) ) NEW_LINE ans = ( ans + num_greater_than_d * ( d - c + 1 ) ) NEW_LINE r = min ( max ( c , c + x ) , d ) - c ; NEW_LINE l = min ( max ( c , b + x - 1 ) , d ) - c ; NEW_LINE x1 = int ( ( r * ( r + 1 ) ) / 2 ) NEW_LINE x2 = int ( ( l * ( l + 1 ) ) / 2 ) NEW_LINE ans = ans + ( x1 - x2 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT a = 2 NEW_LINE b = 3 NEW_LINE c = 4 NEW_LINE d = 5 NEW_LINE print ( count_triangles ( a , b , c , d ) , end = ' ' ) NEW_LINE
Minimum number of swaps required to make the string K periodic | Python3 code to find the minimum number of swaps required to make the string K periodic ; Mark all allowed characters as true ; Initialize the freq array to 0 ; Increase the frequency of each character ; Total number of periods of size K in the string ; Check if the current character is present in allowed and whether the current frequency is greater than all previous frequencies for this position ; Update the answer by subtracting the maxfrequency from total positions if there exist extra character at the end of the string apart from the n / k characters then add 1. ; Driver code
def minFlip ( s , n , k , a , p ) : NEW_LINE INDENT allowed = [ 0 ] * 26 NEW_LINE for i in range ( p ) : NEW_LINE INDENT allowed [ ord ( a [ i ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT freq = [ [ 0 for x in range ( 26 ) ] for y in range ( k ) ] NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( 26 ) : NEW_LINE INDENT freq [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT freq [ i % k ] [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE totalpositions = n // k NEW_LINE for i in range ( k ) : NEW_LINE INDENT maxfrequency = 0 NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] [ j ] > maxfrequency and allowed [ j ] == True ) : NEW_LINE INDENT maxfrequency = freq [ i ] [ j ] NEW_LINE DEDENT DEDENT ans += ( totalpositions - maxfrequency ) NEW_LINE if ( i % k < n % k ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " nihsiakyt " NEW_LINE n = len ( S ) NEW_LINE K = 3 NEW_LINE A = [ ' n ' , ' i ' , ' p ' , ' s ' , ' q ' ] NEW_LINE p = len ( A ) NEW_LINE minFlip ( S , n , K , A , p ) NEW_LINE DEDENT
Minimum number of colors required to color a Circular Array | Function that finds minimum number of colors required ; To check that if all the elements are same or not ; To check if only one adjacent exist ; Traverse the array ; If adjacent elements found different means all are not same ; If two adjacent elements found to be same then make one_adjacent_same true ; If all elements are same then print 1 ; If total number of elements are even or there exist two adjacent elements that are same then print 2 ; Else 3 type of colors are required ; Driver Code ; Function call
def colorRequired ( arr , n ) : NEW_LINE INDENT all_same = True NEW_LINE one_adjacent_same = False NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i + 1 ] ) : NEW_LINE INDENT all_same = False NEW_LINE DEDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT one_adjacent_same = True NEW_LINE DEDENT DEDENT if ( all_same == True ) : NEW_LINE INDENT print ( 1 ) NEW_LINE return NEW_LINE DEDENT if ( n % 2 == 0 or one_adjacent_same == True ) : NEW_LINE INDENT print ( 2 ) NEW_LINE return NEW_LINE DEDENT print ( 3 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE colorRequired ( arr , n ) NEW_LINE DEDENT
Maximize the sum of sum of the Array by removing end elements | Function to find the maximum sum of sum ; Compute the sum of whole array ; Traverse and remove the minimum value from an end to maximum the sum value ; If the left end element is smaller than right end ; Remove the left end element ; If the right end element is smaller than left end ; Remove the right end element ; Add the remaining element sum in the result ; Return the maximum sum of sum ; Driver code
def maxRemainingSum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT i = 0 NEW_LINE j = n - 1 NEW_LINE result = 0 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( arr [ i ] < arr [ j ] ) : NEW_LINE INDENT sum -= arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum -= arr [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT result += sum ; NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 3 , 1 , 7 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maxRemainingSum ( arr , N ) ) NEW_LINE
Split a number as sum of K numbers which are not divisible by K | Function to split into K parts and print them ; Print 1 K - 1 times ; Print N - K + 1 ; Print 1 K - 2 times ; Print 2 and N - K ; Driver code
def printKParts ( N , K ) : NEW_LINE INDENT if ( N % K == 0 ) : NEW_LINE INDENT for i in range ( 1 , K ) : NEW_LINE INDENT print ( "1 , ▁ " ) ; NEW_LINE DEDENT print ( N - ( K - 1 ) , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( K == 2 ) : NEW_LINE INDENT print ( " Not ▁ Possible " , end = " " ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT for i in range ( 1 , K - 1 ) : NEW_LINE INDENT print ( 1 , end = " , ▁ " ) ; NEW_LINE DEDENT print ( 2 , " , ▁ " , ( N - K ) , end = " " ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 18 ; NEW_LINE K = 5 ; NEW_LINE printKParts ( N , K ) ; NEW_LINE DEDENT
Make the intervals non | Function to assign the intervals to two different processors ; Loop to pair the interval with their indices ; sorting the interval by their startb times ; Loop to iterate over the intervals with their start time ; Condition to check if there is a possible solution ; form = ''.join(form) ; Driver Code ; Function Call
def assignIntervals ( interval , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT interval [ i ] . append ( i ) NEW_LINE DEDENT interval . sort ( key = lambda x : x [ 0 ] ) NEW_LINE firstEndTime = - 1 NEW_LINE secondEndTime = - 1 NEW_LINE fin = ' ' NEW_LINE flag = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT if interval [ i ] [ 0 ] >= firstEndTime : NEW_LINE INDENT firstEndTime = interval [ i ] [ 1 ] NEW_LINE interval [ i ] . append ( ' S ' ) NEW_LINE DEDENT elif interval [ i ] [ 0 ] >= secondEndTime : NEW_LINE INDENT secondEndTime = interval [ i ] [ 1 ] NEW_LINE interval [ i ] . append ( ' F ' ) NEW_LINE DEDENT else : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if flag : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT form = [ ' ' ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT indi = interval [ i ] [ 2 ] NEW_LINE form [ indi ] = interval [ i ] [ 3 ] NEW_LINE DEDENT print ( form , " , ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT intervals = [ [ 360 , 480 ] , [ 420 , 540 ] , [ 600 , 660 ] ] NEW_LINE assignIntervals ( intervals , len ( intervals ) ) NEW_LINE DEDENT
Minimum operation required to make a balanced sequence | Python3 implementation of the approach ; Function to return the minimum operations required ; Condition where we got only one closing bracket instead of 2 , here we have to add one more closing bracket to make the sequence balanced ; Add closing bracket that costs us one operation ; Remove the top opening bracket because we got the 1 opening and 2 continuous closing brackets ; Inserting the opening bracket to stack ; After making the sequence balanced closing is now set to 0 ; Case when there is no opening bracket the sequence starts with a closing bracket and one opening bracket is required Now we have one opening and one closing bracket ; Add opening bracket that costs us one operation ; Assigning 1 to cntClosing because we have one closing bracket ; Case where we got two continuous closing brackets need to pop one opening bracket from stack top ; Condition where stack is not empty This is the case where we have only opening brackets ( st . size ( ) * 2 ) will give us the total closing bracket needed cntClosing is the count of closing bracket that we already have ; Driver code
from queue import LifoQueue NEW_LINE def minOperations ( s , len ) : NEW_LINE INDENT operationCnt = 0 ; NEW_LINE st = LifoQueue ( ) ; NEW_LINE cntClosing = 0 ; NEW_LINE for i in range ( 0 , len ) : NEW_LINE INDENT if ( s [ i ] == ' { ' ) : NEW_LINE INDENT if ( cntClosing > 0 ) : NEW_LINE INDENT operationCnt += 1 ; NEW_LINE st . pop ( ) ; NEW_LINE DEDENT st . put ( s [ i ] ) ; NEW_LINE cntClosing = 0 ; NEW_LINE DEDENT elif ( st . empty ( ) ) : NEW_LINE INDENT st . put ( ' { ' ) ; NEW_LINE operationCnt += 1 ; NEW_LINE cntClosing = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT cntClosing = ( cntClosing + 1 ) % 2 ; NEW_LINE if ( cntClosing == 0 ) : NEW_LINE INDENT st . pop ( ) ; NEW_LINE DEDENT DEDENT DEDENT operationCnt += st . qsize ( ) * 2 - cntClosing + 1 ; NEW_LINE return operationCnt ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " { " ; NEW_LINE print ( minOperations ( str , 1 ) ) ; NEW_LINE DEDENT
Longest subsequence with different adjacent characters | Function to find the longest Subsequence with different adjacent character ; Length of the string s ; Previously picked character ; If the current character is different from the previous then include this character and update previous character ; Driver Code ; Function call
def longestSubsequence ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE answer = 0 ; NEW_LINE prev = ' - ' ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( prev != s [ i ] ) : NEW_LINE INDENT prev = s [ i ] ; NEW_LINE answer += 1 ; NEW_LINE DEDENT DEDENT return answer ; NEW_LINE DEDENT str = " ababa " ; NEW_LINE print ( longestSubsequence ( str ) ) ; NEW_LINE
Length of longest subarray of length at least 2 with maximum GCD | Function to calculate GCD of two numbers ; Function to find maximum size subarray having maximum GCD ; Base case ; Let the maximum GCD be 1 initially ; Loop through array to find maximum GCD of subarray with size 2 ; Traverse the array ; Is a multiple of k , increase cnt ; Else update maximum length with consecutive element divisible by k Set cnt to 0 ; Update the maxLength ; Return the maxLength ; Driver Code ; 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 maxGcdSubarray ( arr , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT k = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT k = max ( k , gcd ( arr [ i ] , arr [ i - 1 ] ) ) NEW_LINE DEDENT cnt = 0 NEW_LINE maxLength = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] % k == 0 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT maxLength = max ( maxLength , cnt ) NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT maxLength = max ( maxLength , cnt ) NEW_LINE return maxLength NEW_LINE DEDENT arr = [ 18 , 3 , 6 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxGcdSubarray ( arr , n ) ) NEW_LINE
Split N powers of 2 into two subsets such that their difference of sum is minimum | Python3 program to find the minimum difference possible by splitting all powers of 2 up to N into two sets of equal size ; Store the largest ; Form two separate groups ; Initialize the sum for two groups as 0 ; Insert 2 ^ n in the first group ; Calculate the sum of least n / 2 - 1 elements added to the first set ; sum of remaining n / 2 - 1 elements ; Min Difference between the two groups ; Driver code
def MinDiff ( n ) : NEW_LINE INDENT val = 2 ** n NEW_LINE sep = n // 2 NEW_LINE grp1 = 0 NEW_LINE grp2 = 0 NEW_LINE grp1 = grp1 + val NEW_LINE for i in range ( 1 , sep ) : NEW_LINE INDENT grp1 = grp1 + 2 ** i NEW_LINE DEDENT for i in range ( sep , n ) : NEW_LINE INDENT grp2 = grp2 + 2 ** i NEW_LINE DEDENT print ( abs ( grp1 - grp2 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE MinDiff ( n ) NEW_LINE DEDENT
Count elements in first Array with absolute difference greater than K with an element in second Array | Function to count the such elements ; Store count of required elements in arr1 ; Initialise the smallest and the largest value from the second array arr2 [ ] ; Find the smallest and the largest element in arr2 ; Check if absolute difference of smallest and arr1 [ i ] or largest and arr1 [ i ] is > K then arr [ i ] is a required element ; Print final result ; Driver code
def countDist ( arr1 , n , arr2 , m , k ) : NEW_LINE INDENT count = 0 NEW_LINE smallest = arr2 [ 0 ] NEW_LINE largest = arr2 [ 0 ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT smallest = max ( smallest , arr2 [ i ] ) NEW_LINE largest = min ( largest , arr1 [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( abs ( arr1 [ i ] - smallest ) > k or abs ( arr1 [ i ] - largest ) > k ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 3 , 1 , 4 ] NEW_LINE n = len ( arr1 ) NEW_LINE arr2 = [ 5 , 1 , 2 ] NEW_LINE m = len ( arr2 ) NEW_LINE k = 2 NEW_LINE countDist ( arr1 , n , arr2 , m , k ) NEW_LINE DEDENT
Make sum of all subarrays of length K equal by only inserting elements | Function that prints another array whose all subarray of length k have an equal sum ; Store all distinct elements in the unordered map ; Condition if the number of distinct elements is greater than k ; Push all distinct elements in a vector ; Push 1 while the size of vector not equal to k ; Print the vector 2 times ; Driver Code
def MakeArray ( a , n , k ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in a : NEW_LINE INDENT if i not in mp : NEW_LINE INDENT mp [ a [ i ] ] = 1 NEW_LINE DEDENT DEDENT if ( len ( mp ) > k ) : NEW_LINE print ( " Not ▁ possible " ) NEW_LINE return NEW_LINE ans = [ ] NEW_LINE for i in mp : NEW_LINE INDENT ans . append ( i ) NEW_LINE DEDENT while ( len ( ans ) < k ) : NEW_LINE INDENT ans . append ( 1 ) NEW_LINE DEDENT for i in range ( 2 ) : NEW_LINE INDENT for j in range ( k ) : NEW_LINE INDENT print ( ans [ j ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 1 ] NEW_LINE K = 2 NEW_LINE size = len ( arr ) NEW_LINE MakeArray ( arr , size , K ) NEW_LINE DEDENT
Longest substring with atmost K characters from the given set of characters | Function to find the longest substring in the string which contains atmost K characters from the given set of characters ; Base Condition ; Count for Characters from set in substring ; Two pointers ; Loop to iterate until right pointer is not equal to N ; Loop to increase the substring length until the characters from set are at most K ; Check if current pointer points a character from set ; If the count of the char is exceeding the limit ; update answer with substring length ; Increment the left pointer until the count is less than or equal to K ; If the character which comes out then decrement the count by 1 ; Driver Code ; Construction of set ; Output result
def maxNormalSubstring ( P , Q , K , N ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 0 NEW_LINE left = 0 NEW_LINE right = 0 NEW_LINE ans = 0 NEW_LINE while ( right < N ) : NEW_LINE INDENT while ( right < N and count <= K ) : NEW_LINE INDENT if ( P [ right ] in Q ) : NEW_LINE INDENT if ( count + 1 > K ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT right += 1 NEW_LINE if ( count <= K ) : NEW_LINE INDENT ans = max ( ans , right - left ) NEW_LINE DEDENT DEDENT while ( left < right ) : NEW_LINE INDENT left += 1 NEW_LINE if ( P [ left - 1 ] in Q ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( count < K ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT P = " giraffe " NEW_LINE Q = { chr } NEW_LINE Q . add ( ' a ' ) NEW_LINE Q . add ( ' f ' ) NEW_LINE Q . add ( ' g ' ) NEW_LINE Q . add ( ' r ' ) NEW_LINE K = 2 NEW_LINE N = len ( P ) NEW_LINE print ( maxNormalSubstring ( P , Q , K , N ) ) NEW_LINE
Find the minimum value of the given expression over all pairs of the array | Python3 program to find the minimum value of the given expression over all pairs of the array ; Function to find the minimum value of the expression ; Iterate over all the pairs and find the minimum value ; Driver code
import sys NEW_LINE def MinimumValue ( a , n ) : NEW_LINE INDENT answer = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n , 1 ) : NEW_LINE INDENT answer = min ( answer , ( ( a [ i ] & a [ j ] ) ^ ( a [ i ] a [ j ] ) ) ) NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE A = [ 12 , 3 , 14 , 5 , 9 , 8 ] NEW_LINE print ( MinimumValue ( A , N ) ) NEW_LINE DEDENT
Number of substrings with length divisible by the number of 1 's in it | Function return count of such substring ; Mark 1 at those indices where '1' appears ; Take prefix sum ; Iterate through all the substrings ; Driver Code
def countOfSubstrings ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE prefix_sum = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT prefix_sum [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , n , 1 ) : NEW_LINE INDENT prefix_sum [ i ] += prefix_sum [ i - 1 ] NEW_LINE DEDENT answer = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n , 1 ) : NEW_LINE INDENT if ( i - 1 >= 0 ) : NEW_LINE INDENT countOfOnes = prefix_sum [ j ] - prefix_sum [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT countOfOnes = prefix_sum [ j ] NEW_LINE DEDENT length = j - i + 1 NEW_LINE if ( countOfOnes > 0 and length % countOfOnes == 0 ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "1111100000" NEW_LINE print ( countOfSubstrings ( S ) ) NEW_LINE DEDENT
Find the number of elements X such that X + K also exists in the array | Function to return the count of element x such that x + k also lies in this array ; Key in map will store elements and value will store the frequency of the elements ; Find if i . first + K is present in this map or not ; If we find i . first or key + K in this map then we have to increase in answer the frequency of this element ; Driver code ; array initialisation ; size of array ; initialise k
def count_element ( N , K , arr ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT mp [ arr [ i ] ] = mp . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT answer = 0 NEW_LINE for i in mp : NEW_LINE INDENT if i + K in mp : NEW_LINE INDENT answer += mp [ i ] NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 2 , 8 , 7 , 6 , 5 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( count_element ( N , K , arr ) ) NEW_LINE DEDENT
Find the size of largest group where groups are according to the xor of digits | Function to find out xor of digit ; Calculate xor digitwise ; Return xor ; Function to find the size of largest group ; Hash map for counting frequency ; Counting freq of each element ; Find the maximum ; Initialise N
def digit_xor ( x ) : NEW_LINE INDENT xorr = 0 NEW_LINE while ( x != 0 ) : NEW_LINE INDENT xorr ^= x % 10 NEW_LINE x = x // 10 NEW_LINE DEDENT return xorr NEW_LINE DEDENT def find_count ( n ) : NEW_LINE INDENT mpp = { } NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if digit_xor ( i ) in mpp : NEW_LINE INDENT mpp [ digit_xor ( i ) ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mpp [ digit_xor ( i ) ] = 1 NEW_LINE DEDENT DEDENT maxm = 0 NEW_LINE for x in mpp : NEW_LINE INDENT if ( mpp [ x ] > maxm ) : NEW_LINE INDENT maxm = mpp [ x ] NEW_LINE DEDENT DEDENT return maxm NEW_LINE DEDENT N = 13 NEW_LINE print ( find_count ( N ) ) NEW_LINE
Count of largest sized groups while grouping according to product of digits | Function to find out product of digit ; calculate product ; return the product of digits ; Function to find the count ; hash map for counting frequency ; counting freq of each element ; find the maximum ; count the number of groups having size of equal to largest group . ; initialise N
def digit_prod ( x ) : NEW_LINE INDENT prod = 1 NEW_LINE while ( x ) : NEW_LINE INDENT prod = prod * ( x % 10 ) NEW_LINE x = x // 10 NEW_LINE DEDENT return prod NEW_LINE DEDENT def find_count ( n ) : NEW_LINE INDENT mpp = { } NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT x = digit_prod ( i ) NEW_LINE if x in mpp : NEW_LINE INDENT mpp [ x ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mpp [ x ] = 1 NEW_LINE DEDENT DEDENT ans = 1 NEW_LINE maxm = 0 NEW_LINE for value in mpp . values ( ) : NEW_LINE INDENT if ( value > maxm ) : NEW_LINE INDENT maxm = value NEW_LINE ans = 1 NEW_LINE DEDENT elif ( value == maxm ) : NEW_LINE INDENT ans = ans + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT N = 13 NEW_LINE print ( find_count ( N ) ) NEW_LINE
Count of subarrays having exactly K prime numbers | Python3 program for the above approach ; A utility function to check if the number n is prime or not ; Base Cases ; Check to skip middle five numbers in below loop ; If n is divisible by i & i + 2 then it is not prime ; Function to find number of subarrays with sum exactly equal to k ; STL map to store number of subarrays starting from index zero having particular value of sum . ; To store the sum of element traverse so far ; Add current element to currsum ; If currsum = K , then a new subarray is found ; If currsum > K then find the no . of subarrays with sum currsum - K and exclude those subarrays ; Add currsum to count of different values of sum ; Return the final result ; Function to count the subarray with K primes ; Update the array element ; If current element is prime then update the arr [ i ] to 1 ; Else change arr [ i ] to 0 ; Function Call ; Driver Code ; Function Call
from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 5 , int ( sqrt ( n ) ) + 1 , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def findSubarraySum ( arr , n , K ) : NEW_LINE INDENT prevSum = { i : 0 for i in range ( 100 ) } NEW_LINE res = 0 NEW_LINE currsum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT currsum += arr [ i ] NEW_LINE if ( currsum == K ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT if ( currsum - K ) in prevSum : NEW_LINE INDENT res += ( prevSum [ currsum - K ] ) NEW_LINE DEDENT prevSum [ currsum ] += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def countSubarray ( arr , n , K ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( isPrime ( arr [ i ] ) ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT DEDENT print ( findSubarraySum ( arr , n , K ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE countSubarray ( arr , N , K ) NEW_LINE DEDENT
Count the elements having frequency equals to its value | Function to find the count ; Hash map for counting frequency ; Counting freq of each element ; Check if value equals to frequency and increment the count ; Driver code ; Function call
def find_maxm ( arr , n ) : NEW_LINE INDENT mpp = { } NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] in mpp : NEW_LINE INDENT mpp [ arr [ i ] ] = mpp [ arr [ i ] ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT mpp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for key in mpp : NEW_LINE INDENT value = key NEW_LINE freq = mpp [ key ] NEW_LINE if value == freq : NEW_LINE INDENT ans = ans + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 2 , 2 , 3 , 4 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( find_maxm ( arr , n ) ) NEW_LINE DEDENT
Find the Number of Permutations that satisfy the given condition in an array | Function to calculate x ^ y recursively ; Function to return the number of permutations that satisfy the given condition in an array ; If there is only one element then only one permutation is available ; Sort the array for calculating the number of elements occurring twice ; If the maximum element is occurring twice , then the number of permutations satisfying the condition is 0 ; This variable will store the number of element occurring twice ; Loop to check the number of elements occurring twice ; Check if this element is occurring twice ; If this element is occurring twice then check if this number is occurring more than twice ; If element occurring thrice then no permutation will satisfy the given condition ; Since we have checked the next element as well , then we can increment the loop variable ; Driver code
def pow ( x , y ) : NEW_LINE INDENT if ( y == 1 ) : NEW_LINE INDENT return x NEW_LINE DEDENT if ( y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT temp = pow ( x , y // 2 ) NEW_LINE temp *= temp NEW_LINE if ( y & 1 ) : NEW_LINE INDENT temp *= x NEW_LINE DEDENT return temp NEW_LINE DEDENT def noOfPermutations ( a , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT a . sort ( ) NEW_LINE if ( a [ n - 1 ] == a [ n - 2 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT x = 0 NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT if ( a [ i ] == a [ i + 1 ] ) : NEW_LINE INDENT if ( a [ i ] == a [ i + 2 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT x += 1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT return pow ( 2 , n - 2 * x - 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 2 , 3 , 4 ] NEW_LINE n = len ( a ) NEW_LINE num = noOfPermutations ( a , n ) NEW_LINE print ( num ) NEW_LINE DEDENT
Length of the Smallest Subarray that must be removed in order to Maximise the GCD | Function to find the length of the smallest subarray that must be removed in order to maximise the GCD ; Store the maximum possible GCD of the resulting subarray ; Two pointers initially pointing to the first and last element respectively ; Moving the left pointer to the right if the elements are divisible by the maximum GCD ; Moving the right pointer to the left if the elements are divisible by the maximum GCD ; Return the length of the subarray ; Driver code
def GetMinSubarrayLength ( a , n ) : NEW_LINE INDENT ans = max ( a [ 0 ] , a [ n - 1 ] ) NEW_LINE lo = 0 NEW_LINE hi = n - 1 NEW_LINE while ( lo < n and a [ lo ] % ans == 0 ) : NEW_LINE INDENT lo += 1 NEW_LINE DEDENT while ( hi > lo and a [ hi ] % ans == 0 ) : NEW_LINE INDENT hi -= 1 NEW_LINE DEDENT return ( hi - lo + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 8 , 2 , 1 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE length = GetMinSubarrayLength ( arr , N ) NEW_LINE print ( length ) NEW_LINE DEDENT
Maximize the number of indices such that element is greater than element to its left | Function to find the maximum pairs such that arr [ i + 1 ] > arr [ i ] ; To store the frequency of the element in arr [ ] ; Store the frequency in map M ; To find the maximum frequency store in map M ; Print the maximum number of possible pairs ; Driver Code
def countPairs ( arr , N ) : NEW_LINE INDENT M = dict . fromkeys ( arr , 0 ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT M [ arr [ i ] ] += 1 ; NEW_LINE DEDENT maxFreq = 0 ; NEW_LINE for it in M . values ( ) : NEW_LINE INDENT maxFreq = max ( maxFreq , it ) ; NEW_LINE DEDENT print ( N - maxFreq ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 8 , 5 , 9 , 8 , 8 , 7 , 7 , 5 , 7 , 7 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE countPairs ( arr , N ) ; NEW_LINE DEDENT
Find minimum value of the expression by choosing K elements from given array | Function to find the minimum possible of the expression by choosing exactly K ( ? N ) integers form given array arr ; Sorting the array for least k element selection ; Select first k elements from sorted array ; Return value of solved expression ; Driver code ; Function call
def minimumValue ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE answer = 0 ; NEW_LINE for i in range ( k ) : NEW_LINE INDENT answer += arr [ i ] * arr [ i ] ; NEW_LINE DEDENT return answer * ( 2 * k - 2 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 21 , 5 , 3 , 8 ] ; NEW_LINE k = 3 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( minimumValue ( arr , n , k ) ) ; NEW_LINE DEDENT
Transform N to Minimum possible value | Python3 program to transform N to the minimum value ; Initialising the answer ; Function to find the digitsum ; Iterate over all digits and add them ; Return the digit su , ; Function to transform N to the minimum value ; If the final value is lesser than least value ; If final value is equal to least value then check for lesser number of steps to reach this value ; The value will be obtained in less than 15 steps as proved so applying normal recursive operations ; Driver code ; Function call ; Print the answers
import sys ; NEW_LINE min_val = sys . maxsize ; NEW_LINE min_steps = 0 ; NEW_LINE def sumOfDigits ( n ) : NEW_LINE INDENT s = str ( n ) ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT sum += ( ord ( s [ i ] ) - ord ( '0' ) ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def Transform ( n , d , steps ) : NEW_LINE INDENT global min_val ; global min_steps ; NEW_LINE if ( n < min_val ) : NEW_LINE INDENT min_val = n ; NEW_LINE min_steps = steps ; NEW_LINE DEDENT elif ( n == min_val ) : NEW_LINE INDENT min_steps = min ( min_steps , steps ) ; NEW_LINE DEDENT if ( steps < 15 ) : NEW_LINE INDENT Transform ( sumOfDigits ( n ) , d , steps + 1 ) ; NEW_LINE Transform ( n + d , d , steps + 1 ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 9 ; D = 3 ; NEW_LINE Transform ( N , D , 0 ) ; NEW_LINE print ( min_val , min_steps ) ; NEW_LINE DEDENT
Remove all 1 s from the adjacent left of 0 s in a Binary Array | Function to find the maximum number of 1 's before 0 ; Traverse the array ; If value is 1 ; If consecutive 1 followed by 0 , then update the maxCnt ; Print the maximum consecutive 1 's followed by 0 ; Driver Code ; Function Call ; Function Call
def noOfMoves ( arr , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE maxCnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( cnt != 0 ) : NEW_LINE INDENT maxCnt = max ( maxCnt , cnt ) NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT DEDENT print ( maxCnt ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 1 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 0 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE noOfMoves ( arr , N ) NEW_LINE arr1 = [ 1 , 0 , 1 , 0 , 1 , 0 , 1 , 0 ] NEW_LINE N = len ( arr1 ) NEW_LINE noOfMoves ( arr1 , N ) NEW_LINE DEDENT
Check if given coins can be used to pay a value of S | Function to check if it is possible to pay a value ; Loop to add the value of coin A ; Condition to check if it is possible to pay a value of S ; Driver Code
def knowPair ( a , b , n , s , m ) : NEW_LINE INDENT i = 0 NEW_LINE rem = 0 NEW_LINE count_b = 0 NEW_LINE flag = 0 NEW_LINE while ( i <= a ) : NEW_LINE INDENT rem = s - ( n * i ) NEW_LINE count_b = rem // m NEW_LINE if ( rem % m == 0 and count_b <= b ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( flag == 1 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 1 NEW_LINE B = 2 NEW_LINE n = 3 NEW_LINE S = 4 NEW_LINE m = 2 NEW_LINE knowPair ( A , B , n , S , m ) NEW_LINE DEDENT
Sum of all numbers in the given range which are divisible by M | Function to find the sum of numbers divisible by M in the given range ; Variable to store the sum ; Running a loop from A to B and check if a number is divisible by i . ; If the number is divisible , then add it to sum ; Return the sum ; Driver code ; A and B define the range M is the dividend ; Printing the result
def sumDivisibles ( A , B , M ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( A , B + 1 ) : NEW_LINE INDENT if ( i % M == 0 ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 6 NEW_LINE B = 15 NEW_LINE M = 3 NEW_LINE print ( sumDivisibles ( A , B , M ) ) NEW_LINE DEDENT
Sum of all numbers in the given range which are divisible by M | Function to find the largest number smaller than or equal to N that is divisible by K ; Finding the remainder when N is divided by K ; If the remainder is 0 , then the number itself is divisible by K ; Else , then the difference between N and remainder is the largest number which is divisible by K ; Function to find the smallest number greater than or equal to N that is divisible by K ; Finding the remainder when N is divided by K ; If the remainder is 0 , then the number itself is divisible by K ; Else , then the difference between N and remainder is the largest number which is divisible by K ; Function to find the sum of numbers divisible by M in the given range ; Variable to store the sum ; To bring the smallest and largest numbers in the range [ A , B ] ; To count the number of terms in the AP ; Sum of n terms of an AP ; Driver code ; A and B define the range , M is the dividend ; Printing the result
def findSmallNum ( N , K ) : NEW_LINE INDENT rem = N % K NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT return N NEW_LINE DEDENT else : NEW_LINE INDENT return N - rem NEW_LINE DEDENT DEDENT def findLargeNum ( N , K ) : NEW_LINE INDENT rem = ( N + K ) % K NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT return N NEW_LINE DEDENT else : NEW_LINE INDENT return N + K - rem NEW_LINE DEDENT DEDENT def sumDivisibles ( A , B , M ) : NEW_LINE INDENT sum = 0 NEW_LINE first = findSmallNum ( A , M ) NEW_LINE last = findLargeNum ( B , M ) NEW_LINE if ( first < A ) : NEW_LINE INDENT first += M NEW_LINE DEDENT if ( last > B ) : NEW_LINE INDENT first -= M NEW_LINE DEDENT n = ( B // M ) - ( A - 1 ) // M NEW_LINE return n * ( first + last ) // 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 6 NEW_LINE B = 15 NEW_LINE M = 3 NEW_LINE print ( sumDivisibles ( A , B , M ) ) NEW_LINE DEDENT
Count of all unique substrings with non | Function to count all unique distinct character substrings ; Hashmap to store all substrings ; Iterate over all the substrings ; Boolean array to maintain all characters encountered so far ; Variable to maintain the subtill current position ; Get the position of the character in the string ; Check if the character is encountred ; Add the current character to the substring ; Insert subin Hashmap ; Driver code
def distinctSubstring ( P , N ) : NEW_LINE INDENT S = dict ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq = [ False ] * 26 NEW_LINE s = " " NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT pos = ord ( P [ j ] ) - ord ( ' a ' ) NEW_LINE if ( freq [ pos ] == True ) : NEW_LINE INDENT break NEW_LINE DEDENT freq [ pos ] = True NEW_LINE s += P [ j ] NEW_LINE S [ s ] = 1 NEW_LINE DEDENT DEDENT return len ( S ) NEW_LINE DEDENT S = " abba " NEW_LINE N = len ( S ) NEW_LINE print ( distinctSubstring ( S , N ) ) NEW_LINE
Sum of all subarrays of size K | Function to find the sum of all subarrays of size K ; Loop to consider every subarray of size K ; Initialize sum = 0 ; Calculate sum of all elements of current subarray ; Prsum of each subarray ; Driver Code ; Function Call
def calcSum ( arr , n , k ) : NEW_LINE INDENT for i in range ( n - k + 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( i , k + i ) : NEW_LINE INDENT sum += arr [ j ] NEW_LINE DEDENT print ( sum , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE calcSum ( arr , n , k ) NEW_LINE
Sum of all subarrays of size K | Function to find the sum of all subarrays of size K ; Initialize sum = 0 ; Consider first subarray of size k Store the sum of elements ; Print the current sum ; Consider every subarray of size k Remove first element and add current element to the window ; Add the element which enters into the window and subtract the element which pops out from the window of the size K ; Print the sum of subarray ; Drivers Code ; Function Call
def calcSum ( arr , n , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT print ( sum , end = " ▁ " ) NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT sum = ( sum - arr [ i - k ] ) + arr [ i ] NEW_LINE print ( sum , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE calcSum ( arr , n , k ) NEW_LINE DEDENT
Number of indices pair such that element pair sum from first Array is greater than second Array | Python 3 program to find the number of indices pair such that pair sum from first Array is greater than second Array ; Function to get the number of pairs of indices { i , j } in the given two arrays A and B such that A [ i ] + A [ j ] > B [ i ] + B [ j ] ; Intitializing the difference array D ; Computing the difference between the elements at every index and storing it in the array D ; Sort the array D ; Variable to store the total number of pairs that satisfy the given condition ; Loop to iterate through the difference array D and find the total number of pairs of indices that follow the given condition ; If the value at the index i is positive , then it remains positive for any pairs with j such that j > i . ; If the value at that index is negative then we need to find the index of the value just greater than - D [ i ] ; Driver code
import bisect NEW_LINE def getPairs ( A , B , n ) : NEW_LINE INDENT D = [ 0 ] * ( n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT D [ i ] = A [ i ] - B [ i ] NEW_LINE DEDENT D . sort ( ) NEW_LINE total = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( D [ i ] > 0 ) : NEW_LINE INDENT total += n - i - 1 NEW_LINE DEDENT else : NEW_LINE INDENT k = bisect . bisect_right ( D , - D [ i ] , 0 , len ( D ) ) NEW_LINE total += n - k NEW_LINE DEDENT DEDENT return total NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE A = [ ] NEW_LINE B = [ ] NEW_LINE A . append ( 4 ) ; NEW_LINE A . append ( 8 ) ; NEW_LINE A . append ( 2 ) ; NEW_LINE A . append ( 6 ) ; NEW_LINE A . append ( 2 ) ; NEW_LINE B . append ( 4 ) ; NEW_LINE B . append ( 5 ) ; NEW_LINE B . append ( 4 ) ; NEW_LINE B . append ( 1 ) ; NEW_LINE B . append ( 3 ) ; NEW_LINE print ( getPairs ( A , B , n ) ) NEW_LINE DEDENT
Number of pairs such that their HCF and LCM is equal | Function to return HCF of two numbers ; Function to return LCM of two numbers ; Returns the number of valid pairs ; Traversing the array . For each array element , checking if it follow the condition ; Driver function
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b ; NEW_LINE DEDENT return gcd ( b % a , a ) ; NEW_LINE DEDENT def lcm ( a , b ) : NEW_LINE INDENT return ( a * b ) / gcd ( a , b ) ; NEW_LINE DEDENT def countPairs ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( lcm ( arr [ i ] , arr [ j ] ) == gcd ( arr [ i ] , arr [ j ] ) ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countPairs ( arr , n ) ) ; NEW_LINE DEDENT
Number of pairs such that their HCF and LCM is equal | Python 3 program to count number of pairs such that their hcf and lcm are equal ; Function to count number of pairs such that their hcf and lcm are equal ; Store frequencies of array elements ; Count of pairs ( arr [ i ] , arr [ j ] ) where arr [ i ] = arr [ j ] ; Count of pairs ( arr [ i ] , arr [ j ] ) where arr [ i ] = arr [ j ] , ; Driver function
from collections import defaultdict NEW_LINE def countPairs ( a , n ) : NEW_LINE INDENT frequency = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT frequency [ a [ i ] ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for x in frequency . keys ( ) : NEW_LINE INDENT f = frequency [ x ] NEW_LINE count += f * ( f - 1 ) // 2 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE DEDENT
Find the maximum possible value of last element of the Array | Function to find the maximum possible value of last element of the array ; Traverse for all element ; Find the distance ; If moves less than distance then we can not move this number to end ; How many number we can move to end ; Take the minimum of both of them ; Increment in the end ; Remove taken moves ; Return the last element ; Driver code ; Function call
def maxValue ( arr , n , moves ) : NEW_LINE INDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT distance = n - 1 - i NEW_LINE if ( moves < distance ) : NEW_LINE INDENT break NEW_LINE DEDENT can_take = moves // distance NEW_LINE take = min ( arr [ i ] , can_take ) NEW_LINE arr [ n - 1 ] += take NEW_LINE moves -= take * distance NEW_LINE DEDENT DEDENT return arr [ n - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 0 , 1 ] NEW_LINE M = 5 NEW_LINE N = len ( arr ) NEW_LINE print ( maxValue ( arr , N , M ) ) NEW_LINE DEDENT
Minimum number of Factorials whose sum is equal to N | Array to calculate all factorials less than or equal to N Since there can be only 14 factorials till 10 ^ 10 Hence the maximum size of fact [ ] is 14 ; Store the actual size of fact [ ] ; Function to precompute factorials till N ; Precomputing factorials ; Function to find the minimum number of factorials whose sum represents N ; Precompute factorials ; Initialize result ; Traverse through all factorials ; Find factorials ; Prmin count ; Prresult ; Driver program
fact = [ 0 ] * 14 NEW_LINE size = 1 NEW_LINE def preCompute ( N ) : NEW_LINE INDENT global size NEW_LINE fact [ 0 ] = 1 NEW_LINE i = 1 NEW_LINE while fact [ i - 1 ] <= N : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE size += 1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT def findMin ( N ) : NEW_LINE INDENT preCompute ( N ) NEW_LINE originalN = N NEW_LINE ans = [ ] NEW_LINE for i in range ( size - 1 , - 1 , - 1 ) : NEW_LINE INDENT while ( N >= fact [ i ] ) : NEW_LINE INDENT N -= fact [ i ] NEW_LINE ans . append ( fact [ i ] ) NEW_LINE DEDENT DEDENT print ( len ( ans ) ) NEW_LINE for i in ans : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT n = 27 NEW_LINE findMin ( n ) NEW_LINE
Longest increasing sub | Function to find the LCS ; Loop to create frequency array ; Driver code
def findLCS ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT return len ( mp ) NEW_LINE DEDENT n = 3 NEW_LINE arr = [ 3 , 2 , 1 ] NEW_LINE print ( findLCS ( arr , n ) ) NEW_LINE
Path with maximum product in 2 | Python Program to find maximum product path from ( 0 , 0 ) to ( N - 1 , M - 1 ) ; Function to find maximum product ; It will store the maximum product till a given cell . ; It will store the minimum product till a given cell ( for - ve elements ) ; If we are at topmost or leftmost , just copy the elements . ; If we 're not at the above, we can consider the above value. ; If we 're not on the leftmost, we can consider the left value. ; Store max & min product till i , j . ; Return the max product path from 0 , 0. N - 1 , M - 1. ; Driver Code ; Prmaximum product from ( 0 , 0 ) to ( N - 1 , M - 1 )
import sys NEW_LINE N = 3 ; NEW_LINE M = 3 ; NEW_LINE def maxProductPath ( arr ) : NEW_LINE INDENT maxPath = [ [ 0 for i in range ( M ) ] for j in range ( N ) ] ; NEW_LINE minPath = [ [ 0 for i in range ( M ) ] for j in range ( N ) ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT minVal = sys . maxsize ; NEW_LINE maxVal = - sys . maxsize ; NEW_LINE if ( i == 0 and j == 0 ) : NEW_LINE INDENT maxVal = arr [ i ] [ j ] ; NEW_LINE minVal = arr [ i ] [ j ] ; NEW_LINE DEDENT if ( i > 0 ) : NEW_LINE INDENT tempMax = max ( maxPath [ i - 1 ] [ j ] * arr [ i ] [ j ] , \ minPath [ i - 1 ] [ j ] * arr [ i ] [ j ] ) ; NEW_LINE maxVal = max ( maxVal , tempMax ) ; NEW_LINE tempMin = min ( maxPath [ i - 1 ] [ j ] * arr [ i ] [ j ] , \ minPath [ i - 1 ] [ j ] * arr [ i ] [ j ] ) ; NEW_LINE minVal = min ( minVal , tempMin ) ; NEW_LINE DEDENT if ( j > 0 ) : NEW_LINE INDENT tempMax = max ( maxPath [ i ] [ j - 1 ] * arr [ i ] [ j ] , \ minPath [ i ] [ j - 1 ] * arr [ i ] [ j ] ) ; NEW_LINE maxVal = max ( maxVal , tempMax ) ; NEW_LINE tempMin = min ( maxPath [ i ] [ j - 1 ] * arr [ i ] [ j ] , \ minPath [ i ] [ j - 1 ] * arr [ i ] [ j ] ) ; NEW_LINE minVal = min ( minVal , tempMin ) ; NEW_LINE DEDENT maxPath [ i ] [ j ] = maxVal ; NEW_LINE minPath [ i ] [ j ] = minVal ; NEW_LINE DEDENT DEDENT return maxPath [ N - 1 ] [ M - 1 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , - 2 , 3 ] , [ 4 , - 5 , 6 ] , [ - 7 , - 8 , 9 ] ] ; NEW_LINE print ( maxProductPath ( arr ) ) ; NEW_LINE DEDENT
Vertical and Horizontal retrieval ( MRT ) on Tapes | Python3 program to print Vertical filling ; 2D matrix for vertical insertion on tapes ; It is used for checking whether tape is full or not ; It is used for calculating total retrieval time ; It is used for calculating mean retrieval time ; It is used for calculating mean retrieval time ; vertical insertion on tape ; initialize variables to 0 for each iteration ; Used for getting ' sum ' sizes of records in tape to determine whether tape is full or not ; if tape is not full ; check for ability of tapes to hold value ; initialize variables to 0 for each iteration ; display elements of tape ; calculating total retrieval time ; MRT formula ; calculating mean retrieval time using formula ; v . size ( ) is function of vector is used to get size of vector ; Driver Code ; store the size of records [ ] ; store the size of tape [ ] ; sorting of an array is required to attain greedy approach of algorithm
import numpy as np NEW_LINE def vertical_Fill ( records , tape , m , n ) : NEW_LINE INDENT v = np . zeros ( ( m , n ) ) ; NEW_LINE sum = 0 ; NEW_LINE Retrieval_Time = 0 ; NEW_LINE Mrt = None ; NEW_LINE z = 0 ; j = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for k in range ( i ) : NEW_LINE INDENT sum += v [ j ] [ k ] ; NEW_LINE DEDENT if ( sum + records [ z ] <= tape [ j ] ) : NEW_LINE INDENT v [ j ] [ i ] = records [ z ] ; NEW_LINE z += 1 ; NEW_LINE DEDENT DEDENT if ( v [ 2 ] [ i ] == 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT for i in range ( m ) : NEW_LINE INDENT Retrieval_Time = 0 ; NEW_LINE print ( " tape " , i + 1 , " : ▁ [ " , end = " " ) ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( v [ i ] [ j ] != 0 ) : NEW_LINE INDENT print ( v [ i ] [ j ] , end = " ▁ " ) ; else : break ; print ( " ] " , end = " " ) ; NEW_LINE DEDENT DEDENT k = 0 ; NEW_LINE while v [ i ] [ k ] != 0 : NEW_LINE INDENT Retrieval_Time += v [ i ] [ k ] * ( j - k ) ; NEW_LINE k += 1 ; NEW_LINE DEDENT Mrt = Retrieval_Time / j ; NEW_LINE print ( " MRT ▁ : " , Mrt ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT records = [ 15 , 2 , 8 , 23 , 45 , 50 , 60 , 120 ] ; NEW_LINE tape = [ 25 , 80 , 160 ] ; NEW_LINE n = len ( records ) ; NEW_LINE m = len ( tape ) ; NEW_LINE records . sort ( ) ; NEW_LINE vertical_Fill ( records , tape , m , n ) ; NEW_LINE DEDENT
Minimum number of subsequences required to convert one string to another | Python3 program to find the Minimum number of subsequences required to convert one to another ; Function to find the no of subsequences ; Push the values of indexes of each character ; Find the next index available in the array ; If Character is not in A ; Check if the next index is not equal to the size of array which means there is no index greater than minIndex in the array ; Update value of minIndex with this index ; Update the value of counter and minIndex for next operation ; Driver Code
from bisect import bisect as upper_bound NEW_LINE def minSubsequnces ( A , B ) : NEW_LINE INDENT v = [ [ ] for i in range ( 26 ) ] NEW_LINE minIndex = - 1 NEW_LINE cnt = 1 NEW_LINE j = 0 NEW_LINE flag = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT p = ord ( A [ i ] ) - 97 NEW_LINE v [ p ] . append ( i ) NEW_LINE DEDENT while ( j < len ( B ) ) : NEW_LINE INDENT p = ord ( B [ j ] ) - 97 NEW_LINE k = upper_bound ( v [ p ] , minIndex ) NEW_LINE if ( len ( v [ p ] ) == 0 ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT if ( k != len ( v [ p ] ) ) : NEW_LINE INDENT minIndex = v [ p ] [ k ] NEW_LINE j = j + 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE minIndex = - 1 NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return cnt NEW_LINE DEDENT A1 = " abbace " NEW_LINE B1 = " acebbaae " NEW_LINE print ( minSubsequnces ( A1 , B1 ) ) NEW_LINE
Find two equal subsequences of maximum length with at least one different index | Python implementation of the approach ; Function to return the required length of the subsequences ; To store the result ; To store the last visited position of lowercase letters ; Initialisation of frequency array to - 1 to indicate no character has previously occured ; For every character of the String ; Get the index of the current character ; If the current character has appeared before in the String ; Update the result ; Update the last position of the current character ; Driver code
MAX = 26 ; NEW_LINE def maxLength ( str , len ) : NEW_LINE INDENT res = 0 ; NEW_LINE lastPos = [ 0 ] * MAX ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT lastPos [ i ] = - 1 ; NEW_LINE DEDENT for i in range ( len ) : NEW_LINE INDENT C = ord ( str [ i ] ) - ord ( ' a ' ) ; NEW_LINE if ( lastPos [ C ] != - 1 ) : NEW_LINE INDENT res = max ( len - ( i - lastPos [ C ] - 1 ) - 1 , res ) ; NEW_LINE DEDENT lastPos [ C ] = i ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " geeksforgeeks " ; NEW_LINE len = len ( str ) ; NEW_LINE print ( maxLength ( str , len ) ) ; NEW_LINE DEDENT
Maximum profit by selling N items at two markets | Python3 implementation of the approach ; Max profit will be saved here ; loop to check all possible combinations of sales ; the sum of the profit after the sale for products 0 to i in market A ; the sum of the profit after the sale for products i to n in market B ; Replace the value of Max Profit with a bigger value among maxP and sumA + sumB ; Return the value of Max Profit ; Driver Program
def maxProfit ( a , b , n ) : NEW_LINE INDENT maxP = - 1 NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT sumA = sum ( a [ : i ] ) NEW_LINE sumB = sum ( b [ i : ] ) NEW_LINE maxP = max ( maxP , sumA + sumB ) NEW_LINE DEDENT return maxP NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 3 , 2 ] NEW_LINE b = [ 10 , 30 , 40 ] NEW_LINE print ( maxProfit ( a , b , 4 ) ) NEW_LINE DEDENT
Partitions possible such that the minimum element divides all the other elements of the partition | Python3 implementation of the approach ; Function to return the count partitions possible from the given array such that the minimum element of any partition divides all the other elements of that partition ; Initialize the count variable ; Find the minimum element ; Break if no minimum element present ; Increment the count if minimum element present ; Replace all the element divisible by min_elem ; Driver code
import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def countPartitions ( A , N ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT min_elem = min ( A ) ; NEW_LINE if ( min_elem == INT_MAX ) : NEW_LINE INDENT break ; NEW_LINE DEDENT count += 1 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] % min_elem == 0 ) : NEW_LINE INDENT A [ i ] = INT_MAX ; NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 6 , 5 , 4 , 3 , 2 , 2 , 3 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( countPartitions ( arr , N ) ) ; NEW_LINE DEDENT
Minimum number of swaps to make two binary string equal | Function to calculate min swaps to make binary strings equal ; Count of zero 's ; Count of one 's ; As discussed above ; Driver code
def minSwaps ( s1 , s2 ) : NEW_LINE INDENT c0 = 0 ; c1 = 0 ; NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( s1 [ i ] == '0' and s2 [ i ] == '1' ) : NEW_LINE INDENT c0 += 1 ; NEW_LINE DEDENT elif ( s1 [ i ] == '1' and s2 [ i ] == '0' ) : NEW_LINE INDENT c1 += 1 ; NEW_LINE DEDENT DEDENT ans = c0 // 2 + c1 // 2 ; NEW_LINE if ( c0 % 2 == 0 and c1 % 2 == 0 ) : NEW_LINE INDENT return ans ; NEW_LINE DEDENT elif ( ( c0 + c1 ) % 2 == 0 ) : NEW_LINE INDENT return ans + 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = "0011" ; s2 = "1111" ; NEW_LINE ans = minSwaps ( s1 , s2 ) ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT
Minimum changes required to make all element in an array equal | Function to count of minimum changes required to make all elements equal ; Store the count of each element as key - value pair in Dictionary ; Traverse through the Dictionary and find the maximum occurring element ; Return count of all element minus count of maximum occurring element ; Driver code ; Function call
def minChanges ( arr , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT maxElem = 0 NEW_LINE for x in mp : NEW_LINE INDENT maxElem = max ( maxElem , mp [ x ] ) NEW_LINE DEDENT return n - maxElem NEW_LINE DEDENT arr = [ 2 , 3 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minChanges ( arr , n ) ) NEW_LINE
Minimum operations to make two numbers equal | Python3 implementation of the above approach ; Function to find the minimum no . of operations ; find the maximum of two and store it in p ; increase it until it is achievable from given n and m ; Here value added to n and m will be S ( n ) = p - n + p - m ; check whether integer value of n exist by the formula n = ( - 1 + sqrt ( 1 + 8 * S ( n ) ) ) / 2 ; Driver code ; Function calling
from math import sqrt , floor NEW_LINE def minOperations ( n , m ) : NEW_LINE INDENT a = 0 ; k = 1 ; NEW_LINE p = max ( n , m ) ; NEW_LINE while ( n != m ) : NEW_LINE INDENT s = float ( p - n + p - m ) ; NEW_LINE q = ( - 1 + sqrt ( 8 * s + 1 ) ) / 2 ; NEW_LINE if ( q - floor ( q ) == 0 ) : NEW_LINE INDENT a = q ; NEW_LINE n = m ; NEW_LINE DEDENT p = p + 1 ; NEW_LINE DEDENT return a ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 1 ; m = 3 ; NEW_LINE print ( minOperations ( n , m ) ) ; NEW_LINE DEDENT
Count of subarrays with sum at least K | Function to return the number of subarrays with sum atleast k ; To store the right index and the current sum ; To store the number of sub - arrays ; For all left indexes ; Get elements till current sum is less than k ; No such subarray is possible ; Add all possible subarrays ; Remove the left most element ; Return the required answer ; Driver code
def k_sum ( a , n , k ) : NEW_LINE INDENT r , sum = 0 , 0 ; NEW_LINE ans = 0 ; NEW_LINE for l in range ( n ) : NEW_LINE INDENT while ( sum < k ) : NEW_LINE INDENT if ( r == n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT else : NEW_LINE INDENT sum += a [ r ] ; NEW_LINE r += 1 ; NEW_LINE DEDENT DEDENT if ( sum < k ) : NEW_LINE INDENT break ; NEW_LINE DEDENT ans += n - r + 1 ; NEW_LINE sum -= a [ l ] ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT a = [ 6 , 1 , 2 , 7 ] ; k = 10 ; NEW_LINE n = len ( a ) ; NEW_LINE print ( k_sum ( a , n , k ) ) ; NEW_LINE
Find if a crest is present in the index range [ L , R ] of the given array | Function that returns true if the array contains a crest in the index range [ L , R ] ; To keep track of elements which satisfy the Property ; Property is satisfied for the current element ; Cumulative Sum ; If a crest is present in the given index range ; Driver code
def hasCrest ( arr , n , L , R ) : NEW_LINE INDENT present = [ 0 ] * n ; NEW_LINE for i in range ( 1 , n - 2 + 1 ) : NEW_LINE INDENT if ( ( arr [ i ] <= arr [ i + 1 ] ) and ( arr [ i ] <= arr [ i - 1 ] ) ) : NEW_LINE INDENT present [ i ] = 1 ; NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT present [ i ] += present [ i - 1 ] ; NEW_LINE DEDENT if ( present [ L ] == present [ R - 1 ] ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 1 , 3 , 5 , 12 , 11 , 7 , 9 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE L = 2 ; NEW_LINE R = 6 ; NEW_LINE if ( hasCrest ( arr , N , L , R ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Maximum Sum of Products of two arrays by toggling adjacent bits | Python3 program to find the maximum SoP of two arrays by toggling adjacent bits in the second array ; Function to return Max Sum ; intialParity and finalParity are 0 if total no . of 1 's is even else 1 ; minPositive and maxNegative will store smallest positive and smallest negative integer respectively . ; Count of Initial Parity ; if arr1 [ i ] is positive then add 1 in finalParity to get 1 at arr2 [ i ] ; if both parity are odd or even then return sum ; else add one more 1 or remove 1 ; if minPositive > maxNegative , put 1 at maxNegative and add it to our sum ; else remove minPositive no . ; Driver code
import sys NEW_LINE def maxSum ( arr1 , arr2 , n ) : NEW_LINE INDENT initialParity , finalParity = 0 , 0 NEW_LINE sum = 0 NEW_LINE minPositive = sys . maxsize NEW_LINE maxNegative = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT initialParity += arr2 [ i ] ; NEW_LINE if ( arr1 [ i ] >= 0 ) : NEW_LINE INDENT finalParity += 1 NEW_LINE sum += arr1 [ i ] NEW_LINE minPositive = min ( minPositive , arr1 [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT maxNegative = max ( maxNegative , arr1 [ i ] ) NEW_LINE DEDENT DEDENT if ( initialParity % 2 == finalParity % 2 ) : NEW_LINE INDENT return sum NEW_LINE DEDENT else : NEW_LINE INDENT if ( minPositive + maxNegative >= 0 ) : NEW_LINE INDENT return sum + maxNegative NEW_LINE DEDENT else : NEW_LINE INDENT return sum - minPositive NEW_LINE DEDENT DEDENT DEDENT arr1 = [ 2 , - 4 , 5 , 3 ] NEW_LINE arr2 = [ 0 , 1 , 0 , 1 ] NEW_LINE n = len ( arr1 ) NEW_LINE print ( maxSum ( arr1 , arr2 , n ) ) NEW_LINE
Minimum number to be added to all digits of X to make X > Y | Function to check if X is lexicographically larger Y ; It is lexicographically larger ; Utility function to check minimum value of d ; If X is already larger do not need to add anything ; Adding d to all elements of X ; If X is larger now print d ; else print d + 1 ; Driver Code ; Taking the numbers as sequences
def IsLarger ( X , Y , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( X [ i ] < Y [ i ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def solve ( X , Y , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE if ( IsLarger ( X , Y , n ) ) : NEW_LINE INDENT ans = 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT d = Y [ 0 ] - X [ 0 ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT X [ i ] += d ; NEW_LINE DEDENT if ( IsLarger ( X , Y , n ) ) : NEW_LINE INDENT ans = d ; NEW_LINE DEDENT else : NEW_LINE INDENT ans = d + 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = [ 2 , 3 , 6 , 9 ] ; NEW_LINE Y = [ 3 , 4 , 8 , 1 ] ; NEW_LINE n = len ( X ) ; NEW_LINE print ( solve ( X , Y , n ) ) ; NEW_LINE DEDENT
Maximum possible Bitwise OR of the two numbers from the range [ L , R ] | Function to return the maximum bitwise OR of any pair from the given range ; Converting L to its binary representation ; Converting R to its binary representation ; In order to make the number of bits of L and R same ; Push 0 to the MSB ; When ith bit of R is 1 and ith bit of L is 0 ; From MSB side set all bits of L to be 1 ; From ( i + 1 ) th bit , all bits of L changed to be 1 ; Driver code
def max_bitwise_or ( L , R ) : NEW_LINE INDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE v3 = [ ] NEW_LINE z = 0 NEW_LINE i = 0 NEW_LINE ans = 0 NEW_LINE cnt = 1 NEW_LINE while ( L > 0 ) : NEW_LINE INDENT v1 . append ( L % 2 ) NEW_LINE L = L // 2 NEW_LINE DEDENT while ( R > 0 ) : NEW_LINE INDENT v2 . append ( R % 2 ) NEW_LINE R = R // 2 NEW_LINE DEDENT while ( len ( v1 ) != len ( v2 ) ) : NEW_LINE INDENT v1 . append ( 0 ) NEW_LINE DEDENT for i in range ( len ( v2 ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( v2 [ i ] == 1 and v1 [ i ] == 0 and z == 0 ) : NEW_LINE INDENT z = 1 NEW_LINE continue NEW_LINE DEDENT if ( z == 1 ) : NEW_LINE INDENT v1 [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( len ( v2 ) ) : NEW_LINE INDENT v3 . append ( v2 [ i ] v1 [ i ] ) NEW_LINE DEDENT for i in range ( len ( v2 ) ) : NEW_LINE INDENT if ( v3 [ i ] == 1 ) : NEW_LINE INDENT ans += cnt NEW_LINE DEDENT cnt *= 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT L = 10 NEW_LINE R = 20 NEW_LINE print ( max_bitwise_or ( L , R ) ) NEW_LINE
Find the minimum value of X for an expression | Function to calculate value of X ; Check for both possibilities ; Driver Code
def valueofX ( ar , n ) : NEW_LINE INDENT summ = sum ( ar ) NEW_LINE if ( summ % n == 0 ) : NEW_LINE INDENT return summ // n NEW_LINE DEDENT else : NEW_LINE INDENT A = summ // n NEW_LINE B = summ // n + 1 NEW_LINE ValueA = 0 NEW_LINE ValueB = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ValueA += ( ar [ i ] - A ) * ( ar [ i ] - A ) NEW_LINE ValueB += ( ar [ i ] - B ) * ( ar [ i ] - B ) NEW_LINE DEDENT if ( ValueA < ValueB ) : NEW_LINE INDENT return A NEW_LINE DEDENT else : NEW_LINE INDENT return B NEW_LINE DEDENT DEDENT DEDENT n = 7 NEW_LINE arr = [ 6 , 9 , 1 , 6 , 1 , 3 , 7 ] NEW_LINE print ( valueofX ( arr , n ) ) NEW_LINE
Minimum length String with Sum of the alphabetical values of the characters equal to N | Function to find the minimum length ; Function to find the minimum length String ; Driver code
def minLength ( n ) : NEW_LINE INDENT ans = n // 26 NEW_LINE if ( n % 26 != 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def minString ( n ) : NEW_LINE INDENT ans = n // 26 NEW_LINE res = " " NEW_LINE while ( ans ) : NEW_LINE INDENT res = res + " z " NEW_LINE ans -= 1 NEW_LINE DEDENT if ( n % 26 != 0 ) : NEW_LINE INDENT res = res + chr ( ( n % 26 ) + 96 ) NEW_LINE DEDENT return res NEW_LINE DEDENT n = 50 ; NEW_LINE print ( minLength ( n ) ) NEW_LINE print ( minString ( n ) ) NEW_LINE
Minimum halls required for class scheduling | Python3 implementation of the approach ; Function to return the minimum number of halls required ; Array to store the number of lectures ongoing at time t ; For every lecture increment start point s decrement ( end point + 1 ) ; Perform prefix sum and update the ans to maximum ; Driver code
MAX = 100001 NEW_LINE def minHalls ( lectures , n ) : NEW_LINE INDENT prefix_sum = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix_sum [ lectures [ i ] [ 0 ] ] += 1 ; NEW_LINE prefix_sum [ lectures [ i ] [ 1 ] + 1 ] -= 1 ; NEW_LINE DEDENT ans = prefix_sum [ 0 ] ; NEW_LINE for i in range ( 1 , MAX ) : NEW_LINE INDENT prefix_sum [ i ] += prefix_sum [ i - 1 ] ; NEW_LINE ans = max ( ans , prefix_sum [ i ] ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT lectures = [ [ 0 , 5 ] , [ 1 , 2 ] , [ 1 , 10 ] ] ; NEW_LINE n = len ( lectures ) ; NEW_LINE print ( minHalls ( lectures , n ) ) ; NEW_LINE DEDENT
Find the minimum capacity of the train required to hold the passengers | Function to return the minimum capacity required ; To store the minimum capacity ; To store the current capacity of the train ; For every station ; Add the number of people entering the train and subtract the number of people exiting the train to get the current capacity of the train ; Update the minimum capacity ; Driver code
def minCapacity ( enter , exit , n ) : NEW_LINE INDENT minCap = 0 ; NEW_LINE currCap = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT currCap = currCap + enter [ i ] - exit [ i ] ; NEW_LINE minCap = max ( minCap , currCap ) ; NEW_LINE DEDENT return minCap ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT enter = [ 3 , 5 , 2 , 0 ] ; NEW_LINE exit = [ 0 , 2 , 4 , 4 ] ; NEW_LINE n = len ( enter ) ; NEW_LINE print ( minCapacity ( enter , exit , n ) ) ; NEW_LINE DEDENT
Count of numbers in the range [ L , R ] which satisfy the given conditions | Python3 implementation of the approach ; Maximum possible valid number ; To store all the required number from the range [ 1 , MAX ] ; Function that returns true if x satisfies the given conditions ; To store the digits of x ; If current digit appears more than once ; If current digit is greater than 5 ; Put the digit in the map ; Function to generate all the required numbers in the range [ 1 , MAX ] ; Insert first 5 valid numbers ; Inserting 0 externally because 0 cannot be the leading digit in any number ; If x satisfies the given conditions ; Cannot append anymore digit as adding a digit will repeat one of the already present digits ; Append all the valid digits one by one and append the new generated number to the queue ; Append the digit ; Push the newly generated number to the queue ; Function to copmpare two strings which represent a numerical value ; Function to return the count of valid numbers in the range [ l , r ] ; Generate all the valid numbers in the range [ 1 , MAX ] ; To store the count of numbers in the range [ l , r ] ; For every valid number in the range [ 1 , MAX ] ; If current number is within the required range ; If number is equal to either l or r ; Driver code
from collections import deque NEW_LINE MAX = 543210 NEW_LINE ans = [ ] NEW_LINE def isValidNum ( x ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( len ( x ) ) : NEW_LINE INDENT if ( ord ( x [ i ] ) - ord ( '0' ) in mp . keys ( ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( ord ( x [ i ] ) - ord ( '0' ) > 5 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT mp [ ord ( x [ i ] ) - ord ( '0' ) ] = 1 NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def generate ( ) : NEW_LINE INDENT q = deque ( ) NEW_LINE q . append ( "1" ) NEW_LINE q . append ( "2" ) NEW_LINE q . append ( "3" ) NEW_LINE q . append ( "4" ) NEW_LINE q . append ( "5" ) NEW_LINE flag = True NEW_LINE ans . append ( "0" ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT x = q . popleft ( ) NEW_LINE if ( isValidNum ( x ) ) : NEW_LINE INDENT ans . append ( x ) NEW_LINE DEDENT if ( len ( x ) == 6 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for i in range ( 6 ) : NEW_LINE INDENT z = str ( i ) NEW_LINE temp = x + z NEW_LINE q . append ( temp ) NEW_LINE DEDENT DEDENT DEDENT def comp ( a , b ) : NEW_LINE INDENT if ( len ( a ) == len ( b ) ) : NEW_LINE INDENT if a < b : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return len ( a ) < len ( b ) NEW_LINE DEDENT DEDENT def findcount ( l , r ) : NEW_LINE INDENT generate ( ) NEW_LINE count = 0 NEW_LINE for i in range ( len ( ans ) ) : NEW_LINE INDENT a = ans [ i ] NEW_LINE if ( comp ( l , a ) and comp ( a , r ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT elif ( a == l or a == r ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT l = "1" NEW_LINE r = "1000" NEW_LINE print ( findcount ( l , r ) ) NEW_LINE
Find permutation with maximum remainder Sum | Function to find the permutation ; Put n at the first index 1 ; Put all the numbers from 2 to n sequentially ; Driver code ; Display the permutation
def Findpermutation ( n ) : NEW_LINE INDENT a = [ 0 ] * ( n + 1 ) ; NEW_LINE a [ 1 ] = n ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT a [ i ] = i - 1 ; NEW_LINE DEDENT return a ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 8 ; NEW_LINE v = Findpermutation ( n ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( v [ i ] , end = ' ▁ ' ) ; NEW_LINE DEDENT DEDENT
Lexicographically smallest string of length N and sum K | Function to return the lexicographically smallest string of length n that satisfies the given condition ; Iteration from the last position in the array ; If k is a positive integer ; ' z ' needs to be inserted ; Add the required character ; Driver code
def lexo_small ( n , k ) : NEW_LINE INDENT arr = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr += ' a ' ; NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT k -= i ; NEW_LINE if ( k >= 0 ) : NEW_LINE INDENT if ( k >= 26 ) : NEW_LINE INDENT arr = arr [ : i ] + ' z ' + arr [ i + 1 : ] ; NEW_LINE k -= 26 ; NEW_LINE DEDENT else : NEW_LINE INDENT c = ( k + 97 - 1 ) ; NEW_LINE arr = arr [ : i ] + chr ( c ) + arr [ i + 1 : ] ; NEW_LINE k -= ord ( arr [ i ] ) - ord ( ' a ' ) + 1 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT k += i ; NEW_LINE DEDENT return arr ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; k = 42 ; NEW_LINE arr = lexo_small ( n , k ) ; NEW_LINE print ( arr ) ; NEW_LINE DEDENT
Check if string can be rearranged so that every Odd length Substring is Palindrome | Function to check is it possible to rearrange the string such that every odd length substring is palindrome ; Length of the string ; To count number of distinct character in string ; To count frequency of each character ; Inserting into set ; Incrementing the frequency ; All characters in the string are same ; There are more than 2 different character in string ; Currently there is 2 different character in string ; Get the frequencies of the characters that present in string ; Difference between their count is less than or equal to 1 ; Driver code
def IsPossible ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE count = set ( ) ; NEW_LINE map = dict . fromkeys ( s , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT count . add ( s [ i ] ) ; NEW_LINE map [ s [ i ] ] += 1 ; NEW_LINE DEDENT if ( len ( count ) == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( len ( count ) > 2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT j = 0 NEW_LINE it = list ( count ) [ j ] ; NEW_LINE x = 0 ; y = 0 ; NEW_LINE x = map [ it ] ; NEW_LINE j += 1 NEW_LINE it = list ( count ) [ j ] ; NEW_LINE y = map [ it ] ; NEW_LINE if ( abs ( x - y ) <= 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aaaddad " ; NEW_LINE if ( IsPossible ( s ) ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE DEDENT DEDENT
Minimum element left from the array after performing given operations | Function to return the minimum possible value of the last element left after performing the given operations ; Driver code
def getMin ( arr , n ) : NEW_LINE INDENT minVal = min ( arr ) ; NEW_LINE return minVal ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 3 , 1 , 6 , 9 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( getMin ( arr , n ) ) ; NEW_LINE DEDENT
Largest substring with same Characters | Function to find largest sub with same characters ; Traverse the string ; If character is same as previous increment temp value ; Return the required answer ; Driver code ; Function call
def Substring ( s ) : NEW_LINE INDENT ans , temp = 1 , 1 NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == s [ i - 1 ] ) : NEW_LINE INDENT temp += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans = max ( ans , temp ) NEW_LINE temp = 1 NEW_LINE DEDENT DEDENT ans = max ( ans , temp ) NEW_LINE return ans NEW_LINE DEDENT s = " abcdddddeff " NEW_LINE print ( Substring ( s ) ) NEW_LINE
Number of balanced parenthesis substrings | Function to find number of balanced parenthesis sub strings ; To store required answer ; Vector to stores the number of balanced brackets at each depth . ; d stores checks the depth of our sequence For example level of ( ) is 1 and that of ( ( ) ) is 2. ; If open bracket increase depth ; If closing bracket ; Return the required answer ; Driver code ; Function call
def Balanced_Substring ( s , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE arr = [ 0 ] * ( int ( n / 2 ) + 1 ) ; NEW_LINE d = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT d += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( d == 1 ) : NEW_LINE INDENT j = 2 NEW_LINE while ( j <= n // 2 + 1 and arr [ j ] != 0 ) : NEW_LINE INDENT arr [ j ] = 0 NEW_LINE DEDENT DEDENT ans += 1 ; NEW_LINE ans += arr [ d ] ; NEW_LINE arr [ d ] += 1 ; NEW_LINE d -= 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT s = " ( ) ( ) ( ) " ; NEW_LINE n = len ( s ) ; NEW_LINE print ( Balanced_Substring ( s , n ) ) ; NEW_LINE
Count ways to divide circle using N non | Function to calculate x ^ y % mod efficiently ; Initialize the answer ; If power is odd ; Update the answer ; Square the base and half the exponent ; Return the value ; Function to calculate ncr % mod efficiently ; Initialize the answer ; Calculate ncr in O ( r ) ; Multiply with the numerator factor ; Calculate the inverse of factor of denominator ; Multiply with inverse value ; Return answer value ; Function to return the number of non intersecting chords ; define mod value ; Value of C ( 2 n , n ) ; Modulo inverse of ( n + 1 ) ; Multiply with modulo inverse ; Return the answer ; Driver code ; Function call
def power ( x , y , mod ) : NEW_LINE INDENT res = 1 NEW_LINE while ( y ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % mod NEW_LINE DEDENT x = ( x * x ) % mod NEW_LINE y = ( y >> 1 ) NEW_LINE DEDENT return ( res % mod ) NEW_LINE DEDENT def ncr ( n , r , mod ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 1 , r + 1 ) : NEW_LINE INDENT res = ( res * ( n - i + 1 ) ) % mod NEW_LINE inv = power ( i , mod - 2 , mod ) NEW_LINE res = ( res * inv ) % mod NEW_LINE DEDENT return ( res % mod ) NEW_LINE DEDENT def NoOfChords ( A ) : NEW_LINE INDENT mod = 10 ** 9 + 7 NEW_LINE ans = ncr ( 2 * A , A , mod ) NEW_LINE inv = power ( A + 1 , mod - 2 , mod ) NEW_LINE ans = ( ans * inv ) % mod NEW_LINE return ( ans % mod ) NEW_LINE DEDENT N = 2 NEW_LINE print ( NoOfChords ( N ) ) NEW_LINE
Longest Subarray having strictly positive XOR | Function to return the length of the longest sub - array having positive XOR ; To store the XOR of all the elements ; To check if all the elements of the array are 0 s ; Take XOR of all the elements ; If any positive value is found the make the checkallzero false ; If complete array is the answer ; If all elements are equal to zero ; Initialize l and r ; First positive value of the array ; Last positive value of the array ; Maximum length among these two subarrays ; Driver code
def StrictlyPositiveXor ( A , N ) : NEW_LINE INDENT allxor = 0 ; NEW_LINE checkallzero = True ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT allxor ^= A [ i ] ; NEW_LINE if ( A [ i ] > 0 ) : NEW_LINE INDENT checkallzero = False ; NEW_LINE DEDENT DEDENT if ( allxor != 0 ) : NEW_LINE INDENT return N ; NEW_LINE DEDENT if ( checkallzero ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT l = N ; r = - 1 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] > 0 ) : NEW_LINE INDENT l = i + 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ i ] > 0 ) : NEW_LINE INDENT r = i + 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT return max ( N - l , r - 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 0 , 0 , 1 ] ; NEW_LINE N = len ( A ) ; NEW_LINE print ( StrictlyPositiveXor ( A , N ) ) ; NEW_LINE DEDENT
Find minimum length sub | Python3 implementation of the approach ; Function to return the minimum length of a sub - array which contains 0 , 1 , 2 , 3 , 4 as a sub - sequence ; To store the indices where 0 , 1 , 2 , 3 and 4 are present ; To store if there exist a valid prefix of sequence in array ; Base Case ; If current element is 0 ; Update the count of 0 s till now ; Push the index of the new 0 ; To check if previous element of the given sequence is found till now ; If it is the end of sequence ; Iterate for other elements of the sequence ; Binary Search to find closest occurrence less than equal to starting point ; Update the starting point ; Driver code
MAX_INT = 1000000 NEW_LINE def solve ( Array , N ) : NEW_LINE INDENT pos = [ [ ] for i in range ( 5 ) ] NEW_LINE pref = [ 0 for i in range ( 5 ) ] NEW_LINE if ( Array [ 0 ] == 0 ) : NEW_LINE INDENT pref [ 0 ] = 1 NEW_LINE pos [ 0 ] . append ( 0 ) NEW_LINE DEDENT ans = MAX_INT NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( Array [ i ] == 0 ) : NEW_LINE INDENT pref [ 0 ] += 1 NEW_LINE pos [ 0 ] . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( pref [ Array [ i ] - 1 ] > 0 ) : NEW_LINE INDENT pref [ Array [ i ] ] += 1 NEW_LINE pos [ Array [ i ] ] . append ( i ) NEW_LINE if ( Array [ i ] == 4 ) : NEW_LINE INDENT end = i NEW_LINE start = i NEW_LINE for j in range ( 3 , - 1 , - 1 ) : NEW_LINE INDENT s = 0 NEW_LINE e = len ( pos [ j ] ) - 1 NEW_LINE temp = - 1 NEW_LINE while ( s <= e ) : NEW_LINE INDENT m = ( s + e ) // 2 NEW_LINE if ( pos [ j ] [ m ] <= start ) : NEW_LINE INDENT temp = pos [ j ] [ m ] NEW_LINE s = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT e = m - 1 NEW_LINE DEDENT DEDENT start = temp NEW_LINE DEDENT ans = min ( ans , end - start + 1 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT Array = [ 0 , 1 , 2 , 3 , 4 , 2 , 0 , 3 , 4 ] NEW_LINE N = len ( Array ) NEW_LINE print ( solve ( Array , N ) ) NEW_LINE
Find optimal weights which can be used to weigh all the weights in the range [ 1 , X ] | Function to find the optimal weights ; Number of weights required ; Finding the value of required powers of 3 ; Optimal Weights are powers of 3 ; Driver code
def findWeights ( X ) : NEW_LINE INDENT sum = 0 NEW_LINE power = 0 NEW_LINE while ( sum < X ) : NEW_LINE INDENT sum = pow ( 3 , power + 1 ) - 1 NEW_LINE sum //= 2 NEW_LINE power += 1 NEW_LINE DEDENT ans = 1 NEW_LINE for i in range ( 1 , power + 1 ) : NEW_LINE INDENT print ( ans , end = " ▁ " ) NEW_LINE ans = ans * 3 NEW_LINE DEDENT DEDENT X = 2 NEW_LINE findWeights ( X ) NEW_LINE
Order of indices which is lexicographically smallest and sum of elements is <= X | Python3 implementation of the approach ; Function to return the chosen indices ; Maximum indices chosen ; Try to replace the first element in ans by i , making the order lexicographically smaller ; If no further replacement possible return ; If found an index smaller than ind and sum not exceeding X then remove index of smallest value from ans and then add index i to ans ; Driver code ; Print the chosen indices
import sys ; NEW_LINE def solve ( X , A ) : NEW_LINE INDENT minimum = sys . maxsize ; NEW_LINE ind = - 1 ; NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] < minimum ) : NEW_LINE INDENT minimum = A [ i ] ; NEW_LINE ind = i ; NEW_LINE DEDENT DEDENT maxIndChosen = X // minimum ; NEW_LINE ans = [ ] ; NEW_LINE if ( maxIndChosen == 0 ) : NEW_LINE INDENT return ans ; NEW_LINE DEDENT for i in range ( maxIndChosen ) : NEW_LINE INDENT ans . append ( ind ) ; NEW_LINE DEDENT temp = maxIndChosen ; NEW_LINE sum = maxIndChosen * A [ ind ] ; NEW_LINE for i in range ( ind ) : NEW_LINE INDENT if ( sum - X == 0 or temp == 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT while ( ( sum - A [ ind ] + A [ i ] ) <= X and temp != 0 ) : NEW_LINE INDENT del ( ans [ 0 ] ) ; NEW_LINE ans . append ( i ) ; NEW_LINE temp -= 1 ; NEW_LINE sum += ( A [ i ] - A [ ind ] ) ; NEW_LINE DEDENT DEDENT ans . sort ( ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 5 , 6 , 4 , 8 ] ; NEW_LINE X = 18 ; NEW_LINE ans = solve ( X , A ) ; NEW_LINE for i in range ( len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT
Find if a binary matrix exists with given row and column sums | Function to check if matrix exists ; Store sum of rowsums , max of row sum number of non zero row sums ; Store sum of column sums , max of column sum number of non zero column sums ; Check condition 1 , 2 , 3 ; Driver Code
def matrix_exist ( row , column , r , c ) : NEW_LINE INDENT row_sum = 0 NEW_LINE column_sum = 0 NEW_LINE row_max = - 1 NEW_LINE column_max = - 1 NEW_LINE row_non_zero = 0 NEW_LINE column_non_zero = 0 NEW_LINE for i in range ( r ) : NEW_LINE INDENT row_sum += row [ i ] NEW_LINE row_max = max ( row_max , row [ i ] ) NEW_LINE if ( row [ i ] ) : NEW_LINE INDENT row_non_zero = row_non_zero + 1 NEW_LINE DEDENT DEDENT for i in range ( c ) : NEW_LINE INDENT column_sum = column_sum + column [ i ] NEW_LINE column_max = max ( column_max , column [ i ] ) NEW_LINE if ( column [ i ] ) : NEW_LINE INDENT column_non_zero = column_non_zero + 1 NEW_LINE DEDENT DEDENT if ( ( row_sum != column_sum ) or ( row_max > column_non_zero ) or ( column_max > row_non_zero ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT row = [ 2 , 2 , 2 , 2 , 2 ] NEW_LINE column = [ 5 , 5 , 0 , 0 ] NEW_LINE r = len ( row ) NEW_LINE c = len ( column ) NEW_LINE if matrix_exist ( row , column , r , c ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Length of longest sub | Function to find maximum distance between unequal elements ; Calculate maxMean ; Iterate over array and calculate largest subarray with all elements greater or equal to maxMean ; Driver code
def longestSubarray ( arr , n ) : NEW_LINE INDENT maxMean = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT maxMean = max ( maxMean , ( arr [ i ] + arr [ i - 1 ] ) // 2 ) ; NEW_LINE DEDENT ans = 0 ; NEW_LINE subarrayLength = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] >= maxMean ) : NEW_LINE INDENT subarrayLength += 1 ; NEW_LINE ans = max ( ans , subarrayLength ) ; NEW_LINE DEDENT else : NEW_LINE INDENT subarrayLength = 0 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT arr = [ 4 , 3 , 3 , 2 , 1 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( longestSubarray ( arr , n ) ) ; NEW_LINE
Maximum distance between two unequal elements | Function to return the maximum distance between two unequal elements ; If first and last elements are unequal they are maximum distance apart ; Fix first element as one of the elements and start traversing from the right ; Break for the first unequal element ; To store the distance from the first element ; Fix last element as one of the elements and start traversing from the left ; Break for the first unequal element ; To store the distance from the last element ; Maximum possible distance ; Driver code
def maxDistance ( arr , n ) : NEW_LINE INDENT if ( arr [ 0 ] != arr [ n - 1 ] ) : NEW_LINE INDENT return ( n - 1 ) ; NEW_LINE DEDENT i = n - 1 ; NEW_LINE while ( i > 0 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ 0 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT i -= 1 ; NEW_LINE DEDENT distFirst = - 1 if ( i == 0 ) else i ; NEW_LINE i = 0 ; NEW_LINE while ( i < n - 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ n - 1 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT distLast = - 1 if ( i == n - 1 ) else ( n - 1 - i ) ; NEW_LINE maxDist = max ( distFirst , distLast ) ; NEW_LINE return maxDist ; NEW_LINE DEDENT arr = [ 4 , 4 , 1 , 2 , 1 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxDistance ( arr , n ) ) ; NEW_LINE
Minimum number of pairs required to make two strings same | Python3 implementation of the approach ; Function which will check if there is a path between a and b by using BFS ; Function to return the minimum number of pairs ; To store the count of pairs ; Iterating through the strings ; Check if we can add an edge in the graph ; Return the count of pairs ; Driver code
from collections import defaultdict , deque NEW_LINE def Check_Path ( a , b , G ) : NEW_LINE INDENT visited = defaultdict ( bool ) NEW_LINE queue = deque ( ) NEW_LINE queue . append ( a ) NEW_LINE visited [ a ] = True NEW_LINE while queue : NEW_LINE INDENT n = queue . popleft ( ) NEW_LINE if n == b : NEW_LINE INDENT return True NEW_LINE DEDENT for i in list ( G [ n ] ) : NEW_LINE INDENT if visited [ i ] == False : NEW_LINE INDENT queue . append ( i ) NEW_LINE visited [ i ] = True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT def countPairs ( s1 , s2 , G ) : NEW_LINE INDENT name = defaultdict ( bool ) NEW_LINE count = 0 NEW_LINE for i in range ( x ) : NEW_LINE INDENT a = s1 [ i ] NEW_LINE b = s2 [ i ] NEW_LINE if a in G and b not in G and a != b : NEW_LINE INDENT G [ a ] . append ( b ) NEW_LINE G [ b ] . append ( a ) NEW_LINE count += 1 NEW_LINE DEDENT elif b in G and a not in G and a != b : NEW_LINE INDENT G [ b ] . append ( a ) NEW_LINE G [ a ] . append ( b ) NEW_LINE count += 1 NEW_LINE DEDENT elif a not in G and b not in G and a != b : NEW_LINE INDENT G [ a ] . append ( b ) NEW_LINE G [ b ] . append ( a ) NEW_LINE count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if not Check_Path ( a , b , G ) and a != b : NEW_LINE INDENT G [ a ] . append ( b ) NEW_LINE G [ b ] . append ( a ) NEW_LINE count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " abb " NEW_LINE s2 = " dad " NEW_LINE x = len ( s1 ) NEW_LINE G = defaultdict ( list ) NEW_LINE print ( countPairs ( s1 , s2 , G ) ) NEW_LINE DEDENT
Generate an array of K elements such that sum of elements is N and the condition a [ i ] < a [ i + 1 ] <= 2 * a [ i ] is met | Set 2 | Function that print the desired array which satisfies the given conditions ; If the lowest filling condition is void , then it is not possible to generate the required array ; Increase all the elements by cnt ; Start filling from the back till the number is a [ i + 1 ] <= 2 * a [ i ] ; Get the number to be filled ; If it is less than the remaining numbers to be filled ; less than remaining numbers to be filled ; Get the sum of the array ; If this condition is void at any stage during filling up , then print - 1 ; Else add it to the sum ; If the sum condition is not satisified , then print - 1 ; Print the generated array ; Driver code
def solve ( n , k ) : NEW_LINE INDENT mini = 0 NEW_LINE x1 = 1 NEW_LINE a = [ 0 for i in range ( k ) ] NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT mini += x1 NEW_LINE a [ i - 1 ] = x1 NEW_LINE x1 += 1 NEW_LINE DEDENT if ( n < mini ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE return NEW_LINE DEDENT rem = n - mini NEW_LINE cnt = int ( rem / k ) NEW_LINE rem = rem % k NEW_LINE for i in range ( k ) : NEW_LINE INDENT a [ i ] += cnt NEW_LINE DEDENT i = k - 1 NEW_LINE while ( i > 0 and rem > 0 ) : NEW_LINE INDENT xx = a [ i - 1 ] * 2 NEW_LINE left = xx - a [ i ] NEW_LINE if ( rem >= left ) : NEW_LINE INDENT a [ i ] = xx NEW_LINE rem -= left NEW_LINE DEDENT else : NEW_LINE INDENT a [ i ] += rem NEW_LINE rem = 0 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT sum = a [ 0 ] NEW_LINE for i in range ( 1 , k ) : NEW_LINE INDENT if ( a [ i ] > 2 * a [ i - 1 ] ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE return NEW_LINE DEDENT sum += a [ i ] NEW_LINE DEDENT if ( sum != n ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE return NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 26 NEW_LINE k = 6 NEW_LINE solve ( n , k ) NEW_LINE DEDENT
Minimizing array sum by applying XOR operation on all elements of the array | Python3 implementation of the approach ; Function to return the minimized sum ; To store the frequency of bit in every element ; Finding element X ; Taking XOR of elements and finding sum ; Driver code
MAX = 25 ; NEW_LINE def getMinSum ( arr , n ) : NEW_LINE INDENT bits_count = [ 0 ] * MAX NEW_LINE max_bit = 0 ; sum = 0 ; ans = 0 ; NEW_LINE for d in range ( n ) : NEW_LINE INDENT e = arr [ d ] ; f = 0 ; NEW_LINE while ( e > 0 ) : NEW_LINE INDENT rem = e % 2 ; NEW_LINE e = e // 2 ; NEW_LINE if ( rem == 1 ) : NEW_LINE INDENT bits_count [ f ] += rem ; NEW_LINE DEDENT f += 1 NEW_LINE DEDENT max_bit = max ( max_bit , f ) ; NEW_LINE DEDENT for d in range ( max_bit ) : NEW_LINE INDENT temp = pow ( 2 , d ) ; NEW_LINE if ( bits_count [ d ] > n // 2 ) : NEW_LINE INDENT ans = ans + temp ; NEW_LINE DEDENT DEDENT for d in range ( n ) : NEW_LINE INDENT arr [ d ] = arr [ d ] ^ ans ; NEW_LINE sum = sum + arr [ d ] ; NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 5 , 7 , 11 , 15 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( getMinSum ( arr , n ) ) NEW_LINE DEDENT
Maximum money that can be withdrawn in two steps | Function to return the maximum coins we can get ; Update elements such that X > Y ; Take from the maximum ; Refill ; Again , take the maximum ; Driver code
def maxCoins ( X , Y ) : NEW_LINE INDENT if ( X < Y ) : NEW_LINE INDENT X , Y = Y , X ; NEW_LINE DEDENT coins = X ; NEW_LINE X -= 1 ; NEW_LINE coins += max ( X , Y ) ; NEW_LINE return coins ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 7 ; Y = 5 ; NEW_LINE print ( maxCoins ( X , Y ) ) ; NEW_LINE DEDENT
Minimum value of X to make all array elements equal by either decreasing or increasing by X | Function that returns the minimum value of X ; Declare a set ; Iterate in the array element and insert them into the set ; If unique elements is 1 ; Unique elements is 2 ; Get both el2 and el1 ; Check if they are even ; If there are 3 unique elements ; Get three unique elements ; Check if their difference is same ; More than 3 unique elements ; Driver code
def findMinimumX ( a , n ) : NEW_LINE INDENT st = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT st . add ( a [ i ] ) NEW_LINE DEDENT if ( len ( st ) == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( len ( st ) == 2 ) : NEW_LINE INDENT st = list ( st ) NEW_LINE el1 = st [ 0 ] NEW_LINE el2 = st [ 1 ] NEW_LINE if ( ( el2 - el1 ) % 2 == 0 ) : NEW_LINE INDENT return int ( ( el2 - el1 ) / 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( el2 - el1 ) NEW_LINE DEDENT DEDENT if ( len ( st ) == 3 ) : NEW_LINE INDENT st = list ( st ) NEW_LINE el1 = st [ 0 ] NEW_LINE el2 = st [ 1 ] NEW_LINE el3 = st [ 2 ] NEW_LINE if ( ( el2 - el1 ) == ( el3 - el2 ) ) : NEW_LINE INDENT return el2 - el1 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 4 , 4 , 7 , 4 , 1 ] NEW_LINE n = len ( a ) NEW_LINE print ( findMinimumX ( a , n ) ) NEW_LINE DEDENT
Maximum elements which can be crossed using given units of a and b | Function to find the number of elements crossed ; Keep a copy of a ; Iterate in the binary array ; If no a and b left to use ; If there is no a ; use b and increase a by 1 if arr [ i ] is 1 ; simply use b ; Use a if theres no b ; Increase a and use b if arr [ i ] == 1 ; Use a ; Driver code
def findElementsCrossed ( arr , a , b , n ) : NEW_LINE INDENT aa = a NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a == 0 and b == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT elif ( a == 0 ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT b -= 1 NEW_LINE a = min ( aa , a + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT b -= 1 NEW_LINE DEDENT DEDENT elif ( b == 0 ) : NEW_LINE INDENT a -= 1 NEW_LINE DEDENT elif ( arr [ i ] == 1 and a < aa ) : NEW_LINE INDENT b -= 1 NEW_LINE a = min ( aa , a + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT a -= 1 NEW_LINE DEDENT ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 0 , 0 , 1 , 0 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE a = 1 NEW_LINE b = 2 NEW_LINE print ( findElementsCrossed ( arr , a , b , n ) ) NEW_LINE
Move all zeros to start and ones to end in an Array of random integers | Utility function to print the contents of an array ; Function that pushes all the zeros to the start and ones to the end of an array ; To store the count of elements which are not equal to 1 ; Traverse the array and calculate count of elements which are not 1 ; Now all non - ones elements have been shifted to front and ' count1' is set as index of first 1. Make all elements 1 from count to end . ; Initialize lastNonBinary position to zero ; Traverse the array and pull non - zero elements to the required indices ; Ignore the 1 's ; Mark the position Of last NonBinary integer ; Place non - zero element to their required indices ; Put zeros to start of array ; Driver code
def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def pushBinaryToBorder ( arr , n ) : NEW_LINE INDENT count1 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != 1 ) : NEW_LINE INDENT arr [ count1 ] = arr [ i ] NEW_LINE count1 += 1 NEW_LINE DEDENT DEDENT while ( count1 < n ) : NEW_LINE INDENT arr [ count1 ] = 1 NEW_LINE count1 += 1 NEW_LINE DEDENT lastNonOne = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( not lastNonOne ) : NEW_LINE INDENT lastNonOne = i NEW_LINE DEDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT arr [ lastNonOne ] = arr [ i ] NEW_LINE lastNonOne -= 1 NEW_LINE DEDENT DEDENT while ( lastNonOne >= 0 ) : NEW_LINE INDENT arr [ lastNonOne ] = 0 NEW_LINE lastNonOne -= 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 0 , 0 , 0 , 3 , 6 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE pushBinaryToBorder ( arr , n ) NEW_LINE printArr ( arr , n ) NEW_LINE DEDENT
Count the pairs of vowels in the given string | Function that return true if character ch is a vowel ; Function to return the count of adjacent vowel pairs in the given string ; If current character and the character after it are both vowels ; Driver code
def isVowel ( ch ) : NEW_LINE INDENT if ch in [ ' a ' , ' e ' , ' i ' , ' o ' , ' u ' ] : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def vowelPairs ( s , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( isVowel ( s [ i ] ) and isVowel ( s [ i + 1 ] ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT s = " abaebio " NEW_LINE n = len ( s ) NEW_LINE print ( vowelPairs ( s , n ) ) NEW_LINE
Minimum possible final health of the last monster in a game | Function to return the gcd of two numbers ; Function to return the minimum possible health for the monster ; gcd of first and second element ; gcd for all subsequent elements ; Driver code
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def solve ( health , n ) : NEW_LINE INDENT currentgcd = gcd ( health [ 0 ] , health [ 1 ] ) NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT currentgcd = gcd ( currentgcd , health [ i ] ) NEW_LINE DEDENT return currentgcd NEW_LINE DEDENT health = [ 4 , 6 , 8 , 12 ] NEW_LINE n = len ( health ) NEW_LINE print ( solve ( health , n ) ) NEW_LINE
Divide array into increasing and decreasing subsequence without changing the order | Function to print strictly increasing and strictly decreasing sequence if possible ; Arrays to store strictly increasing and decreasing sequence ; Initializing last element of both sequence ; Iterating through the array ; If current element can be appended to both the sequences ; If next element is greater than the current element Then append it to the strictly increasing array ; Otherwise append it to the strictly decreasing array ; If current element can be appended to the increasing sequence only ; If current element can be appended to the decreasing sequence only ; Else we can not make such sequences from the given array ; Print the required sequences ; Driver code
def Find_Sequence ( array , n ) : NEW_LINE INDENT inc_arr , dec_arr = [ ] , [ ] NEW_LINE inc , dec = - 1 , 1e7 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if inc < array [ i ] < dec : NEW_LINE INDENT if array [ i ] < array [ i + 1 ] : NEW_LINE INDENT inc = array [ i ] NEW_LINE inc_arr . append ( array [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dec = array [ i ] NEW_LINE dec_arr . append ( array [ i ] ) NEW_LINE DEDENT DEDENT elif inc < array [ i ] : NEW_LINE INDENT inc = array [ i ] NEW_LINE inc_arr . append ( array [ i ] ) NEW_LINE DEDENT elif dec > array [ i ] : NEW_LINE INDENT dec = array [ i ] NEW_LINE dec_arr . append ( array [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' - 1' ) NEW_LINE break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( inc_arr , dec_arr ) NEW_LINE DEDENT DEDENT arr = [ 5 , 1 , 3 , 6 , 8 , 2 , 9 , 0 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE Find_Sequence ( arr , n ) NEW_LINE
Find the sum of digits of a number at even and odd places | Function to return the reverse of a number ; Function to find the sum of the odd and even positioned digits in a number ; If c is even number then it means digit extracted is at even place ; Driver code
def reverse ( n ) : NEW_LINE INDENT rev = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT rev = ( rev * 10 ) + ( n % 10 ) NEW_LINE n //= 10 NEW_LINE DEDENT return rev NEW_LINE DEDENT def getSum ( n ) : NEW_LINE INDENT n = reverse ( n ) NEW_LINE sumOdd = 0 NEW_LINE sumEven = 0 NEW_LINE c = 1 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( c % 2 == 0 ) : NEW_LINE INDENT sumEven += n % 10 NEW_LINE DEDENT else : NEW_LINE INDENT sumOdd += n % 10 NEW_LINE DEDENT n //= 10 NEW_LINE c += 1 NEW_LINE DEDENT print ( " Sum ▁ odd ▁ = " , sumOdd ) NEW_LINE print ( " Sum ▁ even ▁ = " , sumEven ) NEW_LINE DEDENT n = 457892 NEW_LINE getSum ( n ) NEW_LINE
Find the sum of digits of a number at even and odd places | Function to find the sum of the odd and even positioned digits in a number ; If n is odd then the last digit will be odd positioned ; To store the respective sums ; While there are digits left process ; If current digit is odd positioned ; Even positioned digit ; Invert state ; Remove last digit ; Driver code
def getSum ( n ) : NEW_LINE INDENT if ( n % 2 == 1 ) : NEW_LINE INDENT isOdd = True NEW_LINE DEDENT else : NEW_LINE INDENT isOdd = False NEW_LINE DEDENT sumOdd = 0 NEW_LINE sumEven = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( isOdd ) : NEW_LINE INDENT sumOdd += n % 10 NEW_LINE DEDENT else : NEW_LINE INDENT sumEven += n % 10 NEW_LINE DEDENT isOdd = not isOdd NEW_LINE n //= 10 NEW_LINE DEDENT print ( " Sum ▁ odd ▁ = ▁ " , sumOdd ) NEW_LINE print ( " Sum ▁ even ▁ = ▁ " , sumEven ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 457892 NEW_LINE getSum ( n ) NEW_LINE DEDENT
Count the number of currency notes needed | Function to return the amount of notes with value A required ; If possible ; Driver code
def bankNotes ( A , B , S , N ) : NEW_LINE INDENT numerator = S - ( B * N ) NEW_LINE denominator = A - B NEW_LINE if ( numerator % denominator == 0 ) : NEW_LINE INDENT return ( numerator // denominator ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT A , B , S , N = 1 , 2 , 7 , 5 NEW_LINE print ( bankNotes ( A , B , S , N ) ) NEW_LINE
Length of the longest substring with no consecutive same letters | Function to return the length of the required sub - string ; Get the length of the string ; Iterate in the string ; Check for not consecutive ; If cnt greater than maxi ; Re - initialize ; Check after iteration is complete ; Driver code
def longestSubstring ( s ) : NEW_LINE INDENT cnt = 1 ; NEW_LINE maxi = 1 ; NEW_LINE n = len ( s ) ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] != s [ i - 1 ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT maxi = max ( cnt , maxi ) ; NEW_LINE cnt = 1 ; NEW_LINE DEDENT DEDENT maxi = max ( cnt , maxi ) ; NEW_LINE return maxi ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " ccccdeededff " ; NEW_LINE print ( longestSubstring ( s ) ) ; NEW_LINE DEDENT
Minimum number of changes such that elements are first Negative and then Positive | Function to return the count of minimum operations required ; To store the count of negative integers on the right of the current index ( inclusive ) ; Find the count of negative integers on the right ; If current element is negative ; To store the count of positive elements ; Find the positive integers on the left ; If current element is positive ; Update the answer ; Return the required answer ; Driver code
def Minimum_Operations ( a , n ) : NEW_LINE INDENT np = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT np [ i ] = np [ i + 1 ] NEW_LINE if ( a [ i ] <= 0 ) : NEW_LINE INDENT np [ i ] += 1 NEW_LINE DEDENT DEDENT pos = 0 NEW_LINE ans = n NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( a [ i ] >= 0 ) : NEW_LINE INDENT pos += 1 NEW_LINE DEDENT ans = min ( ans , pos + np [ i + 1 ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ - 1 , 0 , 1 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( Minimum_Operations ( a , n ) ) NEW_LINE
Sum of elements in an array whose difference with the mean of another array is less than k | Function for finding sum of elements whose diff with mean is not more than k ; Find the mean of second array ; Find sum of elements from array1 whose difference with mean is not more than k ; Return result ; Driver code
def findSumofEle ( arr1 , m , arr2 , n , k ) : NEW_LINE INDENT arraySum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT arraySum += arr2 [ i ] NEW_LINE DEDENT mean = arraySum / n NEW_LINE sumOfElements = 0 NEW_LINE difference = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT difference = arr1 [ i ] - mean NEW_LINE if ( ( difference < 0 ) and ( k > ( - 1 ) * difference ) ) : NEW_LINE INDENT sumOfElements += arr1 [ i ] NEW_LINE DEDENT if ( ( difference >= 0 ) and ( k > difference ) ) : NEW_LINE INDENT sumOfElements += arr1 [ i ] NEW_LINE DEDENT DEDENT return sumOfElements NEW_LINE DEDENT arr1 = [ 1 , 2 , 3 , 4 , 7 , 9 ] NEW_LINE arr2 = [ 0 , 1 , 2 , 1 , 1 , 4 ] NEW_LINE k = 2 NEW_LINE m = len ( arr1 ) NEW_LINE n = len ( arr2 ) NEW_LINE print ( findSumofEle ( arr1 , m , arr2 , n , k ) ) NEW_LINE
Find n positive integers that satisfy the given equations | Function to find n positive integers that satisfy the given conditions ; To store n positive integers ; Place N - 1 one 's ; If can not place ( y - ( n - 1 ) ) as the Nth integer ; Place Nth integer ; To store the sum of squares of N integers ; If it is less than x ; Print the required integers ; Driver code
def findIntegers ( n , x , y ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT ans . append ( 1 ) NEW_LINE DEDENT if ( y - ( n - 1 ) <= 0 ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE return NEW_LINE DEDENT ans . append ( y - ( n - 1 ) ) NEW_LINE store = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT store += ans [ i ] * ans [ i ] NEW_LINE DEDENT if ( store < x ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE return ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT n , x , y = 3 , 254 , 18 NEW_LINE findIntegers ( n , x , y ) NEW_LINE
Find the minimum number of steps to reach M from N | Function to find a minimum number of steps to reach M from N ; Continue till m is greater than n ; If m is odd ; add one ; divide m by 2 ; Return the required answer ; Driver code
def Minsteps ( n , m ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( m > n ) : NEW_LINE INDENT if ( m & 1 ) : NEW_LINE INDENT m += 1 NEW_LINE ans += 1 NEW_LINE DEDENT m //= 2 NEW_LINE ans += 1 NEW_LINE DEDENT return ans + n - m NEW_LINE DEDENT n = 4 NEW_LINE m = 6 NEW_LINE print ( Minsteps ( n , m ) ) NEW_LINE
Find the number of jumps to reach X in the number line from zero | Utility function to calculate sum of numbers from 1 to x ; Function to find the number of jumps to reach X in the number line from zero ; First make number positive Answer will be same either it is Positive or negative ; To store the required answer ; Continue till number is lesser or not in same parity ; Return the required answer ; Driver code
def getsum ( x ) : NEW_LINE INDENT return int ( ( x * ( x + 1 ) ) / 2 ) NEW_LINE DEDENT def countJumps ( n ) : NEW_LINE INDENT n = abs ( n ) NEW_LINE ans = 0 NEW_LINE while ( getsum ( ans ) < n or ( getsum ( ans ) - n ) & 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 9 NEW_LINE print ( countJumps ( n ) ) NEW_LINE DEDENT
Maximum number of candies that can be bought | Function to return the maximum candies that can be bought ; Buy all the candies of the last type ; Starting from second last ; Amount of candies of the current type that can be bought ; Add candies of current type that can be bought ; Update the previous bought amount ; Driver code
def maxCandies ( arr , n ) : NEW_LINE INDENT prevBought = arr [ n - 1 ] ; NEW_LINE candies = prevBought ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT x = min ( prevBought - 1 , arr [ i ] ) ; NEW_LINE if ( x >= 0 ) : NEW_LINE INDENT candies += x ; NEW_LINE prevBought = x ; NEW_LINE DEDENT DEDENT return candies ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 3 , 6 ] ; NEW_LINE n = len ( arr ) NEW_LINE print ( maxCandies ( arr , n ) ) ; NEW_LINE DEDENT
Replace all elements by difference of sums of positive and negative numbers after that element | Function to print the array elements ; Function to replace all elements with absolute difference of absolute sums of positive and negative elements ; Calculate absolute sums of positive and negative elements in range i + 1 to N ; calculate difference of both sums ; replace i - th elements with absolute difference ; Driver code
def printArray ( N , arr ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE DEDENT def replacedArray ( N , arr ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT pos_sum = 0 NEW_LINE neg_sum = 0 NEW_LINE for j in range ( i + 1 , N , 1 ) : NEW_LINE INDENT if ( arr [ j ] > 0 ) : NEW_LINE INDENT pos_sum += arr [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT neg_sum += arr [ j ] NEW_LINE DEDENT DEDENT diff = abs ( pos_sum ) - abs ( neg_sum ) NEW_LINE arr [ i ] = abs ( diff ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE arr = [ 1 , - 1 , 2 , 3 , - 2 ] NEW_LINE replacedArray ( N , arr ) NEW_LINE printArray ( N , arr ) NEW_LINE N = 6 NEW_LINE arr1 = [ - 3 , - 4 , - 2 , 5 , 1 , - 2 ] NEW_LINE replacedArray ( N , arr1 ) NEW_LINE printArray ( N , arr1 ) NEW_LINE DEDENT
Minimum cuts required to convert a palindromic string to a different palindromic string | Function to check if string is palindrome or not ; Function to check if it is possible to get result by making just one cut ; Appending last element in front ; Removing last element ; Checking whether string s2 is palindrome and different from s . ; If length is <= 3 then it is impossible ; Array to store frequency of characters ; Store count of characters in a array ; Condition for edge cases ; Return 1 if it is possible to get palindromic string in just one cut . Else we can always reached in two cuttings . ; Driver Code
def isPalindrome ( s ) : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] != s [ len ( s ) - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return true NEW_LINE DEDENT def ans ( s ) : NEW_LINE INDENT s2 = s NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT s2 = s2 [ len ( s2 ) - 1 ] + s2 NEW_LINE s2 = s2 [ 0 : len ( s2 ) - 1 ] NEW_LINE if ( s != s2 and isPalindrome ( s2 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def solve ( s ) : NEW_LINE INDENT if ( len ( s ) <= 3 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT cnt = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT cnt [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT max = cnt [ 0 ] NEW_LINE for i in range ( len ( cnt ) ) : NEW_LINE INDENT if cnt [ i ] > max : NEW_LINE INDENT max = cnt [ i ] NEW_LINE DEDENT DEDENT if ( max >= len ( s ) - 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ans ( s ) == True : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 2 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " nolon " NEW_LINE print ( solve ( s ) ) NEW_LINE DEDENT
Minimum cuts required to convert a palindromic string to a different palindromic string | Recursive function to find minimum number of cuts if length of string is even ; If length is odd then return 2 ; To check if half of palindromic string is itself a palindrome ; If not then return 1 ; Else call function with half palindromic string ; Function to find minimum number of cuts If length of string is odd ; If length is <= 3 then it is impossible ; Array to store frequency of characters ; Store count of characters in a array ; Condition for edge cases ; If length is even ; If length is odd ; Driver Code
def solveEven ( s ) : NEW_LINE INDENT if len ( s ) % 2 == 1 : NEW_LINE INDENT return 2 NEW_LINE DEDENT ls = s [ 0 : len ( s ) // 2 ] NEW_LINE rs = s [ len ( s ) // 2 : len ( s ) ] NEW_LINE if ls != rs : NEW_LINE INDENT return 1 NEW_LINE DEDENT return solveEven ( ls ) NEW_LINE DEDENT def solveOdd ( s ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT def solve ( s ) : NEW_LINE INDENT if len ( s ) <= 3 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT cnt = [ 0 ] * 25 NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT cnt [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT if max ( cnt ) >= len ( s ) - 1 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if len ( s ) % 2 == 0 : NEW_LINE INDENT return solveEven ( s ) NEW_LINE DEDENT if len ( s ) % 2 == 1 : NEW_LINE INDENT return solveOdd ( s ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " nolon " NEW_LINE print ( solve ( s ) ) NEW_LINE DEDENT
Minimum changes required such that the string satisfies the given condition | Function to return the minimum changes required ; To store the count of minimum changes , number of ones and the number of zeroes ; First character has to be '1 ; If condition fails changes need to be made ; Return the required count ; Driver code
def minChanges ( str , n ) : NEW_LINE INDENT count , zeros , ones = 0 , 0 , 0 NEW_LINE DEDENT ' NEW_LINE INDENT if ( ord ( str [ 0 ] ) != ord ( '1' ) ) : NEW_LINE INDENT count += 1 NEW_LINE ones += 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( ord ( str [ i ] ) == ord ( '0' ) ) : NEW_LINE INDENT zeros += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT if ( zeros > ones ) : NEW_LINE INDENT zeros -= 1 NEW_LINE ones += 1 NEW_LINE count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "0000" NEW_LINE n = len ( str ) NEW_LINE print ( minChanges ( str , n ) ) NEW_LINE DEDENT
Count possible moves in the given direction in a grid | Function to return the count of possible steps in a single direction ; It can cover infinite steps ; We are approaching towards X = N ; We are approaching towards X = 1 ; Function to return the count of steps ; Take the minimum of both moves independently ; Update count and current positions ; Driver code
def steps ( cur , x , n ) : NEW_LINE INDENT if x == 0 : NEW_LINE INDENT return float ( ' inf ' ) NEW_LINE DEDENT elif x > 0 : NEW_LINE INDENT return abs ( ( n - cur ) // x ) NEW_LINE DEDENT else : NEW_LINE INDENT return abs ( int ( ( cur - 1 ) / x ) ) NEW_LINE DEDENT DEDENT def countSteps ( curx , cury , n , m , moves ) : NEW_LINE INDENT count = 0 NEW_LINE k = len ( moves ) NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT x = moves [ i ] [ 0 ] NEW_LINE y = moves [ i ] [ 1 ] NEW_LINE stepct = min ( steps ( curx , x , n ) , steps ( cury , y , m ) ) NEW_LINE count += stepct NEW_LINE curx += stepct * x NEW_LINE cury += stepct * y NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , m , x , y = 4 , 5 , 1 , 1 NEW_LINE moves = [ [ 1 , 1 ] , [ 1 , 1 ] , [ 0 , - 2 ] ] NEW_LINE print ( countSteps ( x , y , n , m , moves ) ) NEW_LINE DEDENT
Minimum number of elements that should be removed to make the array good | Function to return the minimum number of elements that must be removed to make the given array good ; Count frequency of each element ; For each element check if there exists another element that makes a valid pair ; If does not exist then increment answer ; Driver Code
def minimumRemoval ( n , a ) : NEW_LINE INDENT c = dict . fromkeys ( a , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT c [ a [ i ] ] += 1 ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT ok = False ; NEW_LINE for j in range ( 31 ) : NEW_LINE INDENT x = ( 1 << j ) - a [ i ] ; NEW_LINE if ( x in c and ( c [ x ] > 1 or ( c [ x ] == 1 and x != a [ i ] ) ) ) : NEW_LINE INDENT ok = True ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( not ok ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 4 , 7 , 1 , 5 , 4 , 9 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( minimumRemoval ( n , a ) ) ; NEW_LINE DEDENT
Minimum elements to be removed such that sum of adjacent elements is always odd | Returns the minimum number of eliminations ; Stores the previous element ; Stores the new value ; Check if the previous and current values are of same parity ; Previous value is now the current value ; Return the counter variable ; Driver code
def min_elimination ( n , arr ) : NEW_LINE INDENT count = 0 NEW_LINE prev_val = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT curr_val = arr [ i ] ; NEW_LINE if ( curr_val % 2 == prev_val % 2 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT prev_val = curr_val NEW_LINE DEDENT return count NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( min_elimination ( n , arr ) ) ; NEW_LINE
Count all possible N digit numbers that satisfy the given condition | Function to return the count of required numbers ; If N is odd then return 0 ; Driver Code
def getCount ( N ) : NEW_LINE INDENT if ( N % 2 == 1 ) : NEW_LINE INDENT return "0" NEW_LINE DEDENT result = "9" NEW_LINE for i in range ( 1 , N // 2 ) : NEW_LINE INDENT result = result + "0" NEW_LINE DEDENT return result NEW_LINE DEDENT N = 4 NEW_LINE print ( getCount ( N ) ) NEW_LINE
Maximum number of teams that can be formed with given persons | Function that returns true if it possible to form a team with the given n and m ; 1 person of Type1 and 2 persons of Type2 can be chosen ; 1 person of Type2 and 2 persons of Type1 can be chosen ; Cannot from a team ; Function to return the maximum number of teams that can be formed ; To store the required count of teams formed ; Choose 2 persons of Type1 ; And 1 person of Type2 ; Choose 2 persons of Type2 ; And 1 person of Type1 ; Another team has been formed ; Driver code
def canFormTeam ( n , m ) : NEW_LINE INDENT if ( n >= 1 and m >= 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( m >= 1 and n >= 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def maxTeams ( n , m ) : NEW_LINE INDENT count = 0 NEW_LINE while ( canFormTeam ( n , m ) ) : NEW_LINE INDENT if ( n > m ) : NEW_LINE INDENT n -= 2 NEW_LINE m -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT m -= 2 NEW_LINE n -= 1 NEW_LINE DEDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE m = 5 NEW_LINE print ( maxTeams ( n , m ) ) NEW_LINE DEDENT