text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Maximize count of strings of length 3 that can be formed from N 1 s and M 0 s | Function that counts the number of strings of length three that can be made with given m 0 s and n 1 s ; Iterate until N & M are positive ; Case 1 : ; Case 2 : ; Print the count of strings ; Driver code ; Given count of 1 s and 0 s ; Function call | def number_of_strings ( N , M ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( N > 0 and M > 0 ) : NEW_LINE INDENT if ( N > M ) : NEW_LINE INDENT if ( N >= 2 ) : NEW_LINE INDENT N -= 2 NEW_LINE M -= 1 NEW_LINE ans += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if M >= 2 : NEW_LINE INDENT M -= 2 NEW_LINE N -= 1 NEW_LINE ans += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE M = 19 NEW_LINE number_of_strings ( N , M ) NEW_LINE DEDENT |
Minimize array length by repeatedly replacing pairs of unequal adjacent array elements by their sum | Function that returns the minimum length of the array after merging unequal adjacent elements ; Stores the first element and its frequency ; Traverse the array ; If all elements are equal ; No merge - pair operations can be performed ; Otherwise ; Given array ; Length of the array ; Function call | def minLength ( A , N ) : NEW_LINE INDENT elem = A [ 0 ] NEW_LINE count = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( A [ i ] == elem ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( count == N ) : NEW_LINE INDENT return N NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT arr = [ 2 , 1 , 3 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minLength ( arr , N ) ) NEW_LINE |
Reduce N to 0 or less by given X and Y operations | Function to check if N can be reduced to <= 0 or not ; Update N to N / 2 + 10 at most X times ; Update N to N - 10 Y times ; Driver Code | def NegEqu ( N , X , Y ) : NEW_LINE INDENT while ( X and N > N // 2 + 10 ) : NEW_LINE INDENT N = N // 2 + 10 NEW_LINE X -= 1 NEW_LINE DEDENT while ( Y ) : NEW_LINE INDENT N = N - 10 NEW_LINE Y -= 1 NEW_LINE DEDENT if ( N <= 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 100 NEW_LINE X = 3 NEW_LINE Y = 4 NEW_LINE if ( NegEqu ( N , X , Y ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Split array into minimum number of subarrays having GCD of its first and last element exceeding 1 | Python3 program for the above approach ; Function to find the minimum number of subarrays ; Right pointer ; Left pointer ; Count of subarrays ; Find GCD ( left , right ) ; Found a valid large subarray between arr [ left , right ] ; Searched the arr [ 0. . right ] and found no subarray having size > 1 and having gcd ( left , right ) > 1 ; Driver Code ; Function call | from math import gcd NEW_LINE def minSubarrays ( arr , n ) : NEW_LINE INDENT right = n - 1 NEW_LINE left = 0 NEW_LINE subarrays = 0 NEW_LINE while ( right >= 0 ) : NEW_LINE INDENT for left in range ( right + 1 ) : NEW_LINE INDENT if ( gcd ( arr [ left ] , arr [ right ] ) > 1 ) : NEW_LINE INDENT subarrays += 1 NEW_LINE right = left - 1 NEW_LINE break NEW_LINE DEDENT if ( left == right and __gcd ( arr [ left ] , arr [ right ] ) == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT DEDENT return subarrays NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE arr = [ 2 , 3 , 4 , 4 , 4 , 3 ] NEW_LINE print ( minSubarrays ( arr , N ) ) NEW_LINE DEDENT |
Find the largest possible value of K such that K modulo X is Y | Python3 program for the above approach ; Function to find the largest positive integer K such that K % x = y ; Stores the minimum solution ; Return the maximum possible value ; Driver Code | import sys NEW_LINE def findMaxSoln ( n , x , y ) : NEW_LINE INDENT ans = - sys . maxsize NEW_LINE for k in range ( n + 1 ) : NEW_LINE INDENT if ( k % x == y ) : NEW_LINE INDENT ans = max ( ans , k ) NEW_LINE DEDENT DEDENT return ( ans if ( ans >= 0 and ans <= n ) else - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 15 NEW_LINE x = 10 NEW_LINE y = 5 NEW_LINE print ( findMaxSoln ( n , x , y ) ) NEW_LINE DEDENT |
Count all numbers up to N having M as the last digit | Function to count the numbers ending with M ; Stores the count of numbers required ; Calculate count upto nearest power of 10 ; Computing the value of x ; Adding the count of numbers ending at M from x to N ; Driver Code ; Function call | def getCount ( N , M ) : NEW_LINE INDENT total_count = 0 NEW_LINE total_count += N // 10 NEW_LINE x = ( N // 10 ) * 10 NEW_LINE if ( ( N - x ) >= M ) : NEW_LINE INDENT total_count = total_count + 1 NEW_LINE DEDENT return total_count NEW_LINE DEDENT N = 100 NEW_LINE M = 1 NEW_LINE print ( getCount ( N , M ) ) NEW_LINE |
Count of Right | Python3 program for the above approach ; Function to find the number of right angled triangle that are formed from given N points whose perpendicular or base is parallel to X or Y axis ; To store the number of points has same x or y coordinates ; Store the total count of triangle ; Iterate to check for total number of possible triangle ; Add the count of triangles formed ; Total possible triangle ; Driver Code ; Given N points ; Function call | from collections import defaultdict NEW_LINE def RightAngled ( a , n ) : NEW_LINE INDENT xpoints = defaultdict ( lambda : 0 ) NEW_LINE ypoints = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT xpoints [ a [ i ] [ 0 ] ] += 1 NEW_LINE ypoints [ a [ i ] [ 1 ] ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( xpoints [ a [ i ] [ 0 ] ] >= 1 and ypoints [ a [ i ] [ 1 ] ] >= 1 ) : NEW_LINE INDENT count += ( ( xpoints [ a [ i ] [ 0 ] ] - 1 ) * ( ypoints [ a [ i ] [ 1 ] ] - 1 ) ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT N = 5 NEW_LINE arr = [ [ 1 , 2 ] , [ 2 , 1 ] , [ 2 , 2 ] , [ 2 , 3 ] , [ 3 , 2 ] ] NEW_LINE print ( RightAngled ( arr , N ) ) NEW_LINE |
Smallest subarray which upon repetition gives the original array | Function to print the array ; Function to find the smallest subarray ; Corner Case ; Initialize the auxiliary subarray ; Push the first 2 elements into the subarray brr [ ] ; Iterate over the length of subarray ; If array can be divided into subarray of i equal length ; Check if on repeating the current subarray gives the original array or not ; Subarray found ; Add current element into subarray ; No subarray found ; Driver Code ; Function call | def printArray ( brr ) : NEW_LINE INDENT for it in brr : NEW_LINE INDENT print ( it , end = ' β ' ) NEW_LINE DEDENT DEDENT def RepeatingSubarray ( arr , N ) : NEW_LINE INDENT if ( N < 2 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT brr = [ ] NEW_LINE brr . append ( arr [ 0 ] ) NEW_LINE brr . append ( arr [ 1 ] ) NEW_LINE for i in range ( 2 , N // 2 + 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT a = False NEW_LINE n = len ( brr ) NEW_LINE j = i NEW_LINE while ( j < N ) : NEW_LINE INDENT K = j % i NEW_LINE if ( arr [ j ] == brr [ K ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT a = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( not a and j == N ) : NEW_LINE INDENT printArray ( brr ) NEW_LINE return NEW_LINE DEDENT DEDENT brr . append ( arr [ i ] ) NEW_LINE DEDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 1 , 2 , 2 , 1 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE RepeatingSubarray ( arr , N ) NEW_LINE DEDENT |
Find all missing numbers from a given sorted array | Function to find the missing elements ; Initialize diff ; Check if diff and arr [ i ] - i both are equal or not ; Loop for consecutive missing elements ; Given array arr [ ] ; Function call | def printMissingElements ( arr , N ) : NEW_LINE INDENT diff = arr [ 0 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] - i != diff ) : NEW_LINE INDENT while ( diff < arr [ i ] - i ) : NEW_LINE INDENT print ( i + diff , end = " β " ) NEW_LINE diff += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT arr = [ 6 , 7 , 10 , 11 , 13 ] NEW_LINE N = len ( arr ) NEW_LINE printMissingElements ( arr , N ) NEW_LINE |
Find all missing numbers from a given sorted array | Function to find the missing elements ; Initialize an array with zero of size equals to the maximum element in the array ; Make b [ i ] = 1 if i is present in the array ; If the element is present make b [ arr [ i ] ] = 1 ; Print the indices where b [ i ] = 0 ; Given array arr [ ] ; Function call | def printMissingElements ( arr , N ) : NEW_LINE INDENT b = [ 0 ] * ( arr [ N - 1 ] + 1 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT b [ arr [ i ] ] = 1 NEW_LINE DEDENT for i in range ( arr [ 0 ] , arr [ N - 1 ] + 1 ) : NEW_LINE INDENT if ( b [ i ] == 0 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 6 , 7 , 10 , 11 , 13 ] NEW_LINE N = len ( arr ) NEW_LINE printMissingElements ( arr , N ) NEW_LINE |
Least common element in given two Arithmetic sequences | Function to find the smallest element common in both the subsequences ; If a is equal to c ; If a exceeds c ; Check for the satisfying equation ; Least value of possible_y satisfying the given equation will yield True in the below if and break the loop ; If the value of possible_y satisfying the given equation lies in range [ 0 , b ] ; If no value of possible_y satisfies the given equation ; Driver Code | def smallestCommon ( a , b , c , d ) : NEW_LINE INDENT if ( a == c ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT if ( a > c ) : NEW_LINE INDENT swap ( a , c ) ; NEW_LINE swap ( b , d ) ; NEW_LINE DEDENT first_term_diff = ( c - a ) ; NEW_LINE possible_y = 0 ; NEW_LINE for possible_y in range ( b ) : NEW_LINE INDENT if ( ( first_term_diff % b + possible_y * d ) % b == 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT if ( possible_y != b ) : NEW_LINE INDENT return c + possible_y * d ; NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT def swap ( x , y ) : NEW_LINE INDENT temp = x ; NEW_LINE x = y ; NEW_LINE y = temp ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 2 ; B = 20 ; C = 19 ; D = 9 ; NEW_LINE print ( smallestCommon ( A , B , C , D ) ) ; NEW_LINE DEDENT |
Minimum number of flips with rotation to make binary string alternating | Function that finds the minimum number of flips to make the binary string alternating if left circular rotation is allowed ; Initialize prefix arrays to store number of changes required to put 1 s at either even or odd position ; If i is odd ; Update the oddone and evenone count ; Else i is even ; Update the oddone and evenone count ; Initialize minimum flips ; Check if substring [ 0 , i ] is appended at end how many changes will be required ; Return minimum flips ; Given String ; Length of given string ; Function call | def MinimumFlips ( s , n ) : NEW_LINE INDENT a = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] = 1 if s [ i ] == '1' else 0 NEW_LINE DEDENT oddone = [ 0 ] * ( n + 1 ) NEW_LINE evenone = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i % 2 != 0 ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT oddone [ i + 1 ] = oddone [ i ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT oddone [ i + 1 ] = oddone [ i ] + 0 NEW_LINE DEDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT evenone [ i + 1 ] = evenone [ i ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT evenone [ i + 1 ] = evenone [ i ] + 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT oddone [ i + 1 ] = oddone [ i ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT oddone [ i + 1 ] = oddone [ i ] + 0 NEW_LINE DEDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT evenone [ i + 1 ] = evenone [ i ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT evenone [ i + 1 ] = evenone [ i ] + 0 NEW_LINE DEDENT DEDENT DEDENT minimum = min ( oddone [ n ] , evenone [ n ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( n % 2 != 0 ) : NEW_LINE INDENT minimum = min ( minimum , oddone [ n ] - oddone [ i + 1 ] + evenone [ i + 1 ] ) NEW_LINE minimum = min ( minimum , evenone [ n ] - evenone [ i + 1 ] + oddone [ i + 1 ] ) NEW_LINE DEDENT DEDENT return minimum NEW_LINE DEDENT S = "000001100" NEW_LINE n = len ( S ) NEW_LINE print ( MinimumFlips ( S , n ) ) NEW_LINE |
Create a Graph by connecting divisors from N to M and find shortest path | Python3 program for the above approach ; Function to check the number is prime or not ; Base Cases ; Iterate till [ 5 , sqrt ( N ) ] to detect primarility of numbers ; Function to print the shortest path ; Use vector to store the factor of m and n ; Use map to check if largest common factor previously present or not ; First store m ; Check whether m is prime or not ; Largest common factor of m ; If m is divisible by i ; Store the largest common factor ; For number n ; Check whether n is prime ; Largest common factor of n ; Store the largest common factor ; Print the path Print factors from m ; To avoid duplicate printing of same element ; Print the factors from n ; Driver Code ; Given N and M ; Function call | import math NEW_LINE def isprm ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i = 5 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i += 6 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def shortestpath ( m , n ) : NEW_LINE INDENT mfactor = [ ] NEW_LINE nfactor = [ ] NEW_LINE fre = dict . fromkeys ( range ( n + 1 ) , 0 ) NEW_LINE mfactor . append ( m ) NEW_LINE fre [ m ] = 1 NEW_LINE while ( m != 1 ) : NEW_LINE INDENT if ( isprm ( m ) ) : NEW_LINE INDENT mfactor . append ( 1 ) NEW_LINE fre [ 1 ] = 1 NEW_LINE m = 1 NEW_LINE DEDENT else : NEW_LINE INDENT sqt = ( int ) ( math . sqrt ( m ) ) NEW_LINE for i in range ( 2 , sqt + 1 ) : NEW_LINE INDENT if ( m % i == 0 ) : NEW_LINE INDENT mfactor . append ( m // i ) NEW_LINE fre [ m // i ] = 1 NEW_LINE m = ( m // i ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT nfactor . append ( n ) NEW_LINE while ( fre [ n ] != 1 ) : NEW_LINE INDENT if ( isprm ( n ) ) : NEW_LINE INDENT nfactor . append ( 1 ) NEW_LINE n = 1 NEW_LINE DEDENT else : NEW_LINE INDENT sqt = ( int ) ( math . sqrt ( n ) ) NEW_LINE for i in range ( 2 , sqt + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT nfactor . append ( n // i ) NEW_LINE n = ( n // i ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( len ( mfactor ) ) : NEW_LINE INDENT if ( mfactor [ i ] == n ) : NEW_LINE INDENT break NEW_LINE DEDENT print ( mfactor [ i ] , end = " β < - - > β " ) NEW_LINE DEDENT for i in range ( len ( nfactor ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT print ( nfactor [ i ] , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( nfactor [ i ] , end = " β < - - > β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m = 18 NEW_LINE n = 19 NEW_LINE shortestpath ( m , n ) NEW_LINE DEDENT |
Possible number of Trees having N vertex | Python3 program for the above approach ; Function to count the total number of trees possible ; Find the max element in the given array ; Level array store the number of Nodes on level i initially all values are zero ; In this case tree can not be created ; To store the count of trees ; Iterate until maxElement ; Calculate level [ i ] ^ level [ i + 1 ] ; Update the count of tree ; Return the final count of trees ; Driver Code ; Given array arr ; Function call | mod = int ( 1e9 + 7 ) NEW_LINE def NumberOfTrees ( arr , N ) : NEW_LINE INDENT maxElement = max ( arr ) ; NEW_LINE level = [ 0 ] * ( maxElement + 1 ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT level [ arr [ i ] ] += 1 ; NEW_LINE DEDENT if ( arr [ 0 ] != 0 or level [ 0 ] != 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT ans = 1 ; NEW_LINE for i in range ( maxElement ) : NEW_LINE INDENT for j in range ( level [ i + 1 ] ) : NEW_LINE INDENT ans = ( ans * level [ i ] ) % mod ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 ; NEW_LINE arr = [ 0 , 3 , 2 , 1 , 2 , 2 , 1 ] ; NEW_LINE print ( NumberOfTrees ( arr , N ) ) ; NEW_LINE DEDENT |
Possible number of Trees having N vertex | Python3 program for the above approach ; Function that finds the value of x ^ y using Modular Exponentiation ; Base Case ; If y is odd , multiply x with result ; Return the value ; Function that counts the total number of trees possible ; Find the max element in array ; Level array store the number nodes on level i initially all values are 0 ; In this case tree can not be created ; Calculate level [ i ] ^ level [ i + 1 ] ; Return the final count ; Driver Code ; Given Queries ; Function call | mod = int ( 1e9 + 7 ) NEW_LINE def power ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT p = power ( x , y // 2 ) % mod NEW_LINE p = ( p * p ) % mod NEW_LINE if ( y & 1 ) : NEW_LINE INDENT p = ( x * p ) % mod NEW_LINE DEDENT return p NEW_LINE DEDENT def NumberOfTrees ( arr , N ) : NEW_LINE INDENT maxElement = max ( arr ) NEW_LINE level = [ 0 ] * ( maxElement + 1 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT level [ arr [ i ] ] += 1 NEW_LINE DEDENT if ( arr [ 0 ] != 0 or level [ 0 ] != 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 1 NEW_LINE for i in range ( maxElement ) : NEW_LINE INDENT ans = ( ans * power ( level [ i ] , level [ i + 1 ] ) ) % mod NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 7 NEW_LINE arr = [ 0 , 3 , 2 , 1 , 2 , 2 , 1 ] NEW_LINE print ( NumberOfTrees ( arr , N ) ) NEW_LINE |
A Binary String Game | Function to return the result of the game ; Length of the string ; List to maintain the lengths of consecutive '1' s in the string ; Variable that keeps a track of the current length of the block of consecutive '1' s ; Adds non - zero lengths ; This takes care of the case when the last character is '1 ; Sorts the lengths in descending order ; Scores of the 2 players ; For player 1 ; For player 2 ; In case of a tie ; Print the result ; Given string S ; Function call | def gameMax ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE list = [ ] NEW_LINE one = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT one += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( one != 0 ) : NEW_LINE INDENT list . append ( one ) NEW_LINE DEDENT one = 0 NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT if ( one != 0 ) : NEW_LINE INDENT list . append ( one ) NEW_LINE DEDENT list . sort ( reverse = True ) NEW_LINE score_1 = 0 NEW_LINE score_2 = 0 NEW_LINE for i in range ( len ( list ) ) : NEW_LINE INDENT if ( list [ i ] % 2 == 1 ) : NEW_LINE INDENT score_1 += list [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT score_2 += list [ i ] NEW_LINE DEDENT DEDENT if ( score_1 == score_2 ) : NEW_LINE INDENT return ' - 1' NEW_LINE DEDENT if ( score_1 > score_2 ) : NEW_LINE INDENT return " Player β 1" NEW_LINE DEDENT else : NEW_LINE INDENT return " Player β 2" NEW_LINE DEDENT DEDENT S = "11111101" NEW_LINE print ( gameMax ( S ) ) NEW_LINE |
Count of carry operations on adding two Binary numbers | Function to count the number of carry operations to add two binary numbers ; To Store the carry count ; Iterate till there is no carry ; Carry now contains common set bits of x and y ; Sum of bits of x and y where at least one of the bits is not set ; Carry is shifted by one so that adding it to x gives the required sum ; Adding number of 1 's of carry to final count ; Return the final count ; Given two numbers ; Function call | def carryCount ( num1 , num2 ) : NEW_LINE INDENT count = 0 NEW_LINE while ( num2 != 0 ) : NEW_LINE INDENT carry = num1 & num2 NEW_LINE num1 = num1 ^ num2 NEW_LINE num2 = carry << 1 NEW_LINE count += bin ( num2 ) . count ( '1' ) NEW_LINE DEDENT return count NEW_LINE DEDENT A = 15 NEW_LINE B = 10 NEW_LINE print ( carryCount ( A , B ) ) NEW_LINE |
Count of all possible ways to reach a target by a Knight | Python3 program to implement above approach ; Function to return X ^ Y % Mod ; Base case ; Function to return the inverse of factorial of N ; Base case ; Function to return factorial of n % Mod ; Base case ; Function to return the value of n ! / ( ( n - k ) ! * k ! ) ; Function to return the count of ways to reach ( n , m ) from ( 0 , 0 ) ; If ( N + M ) % 3 != 0 ; No possible way exists ; Calculate X and Y from the equations X + 2 Y = N and 2 X + Y == M ; Driver code | Mod = int ( 1e9 + 7 ) NEW_LINE def power ( X , Y , Mod ) : NEW_LINE INDENT if Y == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT p = power ( X , Y // 2 , Mod ) % Mod NEW_LINE p = ( p * p ) % Mod NEW_LINE if Y & 1 : NEW_LINE INDENT p = ( X * p ) % Mod NEW_LINE DEDENT return p NEW_LINE DEDENT def Inversefactorial ( N ) : NEW_LINE INDENT if N <= 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT fact = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT fact = ( fact * i ) % Mod NEW_LINE DEDENT return power ( fact , Mod - 2 , Mod ) NEW_LINE DEDENT def factorial ( N ) : NEW_LINE INDENT if N <= 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT fact = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT fact = ( fact * i ) % Mod NEW_LINE DEDENT return fact NEW_LINE DEDENT def nck ( N , K ) : NEW_LINE INDENT factN = factorial ( N ) NEW_LINE inv = Inversefactorial ( K ) NEW_LINE invFact = Inversefactorial ( N - K ) NEW_LINE return ( ( ( factN * inv ) % Mod ) * invFact ) % Mod NEW_LINE DEDENT def TotalWays ( N , M ) : NEW_LINE INDENT if ( N + M ) % 3 != 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT X = N - ( N + M ) // 3 NEW_LINE Y = M - ( N + M ) // 3 NEW_LINE if X < 0 or Y < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT return nck ( X + Y , Y ) NEW_LINE DEDENT N , M = 3 , 3 NEW_LINE print ( TotalWays ( N , M ) ) NEW_LINE |
Lead a life problem | Function that calculates the profit with the earning and cost of expenses ; To store the total Profit ; Loop for n number of days ; If last day , no need to buy food ; Else buy food to gain energy for next day ; Update earning per day ; Update profit with daily spent ; Print the profit ; Driver Code ; Given days ; Given earnings ; Given cost ; Given energy e ; Function call | def calculateProfit ( n , earnings , cost , e ) : NEW_LINE INDENT profit = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT earning_per_day = 0 ; NEW_LINE daily_spent_food = 0 ; NEW_LINE if ( i == ( n - 1 ) ) : NEW_LINE INDENT earning_per_day = earnings [ i ] * e ; NEW_LINE profit = profit + earning_per_day ; NEW_LINE break ; NEW_LINE DEDENT if ( cost [ i ] < earnings [ i ] ) : NEW_LINE INDENT earning_per_day = earnings [ i ] * e ; NEW_LINE daily_spent_food = cost [ i ] * e ; NEW_LINE profit = ( profit + earning_per_day - daily_spent_food ) ; NEW_LINE DEDENT DEDENT print ( profit ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE earnings = [ 1 , 8 , 6 , 7 ] ; NEW_LINE cost = [ 1 , 3 , 4 , 1 ] ; NEW_LINE e = 5 ; NEW_LINE calculateProfit ( n , earnings , cost , e ) ; NEW_LINE DEDENT |
Check if N numbers with Even Sum can be selected from a given Array | Function to check if an odd sum can be made using N integers from the array ; Initialize odd and even counts ; Iterate over the array to count the no . of even and odd integers ; If element is odd ; If element is even ; Check if even_freq is more than N ; If odd_freq is odd ; Consider even count of odd ; Calculate even required ; If even count is less than required count ; Calculate even required ; If even count is less than required count ; Driver Code | def checkEvenSum ( arr , N , size ) : NEW_LINE INDENT even_freq , odd_freq = 0 , 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT odd_freq += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even_freq += 1 NEW_LINE DEDENT DEDENT if ( even_freq >= N ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT if ( odd_freq & 1 ) : NEW_LINE INDENT taken = odd_freq - 1 NEW_LINE req = N - taken NEW_LINE if ( even_freq < req ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT taken = odd_freq NEW_LINE req = N - taken NEW_LINE if ( even_freq < req ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 9 , 2 , 3 , 4 , 18 , 7 , 7 , 6 ] NEW_LINE size = len ( arr ) NEW_LINE N = 5 NEW_LINE if ( checkEvenSum ( arr , N , size ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Minimum count of digits required to obtain given Sum | Function to print the minimum count of digits ; IF N is divisible by 9 ; Count of 9 's is the answer ; If remainder is non - zero ; Driver Code | def mindigits ( n ) : NEW_LINE INDENT if ( n % 9 == 0 ) : NEW_LINE INDENT print ( n // 9 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( ( n // 9 ) + 1 ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n1 = 24 ; NEW_LINE n2 = 18 ; NEW_LINE mindigits ( n1 ) ; NEW_LINE mindigits ( n2 ) ; NEW_LINE DEDENT |
Count of all possible numbers not exceeding M having suffix N | Function to count the no . of digits of N ; Function to count all possible numbers having Suffix as N ; Difference of the A . P ; Count of the number of terms ; Driver code | def digitsOf ( num ) : NEW_LINE INDENT return len ( str ( num ) ) ; NEW_LINE DEDENT def count ( a , tn ) : NEW_LINE INDENT diff = int ( pow ( 10 , digitsOf ( a ) ) ) ; NEW_LINE return ( ( tn - a ) / diff ) + 1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 25 ; m = 4500 ; NEW_LINE print ( int ( count ( n , m ) ) ) ; NEW_LINE DEDENT |
Minimum increment / decrement operations required on Array to satisfy given conditions | Function to find minimum number of operations to get desired array ; For odd ' i ' , sum of elements till ' i ' is positive ; If i is even and sum is positive , make it negative by subtracting 1 + | s | from a [ i ] ; If i is odd and sum is negative , make it positive by adding 1 + | s | into a [ i ] ; For odd ' i ' , sum of elements till ' i ' is negative ; Check if ' i ' is odd and sum is positive , make it negative by subtracting 1 + | s | from a [ i ] ; Check if ' i ' is even and sum is negative , make it positive by adding 1 + | s | into a [ i ] ; Return the minimum of the two ; Driver Code ; Given array arr [ ] ; Function call | def minOperations ( a , N ) : NEW_LINE INDENT num_of_ops1 = num_of_ops2 = sum = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( i % 2 == 0 and sum >= 0 ) : NEW_LINE INDENT num_of_ops1 += ( 1 + abs ( sum ) ) NEW_LINE sum = - 1 NEW_LINE DEDENT elif ( i % 2 == 1 and sum <= 0 ) : NEW_LINE INDENT num_of_ops1 += ( 1 + abs ( sum ) ) NEW_LINE sum = 1 NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( i % 2 == 1 and sum >= 0 ) : NEW_LINE INDENT num_of_ops2 += ( 1 + abs ( sum ) ) NEW_LINE sum = - 1 NEW_LINE DEDENT elif ( i % 2 == 0 and sum <= 0 ) : NEW_LINE INDENT num_of_ops2 += ( 1 + abs ( sum ) ) NEW_LINE sum = 1 NEW_LINE DEDENT DEDENT return min ( num_of_ops1 , num_of_ops2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , - 4 , 5 , 0 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minOperations ( arr , N ) ) NEW_LINE DEDENT |
Check if all elements of a Circular Array can be made equal by increments of adjacent pairs | Function to check if all array elements can be made equal ; Stores the sum of even and odd array elements ; If index is odd ; Driver Code | def checkEquall ( arr , N ) : NEW_LINE INDENT sumEven , sumOdd = 0 , 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT sumOdd += arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT sumEven += arr [ i ] NEW_LINE DEDENT DEDENT if ( sumEven == sumOdd ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 7 , 3 , 5 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE if ( checkEquall ( arr , N ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Check if a number can be expressed as sum of two Perfect powers | Function that returns true if n can be written as a ^ m + b ^ n ; Taking isSum boolean array for check the sum exist or not ; To store perfect squares ; Initially all sums as false ; If sum exist then push that sum into perfect square vector ; Mark all perfect powers as false ; Traverse each perfectPowers ; Calculating Sum with perfect powers array ; Given Number n ; Function call | def isSumOfPower ( n ) : NEW_LINE INDENT isSum = [ 0 ] * ( n + 1 ) NEW_LINE perfectPowers = [ ] NEW_LINE perfectPowers . append ( 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT isSum [ i ] = False NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( isSum [ i ] == True ) : NEW_LINE INDENT perfectPowers . append ( i ) NEW_LINE continue NEW_LINE DEDENT j = i * i NEW_LINE while ( j > 0 and j < ( n + 1 ) ) : NEW_LINE INDENT isSum [ j ] = True NEW_LINE j *= i NEW_LINE DEDENT DEDENT for i in range ( len ( perfectPowers ) ) : NEW_LINE INDENT isSum [ perfectPowers [ i ] ] = False NEW_LINE DEDENT for i in range ( len ( perfectPowers ) ) : NEW_LINE INDENT for j in range ( len ( perfectPowers ) ) : NEW_LINE INDENT sum = ( perfectPowers [ i ] + perfectPowers [ j ] ) NEW_LINE if ( sum < ( n + 1 ) ) : NEW_LINE INDENT isSum [ sum ] = True NEW_LINE DEDENT DEDENT DEDENT return isSum [ n ] NEW_LINE DEDENT n = 9 NEW_LINE if ( isSumOfPower ( n ) ) : NEW_LINE INDENT print ( " true " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " false " ) NEW_LINE DEDENT |
Minimum increments by index value required to obtain at least two equal Array elements | Function to update every element adding to it its index value ; Function to check if at least two elements are equal or not ; Count the frequency of arr [ i ] ; Function to calculate the number of increment operations required ; Stores the minimum number of steps ; Driver code | def update ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT arr [ i ] += ( i + 1 ) ; NEW_LINE DEDENT DEDENT def check ( arr , N ) : NEW_LINE INDENT f = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT count = 0 ; NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT if ( count >= 2 ) : NEW_LINE INDENT f = 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( f == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT def incrementCount ( arr , N ) : NEW_LINE INDENT min = 0 ; NEW_LINE while ( check ( arr , N ) != True ) : NEW_LINE INDENT update ( arr , N ) ; NEW_LINE min += 1 ; NEW_LINE DEDENT print ( min ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 ; NEW_LINE arr = [ 12 , 8 , 4 ] ; NEW_LINE incrementCount ( arr , N ) ; NEW_LINE DEDENT |
Rearrange array such that all even | Function to check if it the array can be rearranged such such that every even indices contains an even element ; Stores the count of even elements ; Traverse array to count even numbers ; If even_no_count exceeds count of even indices ; Driver Code | def checkPossible ( a , n ) : NEW_LINE INDENT even_no_count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 2 == 0 ) : NEW_LINE INDENT even_no_count += 1 NEW_LINE DEDENT DEDENT if ( n // 2 > even_no_count ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT print ( " Yes " ) NEW_LINE j = 0 NEW_LINE for i in range ( 1 , n , 2 ) : NEW_LINE INDENT if ( a [ i ] % 2 == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT while ( j < n and a [ j ] % 2 != 0 ) : NEW_LINE INDENT j += 2 NEW_LINE DEDENT a [ i ] += a [ j ] NEW_LINE a [ j ] = a [ i ] - a [ j ] NEW_LINE a [ i ] -= a [ j ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 4 , 5 , 6 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE checkPossible ( arr , n ) NEW_LINE |
Largest number M having bit count of N such that difference between their OR and XOR value is maximized | Python3 program for the above approach ; Function to find the largest number M having the same length in binary form as N such that the difference between N | M and N ^ M is maximum ; Find the most significant bit of N ; Initialize M ; Set all the bits of M ; Return the answer ; Driver code ; Given Number N ; Function call | import math NEW_LINE def maxORminusXOR ( N ) : NEW_LINE INDENT MSB = int ( math . log2 ( N ) ) ; NEW_LINE M = 0 NEW_LINE for i in range ( MSB + 1 ) : NEW_LINE INDENT M += ( 1 << i ) NEW_LINE DEDENT return M NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE print ( maxORminusXOR ( N ) ) NEW_LINE DEDENT |
Maximum count of Equilateral Triangles that can be formed within given Equilateral Triangle | Function to find the number of equilateral triangle formed within another triangle ; Check for the valid condition ; Number of triangles having upward peak ; Number of inverted triangles ; Total no . of K sized triangle ; Driver Code ; Given N and K ; Function Call | def No_of_Triangle ( N , K ) : NEW_LINE INDENT if ( N < K ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT Tri_up = 0 ; NEW_LINE Tri_up = ( ( N - K + 1 ) * ( N - K + 2 ) ) // 2 ; NEW_LINE Tri_down = 0 ; NEW_LINE Tri_down = ( ( N - 2 * K + 1 ) * ( N - 2 * K + 2 ) ) // 2 ; NEW_LINE return Tri_up + Tri_down ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 ; K = 2 ; NEW_LINE print ( No_of_Triangle ( N , K ) ) ; NEW_LINE DEDENT |
Check if Array forms an increasing | Function to check if the given array forms an increasing decreasing sequence or vice versa ; Base Case ; First subarray is stricly increasing ; Check for strictly increasing condition & find the break point ; Check for strictly decreasing condition & find the break point ; If i is equal to length of array ; First subarray is strictly Decreasing ; Check for strictly increasing condition & find the break point ; Check for strictly increasing condition & find the break point ; If i is equal to length of array - 1 ; Condition if ar [ 0 ] == ar [ 1 ] ; Given array arr ; Function Call | def canMake ( n , ar ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( ar [ 0 ] < ar [ 1 ] ) : NEW_LINE INDENT i = 1 ; NEW_LINE while ( i < n and ar [ i - 1 ] < ar [ i ] ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT while ( i + 1 < n and ar [ i ] > ar [ i + 1 ] ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT if ( i >= n - 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT elif ( ar [ 0 ] > ar [ 1 ] ) : NEW_LINE INDENT i = 1 ; NEW_LINE while ( i < n and ar [ i - 1 ] > ar [ i ] ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT while ( i + 1 < n and ar [ i ] < ar [ i + 1 ] ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT if ( i >= n - 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 2 , n ) : NEW_LINE INDENT if ( ar [ i - 1 ] <= ar [ i ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE if ( canMake ( n , arr ) == False ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Minimum Count of Bit flips required to make a Binary String Palindromic | Function to calculate the length of the binary string ; Length ; Right shift of n ; Increment the length ; Return the length ; Function to check if the bit present at i - th position is a set bit or not ; Returns true if the bit is set ; Function to count the minimum number of bit flips required ; Length of the binary form ; Number of flips ; Pointer to the LSB ; Pointer to the MSB ; Check if the bits are equal ; Decrementing the left pointer ; Incrementing the right pointer ; Returns the number of bits to flip . ; Driver Code | def check_length ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n = n >> 1 NEW_LINE ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def check_ith_bit ( n , i ) : NEW_LINE INDENT if ( n & ( 1 << ( i - 1 ) ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def no_of_flips ( n ) : NEW_LINE INDENT ln = check_length ( n ) NEW_LINE ans = 0 NEW_LINE right = 1 NEW_LINE left = ln NEW_LINE while ( right < left ) : NEW_LINE INDENT if ( check_ith_bit ( n , right ) != check_ith_bit ( n , left ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT left -= 1 NEW_LINE right += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 12 NEW_LINE print ( no_of_flips ( n ) ) NEW_LINE |
Split N into two integers whose addition to A and B makes them equal | Function to calculate the splitted numbers ; Calculate X ; If X is odd ; No pair is possible ; Otherwise ; Calculate X ; Calculate Y ; Driver Code | def findPair ( A , B , N ) : NEW_LINE INDENT X = N - B + A NEW_LINE if ( X % 2 != 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT X = X // 2 NEW_LINE Y = N - X NEW_LINE print ( X , Y ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 1 NEW_LINE B = 3 NEW_LINE N = 4 NEW_LINE findPair ( A , B , N ) NEW_LINE DEDENT |
Find the amplitude and number of waves for the given array | Function to find the amplitude and number of waves for the given array ; Check for both sides adjacent elements that both must be less or both must be greater than current element ; Update amplitude with max value ; Prthe Amplitude ; Driver Code ; Given array a [ ] ; Calculate number of waves ; Function Call | def check ( a , n ) : NEW_LINE INDENT ma = a [ 1 ] - a [ 0 ] NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( ( a [ i ] > a [ i - 1 ] and a [ i + 1 ] < a [ i ] ) or ( a [ i ] < a [ i - 1 ] and a [ i + 1 ] > a [ i ] ) ) : NEW_LINE INDENT ma = max ( ma , abs ( a [ i ] - a [ i + 1 ] ) ) NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT print ( " Amplitude β = β " , ma ) NEW_LINE return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 2 , 1 , 5 , 0 , 7 , - 6 ] NEW_LINE n = len ( a ) NEW_LINE wave = ( n - 1 ) // 2 NEW_LINE if ( check ( a , n ) ) : NEW_LINE INDENT print ( " Waves β = β " , wave ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT |
Find relative rank of each element in array | Function to find relative rank for each element in the array A [ ] ; Create Rank Array ; Stack to store numbers in non - decreasing order from right ; Push last element in stack ; Iterate from second last element to first element ; If current element is less than the top of stack and append A [ i ] in stack ; Rank is stack size - 1 for current element ; Pop elements from stack till current element is greater than the top ; Push current element in Stack ; Rank is stack size - 1 ; Print rank of all elements ; Driver Code ; Given array A [ ] ; Function call | def findRank ( A , N ) : NEW_LINE INDENT rank = [ 0 ] * N NEW_LINE s = [ ] NEW_LINE s . append ( A [ N - 1 ] ) NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ i ] < s [ - 1 ] ) : NEW_LINE INDENT s . append ( A [ i ] ) NEW_LINE rank [ i ] = len ( s ) - 1 NEW_LINE DEDENT else : NEW_LINE INDENT while ( len ( s ) > 0 and A [ i ] >= s [ - 1 ] ) : NEW_LINE INDENT del s [ - 1 ] NEW_LINE DEDENT s . append ( A [ i ] ) NEW_LINE rank [ i ] = len ( s ) - 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( rank [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 5 , 4 ] NEW_LINE N = len ( A ) NEW_LINE findRank ( A , N ) NEW_LINE DEDENT |
Largest string obtained in Dictionary order after deleting K characters | Python3 program for the above approach ; Function to find the largest string after deleting k characters ; Deque dq used to find the largest string in dictionary after deleting k characters ; Iterate till the length of the string ; Condition for popping characters from deque ; To store the resultant string ; To form resultant string ; Return the resultant string ; Driver Code ; Given String ; Function call ; Print the answer | from collections import deque NEW_LINE def largestString ( n , k , sc ) : NEW_LINE INDENT s = [ i for i in sc ] NEW_LINE deq = deque ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( len ( deq ) > 0 and deq [ - 1 ] < s [ i ] and k > 0 ) : NEW_LINE INDENT deq . popleft ( ) NEW_LINE k -= 1 NEW_LINE DEDENT deq . append ( s [ i ] ) NEW_LINE DEDENT st = " " NEW_LINE for c in deq : NEW_LINE INDENT st = st + c NEW_LINE DEDENT return st NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE k = 2 NEW_LINE sc = " ritz " NEW_LINE result = largestString ( n , k , sc ) NEW_LINE print ( result ) NEW_LINE DEDENT |
Count total set bits in all numbers from range L to R | Function that counts the set bits from 0 to N ; To store sum of set bits from 0 - N ; Until n >= to 2 ^ i ; This k will get flipped after 2 ^ i iterations ; Change is iterator from 2 ^ i to 1 ; This will loop from 0 to n for every bit position ; When change = 1 flip the bit ; Again set change to 2 ^ i ; Increment the position ; Function that counts the set bit in the range ( L , R ) ; Return the count ; Driver Code ; Given L and R ; Function Call | def countSetBit ( n ) : NEW_LINE INDENT i = 0 ; NEW_LINE ans = 0 ; NEW_LINE while ( ( 1 << i ) <= n ) : NEW_LINE INDENT k = True ; NEW_LINE change = 1 << i ; NEW_LINE for j in range ( n + 1 ) : NEW_LINE INDENT ans += 0 if k == True else 1 ; NEW_LINE if ( change == 1 ) : NEW_LINE INDENT k = False if k == True else True ; NEW_LINE change = 1 << i ; NEW_LINE DEDENT else : NEW_LINE INDENT change -= 1 ; NEW_LINE DEDENT DEDENT i += 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def countSetBits ( L , R ) : NEW_LINE INDENT return abs ( countSetBit ( R ) - countSetBit ( L - 1 ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 3 ; NEW_LINE R = 5 ; NEW_LINE print ( " Total β set β bit β count β is β " , countSetBits ( L , R ) ) ; NEW_LINE DEDENT |
Count total set bits in all numbers from range L to R | Function to count set bit in range ; Count variable ; Find the set bit in Nth number ; If last bit is set ; Left sift by one bit ; Return count ; Driver Code ; Given range L and R ; Function call | def countSetBits ( L , R ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT n = i ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += ( n & 1 ) ; NEW_LINE n = n >> 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 3 ; R = 5 ; NEW_LINE print ( " Total β set β Bit β count β is β " , countSetBits ( L , R ) ) ; NEW_LINE DEDENT |
Count total set bits in all numbers from range L to R | Function to count set bit in [ L , R ] ; Variable for count set bit in range ; Count set bit for all number in range ; Use inbuilt function ; Driver Code ; Given range L and R ; Function Call | def countSetBits ( L , R ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT count += countSetBit ( i ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def countSetBit ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 3 ; NEW_LINE R = 5 ; NEW_LINE print ( " Total β set β bit β count β is β " , countSetBits ( L , R ) ) ; NEW_LINE DEDENT |
Make max elements in B [ ] equal to that of A [ ] by adding / subtracting integers in range [ 0 , K ] | Function that count the number of integers from array B such that subtracting element in the range [ 0 , K ] given any element in A ; To store the count of element ; Traverse the array B ; Traverse the array A ; Find the difference ; If difference is atmost K then increment the cnt ; Print the count ; Driver Code ; Given array A and B ; Given K ; Function call | def countElement ( A , N , B , M , K ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT currentElement = B [ i ] NEW_LINE for j in range ( N ) : NEW_LINE INDENT diff = abs ( currentElement - A [ j ] ) NEW_LINE if ( diff <= K ) : NEW_LINE INDENT cnt += 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT print ( cnt ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 100 , 65 , 35 , 85 , 55 ] NEW_LINE B = [ 30 , 60 , 75 , 95 ] NEW_LINE N = len ( A ) NEW_LINE M = len ( B ) NEW_LINE K = 5 NEW_LINE countElement ( A , N , B , M , K ) NEW_LINE DEDENT |
Generate a String of having N * N distinct non | Function to construct a string having N * N non - palindromic substrings ; Driver Code | def createString ( N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( ' a ' , end = ' ' ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( ' b ' , end = ' ' ) NEW_LINE DEDENT DEDENT N = 4 NEW_LINE createString ( N ) NEW_LINE |
Maximum Subset Sum possible by negating the entire sum after selecting the first Array element | Function returns maximum subset sum from the given array = ; Case 2 : Negate values from A [ 1 ] to A [ N - 1 ] ; Include only positives for max subset sum ; Return max sum obtained ; Function to return maximum of the maximum subset sum calculated for the two cases ; Case 1 ; Case 2 ; Modifying the sum ; Including first element ; Negating again ; Return the required answer ; Driver Code | def maxSubset ( A , flag ) : NEW_LINE INDENT n = len ( A ) NEW_LINE sum = 0 ; NEW_LINE if ( flag ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT A [ i ] = - A [ i ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( A [ i ] > 0 ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT def findBest ( A ) : NEW_LINE INDENT x = maxSubset ( A , 0 ) NEW_LINE y = maxSubset ( A , 1 ) NEW_LINE y = - y NEW_LINE y += A [ 0 ] NEW_LINE y = - y NEW_LINE return max ( x , y ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 10 , 4 , - 6 , 3 ] NEW_LINE print ( findBest ( A ) ) NEW_LINE DEDENT |
Construct an Array of Strings having Longest Common Prefix specified by the given Array | Function to find the array of strings ; Marks the ( N + 1 ) th string ; To generate remaining N strings ; Find i - th string using ( i + 1 ) - th string ; Check if current character is b ; Otherwise ; Insert the string ; Return the answer ; Driver Code ; Print the strings | def solve ( n , arr ) : NEW_LINE INDENT s = ' a ' * ( n ) NEW_LINE ans = [ ] NEW_LINE ans . append ( s ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if len ( s ) - 1 >= arr [ i ] : NEW_LINE ch = s [ arr [ i ] ] NEW_LINE if ( ch == ' b ' ) : NEW_LINE INDENT ch = ' a ' NEW_LINE DEDENT else : NEW_LINE INDENT ch = ' b ' NEW_LINE DEDENT p = list ( s ) NEW_LINE p [ arr [ i ] ] = ch NEW_LINE s = ' ' . join ( p ) NEW_LINE ans . append ( s ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 0 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE ans = solve ( n , arr ) NEW_LINE for i in range ( len ( ans ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( ans [ i ] ) NEW_LINE DEDENT DEDENT |
Minimize swaps required to maximize the count of elements replacing a greater element in an Array | Function to find the minimum number of swaps required ; Sort the array in ascending order ; Iterate until a greater element is found ; Keep incrementing ind ; If a greater element is found ; Increase count of swap ; Increment ind ; If end of array is reached ; Return the answer ; Driver Code | def countSwaps ( A , n ) : NEW_LINE INDENT A . sort ( ) NEW_LINE ind , res = 1 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( ind < n and A [ ind ] == A [ i ] ) : NEW_LINE INDENT ind += 1 NEW_LINE DEDENT if ( ind < n and A [ ind ] > A [ i ] ) : NEW_LINE INDENT res += 1 NEW_LINE ind += 1 NEW_LINE DEDENT if ( ind >= n ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT A = [ 4 , 3 , 3 , 2 , 5 ] NEW_LINE print ( countSwaps ( A , 5 ) ) NEW_LINE |
Minimize swaps required to maximize the count of elements replacing a greater element in an Array | Function to find the minimum number of swaps required ; Stores the frequency of the array elements ; Stores maximum frequency ; Find the max frequency ; Update frequency ; Update maximum frequency ; Driver code ; function call | def countSwaps ( A , n ) : NEW_LINE INDENT mp = { } NEW_LINE max_frequency = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if A [ i ] in mp : NEW_LINE INDENT mp [ A [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ A [ i ] ] = 1 NEW_LINE DEDENT max_frequency = max ( max_frequency , mp [ A [ i ] ] ) NEW_LINE DEDENT return n - max_frequency NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 6 , 5 , 4 , 3 , 2 , 1 ] NEW_LINE print ( countSwaps ( A , 6 ) ) NEW_LINE DEDENT |
Minimum number of steps required to obtain the given Array by the given operations | Function to calculate the minimum steps to obtain the desired array ; Initialize variable ; Iterate over the array arr [ ] ; Check if i > 0 ; Update the answer ; Return the result ; Driver Code | def min_operation ( a , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i > 0 ) : NEW_LINE INDENT ans += abs ( a [ i ] - a [ i - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT ans += abs ( a [ i ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( min_operation ( arr , n ) ) NEW_LINE DEDENT |
Construct a Matrix with no element exceeding X and sum of two adjacent elements not exceeding Y | Function to print the required matrix ; For 1 * 1 matrix ; Greater number ; Smaller number ; Sets / Resets for alternate filling of the matrix ; Print the matrix ; If end of row is reached ; Driver Code | def FindMatrix ( n , m , x , y ) : NEW_LINE INDENT if ( n * m == 1 ) : NEW_LINE INDENT if ( x > y ) : NEW_LINE INDENT print ( y ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( x ) NEW_LINE DEDENT return NEW_LINE DEDENT a = min ( x , y ) NEW_LINE b = min ( 2 * x , y ) - a NEW_LINE flag = True NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( flag ) : NEW_LINE INDENT print ( a , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( b , end = " β " ) NEW_LINE DEDENT flag = not flag NEW_LINE DEDENT if ( ( ( n % 2 != 0 and m % 2 == 0 ) or ( n % 2 == 0 and m % 2 == 0 ) ) ) : NEW_LINE INDENT flag = not flag NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT N = 3 NEW_LINE M = 3 NEW_LINE X = 5 NEW_LINE Y = 3 NEW_LINE FindMatrix ( N , M , X , Y ) NEW_LINE |
Count distinct elements after adding each element of First Array with Second Array | Function to find Occurrence of each element from 1 to 2 * MAX ; Initialise MAX ; Count vector to store count of each element from 1 to 2 * MAX Count = new int [ 2 * MAX + 1 ] ; ; Size of Arr1 and Arr2 ; Find the elements of arr3 and increase count of element by 1 ; Prthe result ; Driver Code ; Given arrays arr1 and arr2 ; Function call | def findCount ( Arr1 , Arr2 ) : NEW_LINE INDENT MAX = max ( max ( Arr1 ) , max ( Arr2 ) ) ; NEW_LINE Count = [ 0 for i in range ( 2 * MAX + 1 ) ] NEW_LINE n = len ( Arr1 ) ; NEW_LINE m = len ( Arr2 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT element = Arr1 [ i ] + Arr2 [ j ] ; NEW_LINE Count [ element ] += 1 ; NEW_LINE DEDENT DEDENT for i in range ( 1 , 2 * MAX + 1 ) : NEW_LINE INDENT if ( Count [ i ] > 0 ) : NEW_LINE INDENT print ( i , " - > " , Count [ i ] ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 1 , 2 ] ; NEW_LINE arr2 = [ 1 , 2 , 1 ] ; NEW_LINE findCount ( arr1 , arr2 ) ; NEW_LINE DEDENT |
Find two numbers with difference and division both same as N | Function to find two numbers with difference and division both as N ; Condition if the answer is not possible ; Calculate a and b ; Print the values ; Given N ; Function call | def findAandB ( N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT a = N * N / ( N - 1 ) NEW_LINE b = a / N NEW_LINE print ( " a β = β " , a ) NEW_LINE print ( " b β = β " , b ) NEW_LINE DEDENT N = 6 NEW_LINE findAandB ( N ) NEW_LINE |
Maximize number of elements from Array with sum at most K | Function to select a maximum number of elements in array whose sum is at most K ; Sort the array ; Calculate the sum and count while iterating the sorted array ; Iterate for all the elements in the array ; Add the current element to sum ; Increment the count ; Return the answer ; Driver Code ; Given array ; Given sum k ; Function call | def maxSelections ( A , n , k ) : NEW_LINE INDENT A . sort ( ) ; NEW_LINE sum = 0 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + A [ i ] ; NEW_LINE if ( sum > k ) : NEW_LINE break ; NEW_LINE count += 1 ; NEW_LINE return count ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 7 , 2 , 9 , 4 ] ; NEW_LINE k = 15 ; NEW_LINE n = len ( A ) ; NEW_LINE print ( maxSelections ( A , n , k ) ) ; NEW_LINE DEDENT |
Pair of integers with difference K having an element as the K | Function to find the required pair ; No pair possible ; Driver Code | def computePair ( K ) : NEW_LINE INDENT if ( K == 1 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT print ( K * K / ( K - 1 ) , end = " β " ) NEW_LINE print ( K / ( K - 1 ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT K = 6 NEW_LINE computePair ( K ) NEW_LINE DEDENT |
Generate a Binary String without any consecutive 0 ' s β and β at β most β K β consecutive β 1' s | Function to construct the binary string ; Conditions when string construction is not possible ; Stores maximum 1 's that can be placed in between ; Place 0 's ; Place 1 's in between ; Count remaining M 's ; Place 1 's at the end ; Place 1 's at the beginning ; Return the final string ; Driver Code | def ConstructBinaryString ( N , M , K ) : NEW_LINE INDENT if ( M < ( N - 1 ) or M > K * ( N + 1 ) ) : NEW_LINE INDENT return ' - 1' NEW_LINE DEDENT ans = " " NEW_LINE l = min ( K , M // ( N - 1 ) ) NEW_LINE temp = N NEW_LINE while ( temp ) : NEW_LINE INDENT temp -= 1 NEW_LINE ans += '0' NEW_LINE if ( temp == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT for i in range ( l ) : NEW_LINE INDENT ans += '1' NEW_LINE DEDENT DEDENT M -= ( N - 1 ) * l NEW_LINE if ( M == 0 ) : NEW_LINE INDENT return ans NEW_LINE DEDENT l = min ( M , K ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT ans += '1' NEW_LINE DEDENT M -= l NEW_LINE while ( M > 0 ) : NEW_LINE INDENT ans = '1' + ans NEW_LINE M -= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE M = 9 NEW_LINE K = 2 NEW_LINE print ( ConstructBinaryString ( N , M , K ) ) NEW_LINE DEDENT |
Find smallest number formed by inverting digits of given number N | Function to invert the digits of integer N to form minimum possible number ; Initialize the array ; Iterate till the number N exists ; Last digit of the number N ; Checking if the digit is smaller than 9 - digit ; Store the smaller digit in the array ; Reduce the number each time ; Check if the digit starts with 0 or not ; Print the answer ; Driver Code ; Given Number ; Function Call | def number ( num ) : NEW_LINE INDENT a = [ 0 ] * 20 NEW_LINE r , i , j = 0 , 0 , 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT r = num % 10 NEW_LINE if ( 9 - r > r ) : NEW_LINE INDENT a [ i ] = r NEW_LINE DEDENT else : NEW_LINE INDENT a [ i ] = 9 - r NEW_LINE DEDENT i += 1 NEW_LINE num = num // 10 NEW_LINE DEDENT if ( a [ i - 1 ] == 0 ) : NEW_LINE INDENT print ( 9 , end = " " ) NEW_LINE i -= 1 NEW_LINE DEDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( a [ j ] , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num = 4545 NEW_LINE number ( num ) NEW_LINE DEDENT |
Check if the concatenation of first N natural numbers is divisible by 3 | Function that returns True if concatenation of first N natural numbers is divisible by 3 ; Check using the formula ; Driver Code ; Given Number ; Function Call | def isDivisible ( N ) : NEW_LINE INDENT return ( N - 1 ) % 3 != 0 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE if ( isDivisible ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Count of N digit Numbers whose sum of every K consecutive digits is equal | Function to count the number of N - digit numbers such that sum of every k consecutive digits are equal ; Range of numbers ; Extract digits of the number ; Store the sum of first K digits ; Check for every k - consecutive digits ; If sum is not equal then break the loop ; Increment the count if it satisfy the given condition ; Given N and K ; Function call | def countDigitSum ( N , K ) : NEW_LINE INDENT l = pow ( 10 , N - 1 ) NEW_LINE r = pow ( 10 , N ) - 1 NEW_LINE count = 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT num = i NEW_LINE digits = [ 0 ] * N NEW_LINE for j in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT digits [ j ] = num % 10 NEW_LINE num //= 10 NEW_LINE DEDENT sum = 0 NEW_LINE flag = 0 NEW_LINE for j in range ( 0 , K ) : NEW_LINE INDENT sum += digits [ j ] NEW_LINE DEDENT for j in range ( 1 , N - K + 1 ) : NEW_LINE INDENT curr_sum = 0 NEW_LINE for m in range ( j , j + K ) : NEW_LINE INDENT curr_sum += digits [ m ] NEW_LINE DEDENT if ( sum != curr_sum ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT N = 2 NEW_LINE K = 1 NEW_LINE print ( countDigitSum ( N , K ) ) NEW_LINE |
Perfect Square factors of a Number | Function that returns the count of factors that are perfect squares ; Stores the count of number of times a prime number divides N . ; Stores the number of factors that are perfect square ; Count number of 2 's that divides N ; Calculate ans according to above formula ; Check for all the possible numbers that can divide it ; Check the number of times prime number i divides it ; Calculate ans according to above formula ; Return final count ; Driver Code | def noOfFactors ( N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT count = 0 NEW_LINE ans = 1 NEW_LINE while ( N % 2 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE N = N // 2 NEW_LINE DEDENT ans *= ( count // 2 + 1 ) NEW_LINE i = 3 NEW_LINE while i * i <= N : NEW_LINE INDENT count = 0 NEW_LINE while ( N % i == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE N = N // i NEW_LINE DEDENT ans *= ( count // 2 + 1 ) NEW_LINE i += 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 100 NEW_LINE print ( noOfFactors ( N ) ) NEW_LINE DEDENT |
Nth angle of a Polygon whose initial angle and per angle increment is given | Function to check if the angle is possible or not ; Angular sum of a N - sided polygon ; Angular sum of N - sided given polygon ; Check if both sum are equal ; Function to find the nth angle ; Calculate nth angle ; Return the nth angle ; Driver Code ; Checks the possibility of the polygon exist or not ; Print nth angle of the polygon | def possible ( N , a , b , n ) : NEW_LINE INDENT sum_of_angle = 180 * ( N - 2 ) NEW_LINE Total_angle = ( N * ( ( 2 * a ) + ( N - 1 ) * b ) ) / 2 NEW_LINE if ( sum_of_angle != Total_angle ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT def nth_angle ( N , a , b , n ) : NEW_LINE INDENT nth = 0 NEW_LINE nth = a + ( n - 1 ) * b NEW_LINE return nth NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE a = 30 NEW_LINE b = 30 NEW_LINE n = 3 NEW_LINE if ( possible ( N , a , b , n ) ) : NEW_LINE INDENT print ( nth_angle ( N , a , b , n ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT DEDENT |
Check if the given string is linear or not | Function to check if the given is linear or not ; Iterate over string ; If character is not same as the first character then return false ; Increment the tmp ; Driver Code ; Given String str ; Function call | def is_linear ( s ) : NEW_LINE INDENT tmp = 0 NEW_LINE first = s [ 0 ] NEW_LINE pos = 0 NEW_LINE while pos < len ( s ) : NEW_LINE INDENT if ( s [ pos ] != first ) : NEW_LINE INDENT return False NEW_LINE DEDENT tmp += 1 NEW_LINE pos += tmp NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " aapaxyayziabcde " NEW_LINE if ( is_linear ( str ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Minimize cost to color all the vertices of an Undirected Graph | Function to implement DFS Traversal to marks all the vertices visited from vertex U ; Mark U as visited ; Traverse the adjacency list of U ; Function to find the minimum cost to color all the vertices of graph ; To store adjacency list ; Loop through the edges to create adjacency list ; To check if a vertex of the graph is visited ; Mark visited to all the vertices that can be reached by colored vertices ; Perform DFS ; To store count of uncolored sub - graphs ; Loop through vertex to count uncolored sub - graphs ; If vertex not visited ; Increase count of uncolored sub - graphs ; Perform DFS to mark visited to all vertices of current sub - graphs ; Calculate minimum cost to color all vertices ; Print the result ; Driver Code ; Given number of vertices and edges ; Given edges ; Given cost of coloring and adding an edge ; Given array of colored vertices | def DFS ( U , vis , adj ) : NEW_LINE INDENT vis [ U ] = 1 NEW_LINE for V in adj [ U ] : NEW_LINE INDENT if ( vis [ V ] == 0 ) : NEW_LINE INDENT DFS ( V , vis , adj ) NEW_LINE DEDENT DEDENT DEDENT def minCost ( N , M , vCost , eCost , sorc , colored , destination ) : NEW_LINE INDENT adj = [ [ ] for i in range ( N + 1 ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT adj [ sorc [ i ] ] . append ( destination [ i ] ) NEW_LINE adj [ destination [ i ] ] . append ( sorc [ i ] ) NEW_LINE DEDENT vis = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( len ( colored ) ) : NEW_LINE INDENT DFS ( colored [ i ] , vis , adj ) NEW_LINE DEDENT X = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( vis [ i ] == 0 ) : NEW_LINE INDENT X += 1 NEW_LINE DFS ( i , vis , adj ) NEW_LINE DEDENT DEDENT mincost = X * min ( vCost , eCost ) NEW_LINE print ( mincost ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE M = 1 NEW_LINE sorc = [ 1 ] NEW_LINE destination = [ 2 ] NEW_LINE vCost = 3 NEW_LINE eCost = 2 NEW_LINE colored = [ 1 ] NEW_LINE minCost ( N , M , vCost , eCost , sorc , colored , destination ) NEW_LINE DEDENT |
Minimum cost to reduce the integer N to 1 as per given conditions | Function to find the minimum cost to reduce the integer N to 1 by the given operations ; Check if x is 1 ; Print the answer ; Prestore the answer ; Iterate till n exists ; Divide N by x ; Reduce n by x ; Add the cost ; Update the answer ; Return the answer ; Driver Code ; Initialize the variables ; Function call | def min_cost ( n , x , p , q ) : NEW_LINE INDENT if ( x == 1 ) : NEW_LINE INDENT print ( ( n - 1 ) * p ) NEW_LINE return 0 NEW_LINE DEDENT ans = ( n - 1 ) * p NEW_LINE pre = 0 NEW_LINE while ( n > 1 ) : NEW_LINE INDENT tmp = n // x NEW_LINE if ( tmp < 0 ) : NEW_LINE break NEW_LINE pre += ( n - tmp * x ) * p NEW_LINE n //= x NEW_LINE pre += q NEW_LINE ans = min ( ans , pre + ( n - 1 ) * p ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; x = 2 ; NEW_LINE p = 2 ; q = 3 ; NEW_LINE print ( min_cost ( n , x , p , q ) ) NEW_LINE DEDENT |
Number of ways to sum up a total of N from limited denominations | Function to find the number of ways to sum up a total of N from limited denominations ; Store the count of denominations ; Stores the final result ; As one of the denominations is rupee 1 , so we can reduce the computation by checking the equality for N - ( A * 1 ) = N - A ; Increment the count for number of ways ; Driver Code ; Given Denominations ; Function Call | def calculateWays ( arr1 , arr2 , N ) : NEW_LINE INDENT A = arr2 [ 0 ] NEW_LINE B = arr2 [ 1 ] NEW_LINE C = arr2 [ 2 ] NEW_LINE D = arr2 [ 3 ] NEW_LINE ans , b , c , d = 0 , 0 , 0 , 0 NEW_LINE while b <= B and b * 5 <= ( N ) : NEW_LINE INDENT c = 0 NEW_LINE while ( c <= C and b * 5 + c * 10 <= ( N ) ) : NEW_LINE INDENT d = 0 NEW_LINE while ( d <= D and b * 5 + c * 10 + d * 20 <= ( N ) ) : NEW_LINE INDENT if ( ( b * 5 ) + ( c * 10 ) + ( d * 20 ) >= ( N - A ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT d += 1 NEW_LINE DEDENT c += 1 NEW_LINE DEDENT b += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 123 NEW_LINE arr1 = [ 1 , 5 , 10 , 20 ] NEW_LINE arr2 = [ 6 , 4 , 3 , 5 ] NEW_LINE print ( calculateWays ( arr1 , arr2 , N ) ) NEW_LINE DEDENT |
Number of ways to sum up a total of N from limited denominations | Python3 program for the above approach ; Function to find the number of ways to sum up a total of N from limited denominations ; Store the count of denominations ; Stores the final result ; This will give the number of coins for all combinations of coins with value 1 and 5 ; L2 will sum the values of those indices of ways which is equal to ( N - ( c * 10 + d * 20 ) ) ; Return the final count ; Driver Code ; Given denominations ; Function call | ways = [ 0 for i in range ( 1010 ) ] ; NEW_LINE def calculateWays ( arr1 , arr2 , N ) : NEW_LINE INDENT A = arr2 [ 0 ] ; B = arr2 [ 1 ] ; NEW_LINE C = arr2 [ 2 ] ; D = arr2 [ 3 ] ; NEW_LINE ans = 0 ; NEW_LINE for b in range ( 0 , B + 1 ) : NEW_LINE INDENT if ( b * 5 > N ) : NEW_LINE INDENT break ; NEW_LINE DEDENT for a in range ( 0 , A + 1 ) : NEW_LINE INDENT if ( a + b * 5 > N ) : NEW_LINE INDENT break ; NEW_LINE DEDENT ways [ a + b * 5 ] += 5 ; NEW_LINE DEDENT DEDENT for c in range ( 0 , C ) : NEW_LINE INDENT if ( c * 10 > N ) : NEW_LINE INDENT break ; NEW_LINE DEDENT for d in range ( 0 , D ) : NEW_LINE INDENT if ( c * 10 + d * 20 > N ) : NEW_LINE INDENT break ; NEW_LINE DEDENT ans += ways [ N - c * 10 - d * 20 ] ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 123 ; NEW_LINE arr1 = [ 1 , 5 , 10 , 20 ] ; NEW_LINE arr2 = [ 6 , 4 , 3 , 5 ] ; NEW_LINE print ( calculateWays ( arr1 , arr2 , N ) ) ; NEW_LINE DEDENT |
Count of Missing Numbers in a sorted array | Function that find the count of missing numbers in array a [ ] ; Calculate the count of missing numbers in the array ; Driver Code | def countMissingNum ( a , N ) : NEW_LINE INDENT count = a [ N - 1 ] - a [ 0 ] + 1 - N NEW_LINE print ( count ) NEW_LINE DEDENT arr = [ 5 , 10 , 20 , 40 ] NEW_LINE N = len ( arr ) NEW_LINE countMissingNum ( arr , N ) NEW_LINE |
Length of longest subsequence whose XOR value is odd | Function for find max XOR subsequence having odd value ; Initialize odd and even count ; Count the number of odd and even numbers in given array ; If all values are odd in given array ; If all values are even in given array ; If both odd and even are present in given array ; Driver code ; Given array arr [ ] ; Function Call | def maxXorSubsequence ( arr , n ) : NEW_LINE INDENT odd = 0 NEW_LINE even = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] % 2 != 0 : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even += 1 NEW_LINE DEDENT DEDENT if odd == n : NEW_LINE INDENT if odd % 2 == 0 : NEW_LINE INDENT maxlen = n - 1 NEW_LINE DEDENT else : NEW_LINE INDENT maxlen = n NEW_LINE DEDENT DEDENT elif even == n : NEW_LINE INDENT maxlen = 0 NEW_LINE DEDENT else : NEW_LINE INDENT if odd % 2 == 0 : NEW_LINE INDENT maxlen = even + odd - 1 NEW_LINE DEDENT else : NEW_LINE INDENT maxlen = even + odd NEW_LINE DEDENT DEDENT return maxlen NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 5 , 6 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxXorSubsequence ( arr , n ) ) NEW_LINE DEDENT |
Count of pairs with sum N from first N natural numbers | Function to calculate the value of count ; If n is even ; Count of pairs ; Otherwise ; Driver code | def numberOfPairs ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return n // 2 - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return n // 2 ; NEW_LINE DEDENT DEDENT n = 8 ; NEW_LINE print ( numberOfPairs ( n ) ) ; NEW_LINE |
Count pair of strings whose concatenation has every vowel | Function to return the count of all concatenated string with each vowel at least once ; Concatenating all possible pairs of string ; Creating an array which checks , the presence of each vowel ; Checking for each vowel by traversing the concatenated string ; Checking if all the elements are set in vowel [ ] ; Check if all vowels are present or not ; Return the final count ; Driver Code ; Given array of strings ; Function call | def good_pair ( st , N ) : NEW_LINE INDENT countStr = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT res = st [ i ] + st [ j ] NEW_LINE vowel = [ 0 ] * 5 NEW_LINE for k in range ( len ( res ) ) : NEW_LINE INDENT if ( res [ k ] == ' a ' ) : NEW_LINE INDENT vowel [ 0 ] = 1 NEW_LINE DEDENT elif ( res [ k ] == ' e ' ) : NEW_LINE INDENT vowel [ 1 ] = 1 NEW_LINE DEDENT elif ( res [ k ] == ' i ' ) : NEW_LINE INDENT vowel [ 2 ] = 1 NEW_LINE DEDENT elif ( res [ k ] == ' o ' ) : NEW_LINE INDENT vowel [ 3 ] = 1 NEW_LINE DEDENT elif ( res [ k ] == ' u ' ) : NEW_LINE INDENT vowel [ 4 ] = 1 NEW_LINE DEDENT DEDENT temp = 0 NEW_LINE for ind in range ( 5 ) : NEW_LINE INDENT if ( vowel [ ind ] == 1 ) : NEW_LINE INDENT temp += 1 NEW_LINE DEDENT DEDENT if ( temp == 5 ) : NEW_LINE INDENT countStr += 1 NEW_LINE DEDENT DEDENT DEDENT return countStr NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " aaweiolkju " , " oxdfgujkmi " ] NEW_LINE N = len ( arr ) NEW_LINE print ( good_pair ( arr , N ) ) NEW_LINE DEDENT |
Find sum of exponents of prime factors of numbers 1 to N | Function to implement sieve of erastosthenes ; Create a boolean array and initialize all entries as false ; Initializing smallest factor equal to 2 for all the even numbers ; Iterate for odd numbers less then equal to n ; s ( i ) for a prime is the number itself ; For all multiples of current prime number ; i is the smallest prime factor for number " i * j " ; Function to generate prime factors and its power ; s [ i ] is going to store smallest prime factor of i ; Current prime factor of N ; Power of current prime factor ; Calculating prime factors and their powers sum ; Increment the count and continue the process ; Add count to the sum ; Reinitialize count ; Return the result ; Function to find the sum of all the power of prime factors of N ; Iterate for in [ 2 , N ] ; Driver Code ; Given number N ; Function call | def sieveOfEratosthenes ( N , s ) : NEW_LINE INDENT prime = [ False ] * ( N + 1 ) NEW_LINE for i in range ( 2 , N + 1 , 2 ) : NEW_LINE INDENT s [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , N + 1 , 2 ) : NEW_LINE INDENT if ( prime [ i ] == False ) : NEW_LINE INDENT s [ i ] = i NEW_LINE j = i NEW_LINE while ( j * i <= N ) : NEW_LINE INDENT if ( prime [ i * j ] == False ) : NEW_LINE INDENT prime [ i * j ] = True NEW_LINE s [ i * j ] = i NEW_LINE DEDENT j += 2 NEW_LINE DEDENT DEDENT DEDENT DEDENT def generatePrimeFactors ( N ) : NEW_LINE INDENT s = [ 0 ] * ( N + 1 ) NEW_LINE sum = 0 NEW_LINE sieveOfEratosthenes ( N , s ) NEW_LINE curr = s [ N ] NEW_LINE cnt = 1 NEW_LINE while ( N > 1 ) : NEW_LINE INDENT N //= s [ N ] NEW_LINE if ( curr == s [ N ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE continue NEW_LINE DEDENT sum = sum + cnt NEW_LINE curr = s [ N ] NEW_LINE cnt = 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT def findSum ( N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT sum += generatePrimeFactors ( i ) NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE findSum ( N ) NEW_LINE DEDENT |
Minimum LCM of all subarrays of length at least 2 | Python3 program for the above approach ; Function to find LCM pf two numbers ; Initialise lcm value ; Check for divisibility of a and b by the lcm ; Function to find the Minimum LCM of all subarrays of length greater than 1 ; Store the minimum LCM ; Traverse the array ; Find LCM of consecutive element ; Check if the calculated LCM is less than the minLCM then update it ; Print the minimum LCM ; Given array arr [ ] ; Size of the array ; Function call | import sys NEW_LINE def LCM ( a , b ) : NEW_LINE INDENT lcm = a if a > b else b NEW_LINE while ( True ) : NEW_LINE INDENT if ( lcm % a == 0 and lcm % b == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT lcm += 1 NEW_LINE DEDENT DEDENT return lcm NEW_LINE DEDENT def findMinLCM ( arr , n ) : NEW_LINE INDENT minLCM = sys . maxsize NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT val = LCM ( arr [ i ] , arr [ i + 1 ] ) NEW_LINE if ( val < minLCM ) : NEW_LINE INDENT minLCM = val NEW_LINE DEDENT DEDENT print ( minLCM ) NEW_LINE DEDENT arr = [ 4 , 8 , 12 , 16 , 20 , 24 ] NEW_LINE n = len ( arr ) NEW_LINE findMinLCM ( arr , n ) NEW_LINE |
Minimum integer with at most K bits set such that their bitwise AND with N is maximum | Function to find the integer with maximum bitwise with N ; Store answer in the bitset Initialized with 0 ; To maintain the count of set bits that should exceed k ; Start traversing from the Most significant if that bit is set in n then we will set in our answer i . e in X ; Checking if the ith bit is set in n or not ; Converting into integer ; Driver code ; Function Call | def find_max ( n , k ) : NEW_LINE INDENT X = [ 0 ] * 32 NEW_LINE cnt = 0 NEW_LINE i = 31 NEW_LINE while ( i >= 0 and cnt != k ) : NEW_LINE INDENT if ( ( n & ( 1 << i ) ) != 0 ) : NEW_LINE INDENT X [ i ] = 1 NEW_LINE cnt += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT s = " " NEW_LINE for i in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT if X [ i ] == 0 : NEW_LINE INDENT s += '0' NEW_LINE DEDENT else : NEW_LINE INDENT s += '1' NEW_LINE DEDENT DEDENT return int ( s , 2 ) NEW_LINE DEDENT n , k = 10 , 2 NEW_LINE print ( find_max ( n , k ) ) NEW_LINE |
Convert string to integer without using any in | Function to convert string to integer without using functions ; Initialize a variable ; Iterate till length of the string ; Subtract 48 from the current digit ; Print the answer ; Driver code ; Given string of number ; Function Call | def convert ( s ) : NEW_LINE INDENT num = 0 NEW_LINE n = len ( s ) NEW_LINE for i in s : NEW_LINE INDENT num = num * 10 + ( ord ( i ) - 48 ) NEW_LINE DEDENT print ( num ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "123" NEW_LINE convert ( s ) NEW_LINE DEDENT |
Permutation of Array such that sum of adjacent elements are not divisible by 3 | Python3 implementation to find the permutation of the array such that sum of adjacent elements is not divisible by 3 ; Function to segregate numbers based on their remainder when divided by three ; Loop to iterate over the elements of the given array ; Condition to check the remainder of the number ; Function to find the permutation of the array such that sum of adjacent elements is not divisible by 3 ; Condition to check when it 's impossible to arrange ; Condition to check when there are no zeros , and only ones or only twos ; Array to store the permutation ; Place the ones on alternate places in the answer array , leaving spaces for zeros remainder elements in the array ; Adding a zero to connect it with a two ; Place the twos on alternate places in the answer array , leaving spaces for zeros ; Fill the zeros finally , between the ones and the twos ; Print the arrangement of the array ; Function to solve the problem ; As there can be only 3 remainders ; Function Call ; Driver Code | hell = 1000000007 NEW_LINE N = 100005 NEW_LINE c_0 = 0 NEW_LINE c_1 = 0 NEW_LINE c_2 = 0 NEW_LINE def count_k ( arr , ones , twos , zeros ) : NEW_LINE INDENT global c_0 , c_1 , c_2 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] % 3 == 0 ) : NEW_LINE INDENT c_0 += 1 NEW_LINE zeros . append ( arr [ i ] ) NEW_LINE DEDENT elif ( arr [ i ] % 3 == 1 ) : NEW_LINE INDENT c_1 += 1 NEW_LINE ones . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT c_2 += 1 NEW_LINE twos . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT DEDENT def printArrangement ( arr , ones , twos , zeros ) : NEW_LINE INDENT global c_0 , c_1 , c_2 NEW_LINE if ( ( c_0 == 0 and c_1 != 0 and c_2 != 0 ) or c_0 > c_1 + c_2 + 1 ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE return NEW_LINE DEDENT if ( c_0 == 0 ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT return NEW_LINE DEDENT ans = [ - 1 ] * N NEW_LINE i , j = 1 , 0 NEW_LINE while ( j < c_1 ) : NEW_LINE INDENT ans [ i ] = ones [ - 1 ] NEW_LINE ones . pop ( ) NEW_LINE i += 2 NEW_LINE j += 1 NEW_LINE DEDENT ans [ i - 1 ] = zeros [ - 1 ] NEW_LINE zeros . pop ( ) NEW_LINE c_0 -= 1 NEW_LINE j = 0 NEW_LINE while ( j < c_2 ) : NEW_LINE INDENT ans [ i ] = twos [ - 1 ] NEW_LINE twos . pop ( ) NEW_LINE j += 1 NEW_LINE i += 2 NEW_LINE DEDENT k = 0 NEW_LINE while c_0 > 0 : NEW_LINE INDENT if ( ans [ k ] == - 1 ) : NEW_LINE INDENT ans [ k ] = zeros [ - 1 ] NEW_LINE c_0 -= 1 NEW_LINE DEDENT k += 2 NEW_LINE DEDENT for i1 in range ( N ) : NEW_LINE INDENT if ( ans [ i1 ] != - 1 ) : NEW_LINE INDENT print ( ans [ i1 ] , end = " β " ) NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT def solve ( n , arr ) : NEW_LINE INDENT ones = [ ] NEW_LINE zeros = [ ] NEW_LINE twos = [ ] NEW_LINE count_k ( arr , ones , twos , zeros ) NEW_LINE printArrangement ( arr , ones , twos , zeros ) NEW_LINE DEDENT n = 5 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE solve ( n , arr ) NEW_LINE |
Count of unique digits in a given number N | Function that returns the count of unique digits of the given number ; Initialize a variable to store count of unique digits ; Initialize cnt list to store digit count ; Iterate through the digits of N ; Retrieve the last digit of N ; Increase the count of the last digit ; Remove the last digit of N ; Iterate through the cnt list ; If frequency of digit is 1 ; Increment the count of unique digits ; Return the count of unique digit ; Given number N ; Function call | def countUniqueDigits ( N ) : NEW_LINE INDENT res = 0 NEW_LINE cnt = [ 0 ] * 10 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT rem = N % 10 NEW_LINE cnt [ rem ] += 1 NEW_LINE N = N // 10 NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT if ( cnt [ i ] == 1 ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT N = 2234262 NEW_LINE print ( countUniqueDigits ( N ) ) NEW_LINE |
Check if frequency of each element in given array is unique or not | Python3 code for the above approach ; Function to check whether the frequency of elements in array is unique or not . ; Freq map will store the frequency of each element of the array ; Store the frequency of each element from the array ; Check whether frequency of any two or more elements are same or not . If yes , return false ; Return true if each frequency is unique ; Driver Code ; Given array arr [ ] ; Function Call ; Print the result | from collections import defaultdict NEW_LINE def checkUniqueFrequency ( arr , n ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT uniqueFreq = set ( [ ] ) NEW_LINE for i in freq : NEW_LINE INDENT if ( freq [ i ] in uniqueFreq ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT uniqueFreq . add ( freq [ i ] ) NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 5 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE res = checkUniqueFrequency ( arr , n ) NEW_LINE if ( res ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Sum of first N natural numbers with all powers of 2 added twice | Python3 program to implement the above approach ; Function to raise N to the power P and return the value ; Function to calculate the log base 2 of an integer ; Calculate log2 ( N ) indirectly using log ( ) method ; Function to calculate and return the required sum ; Sum of first N natural numbers ; Sum of all powers of 2 up to N ; Driver code | import math NEW_LINE def power ( N , P ) : NEW_LINE INDENT return math . pow ( N , P ) NEW_LINE DEDENT def Log2 ( N ) : NEW_LINE INDENT result = ( math . log ( N ) // math . log ( 2 ) ) NEW_LINE return result NEW_LINE DEDENT def specialSum ( n ) : NEW_LINE INDENT sum = n * ( n + 1 ) // 2 NEW_LINE a = Log2 ( n ) NEW_LINE sum = sum + power ( 2 , a + 1 ) - 1 NEW_LINE return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE print ( specialSum ( n ) ) NEW_LINE DEDENT |
Rearrange an array such that product of every two consecutive elements is a multiple of 4 | Function to rearrange array elements such that the every two consecutive elements is a multiple of 4 ; If element is odd ; Odd ; If element is divisible by 4 ; Divisible by 4 ; If element is not divisible by 4 ; Even but not divisible by 4 ; Condition for rearrangement to be possible ; Print ODD [ i ] and FOUR [ i ] consecutively ; Print the remaining FOUR [ i ] , if any ; Condition for rearrangement to be possible ; Print ODD [ i ] and FOUR [ i ] consecutively ; Print the remaining FOUR [ i ] , if any ; Print the NON_FOUR [ i ] elements at the end ; No possible configuration ; Driver Code | def Permute ( arr , n ) : NEW_LINE INDENT odd = 0 NEW_LINE four = 0 NEW_LINE non_four = 0 NEW_LINE ODD , FOUR , NON_FOUR = [ ] , [ ] , [ ] NEW_LINE for x in arr : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT odd += 1 NEW_LINE ODD . append ( x ) NEW_LINE DEDENT elif ( x % 4 == 0 ) : NEW_LINE INDENT four += 1 NEW_LINE FOUR . append ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT non_four += 1 NEW_LINE NON_FOUR . append ( x ) NEW_LINE DEDENT DEDENT if ( non_four == 0 and four >= odd - 1 ) : NEW_LINE INDENT x = len ( ODD ) NEW_LINE y = len ( FOUR ) NEW_LINE i = 0 NEW_LINE while i < x : NEW_LINE INDENT print ( ODD [ i ] , end = " β " ) NEW_LINE if ( i < y ) : NEW_LINE INDENT print ( FOUR [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT while ( i < y ) : NEW_LINE INDENT print ( FOUR [ i ] , end = " β " ) NEW_LINE i += 1 NEW_LINE DEDENT print ( ) NEW_LINE DEDENT elif ( non_four > 0 and four >= odd ) : NEW_LINE INDENT x = len ( ODD ) NEW_LINE y = len ( FOUR ) NEW_LINE i = 0 NEW_LINE while i < x : NEW_LINE INDENT print ( ODD [ i ] , end = " β " ) NEW_LINE if ( i < y ) : NEW_LINE INDENT print ( FOUR [ i ] , end = " β " ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT while ( i < y ) : NEW_LINE INDENT print ( FOUR [ i ] , end = " β " ) NEW_LINE i += 1 NEW_LINE DEDENT for j in NON_FOUR : NEW_LINE INDENT print ( j , end = " β " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 7 , 1 , 8 , 2 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE Permute ( arr , N ) NEW_LINE DEDENT |
Construct the smallest possible Array with given Sum and XOR | Function to find array ; Array not possible ; Array possible with exactly 1 or no element ; Checking array with two elements possible or not . ; Given sum and value of Bitwise XOR ; Function Call | def findArray ( _sum , xorr ) : NEW_LINE INDENT if ( xorr > _sum or _sum % 2 != xorr % 2 ) : NEW_LINE INDENT print ( " No β Array β Possible " ) NEW_LINE return NEW_LINE DEDENT if ( _sum == xorr ) : NEW_LINE INDENT if ( _sum == 0 ) : NEW_LINE INDENT print ( " Array β is β empty " , " β with β size β 0" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Array β size β is " , 1 ) NEW_LINE print ( " Array β is " , _sum ) NEW_LINE DEDENT return NEW_LINE DEDENT mid = ( _sum - xorr ) // 2 NEW_LINE if ( xorr & mid == 1 ) : NEW_LINE INDENT print ( " Array β size β is " , 3 ) NEW_LINE print ( " Array β is " , xorr , mid , mid ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Array β size β is " , 2 ) NEW_LINE print ( " Array β is " , ( xorr + mid ) , mid ) NEW_LINE DEDENT DEDENT _sum = 4 NEW_LINE xorr = 2 NEW_LINE findArray ( _sum , xorr ) NEW_LINE |
Smallest number greater than X which is K | Function to find the smallest K periodic integer greater than X ; Stores the number in a temporary string ; Set X [ i ] = X [ i - k ] for i > k ; Start from the current index ; Loop upto N change X [ j ] to X [ i ] ; Return X if current Value is greater than original value ; Find the first digit not equal to 9 ; Increment X [ i ] ; Set POS to current index ; Change X [ i ] to 0 for all indices from POS + 1 to K ; Set X [ i ] = X [ i - k ] for i > k ; Loop upto N change X [ j ] to X [ i ] ; Return the final string ; Driver Code | def Kperiodicinteger ( X , N , K ) : NEW_LINE INDENT X = list ( X ) NEW_LINE temp = X . copy ( ) NEW_LINE for i in range ( K ) : NEW_LINE INDENT j = i NEW_LINE while ( j < N ) : NEW_LINE INDENT X [ j ] = X [ i ] NEW_LINE j += K NEW_LINE DEDENT DEDENT if ( X >= temp ) : NEW_LINE INDENT return X NEW_LINE DEDENT POS = 0 NEW_LINE for i in range ( K - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( X [ i ] != '9' ) : NEW_LINE INDENT X [ i ] = str ( int ( X [ i ] ) + 1 ) NEW_LINE POS = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( POS + 1 , K ) : NEW_LINE INDENT X [ i ] = '0' NEW_LINE DEDENT for i in range ( K ) : NEW_LINE INDENT j = i NEW_LINE while ( j < N ) : NEW_LINE INDENT X [ j ] = X [ i ] NEW_LINE j += K NEW_LINE DEDENT DEDENT return X NEW_LINE DEDENT N = 4 NEW_LINE K = 2 NEW_LINE X = "1215" NEW_LINE print ( * Kperiodicinteger ( X , N , K ) , sep = ' ' ) NEW_LINE |
Maximum cost path in an Undirected Graph such that no edge is visited twice in a row | Python3 program for the above approach ; To store the resulting sum of the cost ; To store largest cost leaf vertex ; DFS Traversal to find the update the maximum cost of from any node to leaf ; Mark vertex as visited ; Store vertex initial cost ; Initially assuming edge not to be traversed ; Back edge found so , edge can be part of traversal ; New vertex is found ; Bitwise AND the current check with the returned check by the previous DFS Call ; Adds parent and its children cost ; Updates total cost of parent including child nodes ; Edge is part of the cycle ; Add cost of vertex to the answer ; Updates the largest cost leaf vertex ; Function to find the maximum cost from source vertex such that no two edges is traversed twice ; DFS Call ; Print the maximum cost ; Driver Code ; Cost Array ; Given Graph ; Given Source Node ; Function Call | N = 100000 NEW_LINE canTake = 0 NEW_LINE best = 0 NEW_LINE dp = [ 0 for i in range ( N ) ] NEW_LINE vis = [ 0 for i in range ( N ) ] NEW_LINE def dfs ( g , cost , u , pre ) : NEW_LINE INDENT global canTake , best NEW_LINE vis [ u ] = True NEW_LINE dp [ u ] = cost [ u ] NEW_LINE check = 1 NEW_LINE cur = cost [ u ] NEW_LINE for x in g [ u ] : NEW_LINE INDENT if ( vis [ x ] and x != pre ) : NEW_LINE INDENT check = 0 NEW_LINE DEDENT elif ( not vis [ x ] ) : NEW_LINE INDENT check &= dfs ( g , cost , x , u ) NEW_LINE cur = max ( cur , cost [ u ] + dp [ x ] ) NEW_LINE DEDENT DEDENT dp [ u ] = cur NEW_LINE if ( not check ) : NEW_LINE INDENT canTake += cost [ u ] NEW_LINE DEDENT else : NEW_LINE INDENT best = max ( best , dp [ u ] ) NEW_LINE DEDENT return check NEW_LINE DEDENT def FindMaxCost ( g , cost , source ) : NEW_LINE INDENT dfs ( g , cost , source , - 1 ) NEW_LINE print ( canTake + best ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE m = 5 NEW_LINE cost = [ 2 , 2 , 8 , 6 , 9 ] NEW_LINE g = [ [ ] for i in range ( n ) ] NEW_LINE g [ 0 ] . append ( 1 ) NEW_LINE g [ 1 ] . append ( 0 ) NEW_LINE g [ 0 ] . append ( 2 ) NEW_LINE g [ 2 ] . append ( 0 ) NEW_LINE g [ 0 ] . append ( 3 ) NEW_LINE g [ 3 ] . append ( 0 ) NEW_LINE g [ 1 ] . append ( 2 ) NEW_LINE g [ 2 ] . append ( 1 ) NEW_LINE g [ 1 ] . append ( 4 ) NEW_LINE g [ 4 ] . append ( 1 ) NEW_LINE source = 1 NEW_LINE FindMaxCost ( g , cost , source ) NEW_LINE DEDENT |
Reverse a subarray of the given array to minimize the sum of elements at even position | Function that will give the max negative value ; Check for count greater than 0 as we require only negative solution ; Function to print the minimum sum ; Taking sum of only even index elements ; Initialize two vectors v1 , v2 ; v1 will keep account for change if 1 th index element goes to 0 ; v2 will keep account for change if 1 th index element goes to 2 ; Get the max negative value ; Driver code | def after_rev ( v ) : NEW_LINE INDENT mini = 0 NEW_LINE count = 0 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT count += v [ i ] NEW_LINE if ( count > 0 ) : NEW_LINE INDENT count = 0 NEW_LINE DEDENT if ( mini > count ) : NEW_LINE INDENT mini = count NEW_LINE DEDENT DEDENT return mini NEW_LINE DEDENT def print_f ( arr ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , len ( arr ) , 2 ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT v1 , v2 = [ ] , [ ] NEW_LINE i = 1 NEW_LINE while i + 1 < len ( arr ) : NEW_LINE INDENT v1 . append ( arr [ i + 1 ] - arr [ i ] ) NEW_LINE i += 2 NEW_LINE DEDENT i = 1 NEW_LINE while i + 1 < len ( arr ) : NEW_LINE INDENT v2 . append ( arr [ i ] - arr [ i + 1 ] ) NEW_LINE i += 2 NEW_LINE DEDENT change = min ( after_rev ( v1 ) , after_rev ( v2 ) ) NEW_LINE if ( change < 0 ) : NEW_LINE INDENT sum += change NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 1 , 4 , 3 ] NEW_LINE print_f ( arr ) NEW_LINE DEDENT |
Smallest number to be added in first Array modulo M to make frequencies of both Arrays equal | Python3 program for the above approach ; Utility function to find the answer ; Stores the frequencies of array elements ; Stores the possible values of X ; Generate possible positive values of X ; Initialize answer to MAX value ; Flag to check if the current element of the set can be considered ; If the frequency of an element in A [ ] is not equal to that in B [ ] after the operation ; Current set element cannot be considered ; Update minimum value of X ; Driver Code | import sys NEW_LINE from collections import defaultdict NEW_LINE def moduloEquality ( A , B , n , m ) : NEW_LINE INDENT mapA = defaultdict ( int ) NEW_LINE mapB = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mapA [ A [ i ] ] += 1 NEW_LINE mapB [ B [ i ] ] += 1 NEW_LINE DEDENT possibleValues = set ( ) NEW_LINE FirstElement = B [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT cur = A [ i ] NEW_LINE if cur > FirstElement : NEW_LINE INDENT possibleValues . add ( m - cur + FirstElement ) NEW_LINE DEDENT else : NEW_LINE INDENT possibleValues . add ( FirstElement - cur ) NEW_LINE DEDENT DEDENT ans = sys . maxsize NEW_LINE for it in possibleValues : NEW_LINE INDENT possible = True NEW_LINE for it2 in mapA : NEW_LINE INDENT if ( mapA [ it2 ] != mapB [ ( it2 + it ) % m ] ) : NEW_LINE INDENT possible = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( possible ) : NEW_LINE INDENT ans = min ( ans , it ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE m = 3 NEW_LINE A = [ 0 , 0 , 2 , 1 ] NEW_LINE B = [ 2 , 0 , 1 , 1 ] NEW_LINE print ( moduloEquality ( A , B , n , m ) ) NEW_LINE DEDENT |
Count all indices of cyclic regular parenthesis | Function to find all indices which cyclic shift leads to get balanced parenthesis ; Create auxiliary array ; Finding prefix sum and minimum element ; Update the minimum element ; ChecK if count of ' ( ' and ' ) ' are equal ; Find count of minimum element ; Find the frequency of mn ; Return the count ; Given string S ; Function call | def countCyclicShifts ( S , n ) : NEW_LINE INDENT aux = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( S [ i ] == ' ( ' ) : NEW_LINE INDENT aux [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT aux [ i ] = - 1 NEW_LINE DEDENT DEDENT mn = aux [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT aux [ i ] += aux [ i - 1 ] NEW_LINE mn = min ( mn , aux [ i ] ) NEW_LINE DEDENT if ( aux [ n - 1 ] != 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( aux [ i ] == mn ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT S = " ) ( ) ( " NEW_LINE N = len ( S ) NEW_LINE print ( countCyclicShifts ( S , N ) ) NEW_LINE |
Maximize Profit by trading stocks based on given rate per day | Function to find the maximum profit ; Start from the last day ; Traverse and keep adding the profit until a day with price of stock higher than currentDay is obtained ; Set this day as currentDay with maximum cost of stock currently ; Return the profit ; Given array of prices ; Function call | def maxProfit ( prices , n ) : NEW_LINE INDENT profit = 0 NEW_LINE currentDay = n - 1 NEW_LINE while ( currentDay > 0 ) : NEW_LINE INDENT day = currentDay - 1 NEW_LINE while ( day >= 0 and ( prices [ currentDay ] > prices [ day ] ) ) : NEW_LINE INDENT profit += ( prices [ currentDay ] - prices [ day ] ) NEW_LINE day -= 1 NEW_LINE DEDENT currentDay = day ; NEW_LINE DEDENT return profit ; NEW_LINE DEDENT prices = [ 2 , 3 , 5 ] NEW_LINE N = len ( prices ) NEW_LINE print ( maxProfit ( prices , N ) ) NEW_LINE |
Check given string is oddly palindrome or not | Set 2 | Function to check if string formed by odd indices is palindromic or not ; Check if length of OddString odd , to consider edge case ; Push odd index character of first half of str in stack ; Middle element of odd length palindromic string is not compared ; If stack is empty then return true ; Driver code ; Given string | def isOddStringPalindrome ( str , n ) : NEW_LINE INDENT oddStringSize = n // 2 ; NEW_LINE lengthOdd = True if ( oddStringSize % 2 == 1 ) else False NEW_LINE s = [ ] NEW_LINE i = 1 NEW_LINE c = 0 NEW_LINE while ( i < n and c < oddStringSize // 2 ) : NEW_LINE INDENT s . append ( str [ i ] ) NEW_LINE i += 2 NEW_LINE c += 1 NEW_LINE DEDENT if ( lengthOdd ) : NEW_LINE INDENT i = i + 2 NEW_LINE DEDENT while ( i < n and len ( s ) > 0 ) : NEW_LINE INDENT if ( s [ len ( s ) - 1 ] == str [ i ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT i = i + 2 NEW_LINE DEDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 10 NEW_LINE s = " aeafacafae " NEW_LINE if ( isOddStringPalindrome ( s , N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Check given string is oddly palindrome or not | Set 2 | Functions checks if characters at odd index of the string forms palindrome or not ; Initialise two pointers ; Iterate till left <= right ; If there is a mismatch occurs then return false ; Increment and decrement the left and right pointer by 2 ; Driver Code ; Given string ; Function call | def isOddStringPalindrome ( Str , n ) : NEW_LINE INDENT left , right = 0 , 0 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT left = 1 NEW_LINE right = n - 1 NEW_LINE DEDENT else : NEW_LINE INDENT left = 1 NEW_LINE right = n - 2 NEW_LINE DEDENT while ( left < n and right >= 0 and left < right ) : NEW_LINE INDENT if ( Str [ left ] != Str [ right ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT left += 2 NEW_LINE right -= 2 NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE Str = " aeafacafae " NEW_LINE if ( isOddStringPalindrome ( Str , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Remove minimum characters from string to split it into three substrings under given constraints | Python 3 program for the above approach ; Function that counts minimum character that must be removed ; Length of string ; Create prefix array ; Initialize first position ; Fill prefix array ; Initialise maxi ; Check all the possibilities by putting i and j at different position & find maximum among them ; Print the characters to be removed ; Driver Code ; Given String ; Function Call | import sys NEW_LINE def min_remove ( st ) : NEW_LINE INDENT N = len ( st ) NEW_LINE prefix_a = [ 0 ] * ( N + 1 ) NEW_LINE prefix_b = [ 0 ] * ( N + 1 ) NEW_LINE prefix_c = [ 0 ] * ( N + 1 ) NEW_LINE prefix_a [ 0 ] = 0 NEW_LINE prefix_b [ 0 ] = 0 NEW_LINE prefix_c [ 0 ] = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( st [ i - 1 ] == ' a ' ) : NEW_LINE INDENT prefix_a [ i ] = ( prefix_a [ i - 1 ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT prefix_a [ i ] = prefix_a [ i - 1 ] NEW_LINE DEDENT if ( st [ i - 1 ] == ' b ' ) : NEW_LINE INDENT prefix_b [ i ] = ( prefix_b [ i - 1 ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT prefix_b [ i ] = prefix_b [ i - 1 ] NEW_LINE DEDENT if ( st [ i - 1 ] == ' c ' ) : NEW_LINE INDENT prefix_c [ i ] = ( prefix_c [ i - 1 ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT prefix_c [ i ] = prefix_c [ i - 1 ] NEW_LINE DEDENT DEDENT maxi = - sys . maxsize - 1 ; NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT for j in range ( i , N + 1 ) : NEW_LINE INDENT maxi = max ( maxi , ( prefix_a [ i ] + ( prefix_b [ j ] - prefix_b [ i ] ) + ( prefix_c [ N ] - prefix_c [ j ] ) ) ) NEW_LINE DEDENT DEDENT print ( ( N - maxi ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " aaaabaaxccac " NEW_LINE min_remove ( st ) NEW_LINE DEDENT |
Create an array of size N with sum S such that no subarray exists with sum S or S | Function to create an array with N elements with sum as S such that the given conditions satisfy ; Check if the solution exists ; Print the array as print ( n - 1 ) elements of array as 2 ; Print the last element of the array ; Print the value of k ; If solution doesnot exists ; Given N and sum S ; Function call | def createArray ( n , s ) : NEW_LINE INDENT if ( 2 * n <= s ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT print ( 2 , end = " β " ) NEW_LINE s -= 2 NEW_LINE DEDENT print ( s ) NEW_LINE print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' - 1' ) NEW_LINE DEDENT DEDENT N = 1 NEW_LINE S = 4 NEW_LINE createArray ( N , S ) NEW_LINE |
Maximize partitions such that no two substrings have any common character | Function to calculate and return the maximum number of partitions ; r : Stores the maximum number of partitions k : Stores the ending index of the partition ; Stores the last index of every unique character of the string ; Traverse the and store the last index of every character ; Store the last index of the first character from map ; Update K to find the end of partition ; Otherwise , the end of partition is found ; Increment r ; Update k for the next partition ; Add the last partition ; Driver Code | def maximum_partition ( strr ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE c = 0 NEW_LINE r = 0 NEW_LINE m = { } NEW_LINE for i in range ( len ( strr ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( strr [ i ] not in m ) : NEW_LINE INDENT m [ strr [ i ] ] = i NEW_LINE DEDENT DEDENT i = 0 NEW_LINE k = m [ strr [ i ] ] NEW_LINE for i in range ( len ( strr ) ) : NEW_LINE INDENT if ( i <= k ) : NEW_LINE INDENT c = c + 1 NEW_LINE k = max ( k , m [ strr [ i ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT r = r + 1 NEW_LINE c = 1 NEW_LINE k = max ( k , m [ strr [ i ] ] ) NEW_LINE DEDENT DEDENT if ( c != 0 ) : NEW_LINE INDENT r = r + 1 NEW_LINE DEDENT return r NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " ababcbacadefegdehijhklij " NEW_LINE print ( maximum_partition ( strr ) ) NEW_LINE DEDENT |
Minimize steps required to move all 1 's in a matrix to a given index | Function to calculate and return the minimum number of steps required to move all 1 s to ( X , Y ) ; Iterate the given matrix ; Update the answer with minimum moves required for the given element to reach the given index ; Return the number of steps ; Given matrix ; Given position ; Function call | def findAns ( mat , x , y , n , m ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT ans += ( abs ( x - i ) + abs ( y - j ) ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT mat = [ [ 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 1 ] ] NEW_LINE x = 0 NEW_LINE y = 2 NEW_LINE print ( findAns ( mat , x , y , len ( mat ) , len ( mat [ 0 ] ) ) ) NEW_LINE |
Count of all possible reverse bitonic subarrays | Function that counts all the reverse bitonic subarray in arr [ ] ; To store the count of reverse bitonic subarray ; Iterate the array and select the starting element ; Iterate for selecting the ending element for subarray ; Subarray arr [ i to j ] ; For 1 length , increment the count and continue ; For Decreasing Subarray ; Check if only Decreasing ; For Increasing Subarray ; Print the total count of subarrays ; Given array arr [ ] ; Function Call | def countReversebitonic ( arr , n ) : NEW_LINE INDENT c = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE f = 0 ; NEW_LINE if ( j == i ) : NEW_LINE INDENT c += 1 ; NEW_LINE continue ; NEW_LINE DEDENT k = i + 1 ; NEW_LINE while ( k <= j and temp > arr [ k ] ) : NEW_LINE INDENT temp = arr [ k ] ; NEW_LINE k += 1 ; NEW_LINE DEDENT if ( k > j ) : NEW_LINE INDENT c += 1 ; NEW_LINE f = 2 ; NEW_LINE DEDENT while ( k <= j and temp < arr [ k ] and f != 2 ) : NEW_LINE INDENT temp = arr [ k ] ; NEW_LINE k += 1 ; NEW_LINE DEDENT if ( k > j and f != 2 ) : NEW_LINE INDENT c += 1 ; NEW_LINE f = 0 ; NEW_LINE DEDENT DEDENT DEDENT print ( c ) NEW_LINE DEDENT arr = [ 2 , 3 , 1 , 4 ] ; NEW_LINE countReversebitonic ( arr , len ( arr ) ) ; NEW_LINE |
Longest increasing sequence by the boundary elements of an Array | Python3 program to print the longest increasing subsequence from the boundary elements of an array ; Function to return the length of Longest Increasing subsequence ; Set pointers at both ends ; Stores the recent value added to the subsequence ; Stores the length of the subsequence ; Check if both elements can be added to the subsequence ; Check if the element on the left can be added to the subsequence only ; Check if the element on the right can be added to the subsequence only ; If none of the values can be added to the subsequence ; Driver code ; Length of array | import sys NEW_LINE def longestSequence ( n , arr ) : NEW_LINE INDENT l = 0 NEW_LINE r = n - 1 NEW_LINE prev = - sys . maxsize - 1 NEW_LINE ans = 0 NEW_LINE while ( l <= r ) : NEW_LINE INDENT if ( arr [ l ] > prev and arr [ r ] > prev ) : NEW_LINE INDENT if ( arr [ l ] < arr [ r ] ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ l ] NEW_LINE l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ r ] NEW_LINE r -= 1 NEW_LINE DEDENT DEDENT elif ( arr [ l ] > prev ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ l ] NEW_LINE l += 1 NEW_LINE DEDENT elif ( arr [ r ] > prev ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ r ] NEW_LINE r -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 3 , 5 , 1 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestSequence ( n , arr ) ) NEW_LINE |
Total number of cells covered in a matrix after D days | Function to return the total infected cells after d days ; Top extension ; Bottom extension ; Left extension ; Right extension ; Calculating the cells in each quadrilateral ; Sum all of them to get total cells in each quadrilateral ; Add the singleblocks along the lines of top , down , left , right ; Return the ans ; Driver Code ; Dimensions of cell ; Starting Coordinates ; Number of Days ; Function Call | def solve ( n , m , x , y , d ) : NEW_LINE INDENT top = min ( d , x - 1 ) NEW_LINE down = min ( d , n - x ) NEW_LINE left = min ( d , y - 1 ) NEW_LINE right = min ( d , m - y ) NEW_LINE quad1 = top * left NEW_LINE quad2 = left * down NEW_LINE quad3 = down * right NEW_LINE quad4 = right * top NEW_LINE totalsq = ( quad1 + quad2 + quad3 + quad4 ) NEW_LINE singleBlocks = ( top + down + left + right + 1 ) NEW_LINE return totalsq + singleBlocks NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE m = 10 NEW_LINE x = 7 NEW_LINE y = 8 NEW_LINE d = 4 NEW_LINE d -= 1 NEW_LINE print ( solve ( n , m , x , y , d ) ) NEW_LINE DEDENT |
Smallest subsequence with sum of absolute difference of consecutive elements maximized | Function to print the smallest subsequence and its sum ; Final subsequence ; First element is a default endpoint ; Iterating through the array ; Check for monotonically increasing endpoint ; Check for monotonically decreasing endpoint ; Last element is a default endpoint ; Length of final subsequence ; Print the subsequence ; Driver code | def getSubsequence ( arr , n ) : NEW_LINE INDENT req = [ ] NEW_LINE req . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] and arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT req . append ( arr [ i ] ) NEW_LINE DEDENT elif ( arr [ i ] < arr [ i + 1 ] and arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT req . append ( arr [ i ] ) ; NEW_LINE DEDENT DEDENT req . append ( arr [ n - 1 ] ) ; NEW_LINE print ( len ( req ) ) NEW_LINE for x in req : NEW_LINE INDENT print ( x , end = ' β ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 3 , 6 , 7 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE getSubsequence ( arr , n ) NEW_LINE DEDENT |
Minimum steps to convert all paths in matrix from top left to bottom right as palindromic paths | Python3 implementation to find the minimum number of changes required such that every path from top left to the bottom right are palindromic paths ; Function to find the minimum number of the changes required for the every path to be palindromic ; count variable for maintaining total changes . ; left and right variables for keeping distance values from cell ( 0 , 0 ) and ( N - 1 , M - 1 ) respectively . ; Iterating over the matrix ; Finding minimum number of changes required . ; Minimum no . of changes will be the the minimum no . of different values and we will assume to make them equals to value with maximum frequency element ; Moving ahead with greater distance ; Driver Code ; Function Call | M = 3 NEW_LINE N = 3 NEW_LINE def minchanges ( mat ) : NEW_LINE INDENT count = 0 NEW_LINE left = 0 NEW_LINE right = N + M - 2 NEW_LINE while ( left < right ) : NEW_LINE INDENT mp = { } NEW_LINE totalsize = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( i + j == left ) : NEW_LINE INDENT mp [ mat [ i ] [ j ] ] = NEW_LINE mp . get ( mat [ i ] [ j ] , 0 ) + 1 NEW_LINE totalsize += 1 NEW_LINE DEDENT elif ( i + j == right ) : NEW_LINE INDENT mp [ mat [ i ] [ j ] ] = NEW_LINE mp . get ( mat [ i ] [ j ] , 0 ) + 1 NEW_LINE totalsize += 1 NEW_LINE DEDENT DEDENT DEDENT changes = 0 NEW_LINE for itr in mp : NEW_LINE INDENT changes = max ( changes , mp [ itr ] ) NEW_LINE DEDENT count += totalsize - changes NEW_LINE left += 1 NEW_LINE right -= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 4 , 1 ] , [ 2 , 5 , 3 ] , [ 1 , 3 , 1 ] ] NEW_LINE print ( minchanges ( mat ) ) NEW_LINE DEDENT |
Count of longest possible subarrays with sum not divisible by K | Function to find the count of longest subarrays with sum not divisible by K ; Sum of all elements in an array ; If overall sum is not divisible then return 1 , as only one subarray of size n is possible ; Index of the first number not divisible by K ; Index of the last number not divisible by K ; Subarray doesn 't exist ; Sum of the window ; Calculate the sum of rest of the windows of size len ; Driver Code | def CountLongestSubarrays ( arr , n , k ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s += arr [ i ] NEW_LINE DEDENT if ( s % k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT ini = 0 NEW_LINE while ( ini < n and arr [ ini ] % k == 0 ) : NEW_LINE INDENT ini += 1 NEW_LINE DEDENT final = n - 1 NEW_LINE while ( final >= 0 and arr [ final ] % k == 0 ) : NEW_LINE INDENT final -= 1 NEW_LINE DEDENT sum , count = 0 , 0 NEW_LINE if ( ini == n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT length = max ( n - 1 - ini , final ) NEW_LINE DEDENT for i in range ( length ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum % k != 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT for i in range ( length , n ) : NEW_LINE INDENT sum = sum + arr [ i ] NEW_LINE sum = sum + arr [ i - length ] NEW_LINE if ( sum % k != 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 2 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( CountLongestSubarrays ( arr , n , k ) ) NEW_LINE DEDENT |
Count of triplets in a given Array having GCD K | Python3 program to count the number of triplets in the array with GCD equal to K ; Frequency array ; mul [ i ] stores the count of multiples of i ; cnt [ i ] stores the count of triplets with gcd = i ; Return nC3 ; Function to count and return the number of triplets in the array with GCD equal to K ; Store frequency of array elements ; Store the multiples of i present in the array ; Count triplets with gcd equal to any multiple of i ; Remove all triplets which have gcd equal to a multiple of i ; Driver Code | MAXN = int ( 1e6 + 1 ) NEW_LINE freq = [ 0 ] * MAXN NEW_LINE mul = [ 0 ] * MAXN NEW_LINE cnt = [ 0 ] * MAXN NEW_LINE def nC3 ( n ) : NEW_LINE INDENT if ( n < 3 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( n * ( n - 1 ) * ( n - 2 ) ) / 6 NEW_LINE DEDENT def count_triplet ( arr , N , K ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( 1 , 1000000 + 1 ) : NEW_LINE INDENT for j in range ( i , 1000000 + 1 , i ) : NEW_LINE INDENT mul [ i ] += freq [ j ] NEW_LINE DEDENT cnt [ i ] = nC3 ( mul [ i ] ) NEW_LINE DEDENT for i in range ( 1000000 , 0 , - 1 ) : NEW_LINE INDENT for j in range ( 2 * i , 1000000 + 1 , i ) : NEW_LINE INDENT cnt [ i ] -= cnt [ j ] NEW_LINE DEDENT DEDENT print ( " Number β of β triplets β with β GCD " " β { 0 } β are β { 1 } " . format ( K , int ( cnt [ K ] ) ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 7 , 12 , 6 , 15 , 9 ] NEW_LINE N = 6 NEW_LINE K = 3 NEW_LINE count_triplet ( arr , N , K ) NEW_LINE DEDENT |
Check if a subsequence of length K with odd sum exists | Function to check if any required subsequence exists or not ; Store count of odd and even elements in the array ; Calculate the count of odd and even elements ; If no odd element exists or no even element exists when K even ; Subsequence is not possible ; Otherwise possible ; Driver code | def isSubseqPossible ( arr , N , K ) : NEW_LINE INDENT i = 0 NEW_LINE odd = 0 NEW_LINE even = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even += 1 NEW_LINE DEDENT DEDENT if ( odd == 0 or ( even == 0 and K % 2 == 0 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 7 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( " Yes " if isSubseqPossible ( arr , N , K ) else " No " ) NEW_LINE DEDENT |
Path traversed using exactly M coins in K jumps | Function that pr the path using exactly K jumps and M coins ; If no path exists ; It decides which box to be jump ; It decides whether to jump on left side or to jump on right side ; Print the path ; Driver code ; Function call | def print_path ( N , jump , coin ) : NEW_LINE INDENT if ( jump > coin or jump * ( N - 1 ) < coin ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT pos = 1 ; NEW_LINE while ( jump > 0 ) : NEW_LINE INDENT tmp = min ( N - 1 , coin - ( jump - 1 ) ) ; NEW_LINE if ( pos + tmp <= N ) : NEW_LINE INDENT pos += tmp ; NEW_LINE DEDENT else : NEW_LINE INDENT pos -= tmp ; NEW_LINE DEDENT print ( pos , end = " β " ) NEW_LINE coin -= tmp ; NEW_LINE jump -= 1 ; NEW_LINE DEDENT DEDENT DEDENT N = 5 NEW_LINE K = 4 NEW_LINE M = 12 NEW_LINE print_path ( N , K , M ) ; NEW_LINE |
Minimum salary hike for each employee such that no employee feels unfair | Python3 program for the above approach ; Function that print minimum hike ; Insert INF at begin and end of array ; To store hike of each employee ; For Type 1 employee ; For Type 2 employee ; For Type 3 employee ; For Type 4 employee ; Print the min hike for each employee ; Driver Code ; Given array of rating of employees ; Function Call | INF = 1e9 NEW_LINE def findMinHike ( arr , n ) : NEW_LINE INDENT arr . insert ( 0 , INF ) NEW_LINE arr . append ( INF ) NEW_LINE hike = [ 0 ] * ( n + 2 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] >= arr [ i ] and arr [ i ] <= arr [ i + 1 ] ) : NEW_LINE INDENT hike [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] < arr [ i ] and arr [ i ] <= arr [ i + 1 ] ) : NEW_LINE INDENT hike [ i ] = hike [ i - 1 ] + 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] >= arr [ i ] and arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT hike [ i ] = hike [ i + 1 ] + 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] < arr [ i ] and arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT hike [ i ] = max ( hike [ i - 1 ] , hike [ i + 1 ] ) + 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( hike [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 3 , 4 , 2 , 1 , 6 ] NEW_LINE findMinHike ( arr , len ( arr ) ) NEW_LINE DEDENT |
Minimize the cost to make all the adjacent elements distinct in an Array | Function that prints minimum cost required ; Dp - table ; Base case Not increasing the first element ; Increasing the first element by 1 ; Increasing the first element by 2 ; Condition if current element is not equal to previous non - increased element ; Condition if current element is not equal to previous element after being increased by 1 ; Condition if current element is not equal to previous element after being increased by 2 ; Take the minimum from all cases ; Finding the minimum cost ; Printing the minimum cost required to make all adjacent elements distinct ; Driver Code | def minimumCost ( arr , cost , N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 3 ) ] for i in range ( N ) ] NEW_LINE dp [ 0 ] [ 0 ] = 0 NEW_LINE dp [ 0 ] [ 1 ] = cost [ 0 ] NEW_LINE dp [ 0 ] [ 2 ] = cost [ 0 ] * 2 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT minimum = 1e6 NEW_LINE if ( j + arr [ i ] != arr [ i - 1 ] ) : NEW_LINE INDENT minimum = min ( minimum , dp [ i - 1 ] [ 0 ] ) NEW_LINE DEDENT if ( j + arr [ i ] != arr [ i - 1 ] + 1 ) : NEW_LINE INDENT minimum = min ( minimum , dp [ i - 1 ] [ 1 ] ) NEW_LINE DEDENT if ( j + arr [ i ] != arr [ i - 1 ] + 2 ) : NEW_LINE INDENT minimum = min ( minimum , dp [ i - 1 ] [ 2 ] ) NEW_LINE DEDENT dp [ i ] [ j ] = j * cost [ i ] + minimum NEW_LINE DEDENT DEDENT ans = 1e6 NEW_LINE for i in range ( 3 ) : NEW_LINE INDENT ans = min ( ans , dp [ N - 1 ] [ i ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 2 , 3 , 4 ] NEW_LINE cost = [ 3 , 2 , 5 , 4 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE minimumCost ( arr , cost , N ) NEW_LINE DEDENT |
Subarray with largest sum after excluding its maximum element | Function to find the maximum sum subarray by excluding the maximum element from the array ; Loop to store all the positive elements in the map ; Loop to iterating over the map and considering as the maximum element of the current including subarray ; Make the current element maximum ; Iterate through array and apply kadane 's algorithm ; Condition if current element is greater than mx then make the element - infinity ; Store the indices in some variable ; Driver Code ; Function Call | def maximumSumSubarray ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] >= 0 and arr [ i ] not in mp ) : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT first = 0 NEW_LINE last = 0 NEW_LINE ans = 0 NEW_LINE INF = 1e6 NEW_LINE for i in mp : NEW_LINE INDENT mx = i NEW_LINE curr = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( curr == 0 ) : NEW_LINE INDENT curr_start = j NEW_LINE DEDENT if arr [ j ] > mx : NEW_LINE INDENT val = - INF NEW_LINE DEDENT else : NEW_LINE INDENT val = arr [ j ] ; NEW_LINE DEDENT curr += val NEW_LINE if ( curr < 0 ) : NEW_LINE INDENT curr = 0 NEW_LINE DEDENT if ( curr > ans ) : NEW_LINE INDENT ans = curr NEW_LINE first = curr_start NEW_LINE last = j NEW_LINE DEDENT DEDENT DEDENT print ( first + 1 , last + 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , - 2 , 10 , - 1 , 4 ] NEW_LINE size = len ( arr ) NEW_LINE maximumSumSubarray ( arr , size ) NEW_LINE DEDENT |
Minimum insertions to make XOR of an Array equal to half of its sum | Function to make XOR of the array equal to half of its sum ; Calculate the sum and Xor of all the elements ; If the required condition satisfies already , return the original array ; If Xor is already zero , Insert sum ; Otherwise , insert xr and insert sum + xr ; Driver code | def make_xor_half ( arr ) : NEW_LINE INDENT sum = 0 ; xr = 0 ; NEW_LINE for a in arr : NEW_LINE INDENT sum += a ; NEW_LINE xr ^= a ; NEW_LINE DEDENT if ( 2 * xr == sum ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( xr == 0 ) : NEW_LINE INDENT arr . append ( sum ) ; NEW_LINE return 1 ; NEW_LINE DEDENT arr . append ( xr ) ; NEW_LINE arr . append ( sum + xr ) ; NEW_LINE return 2 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 ; NEW_LINE nums = [ 3 , 4 , 7 , 1 , 2 , 5 , 6 ] ; NEW_LINE count = make_xor_half ( nums ) ; NEW_LINE if ( count == - 1 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT elif ( count == 1 ) : NEW_LINE INDENT print ( nums [ N ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( nums [ N ] , nums [ N + 1 ] ) ; NEW_LINE DEDENT DEDENT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.