text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Minimize value of | A | Function to find the minimum possible value of | A - X | + | B - Y | + | C - Z | such that X * Y = Z for given A , B and C ; Stores the minimum value of | A - X | + | B - Y | + | C - Z | such that X * Y = Z ; Iterate over all values of i in the range [ 1 , 2 * C ] ; Iterate over all values of j ... | def minimizeCost ( A , B , C ) : NEW_LINE INDENT ans = A + B + C NEW_LINE for i in range ( 1 , 2 * C + 1 ) : NEW_LINE INDENT j = 0 NEW_LINE while ( i * j <= 2 * C ) : NEW_LINE INDENT ans = min ( ans , abs ( A - i ) + abs ( B - j ) + abs ( i * j - C ) ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A... |
Average value of set bit count in given Binary string after performing all possible choices of K operations | Function to calculate the average number of Set bits after after given operations ; Stores the average number of set bits after current operation ; Stores the average number of set bits after current operation ... | def averageSetBits ( N , K , arr ) : NEW_LINE INDENT p = N NEW_LINE q = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT _p = p NEW_LINE _q = q NEW_LINE p = _p - _p * arr [ i ] / N + _q * arr [ i ] / N NEW_LINE q = _q - _q * arr [ i ] / N + _p * arr [ i ] / N NEW_LINE DEDENT return p NEW_LINE DEDENT if __name__ == " _... |
Find maximum sum of subsequence after flipping signs of at most K elements in given Array | Function to calculate the max sum of subsequence ; Variable to store the max sum ; Sort the array ; Iterate over the array ; Flip sign ; Decrement k ; Traverse over the array ; Add only positive elements ; Return the max sum ; D... | def maxSubseq ( arr , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT arr [ i ] = - arr [ i ] NEW_LINE K -= 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDE... |
Minimum number of intervals to cover the target interval | Function to find the minimum number of intervals in the array A [ ] to cover the entire target interval ; Sort the array A [ ] in increasing order of starting point ; Insert a pair of INT_MAX to prevent going out of bounds ; Stores start of current interval ; S... | def minimizeSegment ( A , X ) : NEW_LINE INDENT A . sort ( ) NEW_LINE INT_MAX = 2147483647 NEW_LINE A . append ( [ INT_MAX , INT_MAX ] ) NEW_LINE start = X [ 0 ] NEW_LINE end = X [ 0 ] - 1 NEW_LINE cnt = 0 NEW_LINE for i in range ( 0 , len ( A ) ) : NEW_LINE INDENT if ( A [ i ] [ 0 ] <= start ) : NEW_LINE INDENT end = ... |
K | Function to calculate K - th smallest solution ( Y ) of equation X + Y = X | Y ; Initialize the variable to store the answer ; The i - th bit of X is off ; The i - bit of K is on ; Divide K by 2 ; If K becomes 0 then break ; Driver Code | def KthSolution ( X , K ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , 64 ) : NEW_LINE INDENT if ( not ( X & ( 1 << i ) ) ) : NEW_LINE INDENT if ( K & 1 ) : NEW_LINE INDENT ans |= ( 1 << i ) NEW_LINE DEDENT K >>= 1 NEW_LINE if ( not K ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LIN... |
Rearrange sorted array such that all odd indices elements comes before all even indices element | Function to print the array ; Function to rearrange the array such that odd indexed elements come before even indexed elements ; Reduces the size of array by one because last element does not need to be changed in case N =... | def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT def rearrange ( arr , N ) : NEW_LINE INDENT if ( N & 1 ) : NEW_LINE INDENT N -= 1 NEW_LINE DEDENT odd_idx = 1 NEW_LINE even_idx = 0 NEW_LINE max_elem = arr ... |
Find range of values for S in given Array with values satisfying [ arr [ i ] = floor ( ( i * S ) / K ) ] | Python 3 program for the above approach ; Function to find the range of values for S in a given array that satisfies the given condition ; Stores the left range value ; Stores the right range value ; Find the curr... | from math import ceil , floor NEW_LINE import sys NEW_LINE def findRange ( arr , N , K ) : NEW_LINE INDENT L = - sys . maxsize - 1 NEW_LINE R = sys . maxsize NEW_LINE for i in range ( N ) : NEW_LINE INDENT l = ceil ( 1.0 * arr [ i ] * K / ( i + 1 ) ) NEW_LINE r = ceil ( ( 1.0 + arr [ i ] ) * K / ( i + 1 ) - 1 ) NEW_LIN... |
Find an anagram of given String having different characters at corresponding indices | Function to find anagram of string such that characters at the same indices are different ; Copying our original string for comparison ; Declaring the two pointers ; Checking the given condition ; When string length is odd ; The mid ... | def findAnagram ( s ) : NEW_LINE INDENT check = s NEW_LINE st = list ( s ) NEW_LINE i = 0 NEW_LINE j = len ( st ) - 1 NEW_LINE while ( i < len ( st ) and j >= 0 ) : NEW_LINE INDENT if ( st [ i ] != st [ j ] and check [ i ] != st [ j ] and check [ j ] != st [ i ] ) : NEW_LINE INDENT st [ i ] , st [ j ] = st [ j ] , st [... |
Lexicographically smallest permutation of [ 1 , N ] based on given Binary string | Function to generate the lexicographically smallest permutation according to the given criteria ; Stores the resultant permutation ; Initialize the first elements to 1 ; Traverse the given string S ; Number greater than last number ; Num... | def constructPermutation ( S , N ) : NEW_LINE INDENT ans = [ 0 ] * N NEW_LINE ans [ 0 ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( S [ i - 1 ] == '0' ) : NEW_LINE INDENT ans [ i ] = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans [ i ] = ans [ i - 1 ] NEW_LINE DEDENT for j in range ( i ) : NEW_LINE I... |
Kth smallest positive integer Y such that its sum with X is same as its bitwise OR with X | Function to calculate K - th smallest solution ( Y ) of equation X + Y = X | Y ; Initialize the variable to store the answer ; The i - th bit of X is off ; The i - bit of K is on ; Divide K by 2 ; If K becomes 0 then break ; Dri... | def KthSolution ( X , K ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 64 ) : NEW_LINE INDENT if not ( X & ( 1 << i ) ) : NEW_LINE INDENT if ( K & 1 ) : NEW_LINE INDENT ans |= ( 1 << i ) NEW_LINE DEDENT K >>= 1 NEW_LINE if not K : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT X =... |
Count of distinct N | Function to find the count of distinct arrays of size n having elements in range [ 1 , k ] and all adjacent elements ( P , Q ) follows ( P <= Q ) or ( P % Q > 0 ) ; Stores the divisors of all integers in the range [ 1 , k ] ; Calculate the divisors of all integers using the Sieve ; Stores the dp s... | def countArrays ( n , k ) : NEW_LINE INDENT divisors = [ [ ] for i in range ( k + 1 ) ] NEW_LINE for i in range ( 1 , k + 1 , 1 ) : NEW_LINE INDENT for j in range ( 2 * i , k + 1 , i ) : NEW_LINE INDENT divisors [ j ] . append ( i ) NEW_LINE DEDENT DEDENT dp = [ [ 0 for i in range ( k + 1 ) ] for j in range ( n + 1 ) ]... |
Minimize increment | Function to calculate the minimum number of operations to convert array A to array B by incrementing and decrementing adjacent elements ; Stores the final count ; Stores the sum of array A and B respectivelly ; Check of the sums are unequall ; Pointer to iterate through array ; Case 1 where A [ i ]... | def minimumMoves ( A , B , N ) : NEW_LINE INDENT ans = 0 NEW_LINE sum_A = 0 NEW_LINE sum_B = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum_A += A [ i ] NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT sum_B += B [ i ] NEW_LINE DEDENT if ( sum_A != sum_B ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT i = 0... |
Check if X can be reduced to 0 in exactly T moves by substracting D or 1 from it | Function to check the above problem condition ; Check the base case . ; check if X - T is a divisor of D - 1 ; Driver code | def possibleReachingSequence ( X , D , T ) : NEW_LINE INDENT if X < T : NEW_LINE INDENT return " NO " NEW_LINE DEDENT if T * D < X : NEW_LINE INDENT return " NO " NEW_LINE DEDENT if ( X - T ) % ( D - 1 ) == 0 : NEW_LINE INDENT return " YES " NEW_LINE DEDENT return " NO " NEW_LINE DEDENT X = 10 NEW_LINE D = 3 NEW_LINE T... |
Maximum number of times Array can be reduced in half when its all elements are even | Python 3 code implementation for the above approach ; Function to return the number of operations possible ; counter to store the number of times the current element is divisible by 2 ; variable to store the final answer ; Initialize ... | import sys NEW_LINE def arrayDivisionByTwo ( arr , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT arr [ i ] = arr [ i ] // 2 NEW_LINE cnt += 1 NEW_LINE DEDENT ans = min ( ans , cnt ) NEW_LINE DEDE... |
Find smallest number with given digits and sum of digits | Function to print minimum integer having only digits P and Q and the sum of digits as N ; If Q is greater that P then swap the values of P and Q ; If P and Q are both zero or if Q is zero and N is not divisible by P then there is no possible integer which satis... | def printMinInteger ( P , Q , N ) : NEW_LINE INDENT if ( Q > P ) : NEW_LINE INDENT t = P NEW_LINE P = Q NEW_LINE Q = t NEW_LINE DEDENT if ( Q == 0 and ( P == 0 or N % P != 0 ) ) : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE return NEW_LINE DEDENT count_P = 0 NEW_LINE count_Q = 0 NEW_LINE while ( N > 0 ) : NEW... |
Minimum number of sum and modulo operations using given numbers to reach target | Function to find the minimum moves to reach K from N ; Initialization of dp vector ; dp [ i ] = minimum pushes required to reach i ; Traversing through the buttons ; Iterating through all the positions ; If not visited ; Next status of lo... | def minPushes ( N , K , arr ) : NEW_LINE INDENT dp = [ - 1 ] * 100000 NEW_LINE dp [ N ] = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT for xx in range ( 100000 ) : NEW_LINE INDENT x = xx NEW_LINE if ( dp [ x ] == - 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT next = ( x + arr [ i ] ) % 100000 NEW_LINE ... |
Minimum number of Apples to be collected from trees to guarantee M red apples | Function to minimum no . of apples ; If we get all required apple from South ; If we required trees at East and West ; If we doesn 't have enough red apples ; Driver Code ; No . of red apple for gift ; No . of red apple in each tree ; No .... | def minApples ( ) : NEW_LINE INDENT if M <= S * K : NEW_LINE INDENT return M NEW_LINE DEDENT elif M <= S * K + E + W : NEW_LINE INDENT return S * K + ( M - S * K ) * K NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT M = 10 NEW_LINE K = 15 NEW_LI... |
Minimum increments or decrements required to signs of prefix sum array elements alternating | Function to find the minimum number of increments / decrements of array elements by 1 to make signs of prefix sum array elements alternating ; Case 1. neg - pos - neg ; Stores the current sign of the prefix sum of array ; Stor... | def minimumOperations ( A , N ) : NEW_LINE INDENT cur_prefix_1 = 0 NEW_LINE parity = - 1 NEW_LINE minOperationsCase1 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cur_prefix_1 += A [ i ] NEW_LINE if ( cur_prefix_1 == 0 or parity * cur_prefix_1 < 0 ) : NEW_LINE INDENT minOperationsCase1 += abs ( parity - cur_prefi... |
Generate an array of maximum sum such that each element exceeds all elements present either on its left or right | Function to construct the array having maximum sum satisfying the given criteria ; Declaration of the array arrA [ ] and ans [ ] ; Stores the maximum sum of the resultant array ; Initialize the array arrA ... | def maximumSumArray ( arr , N ) : NEW_LINE INDENT arrA = [ 0 ] * N NEW_LINE ans = [ 0 ] * N NEW_LINE maxSum = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT arrA [ i ] = arr [ i ] ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT arrB = [ 0 ] * N NEW_LINE maximum = arrA [ i ] ; NEW_LINE arrB [ i ] = maximum... |
Minimize product of two scores possible by at most M reductions | Utility function to find the minimum product of R1 and R2 possible ; Reaching to its limit ; If M is remaining ; Function to find the minimum product of R1 and R2 ; Case 1 - R1 reduces first ; case 2 - R2 reduces first ; Driver Code ; Given Input ; Funct... | def minProductUtil ( R1 , B1 , R2 , B2 , M ) : NEW_LINE INDENT x = min ( R1 - B1 , M ) NEW_LINE M -= x NEW_LINE R1 -= x NEW_LINE if M > 0 : NEW_LINE INDENT y = min ( R2 - B2 , M ) NEW_LINE M -= y NEW_LINE R2 -= y NEW_LINE DEDENT return R1 * R2 NEW_LINE DEDENT def minProduct ( R1 , B1 , R2 , B2 , M ) : NEW_LINE INDENT r... |
Maximize the profit after selling the tickets | Set 2 ( For elements in range [ 1 , 10 ^ 6 ] ) | Function to find maximum profit after selling K tickets ; Frequency array to store freq of every element of the array ; Modify the arr [ ] so that the array is sorted in O ( N ) ; Variable to store answer ; Traverse the arr... | def maxAmount ( n , k , arr ) : NEW_LINE INDENT A = [ 0 for i in range ( 1000001 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT A [ arr [ i ] ] += 1 NEW_LINE DEDENT j = 0 NEW_LINE for j in range ( 1000001 ) : NEW_LINE INDENT while ( A [ i ] != 0 ) : NEW_LINE INDENT arr [ j ] = i ; NEW_LINE j += 1 NEW_LINE A [ i ] ... |
Maximize sum of averages of subsequences of lengths lying in a given range | Function to find the maximum sum of average of groups ; Sort the given array ; Stores the sum of averages ; Stores count of array element ; Add the current value to the variable sum ; Increment the count by 1 ; If the current size is X ; If th... | def maxAverage ( A , N , X , Y ) : NEW_LINE INDENT A . sort ( ) NEW_LINE sum = 0 NEW_LINE res = 0 NEW_LINE count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE count += 1 NEW_LINE if ( count == X ) : NEW_LINE INDENT if ( N - i - 1 < X ) : NEW_LINE INDENT i += 1 NEW_LINE cnt = 0 NEW_LINE whi... |
Rearrange characters in a sorted string such that no pair of adjacent characters are the same | Python 3 program for the above approach ; Function to check if a string S contains pair of adjacent characters that are equal or not ; Traverse the string S ; If S [ i ] and S [ i + 1 ] are equal ; Otherwise , return false ;... | S = " aaabc " NEW_LINE def isAdjChar ( s ) : NEW_LINE INDENT for i in range ( len ( s ) - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def rearrangeStringUtil ( N ) : NEW_LINE INDENT global S NEW_LINE S = list ( S ) NEW_LINE i = 0 ... |
Lexicographically largest string possible by repeatedly appending first character of two given strings | Function to make the lexicographically largest string by merging two strings ; Stores the resultant string ; If the string word1 is lexographically greater than or equal to word2 ; Update the string merge ; Erase th... | def largestMerge ( word1 , word2 ) : NEW_LINE INDENT merge = " " NEW_LINE while len ( word1 ) != 0 or len ( word2 ) != 0 : NEW_LINE INDENT if word1 >= word2 : NEW_LINE INDENT merge = merge + word1 [ 0 ] NEW_LINE word1 = word1 [ 1 : ] NEW_LINE DEDENT else : NEW_LINE INDENT merge = merge + word2 [ 0 ] NEW_LINE word2 = wo... |
Maximum rods to put horizontally such that no two rods overlap on X coordinate | Python 3 program for the above approach ; Function to find the maximum number of rods that can be put horizontally ; Stores the result ; Stores the last occupied point ; Traverse the array arr [ ] ; If the current point can be put on the l... | import sys NEW_LINE def findMaximumPoints ( N , X , H ) : NEW_LINE INDENT ans = 0 NEW_LINE prev = - sys . maxsize - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( prev < ( X [ i ] - H [ i ] ) ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = X [ i ] NEW_LINE DEDENT elif ( i == N - 1 or ( X [ i ] + H [ i ] ) < X [ i ... |
Maximize the missing values in given time in HH : MM format | Function to find the maximum time by replacing ' ? ' by any digits ; If the 0 th index is '? ; If the 1 st index is '? ; If the 3 rd index is '? ; If the 4 th index is '? ; Return new string ; Driver Code | def maxTime ( s ) : NEW_LINE ' NEW_LINE INDENT s = list ( s ) NEW_LINE if ( s [ 0 ] == ' ? ' ) : NEW_LINE INDENT if ( s [ 1 ] <= '3' or s [ 1 ] == ' ? ' ) : NEW_LINE INDENT s [ 0 ] = '2' NEW_LINE DEDENT else : NEW_LINE INDENT s [ 0 ] = '1' NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT if ( s [ 1 ] == ' ? ' ) : NEW_LI... |
Maximum GCD of two numbers possible by adding same value to them | Function to calculate maximum gcd of two numbers possible by adding same value to both a and b ; Given Input | def maxGcd ( a , b ) : NEW_LINE INDENT print ( abs ( a - b ) ) NEW_LINE DEDENT a = 2231 NEW_LINE b = 343 NEW_LINE maxGcd ( a , b ) NEW_LINE |
Count the combination of 4 s and / or 5 s required to make each Array element 0 | Function to print the count of the combination of 4 or 5 required to make the arr [ i ] for each 0 < i < N ; Vector to store the answer ; Iterate in the range [ 0 , N - 1 ] ; Initialize sum to store the count of numbers and cnt for the cu... | def sumOfCombinationOf4OR5 ( arr , N ) : NEW_LINE INDENT ans = [ - 1 for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] < 4 ) : NEW_LINE INDENT continue NEW_LINE DEDENT sum = 10 ** 9 NEW_LINE cnt = 0 NEW_LINE for j in range ( 0 , arr [ i ] + 1 , 4 ) : NEW_LINE INDENT if ( ( arr [ i ] ... |
Find an N | Function to find an N - length binary string having maximum sum of elements from all given ranges ; Iterate over the range [ 1 , N ] ; If i is odd , then print 0 ; Otherwise , print 1 ; Driver Code ; Function Call | def printBinaryString ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i % 2 ) : NEW_LINE INDENT print ( 0 , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( 1 , end = " " ) ; NEW_LINE DEDENT DEDENT DEDENT N = 5 ; NEW_LINE M = 3 ; NEW_LINE arr = [ [ 1 , 3 ] , [ 2 , 4 ] , [ 2... |
Maximize 0 s in given Array after replacing each element A [ i ] with ( A [ i ] * D + B [ i ] ) | Python program for the above approach ; Function to find the maximum number of 0 s in the array A [ ] after changing the array element to A [ i ] * D + B [ i ] ; Stores the frequency of fractions needed to make each elemen... | from math import gcd NEW_LINE def maxZeroes ( A , B ) : NEW_LINE INDENT mp = { } NEW_LINE N = len ( A ) NEW_LINE ans = 0 NEW_LINE cnt = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT num = - B [ i ] NEW_LINE den = A [ i ] NEW_LINE gc = gcd ( num , den ) NEW_LINE if ( den != 0 ) : NEW_LINE INDENT num //= gc NEW_LINE ... |
Minimum cost to complete given tasks if cost of 1 , 7 and 30 days are given | Function to find the minimum cost to hire the workers for the given days in the array days [ ] ; Initialize the array dp ; Minimum Cost for Nth day ; Poleter of the array arr [ ] ; Traverse from right to left ; If worker is hired for 1 day ; ... | def MinCost ( days , cost , N ) : NEW_LINE INDENT size = days [ N - 1 ] + 1 NEW_LINE dp = [ 0 for i in range ( size ) ] NEW_LINE dp [ size - 1 ] = min ( cost [ 0 ] , min ( cost [ 1 ] , cost [ 2 ] ) ) NEW_LINE ptr = N - 2 NEW_LINE for i in range ( size - 2 , 0 , - 1 ) : NEW_LINE INDENT if ( ptr >= 0 and days [ ptr ] == ... |
Maximum Pairs of Bracket Sequences which can be concatenated to form a Regular Bracket Sequence | Function to count the number of pairs whose concatenation results in the regular bracket sequence ; Stores the count of opening and closing parenthesis for each string arr [ i ] ; Stores maximum count of pairs ; Traverse t... | def countPairs ( N , arr ) : NEW_LINE INDENT open = [ 0 ] * 100 NEW_LINE close = [ 0 ] * 100 NEW_LINE ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT c = [ i for i in arr [ i ] ] NEW_LINE d = 0 NEW_LINE minm = 0 NEW_LINE for j in range ( len ( c ) ) : NEW_LINE INDENT if ( c [ j ] == ' ( ' ) : NEW_LINE INDENT d ... |
Minimum count of elements to be inserted in Array to form all values in [ 1 , K ] using subset sum | Function to find the count of minimum elements to be inserted to form every number in a range ; Stores the count of numbers needed ; Stores the numbers upto which every numbers can be formed ; Stores the index of the ar... | def minElements ( arr , N , K ) : NEW_LINE INDENT count = 0 NEW_LINE requiredNum = 1 NEW_LINE i = 0 NEW_LINE while ( requiredNum <= K ) : NEW_LINE INDENT if ( i < N and requiredNum >= arr [ i ] ) : NEW_LINE INDENT requiredNum += arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE requir... |
Theft at World Bank | Python3 program for the above approach ; Custom comparator ; Function to find the maximum profit ; Stores the pairs of elements of B and A at the same index ; Iterate over the range [ 0 , N ] ; If current integer is perfect square ; Push the pair of B [ i ] and A [ i ] in vector V ; Sort the vecto... | import math NEW_LINE from functools import cmp_to_key NEW_LINE def comparator ( p1 , p2 ) : NEW_LINE INDENT a = p1 [ 0 ] NEW_LINE b = p1 [ 1 ] NEW_LINE c = p2 [ 0 ] NEW_LINE d = p2 [ 1 ] NEW_LINE val1 = a / b NEW_LINE val2 = c / d NEW_LINE return val1 > val2 NEW_LINE DEDENT def maximumProfit ( A , B , N , W ) : NEW_LIN... |
Maximize the count of adjacent element pairs with even sum by rearranging the Array | Function to find maximum count pair of adjacent elements with even sum ; Stores count of odd numbers ; Stores count of even numbers ; Traverse the array arr [ ] ; If arr [ i ] % 2 is 1 ; Else ; If odd and even both are greater than 0 ... | def maximumCount ( arr , N ) : NEW_LINE INDENT odd = 0 NEW_LINE even = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even += 1 NEW_LINE DEDENT DEDENT if ( odd and even ) : NEW_LINE INDENT return N - 2 NEW_LINE DEDENT else : NEW_L... |
Smallest number possible by repeatedly multiplying with K or 2 exactly N times starting from 1 | Function to find the minimum value of X after increment X by K or twice value of X in each of N operations ; Iterate over the range [ 1 , N ] ; If the value of X is less than equal to K ; Otherwise ; Return the minimum valu... | def minPossibleValue ( N , K , X ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( X <= K ) : NEW_LINE INDENT X = X * 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT X = X + K ; NEW_LINE DEDENT DEDENT return X ; NEW_LINE DEDENT N = 7 ; NEW_LINE K = 4 ; NEW_LINE X = 1 ; NEW_LINE print ( minPossibleValue... |
Smallest number that can replace all | Python 3 program for the above approach ; Function to find the value of K to minimize the value of maximum absolute difference between adjacent elements ; Stores the maximum and minimum among array elements that are adjacent to " - 1" ; Traverse the given array arr [ ] ; If arr [ ... | import sys NEW_LINE def findMissingValue ( arr , N ) : NEW_LINE INDENT minE = sys . maxsize NEW_LINE maxE = - sys . maxsize - 1 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( arr [ i ] == - 1 and arr [ i + 1 ] != - 1 ) : NEW_LINE INDENT minE = min ( minE , arr [ i + 1 ] ) NEW_LINE maxE = max ( maxE , arr [ i ... |
Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times | Function to find the last element after performing given operations ; Length of the array ; Increment j until condition is satisfied ; In each pair every value is repeating r number of t... | def findLastElement ( N , A ) : NEW_LINE INDENT l = len ( A ) NEW_LINE j = 0 NEW_LINE while ( N > l * ( 2 ** j ) ) : NEW_LINE INDENT N = N - l * 2 ** j NEW_LINE j += 1 NEW_LINE DEDENT k = 1 NEW_LINE r = 2 ** j NEW_LINE for i in range ( 1 , l ) : NEW_LINE INDENT if N > r * i : NEW_LINE INDENT k += 1 NEW_LINE DEDENT DEDE... |
Minimum possible value of D which when added to or subtracted from K repeatedly obtains every array element | Recursive function tox previous gcd of a and b ; Function to find the maximum value of D such that every element in the array can be obtained by performing K + D or K - D ; Traverse the array arr [ ] ; Update a... | 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 findMaxD ( arr , N , K ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT arr [ i ] = abs ( arr [ i ] - K ) NEW_LINE DEDENT D = arr [ 0 ] NEW_LINE for i in range ( 1 , N ... |
Maximize the number of times a character can be removed from substring 01 from given Binary String | Function to find the maximum moves that can be performed on a string ; Stores 0 s in suffix ; Stores 1 s in prefix ; Iterate over the characters of the string ; Iterate until i is greater than or equal to 0 ; If N is eq... | def maxOperations ( S , N ) : NEW_LINE INDENT X = 0 NEW_LINE Y = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT break NEW_LINE DEDENT Y += 1 NEW_LINE DEDENT i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT break NEW_LINE DEDENT X +=... |
Maximize frequency sum of K chosen characters from given string | Function to find the maximum sum of frequencies of the exactly K chosen characters from the string S ; Stores the resultant maximum sum ; Stores the frequency of array elements ; Find the frequency of character ; Sort the frequency array in the descendin... | def maximumSum ( S , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE freq = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ ord ( S [ i ] ) ] += 1 NEW_LINE DEDENT freq = sorted ( freq ) [ : : - 1 ] NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT if ( K > freq [ i ] ) : NEW_LINE INDENT sum += freq [ i ] ... |
Count of N | Python3 program for the above approach ; Function to count N - digit numbers having absolute difference between adjacent digits in non - increasing order ; If digit = n + 1 , a valid n - digit number has been formed ; If the state has already been computed ; If the current digit is 1 , then any digit from ... | dp = [ [ [ 0 for i in range ( 10 ) ] for col in range ( 10 ) ] for row in range ( 100 ) ] NEW_LINE def countOfNumbers ( digit , prev1 , prev2 , n ) : NEW_LINE INDENT if ( digit == n + 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT val = dp [ digit ] [ prev1 ] [ prev2 ] NEW_LINE if ( val != - 1 ) : NEW_LINE INDENT retur... |
Print all numbers that can be obtained by adding A or B to N exactly M times | Function to find all possible numbers that can be obtained by adding A or B to N exactly N times ; If number of steps is 0 and only possible number is N ; Add A to N and make a recursive call for M - 1 steps ; Add B to N and make a recursive... | def possibleNumbers ( numbers , N , M , A , B ) : NEW_LINE INDENT if ( M == 0 ) : NEW_LINE INDENT numbers . add ( N ) NEW_LINE return NEW_LINE DEDENT possibleNumbers ( numbers , N + A , M - 1 , A , B ) NEW_LINE possibleNumbers ( numbers , N + B , M - 1 , A , B ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LIN... |
Maximum sum of array after removing a positive or negative subarray | python 3 program for the above approach ; Function to find the maximum sum of array after removing either the contiguous positive or negative elements ; Store the total sum of array ; Store the maximum contiguous negative sum ; Store the sum of curre... | import sys NEW_LINE def maxSum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE max_neg = sys . maxsize NEW_LINE tempsum = 0 NEW_LINE small = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE small = min ( small , arr [ i ] ) NEW_LINE if ( arr [ i ] > 0 ) : NEW_LINE INDENT tempsum = ... |
Count characters of a string which when removed individually makes the string equal to another string | Function to count characters from A whose removal makes the strings A and B equal ; Stores the index of the longest prefix ; Stores the index of the longest suffix ; Traverse the B ; Traverse the B ; If N - M is equa... | def RemoveOneChar ( A , B , N , M ) : NEW_LINE INDENT X = 0 NEW_LINE Y = N - 1 NEW_LINE for i in range ( M ) : NEW_LINE INDENT if ( A [ X ] != B [ i ] ) : NEW_LINE INDENT break NEW_LINE DEDENT X += 1 NEW_LINE DEDENT for i in range ( M - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ Y ] != B [ i ] ) : NEW_LINE INDENT break... |
Minimum flips or swapping of adjacent characters required to make a string equal to another | Function to find minimum operations required to convert A to B ; Store the size of the string ; Store the required result ; Traverse the string , a ; If a [ i ] is equal to b [ i ] ; Check if swapping adjacent characters make ... | def minimumOperation ( a , b ) : NEW_LINE INDENT n = len ( a ) NEW_LINE i = 0 NEW_LINE minoperation = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( a [ i ] == b [ i ] ) : NEW_LINE INDENT i = i + 1 NEW_LINE continue NEW_LINE DEDENT elif ( a [ i ] == b [ i + 1 ] and a [ i + 1 ] == b [ i ] and i < n - 1 ) : NEW_LINE I... |
Minimum replacements required to make sum of all K | Function to find minimum number of operations required to make sum of all subarrays of size K equal ; Stores number of operations ; Iterate in the range [ 0 , K - 1 ] ; Stores frequency of elements separated by distance K ; Stores maximum frequency and corresponding ... | def findMinOperations ( arr , N , K ) : NEW_LINE INDENT operations = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT freq = { } NEW_LINE for j in range ( i , N , K ) : NEW_LINE INDENT if arr [ j ] in freq : NEW_LINE INDENT freq [ arr [ j ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ arr [ j ] ] = 1 NEW_LINE ... |
Count of pairs of integers up to X and Y that generates equal Quotient and Remainder | python 3 Program for the above approach ; Function to calculate the number of pairs satisfying ( m / n = m % n ) ; Iterate from 1 to sqrt ( x ) ; Combining the conditions - 1 ) n > k 2 ) n <= y 3 ) n <= ( x / k - 1 ) ; Driver code | from math import sqrt NEW_LINE def countOfPairs ( x , y ) : NEW_LINE INDENT count = 0 NEW_LINE for k in range ( 1 , int ( sqrt ( x ) ) + 1 , 1 ) : NEW_LINE INDENT count += max ( 0 , min ( y , x / k - 1 ) - k ) NEW_LINE DEDENT print ( int ( count ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = ... |
Count permutations of first N natural numbers having sum of adjacent elements equal to a perfect square | python program for the above approach ; Function to count total number of permutation of the first N natural number having the sum of adjacent elements as perfect square ; Create an adjacency matrix ; bCount elemen... | from math import sqrt , floor , ceil NEW_LINE def countPermutations ( N ) : NEW_LINE INDENT adj = [ [ ] for i in range ( 105 ) ] NEW_LINE indeg = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT sum = i + j ... |
Generate a permutation of first N natural numbers having count of unique adjacent differences equal to K | Function to construct the lst with exactly K unique adjacent element differences ; Stores the resultant array ; Stores the left and the right most element of the range ; Traverse the array ; If k is even , the add... | def makelst ( N , K ) : NEW_LINE INDENT lst = [ 0 for i in range ( N ) ] NEW_LINE left = 1 NEW_LINE right = N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( K % 2 == 0 ) : NEW_LINE INDENT lst [ i ] = left NEW_LINE left = left + 1 NEW_LINE DEDENT else : NEW_LINE INDENT lst [ i ] = right NEW_LINE right = right - 1 ... |
Find the date after next half year from a given date | Function to find the date after the next half - year ; Stores the number of days in the months of a leap year ; List of months ; Days in half of a year ; Index of current month ; Starting day ; Decrement the value of cnt by 1 ; Increment cur_date ; If cnt is equal ... | def getDate ( d , m ) : NEW_LINE INDENT days = [ 31 , 29 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ] NEW_LINE month = [ ' January ' , ' February ' , ' March ' , ' April ' , ' May ' , ' June ' , ' July ' , ' August ' , ' September ' , ' October ' , ' November ' , ' December ' ] NEW_LINE cnt = 183 NEW_LINE cur_mo... |
Maximum number made up of distinct digits whose sum is equal to N | Function to find the largest positive number made up of distinct digits having the sum of its digits as N ; If given number is greater than 45 , print - 1 ; Store the required number and the digit to be considered ; Loop until N > 0 and digit > 0 ; If ... | def largestNumber ( N ) : NEW_LINE INDENT if ( N > 45 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT num = 0 NEW_LINE digit = 9 NEW_LINE while ( N > 0 and digit > 0 ) : NEW_LINE INDENT if ( digit <= N ) : NEW_LINE INDENT num *= 10 NEW_LINE num += digit NEW_LINE N -= digit NEW_LINE DEDENT digit -= 1 NEW_LINE DEDENT retu... |
Minimum number that can be obtained by applying ' + ' and ' * ' operations on array elements | Function to find the smallest number that can be obtained after applying the arithmetic operations mentioned in the string S ; Stores the count of multiplication operator in the string ; Store the required result ; Iterate in... | def minimumSum ( A , N , S ) : NEW_LINE INDENT mul = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( S [ i ] == " * " ) : NEW_LINE INDENT mul += 1 NEW_LINE DEDENT DEDENT ans = 1000000 NEW_LINE for i in range ( 1 << ( N - 1 ) ) : NEW_LINE INDENT cnt = 0 NEW_LINE v = [ ] NEW_LINE for j in range ( N - 1 ) :... |
Minimum sum of medians of all possible K length subsequences of a sorted array | Function to find the minimum sum of all the medians of the K sized sorted arrays formed from the given array ; Stores the distance between the medians ; Stores the number of subsequences required ; Stores the resultant sum ; Iterate from s... | def sumOfMedians ( arr , N , K ) : NEW_LINE INDENT selectMedian = ( K + 1 ) // 2 NEW_LINE totalArrays = N // K NEW_LINE minSum = 0 NEW_LINE i = selectMedian - 1 NEW_LINE while ( i < N and totalArrays != 0 ) : NEW_LINE INDENT minSum = minSum + arr [ i ] NEW_LINE i = i + selectMedian NEW_LINE totalArrays -= 1 NEW_LINE DE... |
Find K positive integers not exceeding N and having sum S | Function to represent S as the sum of K positive integers less than or equal to N ; If S can cannot be represented as sum of K integers ; If sum of first i natural numbers exceeds S ; Insert i into nums [ ] ; Insert first K - 1 positive numbers into answer [ ]... | def solve ( S , K , N ) : NEW_LINE INDENT if ( K > N ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT max_sum , min_sum = 0 , 0 NEW_LINE for i in range ( K + 1 ) : NEW_LINE INDENT min_sum += i NEW_LINE max_sum += N - i + 1 NEW_LINE DEDENT if ( S < min_sum or S > max_sum ) : NEW_LINE INDENT print ( "... |
Generate an N | Python3 program for the above approach ; Function to minimize the maximum element present in an N - length array having sum of elements divisible by K ; Return the ceil value of ( K / N ) ; Driver Code | import math NEW_LINE def minimumValue ( N , K ) : NEW_LINE INDENT return math . ceil ( K / N ) NEW_LINE DEDENT N = 4 NEW_LINE K = 50 NEW_LINE print ( minimumValue ( N , K ) ) NEW_LINE |
Minimum removal of elements from end of an array required to obtain sum K | Function to find the minimum number of elements required to be removed from the ends of an array to obtain a sum K ; Number of elements removed from the left and right ends of the array ; Sum of left and right subarrays ; No element is taken fr... | def minSizeArr ( A , N , K ) : NEW_LINE INDENT leftTaken = N NEW_LINE rightTaken = N NEW_LINE leftSum = 0 NEW_LINE rightSum = 0 NEW_LINE for left in range ( - 1 , N ) : NEW_LINE INDENT if ( left != - 1 ) : NEW_LINE INDENT leftSum += A [ left ] NEW_LINE DEDENT rightSum = 0 NEW_LINE for right in range ( N - 1 , left , - ... |
Minimum removal of elements from end of an array required to obtain sum K | Function to find the smallest array that can be removed from the ends of an array to obtain sum K ; Sum of complete array ; If given number is greater than sum of the array ; If number is equal to the sum of array ; tar is sum of middle subarra... | def minSizeArr ( A , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE DEDENT if ( K > sum ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE return NEW_LINE DEDENT if ( K == sum ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( A [ i ] , end = " β " ) ... |
Minimum product modulo N possible for any pair from a given range | Function to return the minimum possible value of ( i * j ) % N ; Stores the minimum remainder ; Iterate from L to R ; Iterate from L to R ; Print the minimum value of remainder ; If R - L >= N ; Driver Code | def minModulo ( L , R , N ) : NEW_LINE INDENT if ( R - L < N ) : NEW_LINE INDENT ans = 10 ** 9 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT for j in range ( L , R + 1 ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT ans = min ( ans , ( i * j ) % N ) NEW_LINE DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DED... |
Count numbers having GCD with N equal to the number itself | Function to count numbers whose GCD with N is the number itself ; Stores the count of factors of N ; Iterate over the range [ 1 , sqrt ( N ) ] ; If i is divisible by i ; Increment count ; Avoid counting the same factor twice ; Return the resultant count ; Dri... | def countNumbers ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT if ( N % i == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE if ( N // i != i ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDE... |
Maximum length of all possible K equal length ropes generated by cutting N ropes | Function to find the maximum size of ropes having frequency at least K by cutting the given ropes ; Stores the left and the right boundaries ; Stores the maximum length of rope possible ; Iterate while low is less than or equal to high ;... | def maximumSize ( a , k ) : NEW_LINE INDENT low = 1 NEW_LINE high = max ( a ) NEW_LINE ans = - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE count = 0 NEW_LINE for c in range ( len ( a ) ) : NEW_LINE INDENT count += a // mid NEW_LINE DEDENT if ( count >= k ) : NEW_LINE INDE... |
Quadratic equation whose roots are K times the roots of given equation | Function to find the quadratic equation whose roots are K times the roots of the given equation ; Prquadratic equation ; Driver Code | def findEquation ( A , B , C , K ) : NEW_LINE INDENT print ( A , K * B , K * K * C ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A , B , C , K = 1 , 2 , 1 , 2 NEW_LINE findEquation ( A , B , C , K ) NEW_LINE DEDENT |
Maximum the value of a given expression for any pair of coordinates on a 2D plane | Function to find the maximum value of the given expression possible for any pair of co - ordinates ; Stores the differences between pairs ; Stores the maximum value ; Traverse the array arr [ ] [ ] ; While pq is not empty and difference... | def findMaxValueOfEquation ( arr , K ) : NEW_LINE INDENT pq = [ ] NEW_LINE res = - 10 ** 8 NEW_LINE for point in arr : NEW_LINE INDENT while ( len ( pq ) > 0 and point [ 0 ] - pq [ - 1 ] [ 1 ] > K ) : NEW_LINE INDENT del pq [ - 1 ] NEW_LINE DEDENT if ( len ( pq ) > 0 ) : NEW_LINE INDENT res = max ( res , pq [ - 1 ] [ 0... |
Minimum increments required to make absolute difference of all pairwise adjacent array elements even | Function to find the minimum number of increments of array elements required to make difference between all pairwise adjacent elements even ; Stores the count of odd and even elements ; Traverse the array ; Increment ... | def minOperations ( arr , n ) : NEW_LINE INDENT oddcount , evencount = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT oddcount += 1 NEW_LINE DEDENT else : NEW_LINE INDENT evencount += 1 NEW_LINE DEDENT DEDENT return min ( oddcount , evencount ) NEW_LINE DEDENT if __nam... |
Count numbers up to C that can be reduced to 0 by adding or subtracting A or B | Function to calculate GCD of the two numbers a and b ; Base Case ; Recursively find the GCD ; Function to count the numbers up to C that can be reduced to 0 by adding or subtracting A or B ; Stores GCD of A and B ; Stores the count of mult... | 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 countDistinctNumbers ( A , B , C ) : NEW_LINE INDENT g = gcd ( A , B ) NEW_LINE count = C // g NEW_LINE print ( count ) NEW_LINE DEDENT A = 2 NEW_LINE B = 3 NEW_LINE C = 5 NEW_LINE c... |
Find the last element after repeatedly removing every second element from either end alternately | Function to find the last element remaining in the array after performing the given operations ; Checks if traversal is from left to right or vice versa ; Store the elements currently present in the array ; Store the dist... | def printLastElement ( arr , N ) : NEW_LINE INDENT leftTurn = True NEW_LINE remainElements = N NEW_LINE step = 1 NEW_LINE head = 1 NEW_LINE while ( remainElements > 1 ) : NEW_LINE INDENT if ( leftTurn ) : NEW_LINE INDENT head = head + step NEW_LINE DEDENT else : NEW_LINE INDENT if ( remainElements % 2 == 1 ) : NEW_LINE... |
Distributed C candies among N boys such that difference between maximum and minimum candies received is K | Function to calculate the maximum and minimum number of candies a boy can possess ; All candies will be given to one boy ; All the candies will be given to 1 boy ; Give K candies to 1 st boy initially ; Count rem... | def max_min ( N , C , K ) : NEW_LINE INDENT maximum = 0 NEW_LINE minimum = 0 NEW_LINE if ( N == 1 ) : NEW_LINE INDENT maximum = minimum = C NEW_LINE DEDENT elif ( K >= C ) : NEW_LINE INDENT maximum = C NEW_LINE minimum = 0 NEW_LINE DEDENT else : NEW_LINE INDENT maximum = K NEW_LINE minimum = 0 NEW_LINE remain_candy = C... |
Length of smallest subarray required to be removed to make remaining elements consecutive | Function to find the length of the smallest subarray to be removed to make remaining array elements consecutive ; Store the ending index of the longest prefix consecutive array ; Traverse the array to find the longest prefix con... | def shortestSubarray ( A , N ) : NEW_LINE INDENT i = 0 NEW_LINE left_index = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i ] + 1 != A [ i + 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT left_index = i NEW_LINE right_index = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT if ( ... |
Check if a string can be split into 3 substrings such that one of them is a substring of the other two | Function to check if string S contains any character with frequency >= 3 or not ; Stores frequency of characters ; Iterate over the string ; Update the frequency of current character ; Iterate over the hash array ; ... | def freqCheck ( S , N ) : NEW_LINE INDENT hash = [ 0 ] * 26 NEW_LINE for i in range ( N ) : NEW_LINE INDENT hash [ ord ( S [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( hash [ i ] > 2 ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT DEDENT return " No " NEW_LINE DEDENT if... |
Minimize length of a string by removing suffixes and prefixes of same characters | Function to find the minimum length of the string after removing the same characters from the end and front of the two strings after dividing into 2 substrings ; Initialize two pointers ; Traverse the string S ; Current char on left poin... | def minLength ( s ) : NEW_LINE INDENT i = 0 ; j = len ( s ) - 1 NEW_LINE while ( i < j and s [ i ] == s [ j ] ) : NEW_LINE INDENT d = s [ i ] NEW_LINE while ( i <= j and s [ i ] == d ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT while ( i <= j and s [ j ] == d ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT return j - i... |
Number of Binary Search Trees of height H consisting of H + 1 nodes | Function to calculate x ^ y modulo 1000000007 in O ( log y ) ; Stores the value of x ^ y ; Update x if it exceeds mod ; If x is divisible by mod ; If y is odd , then multiply x with result ; Divide y by 2 ; Update the value of x ; Return the value of... | def power ( x , y ) : NEW_LINE INDENT mod = 1000000007 NEW_LINE res = 1 NEW_LINE x = x % mod NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % mod NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % mod NEW_LINE DEDENT ... |
Check if any pair of consecutive 1 s can be separated by at most M 0 s by circular rotation of a Binary String | Function to check if any pair of consecutive 1 s can be separated by at most M 0 s by circular rotation of string S ; Stores the indices of all 1 s ; Store the number of pairs separated by at least M 0 s ; T... | def rotateString ( n , m , s ) : NEW_LINE INDENT v = [ ] NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( 1 , len ( v ) ) : NEW_LINE INDENT if ( ( v [ i ] - v [ i - 1 ] - 1 ) > m ) : NEW_LINE INDENT cnt += 1... |
Number obtained by reducing sum of digits of 2 N into a single digit | Function to find the number obtained by reducing sum of digits of 2 ^ N into a single digit ; Stores answers for different values of N ; Driver Code | def findNumber ( N ) : NEW_LINE INDENT ans = [ 1 , 2 , 4 , 8 , 7 , 5 ] NEW_LINE return ans [ N % 6 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE print ( findNumber ( N ) ) NEW_LINE DEDENT |
Check if two piles of coins can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other | Function to check if two given piles can be emptied by repeatedly removing 2 coins from a pile and 1 coin from the other ; If maximum of A & B exceeds the twice of minimum of A & B ; Not possible to empty t... | def canBeEmptied ( A , B ) : NEW_LINE INDENT if ( max ( A , B ) > 2 * min ( A , B ) ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT if ( ( A + B ) % 3 == 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main ... |
Maximum index a pointer can reach in N steps by avoiding a given index B | Set 2 | Function to find the maximum index the pointer can reach ; Initialize two pointers ; Stores number of steps ; Stores sum of first N natural numbers ; Increment i with j ; Increment j with 1 ; Increment count ; If i points to B ; Break ; ... | def maximumIndex ( N , B ) : NEW_LINE INDENT i , j = 0 , 1 NEW_LINE cnt = 0 NEW_LINE sum = N * ( N + 1 ) // 2 NEW_LINE flag = False NEW_LINE while ( cnt < N ) : NEW_LINE INDENT i += j NEW_LINE j += 1 NEW_LINE cnt += 1 NEW_LINE if ( i == B ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( not fl... |
Generate longest possible array with product K such that each array element is divisible by its previous adjacent element | Function to construct longest array with product K such that each element is divisible by its previous element ; Stores the prime factors of K ; Stores the power to which primefactor i is raised ;... | def findLongestArray ( K ) : NEW_LINE INDENT primefactors = [ ] NEW_LINE K_temp = K NEW_LINE i = 2 NEW_LINE while i * i <= K : NEW_LINE INDENT count = 0 NEW_LINE while ( K_temp % i == 0 ) : NEW_LINE INDENT K_temp //= i NEW_LINE count += 1 NEW_LINE DEDENT if ( count > 0 ) : NEW_LINE INDENT primefactors . append ( [ coun... |
Minimum number of steps required to place all 1 s at a single index | Function to print minimum steps required to shift all 1 s to a single index in a binary array ; Size of array ; Used to store cumulative sum ; Initialize count ; Traverse the array in forward direction ; Steps needed to store all previous ones to ith... | def minsteps ( A ) : NEW_LINE INDENT n = len ( A ) NEW_LINE left , right , res = [ 0 ] * n , [ 0 ] * n , [ 0 ] * n NEW_LINE count = A [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT left [ i ] = left [ i - 1 ] + count NEW_LINE count += A [ i ] NEW_LINE DEDENT count = A [ n - 1 ] NEW_LINE for i in range ( n - ... |
Minimize flips on K | Function to find the minimum number K - length subarrays required to be flipped to make all array elements 1 ; Stores whether an element can be flipped or not ; Store the required number of flips ; Traverse the array , A [ ] ; Find the prefix sum for the indices i > 0 ; Check if the current elemen... | def minimumOperations ( A , K ) : NEW_LINE INDENT isflipped = [ 0 ] * ( len ( A ) + 1 ) NEW_LINE ans = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( i > 0 ) : NEW_LINE INDENT isflipped [ i ] += isflipped [ i - 1 ] NEW_LINE isflipped [ i ] %= 2 NEW_LINE DEDENT if ( A [ i ] == 0 and not isflipped [ i ] )... |
Calculate sum of scores after N days based on given conditions | Function to c sum of calculate sum of scores after n days ; Store the required sum ; Store the score on previous monday and current day respectively ; Iterate over the range [ 1 , n ] ; If the current day is monday ; Increment score of prev_monday by 1 ; ... | def findScoreSum ( n ) : NEW_LINE INDENT total = 0 NEW_LINE prev_monday , curr_day = 0 , 0 NEW_LINE for day in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( day % 7 == 1 ) : NEW_LINE INDENT prev_monday += 1 NEW_LINE curr_day = prev_monday NEW_LINE DEDENT total += curr_day NEW_LINE curr_day += 1 NEW_LINE DEDENT print ( tot... |
Calculate sum of scores after N days based on given conditions | Function to calculate sum of scores after n days ; Store the number of full weeks ; Stores the remaining days in the last week ; Store the sum of scores in the first F full weeks ; Store the sum of scores in the last week ; Print the result ; Driver Code | def findScoreSum ( n ) : NEW_LINE INDENT F = n // 7 NEW_LINE D = n % 7 NEW_LINE fullWeekScore = ( 49 + 7 * F ) * F // 2 NEW_LINE lastNonFullWeekScore = ( 2 * F + D + 1 ) * D // 2 NEW_LINE print ( fullWeekScore + lastNonFullWeekScore ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE find... |
Largest number up to N whose modulus with X is equal to Y modulo X | Function to print the largest number upto N whose modulus with X is same as Y % X ; Stores the required number ; Update num as the result ; Return the resultant number ; Driver Code | def maximumNum ( X , Y , N ) : NEW_LINE INDENT num = 0 NEW_LINE if ( N - N % X + Y <= N ) : NEW_LINE INDENT num = N - N % X + Y NEW_LINE DEDENT else : NEW_LINE INDENT num = N - N % X - ( X - Y ) NEW_LINE DEDENT return num NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 10 NEW_LINE Y = 5 NEW_LINE N... |
Number of points lying inside a rectangle as well as a triangle | Function to calculate area of a triangle ; Return the resultant area ; Function to check if a point lies inside a triangle or not ; Calculate area of triangle ABC ; Calculate area of triangle formed by connecting B , C , point ; Calculate area of triangl... | def getArea ( x1 , y1 , x2 , y2 , x3 , y3 ) : NEW_LINE INDENT return abs ( ( x1 * ( y2 - y3 ) + x2 * ( y3 - y1 ) + x3 * ( y1 - y2 ) ) / 2 ) NEW_LINE DEDENT def isInside ( triangle , point ) : NEW_LINE INDENT A , B , C = triangle NEW_LINE x , y = point NEW_LINE ABC = getArea ( A [ 0 ] , A [ 1 ] , B [ 0 ] , B [ 1 ] , C [... |
Generate an N | Function to calculate GCD of two integers ; Function to calculate GCD of a given array ; Utility function to check for all the possible combinations ; If an N - length sequence is obtained ; If GCD of the sequence is K ; Otherwise ; Add an element from the first array ; Recursively proceed further ; If ... | def GCD ( a , b ) : NEW_LINE INDENT if not b : NEW_LINE INDENT return a NEW_LINE DEDENT return GCD ( b , a % b ) NEW_LINE DEDENT def GCDArr ( a ) : NEW_LINE INDENT ans = a [ 0 ] NEW_LINE for i in a : NEW_LINE INDENT ans = GCD ( ans , i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def findSubseqUtil ( a , b , ans , k , ... |
Minimize count of swaps of adjacent elements required to make an array increasing | Function to count minimum number of operations required to obtain an increasing array from given array A [ ] ; Store the required result ; Traverse the array A [ ] ; If the current element is not in its correct position ; Check if it is... | def minimumOperations ( A , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ i ] != ( i + 1 ) ) : NEW_LINE INDENT if ( ( ( i - 1 ) >= 0 ) and A [ i - 1 ] == ( i + 1 ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE A [ i ] , A [ i - 1 ] = A [ i - 1 ] , A [ i ] NEW_LINE DEDENT... |
Count occurrences of an element in a matrix of size N * N generated such that each element is equal to product of its indices | Set | Function to count the occurrences of X in the generated square matrix ; Store the required result ; Iterate over the range [ 1 , N ] ; Check if x is a multiple of i or not ; Check if the... | def countOccurrences ( n , x ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT if ( x // i <= n ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 NEW... |
Reduce all array elements to zero by performing given operations thrice | Function to reduce all array elements to zero ; If size of array is 1 ; First operation ; 2 nd Operation ; 3 rd Operation ; Otherwise ; 1 st Operation ; 2 nd Operation ; 3 rd Operation ; Driver Code ; Input ; Function call to make all array eleme... | def ConvertArray ( arr , N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( " Operation β 1 β : " , 1 , 1 ) NEW_LINE print ( " Added β elements : " , - 1 * arr [ 0 ] ) NEW_LINE print ( " " , end β = β " " ) NEW_LINE print ( " Operation β 2 β : " , 1 , 1 ) NEW_LINE print ( " Added β elements : " , 1 * arr [ 0... |
Count pairs from an array with even product of count of distinct prime factors | Python 3 implementation of the above approach ; Function to calculate count of distinct prime factors of a number ; Sieve of Eratosthenes ; Function to count pairs with even product of distinct prime factors ; Stores count of distinct prim... | MAX = 1000000 NEW_LINE def countOfPrimefactors ( CountDistinct ) : NEW_LINE INDENT global MAX NEW_LINE prime = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE for i in range ( MAX + 1 ) : NEW_LINE INDENT CountDistinct [ i ] = 0 NEW_LINE prime [ i ] = True NEW_LINE DEDENT for i in range ( 2 , MAX + 1 , 1 ) : NEW_LINE INDENT i... |
Minimum array elements required to be subtracted from either end to reduce K to 0 | Function to find the length of longest subarray having sum K ; Stores the index of the prefix sum ; Traverse the given array ; Update sum ; If the subarray starts from index 0 ; Add the current prefix sum with index if it is not present... | def longestSubarray ( arr , N , K ) : NEW_LINE INDENT um = { } NEW_LINE sum , maxLen = 0 , 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE if ( sum == K ) : NEW_LINE INDENT maxLen = i + 1 NEW_LINE DEDENT if ( sum not in um ) : NEW_LINE INDENT um [ sum ] = i NEW_LINE DEDENT if ( ( sum - K ) i... |
Minimum number of digits required to be removed to make a number divisible by 4 | Function to count the minimum number of digits required to be removed to make a given number divisible by 4 ; Store the size of the string ; Stores the required result ; Check for every pair of digits if the number formed by them is divis... | def minimumDeletions ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = n NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT t = ord ( s [ i ] ) - ord ( '0' ) NEW_LINE if ( t % 2 == 0 ) : NEW_LINE INDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT num = ( ord ( s [ j ] ) - ord ( '0' ) ) * 10 +... |
Generate a sequence such that float division of array elements is maximized | Function to place the parenthesis such that the result is maximized ; Store the required string ; Add the first integer to string ; If the size of array is 1 ; If the size of array is 2 , print the 1 st integer followed by / operator followed... | def generateSequence ( arr , n ) : NEW_LINE INDENT ans = " " NEW_LINE ans = str ( arr [ 0 ] ) NEW_LINE if ( n == 1 ) : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT elif ( n == 2 ) : NEW_LINE INDENT print ( ans + " / " + str ( arr [ 1 ] ) ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT else : NEW_LINE INDENT ans += " / ( " ... |
Count of pairs having even and odd LCM from an array | Function to find count of distinct pairs having even LCM and odd LCM ; Store the total number of pairs ; Stores the count of odd numbers in the array ; Traverse the array arr [ ] ; Update the count of pairs with odd LCM ; Print the count of required pairs ; Driver ... | def LCMPairs ( arr , N ) : NEW_LINE INDENT total_pairs = ( N * ( N - 1 ) ) / 2 NEW_LINE odd = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT DEDENT odd = ( odd * ( odd - 1 ) ) // 2 NEW_LINE print ( " Even β = " , int ( total_pairs - odd ) , " , " , " β ... |
Value required to be added to N to obtain the sum of first M multiples of K | Function to print the value to be added to N to obtain sum of first M multiples of K ; Store the sum of the first M multiples of K ; Store the value to be added to obtain N ; Input | def printNumber ( N , K , M ) : NEW_LINE INDENT sum = K * ( M * ( M + 1 ) / 2 ) NEW_LINE return sum - N NEW_LINE DEDENT N = 17 NEW_LINE K = 3 NEW_LINE M = 4 NEW_LINE print ( int ( printNumber ( N , K , M ) ) ) NEW_LINE |
Count even and odd Bitwise XORs of consecutive numbers in a range [ L , R ] starting from L | Prcount of even and odd numbers of XOR value from L to R ; Store the number of elements between L and R ; Count of even XOR values ; If L is odd and range % 4 = 3 ; Increment even by 1 ; If L is even and range % 4 != 0 ; Incre... | def countEvenOdd ( L , R ) : NEW_LINE INDENT range = R - L + 1 ; NEW_LINE even = ( range // 4 ) * 2 ; NEW_LINE if ( ( L & 1 ) != 0 and ( range % 4 == 3 ) ) : NEW_LINE INDENT even += 1 ; NEW_LINE DEDENT elif ( ( L & 1 ) == 0 and ( range % 4 != 0 ) ) : NEW_LINE INDENT even += 1 ; NEW_LINE DEDENT print ( " Even β = β " , ... |
Minimize swaps of same | Function to count the number of swaps required to make the sum of ASCII values of the characters of both strings odd ; Initialize alphabets with value ; Initialize values for each alphabet ; Size of the string ; Sum of S ; Sum of T ; Stores whether there is any index i such that S [ i ] and T [... | def countSwaps ( S , T ) : NEW_LINE INDENT value = [ 0 ] * 26 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT value [ i ] = i + 1 NEW_LINE DEDENT N = len ( S ) NEW_LINE sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE flag = False NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum1 += value [ ord ( S [ i ] ) - ord ( ' a ' ) ] NEW... |
Count distinct prime triplets up to N such that sum of two primes is equal to the third prime | Python3 program for the above approach ; Function to check if a number is a prime or not ; Function to count the number of valid prime triplets ; Stores the count of prime triplets ; Iterate from 2 to N and check for each p ... | import math NEW_LINE def isPrime ( N ) : NEW_LINE INDENT if ( N <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , int ( math . sqrt ( N ) + 1 ) ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def countPrimeTuples ( N ) : NE... |
Count pairs from an array whose Bitwise OR is greater than Bitwise AND | Function to count the number of pairs ( i , j ) their Bitwise OR is greater than Bitwise AND ; Store the required answer ; Check for all possible pairs ; If the condition satisfy then increment count by 1 ; Prthe answer ; Driver Code ; Function Ca... | def countPairs ( A , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( ( A [ i ] A [ j ] ) > ( A [ i ] & A [ j ] ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT print ( count ) ; NEW_LINE DEDENT if __name__ == ' _ _ mai... |
Count maximum number of consumable candies | Function to find the count of maximum consumable candies ; Store the count of total candies ; Stores the count of maximum consumable candies ; Checks if it is safe to counsume all candies ; Traverse the array arr ; If A [ i ] + M is greater than B [ i ] ; Mark all_safe as fa... | def maximumCandy ( candies , safety , N , M ) : NEW_LINE INDENT total = 0 NEW_LINE ans = 10 ** 8 NEW_LINE all_safe = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( candies [ i ] + M > safety [ i ] ) : NEW_LINE INDENT all_safe = False NEW_LINE ans = min ( ans , safety [ i ] ) NEW_LINE DEDENT else : NEW_LINE I... |
Check if two arrays can be made equal by swapping pairs of one of the arrays | Function to check if two arrays can be made equal or not by swapping pairs of only one of the arrays ; Stores elements required to be replaced ; To check if the arrays can be made equal or not ; Traverse the array ; If array elements are not... | def checkArrays ( arr1 , arr2 , N ) : NEW_LINE INDENT count = 0 NEW_LINE flag = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr1 [ i ] != arr2 [ i ] ) : NEW_LINE INDENT if ( arr1 [ i ] == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count -= 1 NEW_LINE if ( count < 0 ) : NEW_LIN... |
Generate an N | Function to construct an array with sum of each subarray divisible by K ; Traverse a loop from 1 to N ; Pri - th multiple of K ; Driver Code | def construct_Array ( N , K ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( K * i , end = " β " ) NEW_LINE DEDENT DEDENT N = 3 NEW_LINE K = 3 NEW_LINE construct_Array ( N , K ) NEW_LINE |
Generate an N | Fun dtion to print the required sequence ; Stores count of even and odd elements ; Stores sum of even and odd elements ; Print N / 2 even elements ; Print N / 2 - 1 odd elements ; Print final odd element ; Driver Code | def Print ( N ) : NEW_LINE INDENT if ( ( N / 2 ) % 2 or ( N % 2 ) ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT CurEven = 2 NEW_LINE CurOdd = 1 NEW_LINE SumOdd = 0 NEW_LINE SumEven = 0 NEW_LINE for i in range ( N // 2 ) : NEW_LINE INDENT print ( CurEven , end = " β " ) NEW_LINE SumEven += CurEven NE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.