text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Check if a number can be represented as a sum of a Prime Number and a Perfect Square | Python3 program for the above approach ; Function to check if a number is prime or not ; Base Cases ; Check if n is divisible by 2 or 3 ; Iterate over every 6 number from the range [ 5 , sqrt ( N ) ] ; If n is found to be non - prime ; Otherwise , return true ; Function to check if a number can be represented as the sum of a prime number and a perfect square or not ; Stores all perfect squares less than N ; Store the perfect square in the array ; Iterate over all perfect squares ; Store the difference of perfect square from n ; If difference is prime ; Update flag ; Break out of the loop ; If N is the sum of a prime number and a perfect square ; Driver Code
from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 5 , int ( sqrt ( n ) ) + 1 , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def sumOfPrimeSquare ( n ) : NEW_LINE INDENT i = 0 NEW_LINE squares = [ ] NEW_LINE while ( i * i < n ) : NEW_LINE INDENT squares . append ( i * i ) NEW_LINE i += 1 NEW_LINE DEDENT flag = False NEW_LINE for i in range ( len ( squares ) ) : NEW_LINE INDENT difference = n - squares [ i ] NEW_LINE if ( isPrime ( difference ) ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 27 NEW_LINE sumOfPrimeSquare ( N ) NEW_LINE DEDENT
Check if a number can be represented as a sum of a Prime Number and a Perfect Square | Python3 program for the above approach ; Function to store all prime numbers less than or equal to N ; Update prime [ 0 ] and prime [ 1 ] as false ; Iterate over the range [ 2 , sqrt ( N ) ] ; If p is a prime ; Update all multiples of p which are <= n as non - prime ; Function to check whether a number can be represented as the sum of a prime number and a perfect square ; Stores all the prime numbers less than or equal to n ; Update the array prime [ ] ; Iterate over the range [ 0 , n ] ; If current number is non - prime ; Update difference ; If difference is a perfect square ; If true , update flag and break out of loop ; If N can be expressed as sum of prime number and perfect square ; Driver Code
import math NEW_LINE def SieveOfEratosthenes ( prime , n ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( n ** ( 1 / 2 ) ) ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p ** 2 , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def sumOfPrimeSquare ( n ) : NEW_LINE INDENT flag = False NEW_LINE prime = [ True ] * ( n + 1 ) NEW_LINE SieveOfEratosthenes ( prime , n ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( not prime [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT dif = n - i NEW_LINE if ( math . ceil ( dif ** ( 1 / 2 ) ) == math . floor ( dif ** ( 1 / 2 ) ) ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 27 NEW_LINE sumOfPrimeSquare ( N ) NEW_LINE DEDENT
Check if any subarray of length M repeats at least K times consecutively or not | Function to check if there exists any subarray of length M repeating at least K times consecutively ; Iterate from i equal 0 to M ; Iterate from j equals 1 to K ; If elements at pos + i and pos + i + j * M are not equal ; Function to check if a subarray repeats at least K times consecutively or not ; Iterate from ind equal 0 to M ; Check if subarray arr [ i , i + M ] repeats atleast K times or not ; Otherwise , return false ; Driver Code
def check ( arr , M , K , ind ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( 1 , K , 1 ) : NEW_LINE INDENT if ( arr [ ind + i ] != arr [ ind + i + j * M ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def SubarrayRepeatsKorMore ( arr , N , M , K ) : NEW_LINE INDENT for ind in range ( N - M * K + 1 ) : NEW_LINE INDENT if ( check ( arr , M , K , ind ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 2 , 1 , 1 , 1 , 3 ] NEW_LINE M = 2 NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE if ( SubarrayRepeatsKorMore ( arr , N , M , K ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Check if any subarray of length M repeats at least K times consecutively or not | Function to check if any subarray of length M repeats at least K times consecutively or not ; Stores the required count of repeated subarrays ; Check if the next continuous subarray has equal elements ; Check if K continuous subarray of length M are found or not ; If no subarrays are found ; Driver Code
def checkExists ( arr , N , M , K ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N - M ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + M ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = 0 NEW_LINE DEDENT if ( count == M * ( K - 1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 2 , 1 , 1 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE M = 2 NEW_LINE K = 2 NEW_LINE if ( checkExists ( arr , N , M , K ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Number of common digits present in two given numbers | Function to count number of digits that are common in both N and M ; Stores the count of common digits ; Stores the count of digits of N ; Stores the count of digits of M ; Iterate over the digits of N ; Increment the count of last digit of N ; Update N ; Iterate over the digits of M ; Increment the count of last digit of M ; Update M ; Iterate over the range [ 0 , 9 ] ; If freq1 [ i ] and freq2 [ i ] both exceeds 0 ; Increment count by 1 ; Return the count ; Driver Code ; Input
def CommonDigits ( N , M ) : NEW_LINE INDENT count = 0 NEW_LINE freq1 = [ 0 ] * 10 NEW_LINE freq2 = [ 0 ] * 10 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT freq1 [ N % 10 ] += 1 NEW_LINE N = N // 10 NEW_LINE DEDENT while ( M > 0 ) : NEW_LINE INDENT freq2 [ M % 10 ] += 1 NEW_LINE M = M // 10 NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT if ( freq1 [ i ] > 0 and freq2 [ i ] > 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 748294 NEW_LINE M = 34298156 NEW_LINE print ( CommonDigits ( N , M ) ) NEW_LINE DEDENT
Smallest value of N such that the sum of all natural numbers from K to N is at least X | Function to find the minimum possible value of N such that sum of natural numbers from K to N is at least X ; If K is greater than X ; Stores value of minimum N ; Stores the sum of values over the range [ K , ans ] ; Iterate over the range [ K , N ] ; Check if sum of first i natural numbers is >= X ; Print the possible value of ans ; Driver Code
def minimumNumber ( K , X ) : NEW_LINE INDENT if ( K > X ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT ans = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( K , X + 1 ) : NEW_LINE INDENT sum += i NEW_LINE if ( sum >= X ) : NEW_LINE INDENT ans = i NEW_LINE break NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT K = 5 NEW_LINE X = 13 NEW_LINE minimumNumber ( K , X ) NEW_LINE
Smallest value of N such that the sum of all natural numbers from K to N is at least X | Function to check if the sum of natural numbers from K to N is >= X ; Function to find the minimum value of N such that the sum of natural numbers from K to N is at least X ; If K is greater than X ; Perform the Binary Search ; If the sum of the natural numbers from K to mid is atleast X ; Update res ; Update high ; Otherwise , update low ; Print the value of res as the answer ; Driver Code
def isGreaterEqual ( N , K , X ) : NEW_LINE INDENT return ( ( ( N * ( N + 1 ) // 2 ) - ( ( K - 1 ) * K // 2 ) ) >= X ) NEW_LINE DEDENT def minimumNumber ( K , X ) : NEW_LINE INDENT if ( K > X ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT low = K NEW_LINE high = X NEW_LINE res = - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( ( high - low ) // 2 ) NEW_LINE if ( isGreaterEqual ( mid , K , X ) ) : NEW_LINE INDENT res = mid NEW_LINE high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT print ( res ) NEW_LINE DEDENT K = 5 NEW_LINE X = 13 NEW_LINE minimumNumber ( K , X ) NEW_LINE
Count pairs with product of indices equal to the product of elements present at those indices | Function to count the number of pairs having product of indices equal to the product of elements at that indices ; Stores the count of valid pairs ; Generate all possible pairs ; If the condition is satisfied ; Increment the count ; Return the total count ; Driver Code
def CountPairs ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( ( i * j ) == ( arr [ i ] * arr [ j ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 0 , 3 , 2 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( CountPairs ( arr , N ) ) NEW_LINE DEDENT
Maximize remainder of sum of a pair of array elements with different parity modulo K | Python3 program for the above approach ; Function to find the maximum remainder of sum of a pair of array elements modulo K ; Stores all even numbers ; Stores all odd numbers ; Segregate remainders of even and odd numbers in respective sets ; Stores the maximum remainder obtained ; Find the complement of remainder of each even number in odd set ; Find the complement of remainder x ; Print the answer ; Driver code ; Given array ; Size of the array ; Given value of K
from bisect import bisect_left NEW_LINE def maxRemainder ( A , N , K ) : NEW_LINE INDENT even = { } NEW_LINE odd = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT num = A [ i ] NEW_LINE if ( num % 2 == 0 ) : NEW_LINE INDENT even [ num % K ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd [ num % K ] = 1 NEW_LINE DEDENT DEDENT max_rem = 0 NEW_LINE for x in even : NEW_LINE INDENT y = K - 1 - x NEW_LINE od = list ( odd . keys ( ) ) NEW_LINE it = bisect_left ( od , y ) NEW_LINE if ( it != 0 ) : NEW_LINE INDENT max_rem = max ( max_rem , x + od [ it ] ) NEW_LINE DEDENT DEDENT print ( max_rem ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 4 , 11 , 6 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE K = 7 NEW_LINE maxRemainder ( arr , N , K ) NEW_LINE DEDENT
Length of the longest path ending at vertex V in a Graph | Python3 program for the above approach ; Function to perform DFS Traversal from source node to the deepest node and update maximum distance to the deepest node ; Mark source as visited ; Update the maximum distance ; Traverse the adjacency list of the current source node ; Recursively call for the child node ; Backtracking step ; Function to calculate maximum length of the path ending at vertex V from any source node ; Stores the maximum length of the path ending at vertex V ; Stores the size of the matrix ; Stores the adjacency list of the given graph ; Traverse the matrix to create adjacency list ; Perform DFS Traversal to update the maximum distance ; Driver Code
visited = [ False for i in range ( 4 ) ] NEW_LINE def dfs ( src , Adj , level , distance ) : NEW_LINE INDENT global visited NEW_LINE visited [ src ] = True NEW_LINE distance = max ( distance , level ) NEW_LINE for child in Adj [ src ] : NEW_LINE INDENT if ( child != src and visited [ child ] == False ) : NEW_LINE INDENT dfs ( child , Adj , level + 1 , distance ) NEW_LINE DEDENT DEDENT visited [ src ] = False NEW_LINE DEDENT def maximumLength ( mat , V ) : NEW_LINE INDENT distance = 0 NEW_LINE N = len ( mat ) NEW_LINE Adj = [ [ ] for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT Adj [ i ] . append ( j ) NEW_LINE DEDENT DEDENT DEDENT dfs ( V , Adj , 0 , distance ) NEW_LINE return distance + 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 0 , 1 , 0 , 0 ] , [ 1 , 0 , 1 , 1 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 1 , 0 , 0 ] ] NEW_LINE V = 2 NEW_LINE print ( maximumLength ( mat , V ) ) NEW_LINE DEDENT
Minimum removals required such that given string consists only of a pair of alternating characters | Function to find the maximum length of alternating occurrences of a pair of characters in a string s ; Stores the next character for alternating sequence ; Stores the length of alternating occurrences of a pair of characters ; Traverse the given string ; If current character is same as the required character ; Increase length by 1 ; Reset required character ; Return the length ; Function to find minimum characters required to be deleted from S to obtain an alternating sequence ; Stores maximum length of alternating sequence of two characters ; Stores length of the string ; Generate every pair of English alphabets ; Function call to find length of alternating sequence for current pair of characters ; Update len to store the maximum of len and newLen in len ; Return n - len as the final result ; Driver Code ; Given Input ; Function call to find minimum characters required to be removed from S to make it an alternating sequence of a pair of characters
def findLength ( s , i , j ) : NEW_LINE INDENT required = i NEW_LINE length = 0 NEW_LINE for curr in s : NEW_LINE INDENT if ( curr == required ) : NEW_LINE INDENT length += 1 NEW_LINE if ( required == i ) : NEW_LINE INDENT required = j NEW_LINE DEDENT else : NEW_LINE INDENT required = i NEW_LINE DEDENT DEDENT DEDENT return length NEW_LINE DEDENT def minimumDeletions ( S ) : NEW_LINE INDENT len1 = 0 NEW_LINE n = len ( S ) NEW_LINE for i in range ( 0 , 26 , 1 ) : NEW_LINE INDENT for j in range ( i + 1 , 26 , 1 ) : NEW_LINE INDENT newLen = findLength ( S , chr ( i + 97 ) , chr ( j + 97 ) ) NEW_LINE len1 = max ( len1 , newLen ) NEW_LINE DEDENT DEDENT return n - len1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " adebbeeaebd " NEW_LINE print ( minimumDeletions ( S ) ) NEW_LINE DEDENT
Smallest value of X satisfying the condition X % A [ i ] = B [ i ] for two given arrays | Python3 program for the above approach ; Function to calculate modulo inverse of a w . r . t m using Extended Euclid Algorithm ; Base Case ; Perform extended euclid algorithm ; q is quotient ; m is remainder now , process same as euclid 's algorithm ; If x1 is negative ; Make x1 positive ; Function to implement Chinese Remainder Theorem to find X ; Stores the product of array elements ; Traverse the array ; Update product ; Initialize the result ; Apply the above formula ; Function to calculate the product of all elements of the array a [ ] ; Stores product of all array elements ; Traverse the array ; Return the product ; Function to find the value of X that satisfies the given condition ; Stores the required smallest value using Chinese Remainder Theorem ; Stores the product of all array elements ; The equation is Y + K * M >= P Therefore , calculate K = ceil ( ( P - Y ) / M ) ; So , X = Y + K * M ; Print the resultant value of X ; Driver Code
import math NEW_LINE def inv ( a , m ) : NEW_LINE INDENT m0 = m NEW_LINE x0 = 0 NEW_LINE x1 = 1 NEW_LINE if ( m == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( a > 1 ) : NEW_LINE INDENT q = a // m NEW_LINE t = m NEW_LINE m = a % m NEW_LINE a = t NEW_LINE t = x0 NEW_LINE x0 = x1 - q * x0 NEW_LINE x1 = t NEW_LINE DEDENT if ( x1 < 0 ) : NEW_LINE INDENT x1 += m0 NEW_LINE DEDENT return x1 NEW_LINE DEDENT def findMinX ( A , B , N ) : NEW_LINE INDENT prod = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT prod *= A [ i ] NEW_LINE DEDENT result = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT pp = prod // A [ i ] NEW_LINE result += B [ i ] * inv ( pp , A [ i ] ) * pp NEW_LINE DEDENT return result % prod NEW_LINE DEDENT def product ( a , n ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans *= a [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT def findSmallestInteger ( A , B , P , n ) : NEW_LINE INDENT Y = findMinX ( A , B , n ) NEW_LINE M = product ( A , n ) NEW_LINE K = math . ceil ( ( P - Y ) / M ) NEW_LINE X = Y + K * M NEW_LINE print ( X ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 3 , 4 , 5 ] NEW_LINE B = [ 2 , 3 , 1 ] NEW_LINE n = len ( A ) NEW_LINE P = 72 NEW_LINE findSmallestInteger ( A , B , P , n ) NEW_LINE DEDENT
Minimum number of jumps required to sort the given array in ascending order | Function to count minimum number of jumps required to sort the array ; Stores minimum number of jumps ; Stores distances of jumps ; Stores the array elements with their starting indices ; Push the pairs { arr [ i ] , i + 1 } into the vector of pairs vect ; Update vect ; Populate the array temp [ ] ; Update temp [ arr [ i ] ] ; Sort the vector in the ascending order ; Jump till the previous index <= current index ; Update vect [ i ] ; Increment the number of jumps ; Print the minimum number of jumps required ; Driver Code ; Input ; Size of the array
def minJumps ( arr , jump , N ) : NEW_LINE INDENT jumps = 0 NEW_LINE temp = [ 0 for i in range ( 1000 ) ] NEW_LINE vect = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT vect . append ( [ arr [ i ] , i + 1 ] ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT temp [ arr [ i ] ] = jump [ i ] NEW_LINE DEDENT vect . sort ( reverse = False ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT while ( vect [ i ] [ 1 ] <= vect [ i - 1 ] [ 1 ] ) : NEW_LINE INDENT vect [ i ] = [ vect [ i ] [ 0 ] , vect [ i ] [ 1 ] + temp [ vect [ i ] [ 0 ] ] ] NEW_LINE jumps += 1 NEW_LINE DEDENT DEDENT print ( jumps ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 ] NEW_LINE jump = [ 1 , 1 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE minJumps ( arr , jump , N ) NEW_LINE DEDENT
Minimum number of basic logic gates required to realize given Boolean expression | Function to count the total number of gates required to realize the boolean expression S ; Length of the string ; Stores the count of total gates ; Traverse the string ; AND , OR and NOT Gate ; Print the count of gates required ; Driver Code ; Input ; Function call to count the total number of gates required
def numberOfGates ( s ) : NEW_LINE INDENT N = len ( s ) NEW_LINE ans = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' . ' or s [ i ] == ' + ' or s [ i ] == '1' ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT print ( ans , end = " " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " ( 1 - A ) . B + C " NEW_LINE numberOfGates ( S ) NEW_LINE DEDENT
Count pairs ( i , j ) from an array such that | arr [ i ] | and | arr [ j ] | both lies between | arr [ i ] | Function to find pairs ( i , j ) such that | arr [ i ] | and | arr [ j ] | lies in between | arr [ i ] - arr [ j ] | and | arr [ i ] + arr [ j ] | ; Calculate absolute value of all array elements ; Sort the array ; Stores the count of pairs ; Traverse the array ; Increment left ; Add to the current count of pairs ; Print the answer ; Driver Code
def findPairs ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT arr [ i ] = abs ( arr [ i ] ) NEW_LINE DEDENT arr . sort ( ) NEW_LINE left = 0 NEW_LINE ans = 0 NEW_LINE for right in range ( N ) : NEW_LINE INDENT while ( 2 * arr [ left ] < arr [ right ] ) : NEW_LINE INDENT left += 1 NEW_LINE DEDENT ans += ( right - left ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 5 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE findPairs ( arr , N ) NEW_LINE DEDENT
Calculate absolute difference between minimum and maximum sum of pairs in an array | Python 3 program for the above approach ; Function to find the difference between the maximum and minimum sum of a pair ( arr [ i ] , arr [ j ] ) from the array such that i < j and arr [ i ] < arr [ j ] ; Stores the maximum from the suffix of the array ; Set the last element ; Traverse the remaining array ; Update the maximum from suffix for the remaining indices ; Stores the maximum sum of any pair ; Calculate the maximum sum ; Stores the maximum sum of any pair ; Stores the minimum of suffixes from the given array ; Set the last element ; Traverse the remaining array ; Update the maximum from suffix for the remaining indices ; Calculate the minimum sum ; Return the resultant difference ; Driver Code ; Function Call
import sys NEW_LINE def GetDiff ( A , N ) : NEW_LINE INDENT SuffMaxArr = [ 0 for i in range ( N ) ] NEW_LINE SuffMaxArr [ N - 1 ] = A [ N - 1 ] NEW_LINE i = N - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT SuffMaxArr [ i ] = max ( SuffMaxArr [ i + 1 ] , A [ i + 1 ] ) NEW_LINE i -= 1 NEW_LINE DEDENT MaximumSum = - sys . maxsize - 1 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i ] < SuffMaxArr [ i ] ) : NEW_LINE INDENT MaximumSum = max ( MaximumSum , A [ i ] + SuffMaxArr [ i ] ) NEW_LINE DEDENT DEDENT MinimumSum = sys . maxsize NEW_LINE SuffMinArr = [ 0 for i in range ( N ) ] NEW_LINE SuffMinArr [ N - 1 ] = sys . maxsize NEW_LINE i = N - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT SuffMinArr [ i ] = min ( SuffMinArr [ i + 1 ] , A [ i + 1 ] ) NEW_LINE i -= 1 NEW_LINE DEDENT for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i ] < SuffMinArr [ i ] ) : NEW_LINE INDENT MinimumSum = min ( MinimumSum , A [ i ] + SuffMinArr [ i ] ) NEW_LINE DEDENT DEDENT return abs ( MaximumSum - MinimumSum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 1 , 3 , 7 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( GetDiff ( arr , N ) ) NEW_LINE DEDENT
Minimum number of swaps required to make parity of array elements same as their indices | Function to count the minimum number of swaps required to make the parity of array elements same as their indices ; Stores count of even and odd array elements ; Traverse the array ; Check if indices and array elements are not of the same parity ; If index is even ; Update even ; Update odd ; Condition for not possible ; Otherwise ; Driver Code
def minimumSwaps ( arr , N ) : NEW_LINE INDENT even , odd = 0 , 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 != i % 2 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT even += 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT DEDENT DEDENT if ( even != odd ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( even ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 7 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE minimumSwaps ( arr , N ) NEW_LINE DEDENT
Smallest substring occurring only once in a given string | Python3 program of the above approach ; Function to find the smallest substring occurring only once ; Stores all occurences ; Generate all the substrings ; Avoid multiple occurences ; Append all substrings ; Take into account all the substrings ; Iterate over all unique substrings ; If frequency is 1 ; Append into fresh list ; Initialize a dictionary ; Append the keys ; Traverse the dictionary ; Print the minimum of dictionary ; Driver Code
from collections import Counter NEW_LINE def smallestSubstring ( a ) : NEW_LINE INDENT a1 = [ ] NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( a ) ) : NEW_LINE INDENT if i != j : NEW_LINE INDENT a1 . append ( a [ i : j + 1 ] ) NEW_LINE DEDENT DEDENT DEDENT a2 = Counter ( a1 ) NEW_LINE freshlist = [ ] NEW_LINE for i in a2 : NEW_LINE INDENT if a2 [ i ] == 1 : NEW_LINE INDENT freshlist . append ( i ) NEW_LINE DEDENT DEDENT dictionary = dict ( ) NEW_LINE for i in range ( len ( freshlist ) ) : NEW_LINE INDENT dictionary [ freshlist [ i ] ] = len ( freshlist [ i ] ) NEW_LINE DEDENT newlist = [ ] NEW_LINE for i in dictionary : NEW_LINE INDENT newlist . append ( dictionary [ i ] ) NEW_LINE DEDENT return ( min ( newlist ) ) NEW_LINE DEDENT S = " ababaabba " NEW_LINE print ( smallestSubstring ( S ) ) NEW_LINE
Minimize insertions required to make ratio of maximum and minimum of all pairs of adjacent array elements at most K | Function to count the minimum number of insertions required ; Stores the number of insertions required ; Traverse the array ; Store the minimum array element ; Store the maximum array element ; Checking condition ; Increase current count ; Return the count of insertions ; Driver Code
def mininsert ( arr , K , N ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT a = min ( arr [ i ] , arr [ i + 1 ] ) NEW_LINE b = max ( arr [ i ] , arr [ i + 1 ] ) NEW_LINE while ( K * a < b ) : NEW_LINE INDENT a *= K NEW_LINE ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 10 , 25 , 21 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( mininsert ( arr , K , N ) ) NEW_LINE
Sum of numbers formed by consecutive digits present in a given string | Function to calculate the sum of numbers formed by consecutive sequences of digits present in the string ; Stores consecutive digits present in the string ; Stores the sum ; Iterate over characters of the input string ; If current character is a digit ; Append current digit to curr ; Add curr to sum ; Reset curr ; Driver Code
def sumOfDigits ( s ) : NEW_LINE INDENT curr = 0 NEW_LINE ret = 0 NEW_LINE for ch in s : NEW_LINE INDENT if ( ord ( ch ) >= 48 and ord ( ch ) <= 57 ) : NEW_LINE INDENT curr = curr * 10 + ord ( ch ) - ord ( '0' ) NEW_LINE DEDENT else : NEW_LINE INDENT ret += curr NEW_LINE curr = 0 NEW_LINE DEDENT DEDENT ret += curr NEW_LINE return ret NEW_LINE DEDENT S = "11aa32bbb5" NEW_LINE print ( sumOfDigits ( S ) ) NEW_LINE
Find a triplet ( i , j , k ) from an array such that i < j < k and arr [ i ] < arr [ j ] > arr [ k ] | Function to find a triplet such that i < j < k and arr [ i ] < arr [ j ] and arr [ j ] > arr [ k ] ; Traverse the array ; Condition to satisfy for the resultant triplet ; Otherwise , triplet doesn 't exist ; Driver Code
def print_triplet ( arr , n ) : NEW_LINE INDENT 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 print ( i - 1 , i , i + 1 ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( - 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 3 , 5 , 2 , 1 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print_triplet ( arr , N ) NEW_LINE DEDENT
Check if an array element is concatenation of two elements from another array | Python3 program for the above approach ; Function to find elements present in the array b [ ] which are concatenation of any pair of elements in the array a [ ] ; Stores if there doesn 't any such element in the array brr[] ; Stored the size of both the arrays ; Store the presence of an element of array a [ ] ; Traverse the array a [ ] ; Traverse the array b [ ] ; Traverse over all possible concatenations of b [ i ] ; Update right and left parts ; Check if both left and right parts are present in a [ ] ; Driver Code
from collections import defaultdict NEW_LINE def findConcatenatedNumbers ( a , b ) : NEW_LINE INDENT ans = True NEW_LINE n1 = len ( a ) NEW_LINE n2 = len ( b ) NEW_LINE cnt = defaultdict ( int ) NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT cnt [ a [ i ] ] = 1 NEW_LINE DEDENT for i in range ( n2 ) : NEW_LINE INDENT left = b [ i ] NEW_LINE right = 0 NEW_LINE mul = 1 NEW_LINE while ( left > 9 ) : NEW_LINE INDENT right += ( left % 10 ) * mul NEW_LINE left //= 10 NEW_LINE mul *= 10 NEW_LINE if ( cnt [ left ] == 1 and cnt [ right ] == 1 ) : NEW_LINE INDENT ans = False NEW_LINE print ( b [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if ( ans ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 34 , 4 , 5 ] NEW_LINE b = [ 26 , 24 , 345 , 4 , 22 ] NEW_LINE findConcatenatedNumbers ( a , b ) NEW_LINE DEDENT
Number of subarrays having even product | Function to count subarrays with even product ; Stores count of subarrays with even product ; Traverse the array ; Initialize product ; Update product of the subarray ; Print total count of subarrays ; Driver Code ; Input ; Length of an array ; Function call to count subarrays with even product
def evenproduct ( arr , length ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( length + 1 ) : NEW_LINE INDENT product = 1 ; NEW_LINE for j in range ( i , length + 1 ) : NEW_LINE product *= arr [ j ] ; NEW_LINE if ( product % 2 == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT print ( count ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 5 , 4 , 9 ] ; NEW_LINE length = len ( arr ) - 1 ; NEW_LINE evenproduct ( arr , length ) ; NEW_LINE DEDENT
Count pairs of nodes having minimum distance between them equal to the difference of their distances from root | Stores the count of pairs ; Store the adjacency list of the connecting vertex ; Function for theto perform DFS traversal of the given tree ; Traverse the adjacency list of the current node u ; If the current node is the parent node ; Add number of ancestors , which is same as depth of the node ; Function for DFS traversal of the given tree ; Print result ; Function to find the count of pairs such that the minimum distance between them is equal to the difference between distance of the nodes from root node ; Add edges to adj [ ] ; Driver Code
ans = 0 NEW_LINE adj = [ [ ] for i in range ( 10 ** 5 + 1 ) ] NEW_LINE def dfsUtil ( u , par , depth ) : NEW_LINE INDENT global adj , ans NEW_LINE for it in adj [ u ] : NEW_LINE INDENT if ( it != par ) : NEW_LINE INDENT dfsUtil ( it , u , depth + 1 ) NEW_LINE DEDENT DEDENT ans += depth NEW_LINE DEDENT def dfs ( u , par , depth ) : NEW_LINE INDENT global ans NEW_LINE dfsUtil ( u , par , depth ) NEW_LINE print ( ans ) NEW_LINE DEDENT def countPairs ( edges ) : NEW_LINE INDENT global adj NEW_LINE for i in range ( len ( edges ) ) : NEW_LINE INDENT u = edges [ i ] [ 0 ] NEW_LINE v = edges [ i ] [ 1 ] NEW_LINE adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT dfs ( 1 , 1 , 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 4 ] ] NEW_LINE countPairs ( edges ) NEW_LINE DEDENT
Number from a given range that requires Kth smallest number of steps to get reduced to 1 | Python3 program for the above approach ; Function to count the number of steps required to reduce val to 1 by the given operations ; Base Case ; If val is even , divide by 2 ; Otherwise , multiply it by 3 and increment by 1 ; Function to find Kth smallest count of steps required for numbers from the range [ L , R ] ; Stores numbers and their respective count of steps ; Count the number of steps for anumbers from the range [ L , R ] ; Insert in the vector ; Sort the vector in ascending order w . r . t . to power value ; Print the K - th smallest number ; Driver Code
v = [ - 1 ] * ( 1000000 ) NEW_LINE def power_value ( val ) : NEW_LINE INDENT if ( val == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( val % 2 == 0 ) : NEW_LINE INDENT v [ val ] = power_value ( val // 2 ) + 1 NEW_LINE return v [ val ] NEW_LINE DEDENT else : NEW_LINE INDENT temp = val * 3 NEW_LINE temp += 1 NEW_LINE v [ val ] = power_value ( temp ) + 1 NEW_LINE return v [ val ] NEW_LINE DEDENT DEDENT def getKthNumber ( l , r , k ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT if ( v [ i ] == - 1 ) : NEW_LINE INDENT power_value ( i ) NEW_LINE DEDENT DEDENT j = 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT ans . append ( [ v [ i ] , i ] ) NEW_LINE j += 1 NEW_LINE DEDENT ans = sorted ( ans ) NEW_LINE print ( ans [ k - 1 ] [ 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R , K = 7 , 10 , 4 NEW_LINE getKthNumber ( L , R , K ) NEW_LINE DEDENT
Sum of decimal equivalents of binary node values in each level of a Binary Tree | Structure of a Tree Node ; Function to convert binary number to its equivalent decimal value ; Function to calculate sum of decimal equivalent of binary numbers of node values present at each level ; Push root node into queue ; Connect nodes at the same level to form a binary number ; Stores the front element of the queue ; Append the value of the current node to eachLvl ; Insert the Left child to queue , if its not NULL ; Insert the Right child to queue , if its not NULL ; Decrement length by one ; Add decimal equivalent of the binary number formed on the current level to ans ; Finally print ans ; Given Tree ; Function Call
class TreeNode : NEW_LINE INDENT def __init__ ( self , val = 0 , left = None , right = None ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def convertBinaryToDecimal ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in arr : NEW_LINE INDENT ans = ( ans << 1 ) | i NEW_LINE DEDENT return ans NEW_LINE DEDENT def decimalEquilvalentAtEachLevel ( root ) : NEW_LINE INDENT ans = 0 NEW_LINE que = [ root ] NEW_LINE while True : NEW_LINE INDENT length = len ( que ) NEW_LINE if not length : NEW_LINE INDENT break NEW_LINE DEDENT eachLvl = [ ] NEW_LINE while length : NEW_LINE INDENT temp = que . pop ( 0 ) NEW_LINE eachLvl . append ( temp . val ) NEW_LINE if temp . left : NEW_LINE INDENT que . append ( temp . left ) NEW_LINE DEDENT if temp . right : NEW_LINE INDENT que . append ( temp . right ) NEW_LINE DEDENT length -= 1 NEW_LINE DEDENT ans += convertBinaryToDecimal ( eachLvl ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT root = TreeNode ( 0 ) NEW_LINE root . left = TreeNode ( 1 ) NEW_LINE root . right = TreeNode ( 0 ) NEW_LINE root . left . left = TreeNode ( 0 ) NEW_LINE root . left . right = TreeNode ( 1 ) NEW_LINE root . right . left = TreeNode ( 1 ) NEW_LINE root . right . right = TreeNode ( 1 ) NEW_LINE decimalEquilvalentAtEachLevel ( root ) NEW_LINE
Minimize increments required to make differences between all pairs of array elements even | Function to find the minimum increments required to difference between all pairs of array elements even ; Store the count of odd and even numbers ; Traverse the array ; Increment evenCnt by 1 ; Increment eveCnt by 1 ; Prthe minimum of oddCnt and eveCnt ; Driver Code
def minimumOperations ( arr , N ) : NEW_LINE INDENT oddCnt = 0 NEW_LINE evenCnt = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT evenCnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT oddCnt += 1 NEW_LINE DEDENT DEDENT print ( min ( oddCnt , evenCnt ) ) NEW_LINE DEDENT arr = [ 4 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE minimumOperations ( arr , N ) NEW_LINE
Minimum increments required to make array elements alternately even and odd | Function to find the minimum number of increments required to make the array even - odd alternately or vice - versa ; Store the minimum number of increments required ; Traverse the array arr [ ] ; Increment forEven if even element is present at an odd index ; Increment forEven if odd element is present at an even index ; Return the minimum number of increments ; Driver Code
def minIncr ( arr ) : NEW_LINE INDENT forEven = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if i % 2 : NEW_LINE INDENT if not arr [ i ] % 2 : NEW_LINE INDENT forEven += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if arr [ i ] % 2 : NEW_LINE INDENT forEven += 1 NEW_LINE DEDENT DEDENT DEDENT return min ( forEven , len ( arr ) - forEven ) NEW_LINE DEDENT arr = [ 1 , 4 , 6 , 8 , 9 , 5 ] NEW_LINE print ( minIncr ( arr ) ) NEW_LINE
Queries to find the minimum array sum possible by removing elements from either end | Function to find the minimum sum for each query after removing element from either ends till each value Q [ i ] ; Stores the prefix sum from both the ends of the array ; Traverse the array from front ; Insert it into the map m1 ; Traverse the array in reverse ; Insert it into the map m2 ; Traverse the query array ; Print the minimum of the two values as the answer ; Driver Code ; Function Call
def minOperations ( arr , N , Q , M ) : NEW_LINE INDENT m1 = { } NEW_LINE m2 = { } NEW_LINE front = 0 NEW_LINE rear = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT front += arr [ i ] NEW_LINE m1 [ arr [ i ] ] = front NEW_LINE DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT rear += arr [ i ] NEW_LINE m2 [ arr [ i ] ] = rear NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT print ( min ( m1 [ Q [ i ] ] , m2 [ Q [ i ] ] ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 6 , 7 , 4 , 5 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE Q = [ 7 , 6 ] NEW_LINE M = len ( Q ) NEW_LINE minOperations ( arr , N , Q , M ) NEW_LINE
Check if a string contains an anagram of another string as its substring | Function to check if string s2 contains anagram of the string s1 as its substring ; Stores frequencies of characters in substrings of s2 ; Stores frequencies of characters in s1 ; If length of s2 exceeds length of s1 ; Store frequencies of characters in first substring of length s1len in string s2 ; Perform Sliding Window technique ; If hashmaps are found to be identical for any substring ; Driver Code
def checkAnagram ( s1 , s2 ) : NEW_LINE INDENT s2hash = [ 0 for i in range ( 26 ) ] NEW_LINE s1hash = [ 0 for i in range ( 26 ) ] NEW_LINE s1len = len ( s1 ) NEW_LINE s2len = len ( s2 ) NEW_LINE if ( s1len > s2len ) : NEW_LINE INDENT return False NEW_LINE DEDENT left = 0 NEW_LINE right = 0 NEW_LINE while ( right < s1len ) : NEW_LINE INDENT s1hash [ ord ( s1 [ right ] ) - 97 ] += 1 NEW_LINE s2hash [ ord ( s2 [ right ] ) - 97 ] += 1 NEW_LINE right += 1 NEW_LINE DEDENT right -= 1 NEW_LINE while ( right < s2len ) : NEW_LINE INDENT if ( s1hash == s2hash ) : NEW_LINE INDENT return True NEW_LINE DEDENT right += 1 NEW_LINE if ( right != s2len ) : NEW_LINE INDENT s2hash [ ord ( s2 [ right ] ) - 97 ] += 1 NEW_LINE DEDENT s2hash [ ord ( s2 [ left ] ) - 97 ] -= 1 NEW_LINE left += 1 NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " ab " NEW_LINE s2 = " bbpobac " NEW_LINE if ( checkAnagram ( s1 , s2 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Maximum number of intervals that an interval can intersect | Function to count the maximum number of intervals that an interval can intersect ; Store the required answer ; Traverse all the intervals ; Store the number of intersecting intervals ; Iterate in the range [ 0 , n - 1 ] ; Check if jth interval lies outside the ith interval ; Update the overall maximum ; Print the answer ; Driver code ; Function Call
def findMaxIntervals ( v , n ) : NEW_LINE INDENT maxi = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT c = n NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( v [ i ] [ 1 ] < v [ j ] [ 0 ] or v [ i ] [ 0 ] > v [ j ] [ 1 ] ) : NEW_LINE INDENT c -= 1 NEW_LINE DEDENT DEDENT maxi = max ( c , maxi ) NEW_LINE DEDENT print ( maxi ) NEW_LINE DEDENT arr = [ ] NEW_LINE arr . append ( ( 1 , 2 ) ) NEW_LINE arr . append ( ( 3 , 4 ) ) NEW_LINE arr . append ( ( 2 , 5 ) ) NEW_LINE N = len ( arr ) NEW_LINE findMaxIntervals ( arr , N ) NEW_LINE
Check if all disks can be placed at a single rod based on given conditions | Function to check if it is possible to move all disks to a single rod ; Stores if it is possible to move all disks to a single rod ; Traverse the array ; If i - th element is smaller than both its adjacent elements ; If flag is true ; Otherwise ; Driver Code
def check ( a , n ) : NEW_LINE INDENT flag = 0 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( a [ i + 1 ] > a [ i ] and a [ i ] < a [ i - 1 ] ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT if ( flag != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT arr = [ 1 , 3 , 5 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE if ( check ( arr , N ) != 0 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
Smallest positive integer that does not divide any elements of the given array | Function to find the smallest number which doesn 't divides any integer in the given array arr[] ; Traverse the array arr [ ] ; Maximum array element ; Initialize variable ; Traverse from 2 to max ; Stores if any such integer is found or not ; If any array element is divisible by j ; Smallest integer ; Prthe answer ; Driver Code ; Function Call
def smallestNumber ( arr , lenn ) : NEW_LINE INDENT maxi = 0 NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT maxi = max ( maxi , arr [ i ] ) NEW_LINE DEDENT ans = - 1 NEW_LINE for i in range ( 2 , maxi + 2 ) : NEW_LINE INDENT flag = True NEW_LINE for j in range ( lenn ) : NEW_LINE INDENT if ( arr [ j ] % i == 0 ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT ans = i NEW_LINE break NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 6 , 9 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE smallestNumber ( arr , N ) NEW_LINE DEDENT
Find the duplicate characters in a string in O ( 1 ) space | Function to find duplicate characters in str1ing without using any additional data str1ucture ; Check if ( i + ' a ' ) is present in str1 at least once or not . ; Check if ( i + ' a ' ) is present in str1 at least twice or not . ; Iterate over the characters of the str1ing str1 ; If str1 [ i ] has already occurred in str1 ; Set ( str1 [ i ] - ' a ' ) - th bit of second ; Set ( str1 [ i ] - ' a ' ) - th bit of second ; Iterate over the range [ 0 , 25 ] ; If i - th bit of both first and second is Set ; Driver Code
def findDuplicate ( str1 , N ) : NEW_LINE INDENT first = 0 NEW_LINE second = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( first & ( 1 << ( ord ( str1 [ i ] ) - 97 ) ) ) : NEW_LINE INDENT second = second | ( 1 << ( ord ( str1 [ i ] ) - 97 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT first = first | ( 1 << ( ord ( str1 [ i ] ) - 97 ) ) NEW_LINE DEDENT DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( ( first & ( 1 << i ) ) and ( second & ( 1 << i ) ) ) : NEW_LINE INDENT print ( chr ( i + 97 ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " geeksforgeeks " NEW_LINE N = len ( str1 ) NEW_LINE findDuplicate ( str1 , N ) NEW_LINE DEDENT
Minimize insertions required to make all characters of a given string equal | Function to calculate the minimum number of operations required to make all characters of the string same ; Stores count of operations ; Traverse the string ; Check if adjacent characters are same or not ; Increment count ; Prthe count obtained ; Driver Code
def minOperations ( S ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( 1 , len ( S ) ) : NEW_LINE INDENT if ( S [ i ] != S [ i - 1 ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT print ( count ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "0101010101" ; NEW_LINE minOperations ( S ) ; NEW_LINE DEDENT
Count pairs made up of an element divisible by the other from an array consisting of powers of 2 | Function to count the number of pairs as per the given conditions ; Initialize array set_bits as 0 ; Store the total number of required pairs ; Traverse the array arr [ ] ; Store arr [ i ] in x ; Store the position of the leftmost set bit in arr [ i ] ; Increase bit position ; Divide by 2 to shift bits in right at each step ; Count of pairs for index i till its set bit position ; Increasing count of set bit position of current elelement ; Prthe answer ; Driver Code ; Function Call
def numberOfPairs ( arr , N ) : NEW_LINE INDENT set_bits = [ 0 ] * 31 NEW_LINE count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = arr [ i ] NEW_LINE bitpos = - 1 NEW_LINE while ( x > 0 ) : NEW_LINE INDENT bitpos += 1 NEW_LINE x //= 2 NEW_LINE DEDENT for j in range ( bitpos + 1 ) : NEW_LINE INDENT count += set_bits [ j ] NEW_LINE DEDENT set_bits [ bitpos ] += 1 NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 16 , 8 , 64 ] NEW_LINE N = len ( arr ) NEW_LINE numberOfPairs ( arr , N ) NEW_LINE DEDENT
Queries to find minimum sum of array elements from either end of an array | Function to calculate the minimum sum from either end of the arrays for the given queries ; Traverse the query [ ] array ; Stores sum from start and end of the array ; Calculate distance from start ; Calculate distance from end ; Driver Code
def calculateQuery ( arr , N , query , M ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT X = query [ i ] NEW_LINE sum_start = 0 NEW_LINE sum_end = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT sum_start += arr [ j ] NEW_LINE if ( arr [ j ] == X ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for j in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum_end += arr [ j ] NEW_LINE if ( arr [ j ] == X ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( min ( sum_end , sum_start ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 6 , 7 , 4 , 5 , 30 ] NEW_LINE queries = [ 6 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( queries ) NEW_LINE calculateQuery ( arr , N , queries , M ) NEW_LINE DEDENT
Queries to find minimum sum of array elements from either end of an array | Function to find the minimum sum for the given queries ; Stores prefix and suffix sums ; Stores pairs of prefix and suffix sums ; Traverse the array ; Add element to prefix ; Store prefix for each element ; Traverse the array in reverse ; Add element to suffix ; Storing suffix for each element ; Traverse the array queries [ ] ; Minimum of suffix and prefix sums ; Driver Code
def calculateQuery ( arr , N , query , M ) : NEW_LINE INDENT prefix = 0 NEW_LINE suffix = 0 NEW_LINE mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT prefix += arr [ i ] NEW_LINE mp [ arr [ i ] ] = [ prefix , 0 ] NEW_LINE DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT suffix += arr [ i ] NEW_LINE mp [ arr [ i ] ] = [ mp [ arr [ i ] ] [ 0 ] , suffix ] NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT X = query [ i ] NEW_LINE print ( min ( mp [ X ] [ 0 ] , mp [ X ] [ 1 ] ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 6 , 7 , 4 , 5 , 30 ] NEW_LINE queries = [ 6 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( queries ) NEW_LINE calculateQuery ( arr , N , queries , M ) NEW_LINE
Queries to find the maximum array element after removing elements from a given range | Function to find the maximum element after removing elements in range [ l , r ] ; Store prefix maximum element ; Store suffix maximum element ; Prefix max till first index is first index itself ; Traverse the array to fill prefix max array ; Store maximum till index i ; Suffix max till last index is last index itself ; Traverse the array to fill suffix max array ; Store maximum till index i ; Traverse all queries ; Store the starting and the ending index of the query ; Edge Cases ; Otherwise ; Driver Code
def findMaximum ( arr , N , Q , queries ) : NEW_LINE INDENT prefix_max = [ 0 ] * ( N + 1 ) NEW_LINE suffix_max = [ 0 ] * ( N + 1 ) NEW_LINE prefix_max [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT prefix_max [ i ] = max ( prefix_max [ i - 1 ] , arr [ i ] ) NEW_LINE DEDENT suffix_max [ N - 1 ] = arr [ N - 1 ] NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffix_max [ i ] = max ( suffix_max [ i + 1 ] , arr [ i ] ) NEW_LINE DEDENT for i in range ( Q ) : NEW_LINE INDENT l = queries [ i ] [ 0 ] NEW_LINE r = queries [ i ] [ 1 ] NEW_LINE if ( l == 0 and r == ( N - 1 ) ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT elif ( l == 0 ) : NEW_LINE INDENT print ( suffix_max [ r + 1 ] ) NEW_LINE DEDENT elif ( r == ( N - 1 ) ) : NEW_LINE INDENT print ( prefix_max [ l - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( max ( prefix_max [ l - 1 ] , suffix_max [ r + 1 ] ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 6 , 8 , 10 , 15 ] NEW_LINE N = len ( arr ) NEW_LINE queries = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 1 , 4 ] ] NEW_LINE Q = len ( queries ) NEW_LINE findMaximum ( arr , N , Q , queries ) NEW_LINE DEDENT
Queries to find first occurrence of a character in a given range | Python3 implementation for the above approach ; Function to find the first occurence for a given range ; N = length of string ; M = length of queries ; Stores the indices of a character ; Traverse the string ; Push the index i into the vector [ s [ i ] ] ; Traverse the query ; Stores the value L ; Stores the value R ; Stores the character C ; Find index >= L in the vector v ; If there is no index of C >= L ; Stores the value at idx ; If idx > R ; Otherwise ; Driver Code
from bisect import bisect_left NEW_LINE def firstOccurence ( s , Q ) : NEW_LINE INDENT N = len ( s ) NEW_LINE M = len ( Q ) NEW_LINE v = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT v [ ord ( s [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT left = Q [ i ] [ 0 ] NEW_LINE right = Q [ i ] [ 1 ] NEW_LINE c = Q [ i ] [ 2 ] NEW_LINE if ( len ( v [ ord ( c ) - ord ( ' a ' ) ] ) == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE continue NEW_LINE DEDENT idx = bisect_left ( v [ ord ( c ) - ord ( ' a ' ) ] , left ) NEW_LINE if ( idx == len ( v [ ord ( c ) - ord ( ' a ' ) ] ) ) : NEW_LINE INDENT print ( " - 1 ▁ " ) NEW_LINE continue NEW_LINE DEDENT idx = v [ ord ( c ) - ord ( ' a ' ) ] [ idx ] NEW_LINE if ( idx > right ) : NEW_LINE INDENT print ( " - 1 ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( idx , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcabcabc " ; NEW_LINE Q = [ [ 0 , 3 , ' a ' ] , [ 0 , 2 , ' b ' ] , [ 2 , 4 , ' z ' ] ] NEW_LINE firstOccurence ( S , Q ) NEW_LINE DEDENT
Find index of the element differing in parity with all other array elements | Function to prthe element which differs in parity ; Stores the count of odd and even array elements encountered ; Stores the indices of the last odd and even array elements encountered ; Traverse the array ; If array element is even ; Otherwise ; If only one odd element is present in the array ; If only one even element is present in the array ; Given array ; Size of the array
def oddOneOut ( arr , N ) : NEW_LINE INDENT odd = 0 NEW_LINE even = 0 NEW_LINE lastOdd = 0 NEW_LINE lastEven = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT even += 1 NEW_LINE lastEven = i NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 NEW_LINE lastOdd = i NEW_LINE DEDENT DEDENT if ( odd == 1 ) : NEW_LINE INDENT print ( lastOdd ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( lastEven ) NEW_LINE DEDENT DEDENT arr = [ 2 , 4 , 7 , 8 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE oddOneOut ( arr , N ) NEW_LINE
Reduce a string to a valid email address of minimum length by replacing specified substrings | Function to find the minimum length by replacing at with @ and dot with ' . ' such that the string is valid email ; Stores string by replacing at with @ and dot with ' . ' such that the string is valid email ; append first character ; Stores index ; Check if at ( @ ) already included or not ; Iterate over characters of the string ; at can be replaced at most once ; Update ans ; Update i ; Update notAt ; If current substring found dot ; Update ans ; Update i ; Update ans ; Update i ; Driver Code ; To display the result
def minEmail ( email ) : NEW_LINE INDENT ans = ' ' NEW_LINE ans += email [ 0 ] NEW_LINE i = 1 NEW_LINE notAt = True NEW_LINE while i < len ( email ) : NEW_LINE INDENT if ( i < len ( email ) - 3 and notAt and email [ i : i + 2 ] == ' at ' ) : NEW_LINE INDENT ans += ' @ ' NEW_LINE i += 1 NEW_LINE notAt = False NEW_LINE DEDENT elif i < len ( email ) - 4 and email [ i : i + 3 ] == ' dot ' : NEW_LINE INDENT ans += ' . ' NEW_LINE i += 2 NEW_LINE DEDENT else : NEW_LINE INDENT ans += email [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT email = ' geeksforgeeksatgmaildotcom ' NEW_LINE print ( minEmail ( email ) ) NEW_LINE DEDENT
Find the smallest value of N such that sum of first N natural numbers is Γ’ ‰Β₯ X | Function to check if sum of first N natural numbers is >= X ; Finds minimum value of N such that sum of first N natural number >= X ; Check if sum of first i natural number >= X ; Driver Code ; Input ; Finds minimum value of N such that sum of first N natural number >= X
def isGreaterEqual ( N , X ) : NEW_LINE INDENT return ( N * ( N + 1 ) // 2 ) >= X NEW_LINE DEDENT def minimumPossible ( X ) : NEW_LINE INDENT for i in range ( 1 , X + 1 ) : NEW_LINE INDENT if ( isGreaterEqual ( i , X ) ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 14 NEW_LINE print ( minimumPossible ( X ) ) NEW_LINE DEDENT
Queries to count numbers from given range which are divisible by all its digits | Function to check if a number is divisible by all of its non - zero digits or not ; Stores the number ; Iterate over the digits of the numbers ; If digit of number is non - zero ; If number is not divisible by its current digit ; Update n ; Function to count of numbers which are divisible by all of its non - zero digits in the range [ 1 , i ] ; Stores count of numbers which are divisible by all of its non - zero digits in the range [ 1 , i ] ; Iterate over the range [ 1 , Max ] ; Update ; Traverse the array , arr [ ] ; Driver Code
def CheckDivByAllDigits ( number ) : NEW_LINE INDENT n = number NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( n % 10 ) : NEW_LINE INDENT if ( number % ( n % 10 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n //= 10 NEW_LINE DEDENT return True NEW_LINE DEDENT def cntNumInRang ( arr , N ) : NEW_LINE INDENT global Max NEW_LINE prefCntDiv = [ 0 ] * Max NEW_LINE for i in range ( 1 , Max ) : NEW_LINE INDENT prefCntDiv [ i ] = prefCntDiv [ i - 1 ] + ( CheckDivByAllDigits ( i ) ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( prefCntDiv [ arr [ i ] [ 1 ] ] - prefCntDiv [ arr [ i ] [ 0 ] - 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 5 ] , [ 12 , 14 ] ] NEW_LINE Max = 1000005 NEW_LINE N = len ( arr ) NEW_LINE cntNumInRang ( arr , N ) NEW_LINE DEDENT
Longest subset of nested elements from a given array | Function to find length of longest subset such that subset { arr [ i ] , arr [ arr [ i ] ] , . . } ; Stores length of the longest subset that satisfy the condition ; Traverse in the array , arr [ ] ; If arr [ i ] equals to i ; Update res ; Count of elements in a subset ; Stores index of elements in the current subset ; Calculate length of a subset that satisfy the condition ; Make visited the current index ; Update curr_index ; Update count ; Update res ; Driver Code
def arrayNesting ( arr ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if arr [ i ] == i : NEW_LINE INDENT res = max ( res , 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT count = 0 NEW_LINE curr_index = i NEW_LINE while arr [ curr_index ] != curr_index : NEW_LINE INDENT next_index = arr [ curr_index ] NEW_LINE arr [ curr_index ] = curr_index NEW_LINE curr_index = next_index NEW_LINE count += 1 NEW_LINE DEDENT DEDENT res = max ( res , count ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 4 , 0 , 3 , 1 , 6 , 2 ] NEW_LINE res = arrayNesting ( arr ) NEW_LINE print ( res ) NEW_LINE DEDENT
Count numbers from a given range having exactly 5 distinct factors | Python3 implementation of the above approach ; Stores all prime numbers up to 2 * 10 ^ 5 ; Function to generate all prime numbers up to 2 * 10 ^ 5 using Sieve of Eratosthenes ; Mark 0 and 1 as non - prime ; If i is prime ; Mark all its factors as non - prime ; If current number is prime ; Store the prime ; Function to count numbers in the range [ L , R ] having exactly 5 factors ; Stores the required count ; Driver Code
N = 2 * 100000 NEW_LINE prime = [ 0 ] * N NEW_LINE def Sieve ( ) : NEW_LINE INDENT p = [ True ] * ( N + 1 ) NEW_LINE p [ 0 ] = p [ 1 ] = False NEW_LINE i = 2 NEW_LINE while ( i * i <= N ) : NEW_LINE INDENT if ( p [ i ] == True ) : NEW_LINE INDENT for j in range ( i * i , N , i ) : NEW_LINE INDENT p [ j ] = False NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( p [ i ] != False ) : NEW_LINE INDENT prime . append ( pow ( i , 4 ) ) NEW_LINE DEDENT DEDENT DEDENT def countNumbers ( L , R ) : NEW_LINE INDENT Count = 0 NEW_LINE for p in prime : NEW_LINE INDENT if ( p >= L and p <= R ) : NEW_LINE INDENT Count += 1 NEW_LINE DEDENT DEDENT print ( Count ) NEW_LINE DEDENT L = 16 NEW_LINE R = 85000 NEW_LINE Sieve ( ) NEW_LINE countNumbers ( L , R ) NEW_LINE
Minimize remaining array sizes by removing equal pairs of first array elements | Function to count the remaining elements in the arrays ; Stores the count of 1 s in L1 ; Store the count of 0 s in L2 ; Traverse the array L1 ; If condition is True ; Increment one by 1 ; Increment zero by 1 ; Stores the index after which no further removals are possible ; Traverse the array L2 ; If condition is True ; Decrement one by 1 ; If one < 0 , then break out of the loop ; Decrement zero by 1 ; If zero < 0 , then break out of loop ; Print the answer ; Driver Code ; Function Call
def countRemainingElements ( L1 , L2 , n ) : NEW_LINE INDENT one = 0 ; NEW_LINE zero = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( L1 [ i ] == 1 ) : NEW_LINE INDENT one += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT zero += 1 ; NEW_LINE DEDENT DEDENT ans = n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( L2 [ i ] == 1 ) : NEW_LINE INDENT one -= 1 ; NEW_LINE if ( one < 0 ) : NEW_LINE INDENT ans = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT zero -= 1 ; NEW_LINE if ( zero < 0 ) : NEW_LINE INDENT ans = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT print ( n - ans ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L1 = [ 1 , 1 , 0 , 0 ] ; NEW_LINE L2 = [ 0 , 0 , 0 , 1 ] ; NEW_LINE N = len ( L1 ) ; NEW_LINE countRemainingElements ( L1 , L2 , N ) ; NEW_LINE DEDENT
Count pairs of similar rectangles possible from a given array | Function to calculate the count of similar rectangles ; Driver Code ; Input
def getCount ( rows , columns , A ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( rows ) : NEW_LINE INDENT for j in range ( i + 1 , rows , 1 ) : NEW_LINE INDENT if ( A [ i ] [ 0 ] * A [ j ] [ 1 ] == A [ i ] [ 1 ] * A [ j ] [ 0 ] ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ [ 4 , 8 ] , [ 10 , 20 ] , [ 15 , 30 ] , [ 3 , 6 ] ] NEW_LINE columns = 2 NEW_LINE rows = len ( A ) NEW_LINE print ( getCount ( rows , columns , A ) ) NEW_LINE DEDENT
Find the index with minimum score from a given array | Function to find the index with minimum score ; Stores the score of current index ; Traverse the array in reverse ; Update minimum score ; Print the index with minimum score ; Driver Code
def Min_Score_Index ( N , A ) : NEW_LINE INDENT Score = [ 0 ] * N NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if A [ i ] + i < N : NEW_LINE INDENT Score [ i ] = A [ i ] * Score [ A [ i ] + i ] NEW_LINE DEDENT else : NEW_LINE INDENT Score [ i ] = A [ i ] NEW_LINE DEDENT DEDENT min_value = min ( Score ) NEW_LINE ind = Score . index ( min_value ) NEW_LINE print ( ind ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE Min_Score_Index ( N , A ) NEW_LINE DEDENT
Minimize length of a string by removing occurrences of another string from it as a substring | Function to minimize length of string S after removing all occurrences of string T as substring ; Count of characters required to be removed ; Iterate over the string ; Insert the current character to temp ; Check if the last M characters forms t or not ; Getting the last M characters . If they are equal to t then remove the last M characters from the temp string ; Incrementing subtract by M ; Removing last M characters from the string ; Prthe final answer ; Driver Code ; Given string S & T ; Length of string S ; Length of string T ; Prints the count of operations required
def minLength ( S , T , N , M ) : NEW_LINE INDENT temp = " " ; NEW_LINE subtract = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT temp += S [ i ] ; NEW_LINE if ( len ( temp ) >= M ) : NEW_LINE INDENT if ( T == ( temp [ len ( temp ) - M : len ( temp ) ] ) ) : NEW_LINE INDENT subtract += M ; NEW_LINE cnt = 0 ; NEW_LINE while ( cnt != M ) : NEW_LINE INDENT temp = temp [ 0 : len ( temp ) - 1 ] ; NEW_LINE cnt += 1 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( ( N - subtract ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " aabcbcbd " ; NEW_LINE T = " abc " ; NEW_LINE N = len ( S ) ; NEW_LINE M = len ( T ) ; NEW_LINE minLength ( S , T , N , M ) ; NEW_LINE DEDENT
Minimize swaps between two arrays such that sum of the first array exceeds sum of the second array | Function to find the minimum count of swaps required between the two arrays to make the sum of arr1 [ ] greater than that of arr2 [ ] ; Stores the sum of the two arrays ; Calculate sum of arr1 [ ] ; Calculate sum of arr2 [ ] ; Sort the arrays arr1 [ ] and arr2 [ ] ; Traverse the array arr [ ] ; If the sum1 is less than or equal to sum2 ; Swapping the elements ; Update the sum1 and sum2 ; Increment the count ; Return the final count ; Driver Code ; Function Call
def maximumCount ( arr1 , arr2 , s1 , s2 ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE for i in range ( s1 ) : NEW_LINE INDENT sum1 += arr1 [ i ] NEW_LINE DEDENT for j in range ( s2 ) : NEW_LINE INDENT sum2 += arr2 [ j ] NEW_LINE DEDENT len = 0 NEW_LINE if ( s1 >= s2 ) : NEW_LINE INDENT lenn = s2 NEW_LINE DEDENT else : NEW_LINE INDENT lenn = s1 NEW_LINE DEDENT arr1 . sort ( ) ; NEW_LINE arr2 . sort ( ) ; NEW_LINE j = 0 NEW_LINE k = s2 - 1 NEW_LINE count = 0 NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( sum1 <= sum2 ) : NEW_LINE INDENT if ( arr2 [ k ] >= arr1 [ i ] ) : NEW_LINE INDENT dif1 = arr1 [ j ] NEW_LINE dif2 = arr2 [ k ] NEW_LINE sum1 -= dif1 NEW_LINE sum1 += dif2 NEW_LINE sum2 -= dif2 NEW_LINE sum2 += dif1 NEW_LINE j += 1 NEW_LINE k -= 1 NEW_LINE count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr1 = [ 1 , 3 , 2 , 4 ] NEW_LINE arr2 = [ 6 , 7 , 8 ] NEW_LINE N = len ( arr1 ) NEW_LINE M = len ( arr2 ) NEW_LINE print ( maximumCount ( arr1 , arr2 , N , M ) ) NEW_LINE
Count array elements whose all distinct digits appear in K | Function to check a digit occurs in the digit of K or not ; Iterate over all possible digits of K ; If current digit equal to digit ; Update K ; Function to find the count of array elements whose distinct digits are a subset of digits of K ; Stores count of array elements whose distinct digits are subset of digits of K ; Traverse the array , [ ] arr ; Stores the current element ; Check if all the digits arr [ i ] is a subset of the digits of K or not ; Iterate over all possible digits of arr [ i ] ; Stores current digit ; If current digit does not appear in K ; Update flag ; Update no ; If all the digits arr [ i ] appear in K ; Update count ; Finally print count ; Driver Code
def isValidDigit ( digit , K ) : NEW_LINE INDENT while ( K != 0 ) : NEW_LINE INDENT if ( K % 10 == digit ) : NEW_LINE INDENT return True NEW_LINE DEDENT K = K // 10 NEW_LINE DEDENT return False NEW_LINE DEDENT def noOfValidNumbers ( K , arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT no = arr [ i ] NEW_LINE flag = True NEW_LINE while ( no != 0 ) : NEW_LINE INDENT digit = no % 10 NEW_LINE if ( not isValidDigit ( digit , K ) ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT no = no // 10 NEW_LINE DEDENT if ( flag == True ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT K = 12 NEW_LINE arr = [ 1 , 12 , 1222 , 13 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( noOfValidNumbers ( K , arr , n ) ) NEW_LINE DEDENT
Queries to find the minimum index in given array having at least value X | Python3 program to implement the above approachf ; Function to find the smallest index of an array element whose value is less than or equal to Q [ i ] ; Stores size of array ; Stores coun of queries ; Store array elements along with the index ; Store smallest index of an array element whose value is greater than or equal to i ; Traverse the array ; Insert { arr [ i ] , i } into storeArrIdx [ ] ; Sort the array ; Sort the storeArrIdx ; Stores index of arr [ N - 1 ] in sorted order ; Traverse the array storeArrIdx [ ] ; Update minIdx [ i ] ; Traverse the array Q [ ] ; Store the index of lower_bound of Q [ i ] ; If no index found whose value greater than or equal to arr [ i ] ; Prsmallest index whose value greater than or equal to Q [ i ] ; Driver Code
from bisect import bisect_left NEW_LINE def minimumIndex ( arr , Q ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE M = len ( Q ) NEW_LINE storeArrIdx = [ ] NEW_LINE minIdx = [ 0 ] * ( N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT storeArrIdx . append ( [ arr [ i ] , i ] ) NEW_LINE DEDENT arr = sorted ( arr ) NEW_LINE storeArrIdx = sorted ( storeArrIdx ) NEW_LINE minIdx [ N - 1 ] = storeArrIdx [ N - 1 ] [ 1 ] NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT minIdx [ i ] = min ( minIdx [ i + 1 ] , storeArrIdx [ i ] [ 1 ] ) NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT pos = bisect_left ( arr , Q [ i ] ) NEW_LINE if ( pos == N ) : NEW_LINE INDENT print ( - 1 , end = " ▁ " ) NEW_LINE continue NEW_LINE DEDENT print ( minIdx [ pos ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 9 ] NEW_LINE Q = [ 7 , 10 , 0 ] NEW_LINE minimumIndex ( arr , Q ) NEW_LINE DEDENT
Find a K | Utility function to check if subarray of size K exits whose XOR of elements equal to XOR ofremaning array elements ; Find XOR of whole array ; Find XOR of first K elements ; Adding XOR of next element ; Removing XOR of previous element ; Check if XOR of current subarray matches with the XOR of remaining elements or not ; Function to check if subarray of size K exits whose XOR of elements equal to XOR ofremaning array elements ; Driver Code ; Given array ; Size of the array ; Given K ; Function Call
def isSubarrayExistUtil ( arr , K , N ) : NEW_LINE INDENT totalXOR = 0 NEW_LINE SubarrayXOR = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT totalXOR ^= arr [ i ] NEW_LINE DEDENT for i in range ( K ) : NEW_LINE INDENT SubarrayXOR ^= arr [ i ] NEW_LINE DEDENT if ( SubarrayXOR == ( totalXOR ^ SubarrayXOR ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( K , N ) : NEW_LINE INDENT SubarrayXOR ^= arr [ i ] NEW_LINE SubarrayXOR ^= arr [ i - 1 ] NEW_LINE if ( SubarrayXOR == ( totalXOR ^ SubarrayXOR ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def isSubarrayExist ( arr , K , N ) : NEW_LINE INDENT if ( isSubarrayExistUtil ( arr , K , N ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 3 , 5 , 7 , 7 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE K = 5 NEW_LINE isSubarrayExist ( arr , K , N ) NEW_LINE DEDENT
Count pairs from a given range having even sum | Function to find the count of ordered pairs having even sum ; Stores count of even numbers in the range [ L , R ] ; If L is even ; Update count_even ; Update count_odd ; Stores count of odd numbers in the range [ L , R ] ; Update count_odd ; Update count_odd ; Stores count of pairs whose sum is even and both elements of the pairs are also even ; Stores count of pairs whose sum is even and both elements of the pairs are odd ; Print total ordered pairs whose sum is even ; Driver Code ; Given L & R ; Function Call
def countPairs ( L , R ) : NEW_LINE INDENT count_even = 0 NEW_LINE if ( L % 2 == 0 ) : NEW_LINE INDENT count_even = ( ( R // 2 ) - ( L // 2 ) + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT count_even = ( ( R // 2 ) - ( L // 2 ) ) NEW_LINE DEDENT count_odd = 0 NEW_LINE if ( L % 2 == 0 ) : NEW_LINE INDENT count_odd = ( ( ( R + 1 ) // 2 ) - ( ( L + 1 ) // 2 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT count_odd = ( ( ( R + 1 ) // 2 ) - ( ( L + 1 ) // 2 ) + 1 ) NEW_LINE DEDENT count_even *= count_even NEW_LINE count_odd *= count_odd NEW_LINE print ( count_even + count_odd ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R = 1 , 3 NEW_LINE countPairs ( L , R ) NEW_LINE DEDENT
Count of array elements that can be found using Randomized Binary Search on every array element | Python3 program for the above approach ; Function to find minimum count of array elements found by repeatedly applying Randomized Binary Search ; Stores count of array elements ; smallestRight [ i ] : Stores the smallest array element on the right side of i ; Update smallestRight [ 0 ] ; Traverse the array from right to left ; Update smallestRight [ i ] ; Stores the largest element upto i - th index ; Stores the minimum count of elements found by repeatedly applying Randomized Binary Search ; If largest element on left side is less than smallest element on right side ; Update ans ; Update mn ; Given array ; Function Call
import sys NEW_LINE def getDefiniteFinds ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE smallestRight = [ 0 ] * ( n + 1 ) NEW_LINE smallestRight [ n ] = sys . maxsize NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT smallestRight [ i ] = min ( smallestRight [ i + 1 ] , arr [ i ] ) NEW_LINE DEDENT mn = - sys . maxsize - 1 NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( mn < arr [ i ] and arr [ i ] < smallestRight [ i + 1 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT mn = max ( arr [ i ] , mn ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 5 , 4 , 9 ] NEW_LINE print ( getDefiniteFinds ( arr ) ) NEW_LINE
Count numbers from a given range having same first and last digits in their binary representation | Function to count numbers in range [ L , R ] having same first and last digit in the binary representation ; Given range [ L , R ] ; Function Call
def Count_numbers ( L , R ) : NEW_LINE INDENT count = ( R - L ) // 2 NEW_LINE if ( R % 2 != 0 or L % 2 != 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT L = 6 NEW_LINE R = 30 NEW_LINE Count_numbers ( L , R ) NEW_LINE
Find the index having sum of elements on its left equal to reverse of the sum of elements on its right | Function to check if a number is equal to the reverse of digits of other number ; Stores reverse of digits of rightSum ; Stores rightSum ; Calculate reverse of digits of temp ; Update rev ; Update temp ; If reverse of digits of rightSum equal to leftSum ; Function to find the index that satisfies the condition ; Stores sum of array elements on right side of each index ; Stores sum of array elements on left side of each index ; Traverse the array ; Update rightSum ; Traverse the array ; Update rightSum ; If leftSum equal to reverse of digits of rightSum ; Update leftSum ; Driver Code
def checkReverse ( leftSum , rightSum ) : NEW_LINE INDENT rev = 0 NEW_LINE temp = rightSum NEW_LINE while ( temp != 0 ) : NEW_LINE INDENT rev = ( rev * 10 ) + ( temp % 10 ) NEW_LINE temp //= 10 NEW_LINE DEDENT if ( rev == leftSum ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def findIndex ( arr , N ) : NEW_LINE INDENT rightSum = 0 NEW_LINE leftSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT rightSum += arr [ i ] NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT rightSum -= arr [ i ] NEW_LINE if ( checkReverse ( leftSum , rightSum ) ) : NEW_LINE INDENT return i NEW_LINE DEDENT leftSum += arr [ i ] NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 7 , 3 , 6 , 4 , 9 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findIndex ( arr , N ) ) NEW_LINE DEDENT
Print distinct absolute differences of all possible pairs from a given array | Python3 program for the above approach ; Function to find all distinct absolute difference of all possible pairs of the array ; bset [ i ] : Check if i is present in the array or not ; diff [ i ] : Check if there exists a pair whose absolute difference is i ; Traverse the array , arr [ ] ; Iterate over the range [ 0 , Max ] ; If i - th bit is set ; Insert the absolute difference of all possible pairs whose first element is arr [ i ] ; Stores count of set bits ; If there is at least one duplicate element in arr [ ] ; Printing the distinct absolute differences of all possible pairs ; If i - th bit is set ; Driver Code ; Given array ; Given size ; Function Call
Max = 100005 NEW_LINE def printUniqDif ( n , a ) : NEW_LINE INDENT bset = [ 0 for i in range ( 33 ) ] NEW_LINE diff = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT bset [ a [ i ] ] = 1 NEW_LINE DEDENT d = 0 NEW_LINE for i in range ( 1 , 33 ) : NEW_LINE INDENT d = d | ( bset [ i ] << i ) NEW_LINE DEDENT for i in range ( 33 ) : NEW_LINE INDENT if ( bset [ i ] ) : NEW_LINE INDENT diff = diff | d >> i NEW_LINE DEDENT DEDENT X , Y = bset . count ( 1 ) , str ( bin ( diff ) [ 2 : ] ) NEW_LINE if ( X != n ) : NEW_LINE INDENT print ( 0 , end = " ▁ " ) NEW_LINE DEDENT for i in range ( 1 , len ( Y ) ) : NEW_LINE INDENT if ( Y [ i ] == '1' ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 4 , 6 ] NEW_LINE n = len ( a ) NEW_LINE printUniqDif ( n , a ) NEW_LINE DEDENT
Longest Common Subsequence of two arrays out of which one array consists of distinct elements only | Python3 program to to implement the above approach ; Function to find the Longest Common Subsequence between the two arrays ; Maps elements of firstArr [ ] to their respective indices ; Traverse the array firstArr [ ] ; Stores the indices of common elements between firstArr [ ] and secondArr [ ] ; Traverse the array secondArr [ ] ; If current element exists in the Map ; Stores lIS from tempArr [ ] ; Driver Code
from bisect import bisect_left NEW_LINE def LCS ( firstArr , secondArr ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( len ( firstArr ) ) : NEW_LINE INDENT mp [ firstArr [ i ] ] = i + 1 NEW_LINE DEDENT tempArr = [ ] NEW_LINE for i in range ( len ( secondArr ) ) : NEW_LINE INDENT if ( secondArr [ i ] in mp ) : NEW_LINE INDENT tempArr . append ( mp [ secondArr [ i ] ] ) NEW_LINE DEDENT DEDENT tail = [ ] NEW_LINE tail . append ( tempArr [ 0 ] ) NEW_LINE for i in range ( 1 , len ( tempArr ) ) : NEW_LINE INDENT if ( tempArr [ i ] > tail [ - 1 ] ) : NEW_LINE INDENT tail . append ( tempArr [ i ] ) NEW_LINE DEDENT elif ( tempArr [ i ] < tail [ 0 ] ) : NEW_LINE INDENT tail [ 0 ] = tempArr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT it = bisect_left ( tail , tempArr [ i ] ) NEW_LINE it = tempArr [ i ] NEW_LINE DEDENT DEDENT return len ( tail ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT firstArr = [ 3 , 5 , 1 , 8 ] NEW_LINE secondArr = [ 3 , 3 , 5 , 3 , 8 ] NEW_LINE print ( LCS ( firstArr , secondArr ) ) NEW_LINE DEDENT
Count non | Function to find the total count of triplets ( i , j , k ) such that i < j < k and ( j - i ) != ( k - j ) ; Stores indices of 0 s ; Stores indices of 1 s ; Stores indices of 2 s ; Traverse the array ; If current array element is 0 ; If current array element is 1 ; If current array element is 2 ; Total count of triplets ; Traverse the array zero_i [ ] ; Traverse the array one_i [ ] ; Stores index of 0 s ; Stores index of 1 s ; Stores third element of triplets that does not satisfy the condition ; If r present in the map ; Update r ; If r present in the map ; Update r ; If r present in the map and equidistant ; Print the obtained count ; Driver Code
def countTriplets ( arr , N ) : NEW_LINE INDENT zero_i = [ ] NEW_LINE one_i = [ ] NEW_LINE mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT zero_i . append ( i + 1 ) NEW_LINE DEDENT elif ( arr [ i ] == 1 ) : NEW_LINE INDENT one_i . append ( i + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT mp [ i + 1 ] = 1 NEW_LINE DEDENT DEDENT total = len ( zero_i ) * len ( one_i ) * len ( mp ) NEW_LINE for i in range ( len ( zero_i ) ) : NEW_LINE INDENT for j in range ( len ( one_i ) ) : NEW_LINE INDENT p = zero_i [ i ] NEW_LINE q = one_i [ j ] NEW_LINE r = 2 * p - q NEW_LINE if ( r in mp ) : NEW_LINE INDENT total -= 1 NEW_LINE DEDENT r = 2 * q - p NEW_LINE if ( r in mp ) : NEW_LINE INDENT total -= 1 NEW_LINE DEDENT r = ( p + q ) // 2 NEW_LINE if ( ( r in mp ) and abs ( r - p ) == abs ( r - q ) ) : NEW_LINE INDENT total -= 1 NEW_LINE DEDENT DEDENT DEDENT print ( total ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 1 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE countTriplets ( arr , N ) NEW_LINE DEDENT
Print prime factors of a given integer in decreasing order using Stack | Function to print prime factors of N in decreasing order ; Stores prime factors of N in decreasing order ; Insert i into stack ; Update N ; Update i ; Print value of stack st ; Driver Code ; function Call
def PrimeFactors ( N ) : NEW_LINE INDENT st = [ ] NEW_LINE i = 2 NEW_LINE while ( N != 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT st . append ( i ) NEW_LINE while ( N % i == 0 ) : NEW_LINE INDENT N = N // i NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT while ( len ( st ) != 0 ) : NEW_LINE INDENT print ( st [ - 1 ] ) NEW_LINE st . pop ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 8 NEW_LINE PrimeFactors ( N ) NEW_LINE DEDENT
Count subarrays consisting of first K natural numbers in descending order | Function to count subarray having the decreasing sequence K to 1 ; Traverse the array ; Check if required sequence is present or not ; Reset temp to k ; Return the count ; Driver Code ; Function Call
def CountSubarray ( arr , n , k ) : NEW_LINE INDENT temp = k NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == temp ) : NEW_LINE INDENT if ( temp == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE temp = k NEW_LINE DEDENT else : NEW_LINE INDENT temp -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT temp = k NEW_LINE if ( arr [ i ] == k ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 7 , 9 , 3 , 2 , 1 , 8 , 3 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( CountSubarray ( arr , N , K ) ) NEW_LINE DEDENT
Smallest number not less than N which is divisible by all digits of N | Python3 program for the above approach ; Function to calculate the LCM ; Function to find the smallest number satisfying given constraints ; LCM value is 1 initially ; Finding the LCM of all non zero digits ; Update the value lcm ; Stores ceil value ; Print the answer ; Driver Code ; Function Call
import math NEW_LINE def LCM ( A , B ) : NEW_LINE INDENT return ( A * B // math . gcd ( A , B ) ) NEW_LINE DEDENT def findSmallestNumber ( X ) : NEW_LINE INDENT lcm = 1 NEW_LINE temp = X NEW_LINE while ( temp ) : NEW_LINE INDENT last = temp % 10 NEW_LINE temp //= 10 NEW_LINE if ( not last ) : NEW_LINE INDENT continue NEW_LINE DEDENT lcm = LCM ( lcm , last ) NEW_LINE DEDENT answer = ( ( X + lcm - 1 ) // lcm ) * lcm NEW_LINE print ( answer ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 280 NEW_LINE findSmallestNumber ( X ) NEW_LINE DEDENT
Minimum sum of two integers whose product is strictly greater than N | Function to find the minimum sum of two integers such that their product is strictly greater than N ; Initialise low as 0 and high as 1e9 ; Iterate to find the first number ; Find the middle value ; If mid ^ 2 is greater than equal to A , then update high to mid ; Otherwise update low ; Store the first number ; Again , set low as 0 and high as 1e9 ; Iterate to find the second number ; Find the middle value ; If first number * mid is greater than N then update high to mid ; Else , update low to mid ; Store the second number ; Print the result ; Driver Code ; Function Call
def minSum ( N ) : NEW_LINE INDENT low = 0 NEW_LINE high = 1000000000 NEW_LINE while ( low + 1 < high ) : NEW_LINE INDENT mid = low + ( high - low ) / 2 NEW_LINE if ( mid * mid >= N ) : NEW_LINE INDENT high = mid NEW_LINE DEDENT else : NEW_LINE INDENT low = mid NEW_LINE DEDENT DEDENT first = high NEW_LINE low = 0 NEW_LINE high = 1000000000 NEW_LINE while ( low + 1 < high ) : NEW_LINE INDENT mid = low + ( high - low ) / 2 NEW_LINE if ( first * mid > N ) : NEW_LINE INDENT high = mid NEW_LINE DEDENT else : NEW_LINE INDENT low = mid NEW_LINE DEDENT DEDENT second = high NEW_LINE print ( round ( first + second ) ) NEW_LINE DEDENT N = 10 NEW_LINE minSum ( N ) NEW_LINE
Minimum sum of two integers whose product is strictly greater than N | Python3 program for the above approach ; Function to find the minimum sum of two integers such that their product is strictly greater than N ; Store the answer using the AP - GP inequality ; Print the result ; Driver Code ; Function Call
import math NEW_LINE def minSum ( N ) : NEW_LINE INDENT ans = math . ceil ( 2 * math . sqrt ( N + 1 ) ) NEW_LINE print ( math . trunc ( ans ) ) NEW_LINE DEDENT N = 10 NEW_LINE minSum ( N ) NEW_LINE
Query to find length of the longest subarray consisting only of 1 s | Python 3 Program for the above approach ; Arrays to store prefix sums , suffix and MAX 's node respectively ; Function to construct Segment Tree ; MAX array for node MAX ; Array for prefix sum node ; Array for suffix sum node ; Calculate MAX node ; Function to update Segment Tree ; Update at position ; Update sums from bottom to the top of Segment Tree ; Update MAX tree ; Update pref tree ; Update suf tree ; Function to perform given queries ; Stores count of queries ; Traverse each query ; Print longest length of subarray in [ 1 , N ] ; Flip the character ; Driver Code ; Size of array ; Given array ; Given queries ; Number of queries
INF = 1000000 NEW_LINE pref = [ 0 for i in range ( 500005 ) ] NEW_LINE suf = [ 0 for i in range ( 500005 ) ] NEW_LINE MAX = [ 0 for i in range ( 500005 ) ] NEW_LINE def build ( a , tl , tr , v ) : NEW_LINE INDENT global MAX NEW_LINE global pref NEW_LINE global suf NEW_LINE if ( tl == tr ) : NEW_LINE INDENT MAX [ v ] = a [ tl ] NEW_LINE pref [ v ] = a [ tl ] NEW_LINE suf [ v ] = a [ tl ] NEW_LINE DEDENT else : NEW_LINE INDENT tm = ( tl + tr ) // 2 NEW_LINE build ( a , tl , tm , v * 2 ) NEW_LINE build ( a , tm + 1 , tr , v * 2 + 1 ) NEW_LINE MAX [ v ] = max ( MAX [ v * 2 ] , max ( MAX [ v * 2 + 1 ] , suf [ v * 2 ] + pref [ v * 2 + 1 ] ) ) NEW_LINE pref [ v ] = max ( pref [ v * 2 ] , pref [ 2 * v ] + ( pref [ 2 * v ] == tm - tl + 1 ) * pref [ v * 2 + 1 ] ) NEW_LINE suf [ v ] = max ( suf [ v * 2 + 1 ] , suf [ 2 * v + 1 ] + suf [ v * 2 ] * ( suf [ 2 * v + 1 ] == tr - tm ) ) NEW_LINE DEDENT DEDENT def update ( a , pos , tl , tr , v ) : NEW_LINE INDENT global pref NEW_LINE global suf NEW_LINE global MAX NEW_LINE if ( tl > pos or tr < pos ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( tl == tr and tl == pos ) : NEW_LINE INDENT MAX [ v ] = a [ pos ] NEW_LINE pref [ v ] = a [ pos ] NEW_LINE suf [ v ] = a [ pos ] NEW_LINE DEDENT else : NEW_LINE INDENT tm = ( tl + tr ) // 2 NEW_LINE update ( a , pos , tl , tm , v * 2 ) NEW_LINE update ( a , pos , tm + 1 , tr , v * 2 + 1 ) NEW_LINE MAX [ v ] = max ( MAX [ v * 2 ] , max ( MAX [ v * 2 + 1 ] , suf [ v * 2 ] + pref [ v * 2 + 1 ] ) ) NEW_LINE pref [ v ] = max ( pref [ v * 2 ] , pref [ 2 * v ] + ( pref [ 2 * v ] == tm - tl + 1 ) * pref [ v * 2 + 1 ] ) NEW_LINE suf [ v ] = max ( suf [ v * 2 + 1 ] , suf [ 2 * v + 1 ] + ( suf [ 2 * v + 1 ] == tr - tm ) * suf [ v * 2 ] ) NEW_LINE DEDENT DEDENT def solveQueries ( arr , n , Q , k ) : NEW_LINE INDENT global MAX NEW_LINE cntQuery = len ( Q ) NEW_LINE build ( arr , 0 , n - 1 , 1 ) NEW_LINE for i in range ( cntQuery ) : NEW_LINE INDENT if ( Q [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT print ( MAX [ 1 ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT arr [ Q [ i ] [ 1 ] - 1 ] ^= 1 NEW_LINE update ( arr , Q [ i ] [ 1 ] - 1 , 0 , n - 1 , 1 ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE arr = [ 1 , 1 , 0 , 1 , 1 , 1 , 0 , 0 , 1 , 1 ] NEW_LINE Q = [ [ 1 ] , [ 2 , 3 ] , [ 1 ] ] NEW_LINE K = 3 NEW_LINE solveQueries ( arr , N , Q , K ) NEW_LINE DEDENT
Find the array element having maximum frequency of the digit K | Function to find the count of digits , k in the given number n ; Stores count of occurrence of digit K in N ; Iterate over digits of N ; If current digit is k ; Update count ; Update N ; Utility function to find an array element having maximum frequency of digit k ; Stores frequency of digit K in arr [ i ] ; Stores maximum frequency of digit K in the array ; Stores an array element having maximum frequency of digit k ; Traverse the array ; Count the frequency of digit k in arr [ i ] ; Update max with maximum frequency found so far ; Update ele ; If there is no array element having digit k in it ; Function to find an array element having maximum frequency of digit k ; Stores an array element having maximum frequency of digit k ; If there is no element found having digit k in it ; Print element having max frequency of digit k ; Driver Code ; The digit whose max occurrence has to be found ; Given array ; Size of array ; Function Call
def countFreq ( N , K ) : NEW_LINE INDENT count = 0 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N % 10 == K ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT N = N // 10 NEW_LINE DEDENT return count NEW_LINE DEDENT def findElementUtil ( arr , N , K ) : NEW_LINE INDENT c = 0 NEW_LINE max = 0 NEW_LINE ele = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT c = countFreq ( arr [ i ] , K ) NEW_LINE if ( c > max ) : NEW_LINE INDENT max = c NEW_LINE ele = arr [ i ] NEW_LINE DEDENT DEDENT if ( max == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ele NEW_LINE DEDENT DEDENT def findElement ( arr , N , K ) : NEW_LINE INDENT ele = findElementUtil ( arr , N , K ) NEW_LINE if ( ele == - 1 ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ele ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 3 NEW_LINE arr = [ 3 , 77 , 343 , 456 ] NEW_LINE N = len ( arr ) NEW_LINE findElement ( arr , K , N ) NEW_LINE DEDENT
Minimum removals required to make any interval equal to the union of the given Set | Function to count minimum number of removals required to make an interval equal to the union of the given Set ; Stores the minimum number of removals ; Traverse the Set ; Left Boundary ; Right Boundary ; Stores count of intervals lying within current interval ; Traverse over all remaining intervals ; Check if interval lies within the current interval ; Increase count ; Update minimum removals required ; Driver Code ; Returns the minimum removals
def findMinDeletions ( v , n ) : NEW_LINE INDENT minDel = 10 ** 18 NEW_LINE for i in range ( n ) : NEW_LINE INDENT L = v [ i ] [ 0 ] NEW_LINE R = v [ i ] [ 1 ] NEW_LINE Count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( v [ j ] [ 1 ] >= L and v [ j ] [ 0 ] <= R ) : NEW_LINE INDENT Count += 1 NEW_LINE DEDENT DEDENT minDel = min ( minDel , n - Count ) NEW_LINE DEDENT return minDel NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT v = [ ] NEW_LINE v . append ( [ 1 , 3 ] ) NEW_LINE v . append ( [ 4 , 12 ] ) NEW_LINE v . append ( [ 5 , 8 ] ) NEW_LINE v . append ( [ 13 , 2 ] ) NEW_LINE N = len ( v ) NEW_LINE print ( findMinDeletions ( v , N ) ) NEW_LINE DEDENT
Maximum even numbers present in any subarray of size K | Function to find the maximum count of even numbers from all the subarrays of size M ; Stores the count of even numbers in a subarray of size M ; Calculate the count of even numbers in the current subarray ; If current element is an even number ; Stores the maximum count of even numbers from all the subarrays of size M ; Traverse remaining subarrays of size M using sliding window technique ; If the first element of the subarray is even ; update curr ; If i - th element is even increment the count ; update the answer ; Return answer ; Driver Code ; Size of the input array ; Function call
def maxEvenIntegers ( arr , N , M ) : NEW_LINE INDENT curr = 0 NEW_LINE for i in range ( 0 , M ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT curr += 1 NEW_LINE DEDENT DEDENT ans = curr NEW_LINE for i in range ( M , N ) : NEW_LINE INDENT if ( arr [ i - M ] % 2 == 0 ) : NEW_LINE INDENT curr -= 1 NEW_LINE DEDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT curr += 1 NEW_LINE ans = max ( curr , ans ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 4 , 7 , 6 ] NEW_LINE M = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( maxEvenIntegers ( arr , N , M ) ) NEW_LINE DEDENT
Count numbers up to N having digit D in its octal representation | Function to count the numbers in given range whose octal representation contains atleast digit , d ; Store count of numbers up to n whose octal representation contains digit d ; Iterate over the range [ 1 , n ] ; Calculate digit of i in octal representation ; Check if octal representation of x contains digit d ; Update total ; Update x ; Prthe answer ; Driver Code ; Given N and D ; Counts and prints numbers up to N having D as a digit in its octal representation
def countNumbers ( n , d ) : NEW_LINE INDENT total = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT x = i NEW_LINE while ( x > 0 ) : NEW_LINE INDENT if ( x % 8 == d ) : NEW_LINE INDENT total += 1 NEW_LINE break NEW_LINE DEDENT x = x // 8 NEW_LINE DEDENT DEDENT print ( total ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n , d = 20 , 7 NEW_LINE countNumbers ( n , d ) NEW_LINE DEDENT
Maximize length of longest subarray consisting of same elements by at most K decrements | Python3 program to implement the above approach ; Function to construct Segment Tree to return the minimum element in a range ; If leaf nodes of the tree are found ; Update the value in segment tree from given array ; Divide left and right subtree ; Stores smallest element in subarray : arr [ start ] , arr [ mid ] ; Stores smallest element in subarray : arr [ mid + 1 ] , arr [ end ] ; Stores smallest element in subarray : arr [ start ] , arr [ end ] ; Function to find the smallest element present in a subarray ; If elements of the subarray are not in the range [ l , r ] ; If all the elements of the subarray are in the range [ l , r ] ; Divide tree into left and right subtree ; Stores smallest element in left subtree ; Stores smallest element in right subtree ; Function that find length of longest subarray with all equal elements in atmost K decrements ; Stores length of longest subarray with all equal elements in atmost K decrements . ; Store the prefix sum array ; Calculate the prefix sum array ; Build the segment tree for range min query ; Traverse the array ; Stores start index of the subarray ; Stores end index of the subarray ; Stores end index of the longest subarray ; Performing the binary search to find the endpoint for the selected range ; Find the mid for binary search ; Find the smallest element in range [ i , mid ] using Segment Tree ; Stores total sum of subarray after K decrements ; Stores sum of elements of subarray before K decrements ; If subarray found with all equal elements ; Update start ; Update max_index ; If false , it means that the selected range is invalid ; Update end ; Store the length of longest subarray ; Return result ; Driver Code
import sys NEW_LINE def build ( tree , A , start , end , node ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT tree [ node ] = A [ start ] NEW_LINE return tree [ node ] NEW_LINE DEDENT mid = ( int ) ( ( start + end ) / 2 ) NEW_LINE X = build ( tree , A , start , mid , 2 * node + 1 ) NEW_LINE Y = build ( tree , A , mid + 1 , end , 2 * node + 2 ) NEW_LINE return ( tree [ node ] == min ( X , Y ) ) NEW_LINE DEDENT def query ( tree , start , end , l , r , node ) : NEW_LINE INDENT if ( start > r or end < l ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT if ( start >= l and end <= r ) : NEW_LINE INDENT return tree [ node ] NEW_LINE DEDENT mid = ( int ) ( ( start + end ) / 2 ) NEW_LINE X = query ( tree , start , mid , l , r , 2 * node + 1 ) NEW_LINE Y = query ( tree , mid + 1 , end , l , r , 2 * node + 2 ) NEW_LINE return min ( X , Y ) NEW_LINE DEDENT def longestSubArray ( A , N , K ) : NEW_LINE INDENT res = 1 NEW_LINE preSum = [ 0 ] * ( N + 1 ) NEW_LINE preSum [ 0 ] = A [ 0 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT preSum [ i + 1 ] = preSum [ i ] + A [ i ] NEW_LINE DEDENT tree = [ 0 ] * ( 4 * N + 5 ) NEW_LINE build ( tree , A , 0 , N - 1 , 0 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT start = i NEW_LINE end = N - 1 NEW_LINE max_index = i NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( int ) ( ( start + end ) / 2 ) NEW_LINE min_element = query ( tree , 0 , N - 1 , i , mid , 0 ) NEW_LINE expected_sum = ( mid - i + 1 ) * min_element NEW_LINE actual_sum = preSum [ mid + 1 ] - preSum [ i ] NEW_LINE if ( actual_sum - expected_sum <= K ) : NEW_LINE INDENT start = mid + 1 NEW_LINE max_index = max ( max_index , mid ) NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT res = max ( res , max_index - i + 2 ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 1 , 7 , 3 , 4 , 5 , 6 ] NEW_LINE k = 6 NEW_LINE n = 6 NEW_LINE print ( longestSubArray ( arr , n , k ) ) NEW_LINE
Count number of triplets ( a , b , c ) from first N natural numbers such that a * b + c = N | Function to find the count of triplets ( a , b , c ) with a * b + c = N ; Stores count of triplets of 1 st N natural numbers which are of the form a * b + c = N ; Iterate over the range [ 1 , N ] ; If N is divisible by i ; Update cntTriplet ; Update cntTriplet ; Driver code
def findCntTriplet ( N ) : NEW_LINE INDENT cntTriplet = 0 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( N % i != 0 ) : NEW_LINE INDENT cntTriplet += N // i ; NEW_LINE DEDENT else : NEW_LINE INDENT cntTriplet += ( N // i ) - 1 ; NEW_LINE DEDENT DEDENT return cntTriplet ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 ; NEW_LINE print ( findCntTriplet ( N ) ) ; NEW_LINE DEDENT
Count divisors which generates same Quotient and Remainder | Python3 program of the above approach ; Function to calculate the count of numbers such that it gives same quotient and remainder ; Stores divisor of number N . ; Iterate through numbers from 2 to sqrt ( N ) and store divisors of N ; As N is also divisor of itself ; Iterate through divisors ; Checking whether x satisfies the required condition ; Print the count ; Driver Code ; Given N ; Function Call
from math import floor , sqrt NEW_LINE def countDivisors ( n ) : NEW_LINE INDENT count = 0 NEW_LINE divisor = [ ] NEW_LINE for i in range ( 2 , floor ( sqrt ( n ) ) ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n // i == i ) : NEW_LINE INDENT divisor . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT divisor . append ( i ) NEW_LINE divisor . append ( n // i ) NEW_LINE DEDENT DEDENT DEDENT divisor . append ( n ) NEW_LINE for x in divisor : NEW_LINE INDENT x -= 1 NEW_LINE if ( ( n // x ) == ( n % x ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 1000000000000 NEW_LINE countDivisors ( N ) NEW_LINE DEDENT
Smallest indexed array element required to be flipped to make sum of array equal to 0 | Function to find the smallest indexed array element required to be flipped to make sum of the given array equal to 0 ; Stores the required index ; Traverse the given array ; Flip the sign of current element ; Stores the sum of array elements ; Find the sum of the array ; Update sum ; If sum is equal to 0 ; Update pos ; Reset the current element to its original value ; Reset the value of arr [ i ] ; Driver Code
def smallestIndexArrayElementsFlip ( arr , N ) : NEW_LINE INDENT pos = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT arr [ i ] *= - 1 NEW_LINE sum = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT sum += arr [ j ] NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT pos = i NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] *= - 1 NEW_LINE DEDENT DEDENT return pos NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , - 5 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( smallestIndexArrayElementsFlip ( arr , N ) ) NEW_LINE DEDENT
Smallest indexed array element required to be flipped to make sum of array equal to 0 | Function to find the smallest indexed array element required to be flipped to make sum of the given array equal to 0 ; Stores the required index ; Stores the sum of the array ; Traverse the given array ; Update ArrSum ; Traverse the given array ; If sum of array elements double the value of the current element ; Update pos ; Driver Code
def smallestIndexArrayElementsFlip ( arr , N ) : NEW_LINE INDENT pos = - 1 NEW_LINE ArrSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT ArrSum += arr [ i ] NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( 2 * arr [ i ] == ArrSum ) : NEW_LINE INDENT pos = i NEW_LINE break NEW_LINE DEDENT DEDENT return pos NEW_LINE DEDENT arr = [ 1 , 3 , - 5 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( smallestIndexArrayElementsFlip ( arr , N ) ) NEW_LINE
Check if a string can be converted to another given string by removal of a substring | Function to check if S can be converted to T by removing at most one substring from S ; Check if S can be converted to T by removing at most one substring from S ; Stores length of string T ; Stores length of string S ; Iterate over the range [ 0 , M - 1 ] ; Stores Length of the substring S [ 0 ] , ... , S [ i ] ; Stores Length of the substring S [ 0 ] , ... , S [ i ] ; Stores prefix substring ; Stores suffix substring ; Checking if prefix + suffix == T ; Given String S and T ; Function call
def make_string_S_to_T ( S , T ) : NEW_LINE INDENT possible = False NEW_LINE M = len ( T ) NEW_LINE N = len ( S ) NEW_LINE for i in range ( 0 , M + 1 ) : NEW_LINE INDENT prefix_length = i NEW_LINE suffix_length = M - i NEW_LINE prefix = S [ : prefix_length ] NEW_LINE suffix = S [ N - suffix_length : N ] NEW_LINE if ( prefix + suffix == T ) : NEW_LINE INDENT possible = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( possible ) : NEW_LINE INDENT return " YES " NEW_LINE DEDENT else : NEW_LINE INDENT return " NO " NEW_LINE DEDENT DEDENT S = " ababcdcd " NEW_LINE T = " abcd " NEW_LINE print ( make_string_S_to_T ( S , T ) ) NEW_LINE
Sum of maximum of all subarrays by adding even frequent maximum twice | Function to calculate sum of maximum of all subarrays ; Stores the sum of maximums ; Traverse the array ; Store the frequency of the maximum element in subarray ; Finding maximum ; Increment frequency by 1 ; If new maximum is obtained ; If frequency of maximum is even , then add 2 * maxNumber . Otherwise , add maxNumber ; Print the sum obtained ; Driver Code ; Function Call
def findSum ( a ) : NEW_LINE INDENT ans = 0 NEW_LINE for low in range ( 0 , len ( a ) ) : NEW_LINE INDENT for high in range ( low , len ( a ) ) : NEW_LINE count = 0 NEW_LINE maxNumber = 0 NEW_LINE for i in range ( low , high + 1 ) : NEW_LINE INDENT if ( a [ i ] == maxNumber ) : NEW_LINE count += 1 NEW_LINE elif ( a [ i ] > maxNumber ) : NEW_LINE maxNumber = a [ i ] NEW_LINE count = 1 NEW_LINE DEDENT if count % 2 : NEW_LINE INDENT ans += maxNumber NEW_LINE DEDENT else : NEW_LINE INDENT ans += maxNumber * 2 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 2 , 1 , 4 , 4 , 2 ] NEW_LINE findSum ( arr ) NEW_LINE
Count pairs of indices having equal prefix and suffix sums | Function to find the count of index pairs having equal prefix and suffix sums ; Maps indices with prefix sums ; Traverse the array ; Update prefix sum ; Update frequency in Map ; Traverse the array in reverse ; Update suffix sum ; Check if any prefix sum of equal value exists or not ; Print the obtained count ; Driver code ; Given array ; Given size ; Function Call
def countPairs ( arr , n ) : NEW_LINE INDENT mp1 = { } NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE mp1 [ sum ] = mp1 . get ( sum , 0 ) + 1 NEW_LINE DEDENT sum = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE if ( sum in mp1 ) : NEW_LINE INDENT ans += mp1 [ sum ] NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE countPairs ( arr , n ) NEW_LINE DEDENT
Queries to count Composite Magic Numbers from a given range [ L , R ] | Check if a number is magic number or not ; Check number is composite number or not ; Corner cases ; Check if the number is a multiple of 2 or 3 ; Check for multiples of remaining primes ; Function to find Composite Magic Numbers in given ranges ; dp [ i ] : Stores the count of composite Magic numbers up to i ; Traverse in the range [ 1 , 1e5 ) ; Check if number is Composite number as well as a Magic number or not ; Print results for each query ; Driver Code
def isMagic ( num ) : NEW_LINE INDENT return ( num % 9 == 1 ) NEW_LINE DEDENT def isComposite ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 5 , n + 1 , 6 ) : NEW_LINE INDENT if i * i > n + 1 : NEW_LINE INDENT break NEW_LINE DEDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def find ( L , R , q ) : NEW_LINE INDENT dp = [ 0 ] * 1000005 NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = 0 NEW_LINE for i in range ( 1 , 1000005 ) : NEW_LINE INDENT if ( isComposite ( i ) and isMagic ( i ) ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] NEW_LINE DEDENT DEDENT for i in range ( q ) : NEW_LINE INDENT print ( dp [ R [ i ] ] - dp [ L [ i ] - 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = [ 10 , 3 ] NEW_LINE R = [ 100 , 2279 ] NEW_LINE Q = 2 NEW_LINE find ( L , R , Q ) NEW_LINE DEDENT
Smallest positive integer that divides all array elements to generate quotients with sum not exceeding K | Function to find the smallest positive integer that divides array elements to get the sum <= K ; Stores minimum possible of the smallest positive integer satisfying the condition ; Stores maximum possible of the smallest positive integer satisfying the condition ; Apply binary search over the range [ left , right ] ; Stores middle element of left and right ; Stores sum of array elements ; Traverse the array ; Update sum ; If sum is greater than K ; Update left ; Update right ; Driver Code
def findSmallestInteger ( arr , N , K ) : NEW_LINE INDENT left = 1 NEW_LINE right = max ( arr ) NEW_LINE while ( left < right ) : NEW_LINE INDENT mid = ( left + right ) // 2 NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += ( arr [ i ] + mid - 1 ) // mid NEW_LINE DEDENT if ( sum > K ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid NEW_LINE DEDENT DEDENT return left NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE K = 6 NEW_LINE print ( findSmallestInteger ( arr , N , K ) ) NEW_LINE DEDENT
Minimum Deci | Function to find the count of minimum Deci - Binary numbers required to obtain S ; Stores the minimum count ; Iterate over the string s ; Convert the char to its equivalent integer ; If current character is the maximum so far ; Update the maximum digit ; Prthe required result ; Driver Code
def minimum_deci_binary_number ( s ) : NEW_LINE INDENT m = - 10 ** 19 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT temp = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE if ( temp > m ) : NEW_LINE INDENT m = temp NEW_LINE DEDENT DEDENT return m NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "31" NEW_LINE print ( minimum_deci_binary_number ( S ) ) NEW_LINE DEDENT
Make all the elements of array odd by incrementing odd | Function to count minimum subarrays whose odd - indexed elements need to be incremented to make array odd ; Stores the minimum number of operations required ; Iterate over even - indices ; Check if the current element is odd ; If true , continue ; Otherwise , mark the starting of the subarray and iterate until i < n and arr [ i ] is even ; Increment number of operations ; Iterate over odd indexed positions of arr [ ] ; Check if the current element is odd ; If true , continue ; Otherwise , mark the starting of the subarray and iterate until i < n and arr [ i ] is even ; Increment the number of operations ; Print the number of operations ; Driver Code ; Function Call
def minOperations ( arr , n ) : NEW_LINE INDENT flips = 0 ; NEW_LINE i = 0 ; NEW_LINE while i < n : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT i += 2 ; NEW_LINE continue ; NEW_LINE DEDENT while ( i < n and arr [ i ] % 2 == 0 ) : NEW_LINE INDENT i += 2 ; NEW_LINE DEDENT flips += 1 ; NEW_LINE i += 2 ; NEW_LINE DEDENT i = 1 NEW_LINE while i < n : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT i += 2 ; NEW_LINE continue ; NEW_LINE DEDENT while ( i < n and arr [ i ] % 2 == 0 ) : NEW_LINE INDENT i += 2 ; NEW_LINE DEDENT flips += 1 ; NEW_LINE i += 2 ; NEW_LINE DEDENT print ( flips ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 3 , 5 , 3 , 2 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE minOperations ( arr , N ) ; NEW_LINE DEDENT
Minimum substring reversals required to make given Binary String alternating | Function to count the minimum number of substrings required to be reversed to make the string S alternating ; Store count of consecutive pairs ; Stores the count of 1 s and 0 s ; Traverse through the string ; Increment 1 s count ; Increment 0 s count ; Increment K if consecutive same elements are found ; Increment 1 s count ; else : Increment 0 s count ; Check if it is possible or not ; Otherwise , print the number of required operations ; Driver code ; Function Call
def minimumReverse ( s , n ) : NEW_LINE INDENT k = 0 ; NEW_LINE l = 0 ; NEW_LINE sum1 = 0 ; NEW_LINE sum0 = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT sum1 += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT sum0 += 1 ; NEW_LINE DEDENT if ( s [ i ] == s [ i - 1 ] and s [ i ] == '0' ) : NEW_LINE INDENT k += 1 ; NEW_LINE DEDENT elif ( s [ i ] == s [ i - 1 ] and s [ i ] == '1' ) : NEW_LINE INDENT l += 1 ; NEW_LINE DEDENT DEDENT if ( s [ 0 ] == '1' ) : NEW_LINE INDENT sum1 += 1 ; NEW_LINE sum0 += 1 ; NEW_LINE DEDENT if ( abs ( sum1 - sum0 ) > 1 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return max ( k , l ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "10001" ; NEW_LINE N = len ( S ) ; NEW_LINE print ( minimumReverse ( S , N ) ) ; NEW_LINE DEDENT
Count pairs with Even Product from two given arrays | Function to count pairs ( arr [ i ] , brr [ j ] ) whose product is an even number ; Stores count of odd numbers in arr [ ] ; Stores count of odd numbers in brr [ ] ; Traverse the array , arr [ ] ; If arr [ i ] is an odd number ; Update cntOddArr ; Traverse the array , brr [ ] ; If brr [ i ] is an odd number ; Update cntOddArr ; Return pairs whose product is an even number ; Driver Code
def cntPairsInTwoArray ( arr , brr , N , M ) : NEW_LINE INDENT cntOddArr = 0 NEW_LINE cntOddBrr = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT cntOddArr += 1 NEW_LINE DEDENT DEDENT for i in range ( M ) : NEW_LINE INDENT if ( brr [ i ] & 1 ) : NEW_LINE INDENT cntOddBrr += 1 NEW_LINE DEDENT DEDENT return ( N * M ) - ( cntOddArr * cntOddBrr ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE brr = [ 1 , 2 ] NEW_LINE M = len ( brr ) NEW_LINE print ( cntPairsInTwoArray ( arr , brr , N , M ) ) NEW_LINE DEDENT
Maximize count of persons receiving a chocolate | Python3 program for the above approach ; Function to count the maximum number of persons receiving a chocolate ; Initialize count as 0 ; Sort the given arrays ; Initialize a multiset ; Insert B [ ] array values into the multiset ; Traverse elements in array A [ ] ; Search for the lowest value in B [ ] ; If found , increment count , and delete from set ; Return the number of people ; Driver Code ; Function Call
from bisect import bisect_left NEW_LINE def countMaxPersons ( A , n , B , m , x ) : NEW_LINE INDENT count = 0 NEW_LINE A = sorted ( A ) NEW_LINE B = sorted ( B ) NEW_LINE s = [ ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT s . append ( B [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT val = A [ i ] - x NEW_LINE it = bisect_left ( s , val ) NEW_LINE if ( it != len ( s ) and it <= A [ i ] + x ) : NEW_LINE INDENT count += 1 NEW_LINE del s [ it ] NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 90 , 49 , 20 , 39 , 49 ] NEW_LINE B = [ 14 , 24 , 82 ] NEW_LINE X = 15 NEW_LINE N = len ( A ) NEW_LINE M = len ( B ) NEW_LINE print ( countMaxPersons ( A , N , B , M , X ) ) NEW_LINE DEDENT
Maximize frequency of an element by at most one increment or decrement of all array elements | Function to maximize the frequency of an array element by incrementing or decrementing array elements at most once ; Stores the largest array element ; Stores the smallest array element ; freq [ i ] : Stores frequency of ( i + Min ) in the array ; Traverse the array ; Update frequency of arr [ i ] ; Stores maximum frequency of an array element by incrementing or decrementing array elements ; Iterate all the numbers over the range [ Min , Max ] ; Stores sum of three consecutive numbers ; Update maxSum ; Print maxSum ; Driver Code ; Function call
def max_freq ( arr , N ) : NEW_LINE INDENT Max = max ( arr ) NEW_LINE Min = min ( arr ) NEW_LINE freq = [ 0 ] * ( Max - Min + 1 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ arr [ i ] - Min ] += 1 NEW_LINE DEDENT maxSum = 0 NEW_LINE for i in range ( Max - Min - 1 ) : NEW_LINE INDENT val = freq [ i ] + freq [ i + 1 ] + freq [ i + 2 ] NEW_LINE maxSum = max ( maxSum , val ) NEW_LINE DEDENT print ( maxSum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 1 , 4 , 1 , 5 , 9 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE max_freq ( arr , N ) NEW_LINE DEDENT
Longest increasing subsequence consisting of elements from indices divisible by previously selected indices | Function to find length of longest subsequence generated that satisfies the specified conditions ; Stores the length of longest subsequences of all lengths ; Iterate through the given array ; Iterate through the multiples i ; Update dp [ j ] as maximum of dp [ j ] and dp [ i ] + 1 ; Return the maximum element in dp [ ] as the length of longest subsequence ; Driver Code ; Function Call
def findMaxLength ( N , arr ) : NEW_LINE INDENT dp = [ 1 ] * ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 2 * i , N + 1 , i ) : NEW_LINE INDENT if ( arr [ i - 1 ] < arr [ j - 1 ] ) : NEW_LINE INDENT dp [ j ] = max ( dp [ j ] , dp [ i ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT return max ( dp ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findMaxLength ( N , arr ) ) NEW_LINE DEDENT
Queries to check if any pair exists in an array having values at most equal to the given pair | Function that performs binary search to find value less than or equal to first value of the pair ; Perform binary search ; Find the mid ; Update the high ; Else update low ; Return the low index ; Function to modify the second value of each pair ; start from index 1 ; Function to evaluate each query ; Find value less than or equal to the first value of pair ; check if we got the required pair or not ; Function to find a pair whose values is less than the given pairs in query ; Find the size of the vector ; sort the vector based on the first value ; Function Call to modify the second value of each pair ; Traverse each queries ; Evaluate each query ; Print the result ; Driver Code ; Function Call
def binary_search ( vec , n , a ) : NEW_LINE INDENT low , high , mid = 0 , 0 , 0 NEW_LINE low = 0 NEW_LINE high = n - 1 NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = low + ( high - low + 1 ) // 2 NEW_LINE if ( vec [ mid ] [ 0 ] > a ) : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT elif vec [ mid ] [ 0 ] <= a : NEW_LINE INDENT low = mid NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT def modify_vec ( v , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT v [ i ] [ 1 ] = min ( v [ i ] [ 1 ] , v [ i - 1 ] [ 1 ] ) NEW_LINE DEDENT return v NEW_LINE DEDENT def evaluate_query ( v , n , m1 , m2 ) : NEW_LINE INDENT temp = binary_search ( v , n , m1 ) NEW_LINE if ( ( v [ temp ] [ 0 ] <= m1 ) and ( v [ temp ] [ 1 ] <= m2 ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def checkPairs ( v , queries ) : NEW_LINE INDENT n = len ( v ) NEW_LINE v = sorted ( v ) NEW_LINE v = modify_vec ( v , n ) NEW_LINE k = len ( queries ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT m1 = queries [ i ] [ 0 ] NEW_LINE m2 = queries [ i ] [ 1 ] NEW_LINE result = evaluate_query ( v , n , m1 , m2 ) NEW_LINE if ( result > 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 3 , 5 ] , [ 2 , 7 ] , [ 2 , 3 ] , [ 4 , 9 ] ] NEW_LINE queries = [ [ 3 , 4 ] , [ 3 , 2 ] , [ 4 , 1 ] , [ 3 , 7 ] ] NEW_LINE checkPairs ( arr , queries ) NEW_LINE DEDENT
Sort a stream of integers | Function to sort a stream of integers ; Stores the position of array elements ; Traverse through the array ; If any element is found to be greater than the current element ; If an element > num is not present ; Otherwise , place the number at its right position ; Function to print the sorted stream of integers ; Stores the sorted stream of integers ; Traverse the array ; Function Call ; Print the array after every insertion ; Driver Code
def Sort ( ans , num ) : NEW_LINE INDENT pos = - 1 ; NEW_LINE for i in range ( len ( ans ) ) : NEW_LINE INDENT if ( ans [ i ] >= num ) : NEW_LINE INDENT pos = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( pos == - 1 ) : NEW_LINE INDENT ans . append ( num ) ; NEW_LINE DEDENT else : NEW_LINE INDENT ans . insert ( pos , num ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def sortStream ( arr , N ) : NEW_LINE INDENT ans = list ( ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT ans = Sort ( ans , arr [ i ] ) ; NEW_LINE for j in range ( len ( ans ) ) : NEW_LINE INDENT print ( ans [ j ] , end = " ▁ " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 1 , 7 , 6 , 2 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE sortStream ( arr , N ) ; NEW_LINE DEDENT
Count ways to split array into two equal sum subarrays by changing sign of any one array element | Function to count ways of spliting the array in two subarrays of equal sum by changing sign of any 1 element ; Stores the count of elements in prefix and suffix of array ; Stores the total sum of array ; Traverse the array ; Increase the frequency of current element in suffix ; Stores prefix sum upto an index ; Stores sum of suffix from an index ; Stores the count of ways to split the array in 2 subarrays having equal sum ; Traverse the array ; Modify prefix sum ; Add arr [ i ] to prefix Map ; Calculate suffix sum by subtracting prefix sum from total sum of elements ; Remove arr [ i ] from suffix Map ; Store the difference between the subarrays ; Check if diff is even or not ; Count number of ways to split array at index i such that subarray sums are same ; Update the count ; Return the count ; Driver Code ; Function Call
def countSubArraySignChange ( arr , N ) : NEW_LINE INDENT prefixCount = { } NEW_LINE suffixCount = { } NEW_LINE total = 0 NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT total += arr [ i ] NEW_LINE suffixCount [ arr [ i ] ] = suffixCount . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT prefixSum = 0 NEW_LINE suffixSum = 0 NEW_LINE count = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT prefixSum += arr [ i ] NEW_LINE prefixCount [ arr [ i ] ] = prefixCount . get ( arr [ i ] , 0 ) + 1 NEW_LINE suffixSum = total - prefixSum NEW_LINE suffixCount [ arr [ i ] ] -= 1 NEW_LINE diff = prefixSum - suffixSum NEW_LINE if ( diff % 2 == 0 ) : NEW_LINE INDENT y , z = 0 , 0 NEW_LINE if - diff // 2 in suffixCount : NEW_LINE INDENT y = suffixCount [ - dff // 2 ] NEW_LINE DEDENT if diff // 2 in prefixCount : NEW_LINE INDENT z = prefixCount NEW_LINE DEDENT x = z + y NEW_LINE count = count + x NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 2 , - 3 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countSubArraySignChange ( arr , N ) ) NEW_LINE DEDENT
Partition string into two substrings having maximum number of common non | Function to count maximum common non - repeating characters that can be obtained by partitioning the string into two non - empty substrings ; Stores count of non - repeating characters present in both the substrings ; Stores distinct characters in left substring ; Stores distinct characters in right substring ; Traverse left substring ; Insert S [ i ] into ls ; Traverse right substring ; Insert S [ i ] into rs ; Traverse distinct characters of left substring ; If current character is present in right substring ; Update cnt ; Return count ; Function to partition the string into two non - empty substrings in all possible ways ; Stores maximum common distinct characters present in both the substring partitions ; Traverse the string ; Update ans ; Print count of maximum common non - repeating characters ; Driver Code
def countCommonChar ( ind , S ) : NEW_LINE INDENT cnt = 0 NEW_LINE ls = set ( ) NEW_LINE rs = set ( ) NEW_LINE for i in range ( ind ) : NEW_LINE INDENT ls . add ( S [ i ] ) NEW_LINE DEDENT for i in range ( ind , len ( S ) ) : NEW_LINE INDENT rs . add ( S [ i ] ) NEW_LINE DEDENT for v in ls : NEW_LINE INDENT if v in rs : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT def partitionStringWithMaxCom ( S ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , len ( S ) ) : NEW_LINE INDENT ans = max ( ans , countCommonChar ( i , S ) ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " aabbca " NEW_LINE partitionStringWithMaxCom ( string ) NEW_LINE DEDENT
Longest Substring of 1 's after removing one character | Function to calculate the length of the longest substring of '1' s that can be obtained by deleting one character ; Add '0' at the end ; Iterator to traverse the string ; Stores maximum length of required substring ; Stores length of substring of '1' preceding the current character ; Stores length of substring of '1' succeeding the current character ; Counts number of '0' s ; Traverse the string S ; If current character is '1 ; Increase curr_one by one ; Otherwise ; Increment numberofZeros by one ; Count length of substring obtained y concatenating preceding and succeeding substrings of '1 ; Store maximum size in res ; Assign curr_one to prev_one ; Reset curr_one ; If string contains only one '0 ; Return the answer ; Driver Code
def longestSubarray ( s ) : NEW_LINE INDENT s += '0' NEW_LINE i = 0 NEW_LINE res = 0 NEW_LINE prev_one = 0 NEW_LINE curr_one = 0 NEW_LINE numberOfZeros = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE DEDENT ' NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT curr_one += 1 NEW_LINE DEDENT else : NEW_LINE INDENT numberOfZeros += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT prev_one += curr_one NEW_LINE res = max ( res , prev_one ) NEW_LINE prev_one = curr_one NEW_LINE curr_one = 0 NEW_LINE DEDENT ' NEW_LINE INDENT if ( numberOfZeros == 1 ) : NEW_LINE INDENT res -= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "1101" NEW_LINE print ( longestSubarray ( S ) ) NEW_LINE DEDENT
Lexicographically smallest string possible by inserting given character | Function to obtain lexicographically smallest string possible by inserting character c in the string s ; Traverse the string ; Check if current character is greater than the given character ; Insert the character before the first greater character ; Return the string ; Append the character at the end ; Return the string ; Function call
def SmallestString ( s , c ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i < len ( s ) ) : NEW_LINE INDENT if s [ i ] > c : NEW_LINE INDENT s = s [ : i ] + c + s [ i : ] NEW_LINE return s NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT s = s + c NEW_LINE return s NEW_LINE DEDENT S = ' abd ' NEW_LINE C = ' c ' NEW_LINE print ( SmallestString ( S , C ) ) NEW_LINE
Largest Non | Python program to implement the above approach ; Function to find the largest unique element of the array ; Store frequency of each distinct element of the array ; Traverse the array ; Update frequency of arr [ i ] ; Stores largest non - repeating element present in the array ; Stores index of the largest non - repeating array element ; Traverse the array ; If frequency of arr [ i ] is equal to 1 and arr [ i ] exceeds LNRElem ; Update ind ; Update LNRElem ; If no array element is found with frequency equal to 1 ; Prlargest non - repeating element ; Driver Code
import sys NEW_LINE def LarUnEl ( arr , N ) : NEW_LINE INDENT map = dict . fromkeys ( arr , 0 ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT map [ arr [ i ] ] += 1 ; NEW_LINE DEDENT LNRElem = - sys . maxsize ; NEW_LINE ind = - 1 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( map . get ( arr [ i ] ) == 1 and arr [ i ] > LNRElem ) : NEW_LINE INDENT ind = i ; NEW_LINE LNRElem = arr [ i ] ; NEW_LINE DEDENT DEDENT if ( ind == - 1 ) : NEW_LINE INDENT print ( ind ) ; NEW_LINE return ; NEW_LINE DEDENT print ( arr [ ind ] ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 1 , 8 , 8 , 4 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE LarUnEl ( arr , N ) ; NEW_LINE DEDENT
Minimum shifts of substrings of 1 s required to group all 1 s together in a given Binary string | Function to count indices substrings of 1 s need to be shifted such that all 1 s in the string are grouped together ; Stores first occurrence of '1 ; Stores last occurrence of '1 ; Count of 0 s between firstOne and lastOne ; Traverse the string to find the first and last occurrences of '1 ; Count number of 0 s present between firstOne and lastOne ; Print minimum operations ; Given string
def countShifts ( str ) : NEW_LINE ' NEW_LINE INDENT firstOne = - 1 NEW_LINE DEDENT ' NEW_LINE INDENT lastOne = - 1 NEW_LINE count = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT if ( firstOne == - 1 ) : NEW_LINE INDENT firstOne = i NEW_LINE DEDENT lastOne = i NEW_LINE DEDENT DEDENT if ( ( firstOne == - 1 ) or ( firstOne == lastOne ) ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT for i in range ( firstOne , lastOne + 1 , 1 ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT str = "00110111011" NEW_LINE countShifts ( str ) NEW_LINE
Check if a non | Utility Function to check whether a subsequence same as the given subarray exists or not ; Check if first element of the subarray is also present before ; Check if last element of the subarray is also present later ; If above two conditions are not satisfied , then no such subsequence exists ; Function to check and prif a subsequence which is same as the given subarray is present or not ; Driver Code ; Function Call
def checkSubsequenceUtil ( arr , L , R , N ) : NEW_LINE INDENT for i in range ( L ) : NEW_LINE INDENT if ( arr [ i ] == arr [ L ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT for i in range ( R + 1 , N , 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ R ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def checkSubsequence ( arr , L , R , N ) : NEW_LINE INDENT if ( checkSubsequenceUtil ( arr , L , R , N ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 7 , 12 , 1 , 7 , 5 , 10 , 11 , 42 ] NEW_LINE N = len ( arr ) NEW_LINE L = 3 NEW_LINE R = 6 NEW_LINE checkSubsequence ( arr , L , R , N ) NEW_LINE
Longest subarray in which all elements are smaller than K | Function to find the length of the longest subarray with all elements smaller than K ; Stores the length of maximum consecutive sequence ; Stores maximum length of subarray ; Iterate through the array ; Check if array element smaller than K ; Store the maximum of length and count ; Reset the counter ; Print the maximum length ; Driver Code ; Given array arr [ ] ; Size of the array ; Given K ; Function Call
def largestSubarray ( arr , N , K ) : NEW_LINE INDENT count = 0 NEW_LINE length = 0 NEW_LINE for i in range ( N ) : NEW_LINE if ( arr [ i ] < K ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT length = max ( length , count ) NEW_LINE count = 0 NEW_LINE DEDENT if ( count ) : NEW_LINE INDENT length = max ( length , count ) NEW_LINE DEDENT print ( length , end = " " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 8 , 3 , 5 , 2 , 2 , 1 , 13 ] NEW_LINE N = len ( arr ) NEW_LINE K = 6 NEW_LINE largestSubarray ( arr , N , K ) NEW_LINE DEDENT
Smallest pair of indices with product of subarray co | Function to calculate GCD of two integers ; Recursively calculate GCD ; Function to find the lexicographically smallest pair of indices whose product is co - prime with the product of the subarrays on its left and right ; Stores the suffix product of array elements ; Set 0 / 1 if pair satisfies the given condition or not ; Initialize array right_prod ; Update the suffix product ; Stores product of all elements ; Stores the product of subarray in between the pair of indices ; Iterate through every pair of indices ( i , j ) ; Store product of A [ i , j ] ; Check if product is co - prime to product of either the left or right subarrays ; If no such pair is found , then pr - 1 ; Driver Code ; Function Call
def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def findPair ( A , N ) : NEW_LINE INDENT right_prod = [ 0 ] * N NEW_LINE flag = 0 NEW_LINE right_prod [ N - 1 ] = A [ N - 1 ] NEW_LINE for i in range ( N - 2 , 0 , - 1 ) : NEW_LINE INDENT right_prod [ i ] = right_prod [ i + 1 ] * A [ i ] NEW_LINE DEDENT total_prod = right_prod [ 0 ] NEW_LINE product = 1 NEW_LINE for i in range ( 1 , N - 1 ) : NEW_LINE INDENT product = 1 NEW_LINE for j in range ( i , N - 1 ) : NEW_LINE INDENT product *= A [ j ] NEW_LINE if ( gcd ( product , right_prod [ j + 1 ] ) == 1 or gcd ( product , total_prod / right_prod [ i ] ) == 1 ) : NEW_LINE INDENT flag = 1 NEW_LINE print ( " ( " , ( i - 1 ) , " , ▁ " , ( j + 1 ) , " ) " ) NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 1 , 3 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE findPair ( arr , N ) NEW_LINE DEDENT
Count binary strings of length same as given string after removal of substrings "01" and "00" that consists of at least one '1' | Function to count the strings consisting of at least 1 set bit ; Initialize count ; Iterate through string ; The answer is 2 ^ N - 1 ; Driver Code ; Given string ; Function call
def countString ( S ) : NEW_LINE INDENT count = 0 NEW_LINE for i in S : NEW_LINE INDENT if ( i == '0' and count > 0 ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( ( 1 << count ) - 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "1001" NEW_LINE countString ( S ) NEW_LINE DEDENT