text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Count of pairs satisfying the given condition | Function to return the number of pairs satisfying the equation ; Converting integer b to string by using to_function ; Loop to check if all the digits of b are 9 or not ; If '9' doesn 't appear then break the loop ; If all the digits of b contain 9 then multiply a with l...
def countPair ( a , b ) : NEW_LINE INDENT s = str ( b ) NEW_LINE i = 0 NEW_LINE while i < ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] != '9' ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT result = 0 NEW_LINE if ( i == len ( s ) ) : NEW_LINE INDENT result = a * len ( s ) NEW_LINE DEDENT else : NEW_LIN...
Partition the digits of an integer such that it satisfies a given condition | Function to generate sequence from the given string ; Initialize vector to store sequence ; First add all the digits of group A from left to right ; Then add all the digits of group B from left to right ; Return the sequence ; Function that r...
def makeSeq ( s , a ) : NEW_LINE INDENT seq = [ ] ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' A ' ) : NEW_LINE INDENT seq . append ( a [ i ] ) ; NEW_LINE DEDENT DEDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' B ' ) : NEW_LINE INDENT seq . append ( a [ i ] ) ; NEW_...
Area of the circle that has a square and a circle inscribed in it | Python3 implementation of the approach ; Function to return the required area ; Calculate the area ; Driver code
import math NEW_LINE def getArea ( a ) : NEW_LINE INDENT area = ( math . pi * a * a ) / 4 NEW_LINE return area NEW_LINE DEDENT a = 3 NEW_LINE print ( ' { 0 : . 6f } ' . format ( getArea ( a ) ) ) NEW_LINE
Check if all the elements can be made of same parity by inverting adjacent elements | Function to check if parity can be made same or not ; Iterate and count the parity ; Odd ; Even ; Condition check ; Driver Code
def flipsPossible ( a , n ) : NEW_LINE INDENT count_odd = 0 ; count_even = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] & 1 ) : NEW_LINE INDENT count_odd += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT count_even += 1 ; NEW_LINE DEDENT DEDENT if ( count_odd % 2 and count_even % 2 ) : NEW_LINE INDENT r...
Queries On Array with disappearing and reappearing elements | Function to perform the queries ; Size of the array with 1 - based indexing ; Number of queries ; Iterating through the queries ; If m is more than the size of the array ; Count of turns ; Find the remainder ; If the remainder is 0 and turn is odd then the a...
def PerformQueries ( a , vec ) : NEW_LINE INDENT ans = [ ] ; NEW_LINE n = len ( a ) - 1 ; NEW_LINE q = len ( vec ) ; NEW_LINE for i in range ( q ) : NEW_LINE INDENT t = vec [ i ] [ 0 ] ; NEW_LINE m = vec [ i ] [ 1 ] ; NEW_LINE if ( m > n ) : NEW_LINE INDENT ans . append ( - 1 ) ; NEW_LINE continue ; NEW_LINE DEDENT tur...
Number of pairs in an array having sum equal to product | Function to return the count of the required pairs ; Find the count of 0 s and 2 s in the array ; Find the count of required pairs ; Return the count ; Driver code
def sumEqualProduct ( a , n ) : NEW_LINE INDENT zero = 0 NEW_LINE two = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] == 0 : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT if a [ i ] == 2 : NEW_LINE INDENT two += 1 NEW_LINE DEDENT DEDENT cnt = ( zero * ( zero - 1 ) ) // 2 + ( two * ( two - 1 ) ) // 2 NEW_LINE...
Minimize the sum of digits of A and B such that A + B = N | Function to return the minimum possible sum of digits of A and B such that A + B = n ; Find the sum of digits of n ; If num is a power of 10 ; Driver code
def minSum ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT sum += ( n % 10 ) ; NEW_LINE n //= 10 ; NEW_LINE DEDENT if ( sum == 1 ) : NEW_LINE INDENT return 10 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 1884 ; NEW_LINE print ( minSum ...
Multiplication on Array : Range update query in O ( 1 ) | Creates a mul [ ] array for A [ ] and returns it after filling initial values . ; Does range update ; Prints updated Array ; Driver code ; ; Array to be updated ; Create and fill mul and div Array
def initialize ( mul , div , size ) : NEW_LINE INDENT for i in range ( 1 , size ) : NEW_LINE INDENT mul [ i ] = ( mul [ i ] * mul [ i - 1 ] ) / div [ i ] ; NEW_LINE DEDENT DEDENT def update ( l , r , x , mul , div ) : NEW_LINE INDENT mul [ l ] *= x ; NEW_LINE div [ r + 1 ] *= x ; NEW_LINE DEDENT def printArray ( ar , m...
Optimal Strategy for a Game | Special Gold Coin | Function to return the winner of the game ; To store the count of silver coins ; Update the position of the gold coin ; First player will win the game ; Driver code
def getWinner ( string , length ) : NEW_LINE INDENT total = 0 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( string [ i ] == ' S ' ) : NEW_LINE INDENT total += 1 ; NEW_LINE DEDENT DEDENT if ( ( total % 2 ) == 1 ) : NEW_LINE INDENT return " First " ; NEW_LINE DEDENT return " Second " ; NEW_LINE DEDENT if __...
Find the coordinates of a triangle whose Area = ( S / 2 ) | Python3 implementation of the approach ; Function to find the triangle with area = ( S / 2 ) ; Fix the two pairs of coordinates ; Find ( X3 , Y3 ) with integer coordinates ; Driver code
MAX = 1000000000 ; NEW_LINE def findTriangle ( S ) : NEW_LINE INDENT X1 = 0 ; Y1 = 0 ; NEW_LINE X2 = MAX ; Y2 = 1 ; NEW_LINE X3 = ( MAX - S % MAX ) % MAX ; NEW_LINE Y3 = ( S + X3 ) / MAX ; NEW_LINE print ( " ( " , X1 , " , " , Y1 , " ) " ) ; NEW_LINE print ( " ( " , X2 , " , " , Y2 , " ) " ) ; NEW_LINE print ( " ( " , ...
Rearrange array elements such that Bitwise AND of first N | Utility function to print the elements of an array ; Function to find the required arrangement ; There has to be atleast 2 elements ; Minimum element from the array ; Swap any occurrence of the minimum element with the last element ; Find the bitwise AND of th...
def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT def findArrangement ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT print ( " - 1" , end = " " ) ; NEW_LINE return ; NEW_LINE DEDENT minVal = min ( arr ) ; NEW_LINE f...
Maximum prime moves to convert X to Y | Function to return the maximum operations required to convert X to Y ; X cannot be converted to Y ; If the difference is 1 ; If the difference is even ; Add 3 to X and the new difference will be even ; Driver code
def maxOperations ( X , Y ) : NEW_LINE INDENT if ( X > Y ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT diff = Y - X ; NEW_LINE if ( diff == 1 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( diff % 2 == 0 ) : NEW_LINE INDENT return ( diff // 2 ) ; NEW_LINE DEDENT return ( 1 + ( ( diff - 3 ) // 2 ) ) ; NEW_LINE ...
Sum of Digits of the Good Strings | Python3 implementation of the approach ; To store the states of the dp ; Function to fill the dp table ; Sum of digits of the string of length 1 is i as i is only number in that string and count of good strings of length 1 that end with i is also 1 ; Adjacent digits are different ; I...
DIGITS = 10 ; NEW_LINE MAX = 10000 ; NEW_LINE MOD = 1000000007 ; NEW_LINE dp = [ [ 0 for i in range ( DIGITS ) ] for i in range ( MAX ) ] ; NEW_LINE cnt = [ [ 0 for i in range ( DIGITS ) ] for i in range ( MAX ) ] ; NEW_LINE def precompute ( ) : NEW_LINE INDENT for i in range ( DIGITS ) : NEW_LINE INDENT dp [ 1 ] [ i ]...
Count non | Python implementation of the approach ; Function to pre - compute the sequence ; For N = 1 the answer will be 2 ; Starting two terms of the sequence ; Compute the rest of the sequence with the relation F [ i ] = F [ i - 1 ] + F [ i - 2 ] ; Driver code ; Pre - compute the sequence
N = 10000 ; NEW_LINE MOD = 1000000007 ; NEW_LINE F = [ 0 ] * N ; NEW_LINE def precompute ( ) : NEW_LINE INDENT F [ 1 ] = 2 ; NEW_LINE F [ 2 ] = 3 ; NEW_LINE F [ 3 ] = 4 ; NEW_LINE for i in range ( 4 , N ) : NEW_LINE INDENT F [ i ] = ( F [ i - 1 ] + F [ i - 2 ] ) % MOD ; NEW_LINE DEDENT DEDENT n = 8 ; NEW_LINE precomput...
Minimize sum by dividing all elements of a subarray by K | Python3 implementation of the approach ; Function to return the maximum subarray sum ; Function to return the minimized sum of the array elements after performing the given operation ; Find maximum subarray sum ; Find total sum of the array ; Maximum subarray s...
import sys NEW_LINE def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - ( sys . maxsize - 1 ) ; NEW_LINE max_ending_here = 0 ; NEW_LINE for i in range ( size ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] ; NEW_LINE if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_end...
Minimum numbers with one 's place as 9 to be added to get N | Function to find minimum count of numbers ( with one 's digit 9) that sum up to N ; Fetch one 's digit ; Apply Cases mentioned in approach ; If no possible answer exists ; Driver Code
def findMin ( N : int ) : NEW_LINE INDENT digit = N % 10 NEW_LINE if digit == 0 and N >= 90 : NEW_LINE INDENT return 10 NEW_LINE DEDENT elif digit == 1 and N >= 81 : NEW_LINE INDENT return 9 NEW_LINE DEDENT elif digit == 2 and N >= 72 : NEW_LINE INDENT return 8 NEW_LINE DEDENT elif digit == 3 and N >= 63 : NEW_LINE IND...
Random list of M non | Python3 implementation of the approach ; Utility function to print the elements of an array ; Function to generate a list of m random non - negative integers whose sum is n ; Create an array of size m where every element is initialized to 0 ; To make the sum of the final list as n ; Increment any...
from random import randint NEW_LINE def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT def randomList ( m , n ) : NEW_LINE INDENT arr = [ 0 ] * m ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ randint ( 0 , n ) % m ] += 1...
Maximum String Partition | Return the count of string ; P will store the answer ; Current will store current string Previous will store the previous that has been taken already ; Add a character to current string ; Here we will create a partition and update the previous with current string ; Now we will clear the curre...
def maxPartition ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE P = 0 NEW_LINE current = " " NEW_LINE previous = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT current += s [ i ] NEW_LINE if ( current != previous ) : NEW_LINE INDENT previous = current NEW_LINE current = " " NEW_LINE P += 1 NEW_LINE DEDENT DEDENT r...
How to learn Pattern printing easily ? |
N = 4 ; NEW_LINE print ( " Value ▁ of ▁ N : ▁ " , N ) ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT min = i if i < j else j ; NEW_LINE print ( N - min + 1 , end = " " ) ; NEW_LINE DEDENT for j in range ( N - 1 , 0 , - 1 ) : NEW_LINE INDENT min = i if i < j else...
Find the smallest positive number missing from an unsorted array | Set 3 | Function to find the smallest positive missing number ; Default smallest Positive Integer ; Store values in set which are greater than variable m ; Store value when m is less than current index of given array ; Increment m when it is equal to cu...
def findMissingPositive ( arr , n ) : NEW_LINE INDENT m = 1 NEW_LINE x = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( m < arr [ i ] ) : NEW_LINE INDENT x . append ( arr [ i ] ) NEW_LINE DEDENT elif ( m == arr [ i ] ) : NEW_LINE INDENT m = m + 1 NEW_LINE while ( x . count ( m ) ) : NEW_LINE INDENT x . remove...
Sum of all second largest divisors after splitting a number into one or more parts | Python 3 program to find sum of all second largest divisor after splitting a number into one or more parts ; Function to find a number is prime or not ; If there is any divisor ; Function to find the sum of all second largest divisor a...
from math import sqrt NEW_LINE def prime ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def Min_Sum ( n ) : NEW_LI...
Count pairs of strings that satisfy the given conditions | Function that returns true if c is vowel ; Function to return the count of required pairs ; For every of the array ; Vector to store the vowels of the current string ; If current character is a vowel ; If current contains vowels ; Create tuple ( first vowel , l...
def is_vowel ( c ) : NEW_LINE INDENT return ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) NEW_LINE DEDENT def count ( s , n ) : NEW_LINE INDENT map = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT vowel = [ ] NEW_LINE for j in range ( len ( s [ i ] ) ) : NEW_LINE INDENT if ( is_vowel ...
Find maximum value of the last element after reducing the array with given operations | Function to return the maximized value ; Overall minimum absolute value of some element from the array ; Add all absolute values ; Count positive and negative elements ; Both positive and negative values are present ; Only positive ...
def find_maximum_value ( a , n ) : NEW_LINE INDENT sum = 0 NEW_LINE minimum = 10 ** 9 NEW_LINE pos = 0 NEW_LINE neg = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT minimum = min ( minimum , abs ( a [ i ] ) ) NEW_LINE sum += abs ( a [ i ] ) NEW_LINE if ( a [ i ] >= 0 ) : NEW_LINE INDENT pos += 1 NEW_LINE DEDENT else...
Find Nth smallest number that is divisible by 100 exactly K times | Function to find the Nth smallest number ; If N is divisible by 100 then we multiply N + 1 otherwise , it will be divisible by 100 more than K times ; convert integer to string ; if N is not divisible by 100 ; convert integer to string ; add 2 * K 0 's...
def find_number ( N , K ) : NEW_LINE INDENT r = " " NEW_LINE if ( N % 100 == 0 ) : NEW_LINE INDENT N += 1 ; NEW_LINE r = str ( N ) NEW_LINE DEDENT else : NEW_LINE INDENT r = str ( N ) NEW_LINE DEDENT for i in range ( 1 , K + 1 ) : NEW_LINE INDENT r += "00" NEW_LINE DEDENT return r NEW_LINE DEDENT N = 1000 NEW_LINE K = ...
Count of adjacent Vowel Consonant Pairs | Function to count the adjacent pairs of consonant and vowels in the string ; Using a set to store the vowels so that checking each character becomes easier ; Variable to store number of consonant - vowel pairs ; If the ith character is not found in the set , means it is a conso...
def countPairs ( s ) : NEW_LINE INDENT st = set ( ) ; NEW_LINE st . add ( ' a ' ) ; NEW_LINE st . add ( ' e ' ) ; NEW_LINE st . add ( ' i ' ) ; NEW_LINE st . add ( ' o ' ) ; NEW_LINE st . add ( ' u ' ) ; NEW_LINE count = 0 ; NEW_LINE n = len ( s ) ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( s [ i ] not i...
Find the largest interval that contains exactly one of the given N integers . | Function to return the maximum size of the required interval ; Insert the borders for array ; Sort the elements in ascending order ; To store the maximum size ; To store the range [ L , R ] such that only v [ i ] lies within the range ; Tot...
def maxSize ( v , n ) : NEW_LINE INDENT v . append ( 0 ) NEW_LINE v . append ( 100001 ) NEW_LINE n += 2 NEW_LINE v = sorted ( v ) NEW_LINE mx = 0 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT L = v [ i - 1 ] + 1 NEW_LINE R = v [ i + 1 ] - 1 NEW_LINE cnt = R - L + 1 NEW_LINE mx = max ( mx , cnt ) NEW_LINE DEDE...
Maximum length of subarray such that sum of the subarray is even | Function to find Length of the longest subarray such that Sum of the subarray is even ; Check if Sum of complete array is even ; if ( Sum % 2 == 0 ) : total Sum is already even ; Find an index i such the a [ i ] is odd and compare Length of both halfs e...
def maxLength ( a , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE Len = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum += a [ i ] NEW_LINE return n NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 2 == 1 ) : NEW_LINE INDENT Len = max ( Len , max ( n - i - 1 , i ) ) NEW_LINE DEDENT DEDENT return Len...
Find a Symmetric matrix of order N that contain integers from 0 to N | Function to generate the required matrix ; Form cyclic array of elements 1 to n - 1 ; Store initial array into final array ; Fill the last row and column with 0 's ; Swap 0 and the number present at the current indexed row ; Also make changes in the...
def solve ( n ) : NEW_LINE INDENT initial_array = [ [ 0 for i in range ( n - 1 ) ] for j in range ( n - 1 ) ] NEW_LINE final_array = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT initial_array [ 0 ] [ i ] = i + 1 NEW_LINE DEDENT for i in range ( 1 , n - 1 ) : NE...
Generate original array from difference between every two consecutive elements | Function to print the required permutation ; Take x = 0 for simplicity ; Calculate athe differences and store it in a vector ; Preserve the original array ; Check if athe consecutive elements have difference = 1 ; If consecutive elements d...
def findPerm ( n , differences ) : NEW_LINE INDENT ans = [ ] NEW_LINE ans . append ( 0 ) NEW_LINE x = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT diff = differences [ i ] NEW_LINE x = x + diff NEW_LINE ans . append ( x ) NEW_LINE DEDENT anss = ans NEW_LINE ans = sorted ( ans ) NEW_LINE flag = - 1 NEW_LINE for...
Find smallest number K such that K % p = 0 and q % K = 0 | Function to return the minimum value K such that K % p = 0 and q % k = 0 ; If K is possible ; No such K is possible ; Driver code
def getMinVal ( p , q ) : NEW_LINE INDENT if q % p == 0 : NEW_LINE INDENT return p NEW_LINE DEDENT return - 1 NEW_LINE DEDENT p = 24 ; q = 48 NEW_LINE print ( getMinVal ( p , q ) ) NEW_LINE
Sort the numbers according to their sum of digits | Function to return the sum of the digits of n ; Function to sort the array according to the sum of the digits of elements ; Vector to store digit sum with respective element ; Inserting digit sum with element in the vector pair ; Quick sort the vector , this will sort...
def sumOfDigit ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT sum += n % 10 ; NEW_LINE n = n // 10 ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT vp = [ ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT vp . append ( [ sumOfDigit ( arr [ i ] ) , ...
Count all Prime Length Palindromic Substrings | Python3 implementation of the approach ; Function that returns True if sub - str1ing starting at i and ending at j in str1 is a palindrome ; Function to count all palindromic substr1ing whose lwngth is a prime number ; 0 and 1 are non - primes ; If prime [ p ] is not chan...
import math as mt NEW_LINE def isPalindrome ( str1 , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT if ( str1 [ i ] != str1 [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def countPrimePalindrome ( str1 , Len ) : NEW_LINE INDENT pri...
Minimum operations of the given type required to make a complete graph | Python 3 implementation of the approach ; Function to return the minimum number of steps required ; Driver Code
from math import log2 , ceil NEW_LINE def minOperations ( N ) : NEW_LINE INDENT x = log2 ( N ) NEW_LINE ans = ceil ( x ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE print ( minOperations ( N ) ) NEW_LINE DEDENT
Greatest divisor which divides all natural number in range [ L , R ] | Function to return the greatest divisor that divides all the natural numbers in the range [ l , r ] ; Driver Code
def find_greatest_divisor ( l , r ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT return l ; NEW_LINE DEDENT return 1 ; NEW_LINE DEDENT l = 2 ; NEW_LINE r = 12 ; NEW_LINE print ( find_greatest_divisor ( l , r ) ) ; NEW_LINE
Probability of getting two consecutive heads after choosing a random coin among two different types of coins | Function to return the probability of getting two consecutive heads ; Formula derived from Bayes 's theorem ; Driver code ; given the probability of getting a head for both the coins
def getProbability ( p , q ) : NEW_LINE INDENT p /= 100 NEW_LINE q /= 100 NEW_LINE probability = ( p * p + q * q ) / ( p + q ) NEW_LINE return probability NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT p = 80 NEW_LINE q = 40 NEW_LINE print ( getProbability ( p , q ) ) NEW_LINE DEDENT
Check whether bitwise OR of N numbers is Even or Odd | Function to check if bitwise OR of n numbers is even or odd ; if at least one odd number is found , then the bitwise OR of all numbers will be odd ; Bitwise OR is an odd number ; Driver code
def check ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] & 1 : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 9 , 12 , 13 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE if check ( arr , n ) : NEW_...
Time taken by Loop unrolling vs Normal loop | Python program to compare normal loops and loops with unrolling technique ; n is 8 lakhs ; t to note start time ; to store the sum ; Normal loop ; to mark end time ; to mark start time of unrolling ; Unrolling technique ( assuming that n is a multiple of 8 ) . ; to mark the...
from timeit import default_timer as clock NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 800000 ; NEW_LINE t = clock ( ) NEW_LINE sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT t = clock ( ) - t NEW_LINE print ( " sum ▁ is : ▁ " + str ( sum ) ) NEW_LINE print ( ...
Iterated Logarithm log * ( n ) | Recursive Python3 program to find value of Iterated Logarithm ; Driver code
import math NEW_LINE def _log ( x , base ) : NEW_LINE INDENT return ( int ) ( math . log ( x ) / math . log ( base ) ) NEW_LINE DEDENT def recursiveLogStar ( n , b ) : NEW_LINE INDENT if ( n > 1.0 ) : NEW_LINE INDENT return 1.0 + recursiveLogStar ( _log ( n , b ) , b ) NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NE...
Iterated Logarithm log * ( n ) | Iterative Python function to find value of Iterated Logarithm
def iterativeLogStar ( n , b ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n >= 1 ) : NEW_LINE INDENT n = _log ( n , b ) NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT
Tail Recursion | An example of tail recursive function ; The last executed statement is recursive call
def prints ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( str ( n ) , end = ' ▁ ' ) NEW_LINE prints ( n - 1 ) NEW_LINE DEDENT
Find the maximum among the count of positive or negative integers in the array | Function to find the maximum of the count of positive or negative elements ; Initialize the pointers ; Find the value of mid ; If element is negative then ignore the left half ; If element is positive then ignore the right half ; Return ma...
def findMaximum ( arr , size ) : NEW_LINE INDENT i = 0 NEW_LINE j = size - 1 NEW_LINE while ( i <= j ) : NEW_LINE INDENT mid = i + ( j - i ) // 2 NEW_LINE if ( arr [ mid ] < 0 ) : NEW_LINE INDENT i = mid + 1 NEW_LINE DEDENT elif ( arr [ mid ] > 0 ) : NEW_LINE INDENT j = mid - 1 NEW_LINE DEDENT DEDENT return max ( i , s...
Perform given queries on Queue according to the given rules | Function to perform all the queries operations on the given queue ; Stores the count query of type 1 ; Event E1 : increase countE1 ; Event E2 : add the X in set ; Event E3 : Find position of X ; Initial position is ( position - countE1 ) ; If X is already re...
def solve ( n , m , queries ) : NEW_LINE INDENT countE1 = 0 NEW_LINE removed = set ( ) NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT if ( queries [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT countE1 += 1 NEW_LINE DEDENT elif ( queries [ i ] [ 0 ] == 2 ) : NEW_LINE INDENT removed . add ( queries [ i ] [ 1 ] ) NEW_LINE DED...
Maximum index a pointer can reach in N steps by avoiding a given index B | Python 3 program for the above approach ; Function to find the maximum index reachable ; Store the answer ; Store the maximum index possible i . e , N * ( N - 1 ) ; Add bthe previous elements ; Run a loop ; Binary Search ; Driver Code
from bisect import bisect_left NEW_LINE def maxIndex ( N , B ) : NEW_LINE INDENT maximumIndexReached = 0 NEW_LINE Ans = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT maximumIndexReached += i NEW_LINE Ans . append ( i ) NEW_LINE DEDENT Ans . reverse ( ) NEW_LINE for i in range ( len ( Ans ) ) : NEW_LINE IN...
Maximize Kth largest element after splitting the given Array at most C times | Function to find the K - th maximum element after upto C operations ; Check for the base case ; Stores the count iterations of BS ; Create the left and right bounds of binary search ; Perform binary search ; Find the value of mid ; Traverse ...
def maxKth ( arr , N , C , K ) : NEW_LINE INDENT if ( N + C < K ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT iter = 300 NEW_LINE l = 0 NEW_LINE r = 1000000000.0 NEW_LINE while ( iter ) : NEW_LINE INDENT iter = iter - 1 NEW_LINE mid = ( l + r ) * 0.5 NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE for i in range ( N ) : NEW_LI...
Maximize the minimum difference between any element pair by selecting K elements from given Array | To check if selection of K elements is possible such that difference between them is greater than dif ; Selecting first element in the sorted array ; prev is the previously selected element initially at index 0 as first ...
def isPossibleToSelect ( arr , N , dif , K ) : NEW_LINE INDENT count = 1 NEW_LINE prev = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] >= ( prev + dif ) ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count == K ) : NEW_LINE INDENT return True NEW_LINE DEDENT prev = arr [ i ] NEW_LINE DEDENT...
Find maximum height to cut all chocolates horizontally such that at least K amount remains | Function to find the sum of remaining chocolate after making the horizontal cut at height mid ; Stores the sum of chocolates ; Traverse the array arr [ ] ; If the height is at least mid ; Return the possible sum ; Function to f...
def cal ( arr , mid ) : NEW_LINE INDENT chocolate = 0 NEW_LINE for i in arr : NEW_LINE INDENT if i >= mid : NEW_LINE INDENT chocolate += i - mid NEW_LINE DEDENT DEDENT return chocolate NEW_LINE DEDENT def maximumCut ( arr , K ) : NEW_LINE INDENT low = 0 NEW_LINE high = max ( arr ) NEW_LINE while low <= high : NEW_LINE ...
Koko Eating Bananas | Python implementation for the above approach ; to get the ceil value ; in case of odd number ; in case of even number ; check if time is less than or equals to given hour ; as minimum speed of eating must be 1 ; Maximum speed of eating is the maximum bananas in given piles ; Check if the mid ( hou...
def check ( bananas , mid_val , H ) : NEW_LINE INDENT time = 0 ; NEW_LINE for i in range ( len ( bananas ) ) : NEW_LINE INDENT if ( bananas [ i ] % mid_val != 0 ) : NEW_LINE time += bananas [ i ] // mid_val + 1 ; NEW_LINE else : NEW_LINE time += bananas [ i ] // mid_val NEW_LINE DEDENT if ( time <= H ) : NEW_LINE INDEN...
Minimize the sum of pair which upon removing divides the Array into 3 subarrays | Python 3 implementation of the above approach ; Function to find minimum possible sum of pair which breaks the array into 3 non - empty subarrays ; prefixMin [ i ] contains minimum element till i ; Driver Code ; Given array
import sys NEW_LINE def minSumPair ( arr , N ) : NEW_LINE INDENT if ( N < 5 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT prefixMin = [ 0 for i in range ( N ) ] NEW_LINE prefixMin [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , N - 1 , 1 ) : NEW_LINE INDENT prefixMin [ i ] = min ( arr [ i ] , prefixMin [ i - 1 ] ) NEW...
Minimum time remaining for safety alarm to start | Function to check if the value of mid as the minimum number of hours satisfies the condition ; Stores the sum of speed ; Iterate over the range [ 0 , N ] ; Find the value of speed ; If the bike is considered to be fast add it in sum ; Return the resultant sum ; Functio...
def check ( H , A , mid , N , M , L ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT speed = mid * A [ i ] + H [ i ] NEW_LINE if ( speed >= L ) : NEW_LINE INDENT sum += speed NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT def buzzTime ( N , M , L , H , A ) : NEW_LINE INDENT low = 0 NEW_LIN...
Count of different numbers divisible by 3 that can be obtained by changing at most one digit | Function to count the number of possible numbers divisible by 3 ; Calculate the sum ; Store the answer ; Iterate over the range ; Decreasing the sum ; Iterate over the range ; Checking if the new sum is divisible by 3 or not ...
def findCount ( number ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len ( number ) ) : NEW_LINE INDENT sum += int ( number [ i ] ) - 48 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( len ( number ) ) : NEW_LINE INDENT remaining_sum = sum - ( int ( number [ i ] ) - 48 ) NEW_LINE for j in range ( 10 ) : NEW...
Maximum number of teams of size K possible with each player from different country | Function to find if T number of teams can be formed or not ; Store the sum of array elements ; Traverse the array teams [ ] ; Required Condition ; Function to find the maximum number of teams possible ; Lower and Upper part of the rang...
def is_possible ( teams , T , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len ( teams ) ) : NEW_LINE INDENT sum += min ( T , teams [ i ] ) NEW_LINE DEDENT return ( sum >= ( T * k ) ) NEW_LINE DEDENT def countOfTeams ( teams_list , N , K ) : NEW_LINE INDENT lb = 0 NEW_LINE ub = 1000000000 NEW_LINE while ( lb...
Minimum number of decrements by 1 required to reduce all elements of a circular array to 0 | Function to find minimum operation require to make all elements 0 ; Stores the maximum element and its position in the array ; Traverse the array ; Update the maximum element and its index ; Print the minimum number of operatio...
def minimumOperations ( arr , N ) : NEW_LINE INDENT mx = 0 NEW_LINE pos = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] >= mx ) : NEW_LINE INDENT mx = arr [ i ] NEW_LINE pos = i NEW_LINE DEDENT DEDENT print ( ( mx - 1 ) * N + pos + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT...
Maximize the smallest array element by incrementing all elements in a K | Python 3 program for above approach ; Function to check if the smallest value of v is achievable or not ; Create array to store previous moves ; Remove previous moves ; Add balance to ans ; Update contiguous subarray of length k ; Number of moves...
n = 0 NEW_LINE m = 0 NEW_LINE k = 0 NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE i = 0 NEW_LINE from math import pow NEW_LINE def check ( v , a ) : NEW_LINE INDENT tec = 0 NEW_LINE ans = 0 NEW_LINE b = [ 0 for i in range ( n + k + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT tec -= b [ i ] NEW_LINE if ( a [ i ] + te...
Altitude of largest Triangle that can be inscribed in a Rectangle | Function to find the greatest altitude of the largest triangle triangle that can be inscribed in the rectangle ; If L is greater than B ; Variables to perform binary search ; Stores the maximum altitude possible ; Iterate until low is less than high ; ...
def largestAltitude ( L , B ) : NEW_LINE INDENT if ( L > B ) : NEW_LINE INDENT temp = B NEW_LINE B = L NEW_LINE L = temp NEW_LINE DEDENT low = 0 NEW_LINE high = L NEW_LINE res = 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( mid <= ( B / 2 ) ) : NEW_LINE INDENT res = mi...
Find the frequency of each element in a sorted array | Function to print the frequency of each element of the sorted array ; Stores the frequency of an element ; Traverse the array arr [ ] ; If the current element is equal to the previous element ; Increment the freq by 1 ; Otherwise , ; Update freq ; Print the frequen...
def printFreq ( arr , N ) : NEW_LINE INDENT freq = 1 NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT freq += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Frequency ▁ of " , arr [ i - 1 ] , " is : " , freq ) NEW_LINE freq = 1 NEW_LINE DEDENT DEDENT print ...
Count pairs from a given array whose sum lies from a given range | Python3 program for the above approach ; Function to count pairs whose sum lies over the range [ L , R ] ; Sort the given array ; Iterate until right > 0 ; Starting index of element whose sum with arr [ right ] >= L ; Ending index of element whose sum w...
from bisect import bisect_left , bisect_right NEW_LINE def countPairSum ( arr , L , R , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE right = N - 1 NEW_LINE count = 0 NEW_LINE while ( right > 0 ) : NEW_LINE INDENT it1 = bisect_left ( arr , L - arr [ right ] ) NEW_LINE start = it1 NEW_LINE it2 = bisect_right ( arr , R -...
Maximize median of a KxK sub | Function to determine if a given value can be median ; Stores the prefix sum array ; Traverse the matrix arr [ ] [ ] ; Update Pre [ i + 1 ] [ j + 1 ] ; If arr [ i ] [ j ] is less than or equal to mid ; Stores the count of elements should be less than mid ; Stores if the median mid can be ...
def isMaximumMedian ( arr , N , K , mid ) : NEW_LINE INDENT Pre = [ [ 0 for x in range ( N + 5 ) ] for y in range ( N + 5 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT Pre [ i + 1 ] [ j + 1 ] = ( Pre [ i + 1 ] [ j ] + Pre [ i ] [ j + 1 ] - Pre [ i ] [ j ] ) NEW_LINE if ( arr...
Minimum days to make Array elements with value at least K sum at least X | Function to find the minimum number of days such that the sum of array elements >= K is at least X ; Initialize the boundaries of search space ; Perform the binary search ; Find the value of mid ; Traverse the array , arr [ ] ; Find the value of...
def findMinDays ( arr , R , N , X , K ) : NEW_LINE INDENT low = 0 NEW_LINE high = X NEW_LINE minDays = 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT temp = arr [ i ] + R [ i ] * mid NEW_LINE if ( temp >= K ) : NEW_LINE INDEN...
Count of indices pairs such that product of elements at these indices is equal to absolute difference of indices | Function to count the number of pairs ( i , j ) such that arr [ i ] * arr [ j ] is equal to abs ( i - j ) ; Stores the resultant number of pairs ; Generate all possible pairs from the array arr [ ] ; If th...
def getPairsCount ( a , 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 ( ( a [ i ] * a [ j ] ) == abs ( i - j ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ '...
Lexicographically smallest string formed repeatedly deleting character from substring 10 | Function to find smallest lexicogra - phically smallest string ; Stores the index of last occuring 0 ; Stores the lexicographically smallest string ; Traverse the S ; If str [ i ] is 0 ; Assign i to lastZe ; Traverse the str ; If...
def lexicographicallySmallestString ( S , N ) : NEW_LINE INDENT LastZe = - 1 NEW_LINE ans = " " NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT LastZe = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( i <= LastZe and S [ i ] == ...
Count of Nodes at distance K from S in its subtree for Q queries | Python3 program for the above approach ; Function to add edges ; Function to perform Depth First Search ; Stores the entry time of a node ; Stores the entering time of a node at depth d ; Iterate over the children of node ; Stores the Exit time of a nod...
from bisect import bisect_left , bisect_right NEW_LINE tin = [ 0 ] * 100 NEW_LINE tout = [ 0 ] * 100 NEW_LINE depth = [ 0 ] * 100 NEW_LINE t = 0 NEW_LINE def Add_edge ( parent , child , adj ) : NEW_LINE INDENT adj [ parent ] . append ( child ) NEW_LINE adj [ child ] . append ( parent ) NEW_LINE return adj NEW_LINE DEDE...
Maximize boxes required to keep at least one black and one white shirt | Function to find the maximum number of boxes such that each box contains three shirts comprising of at least one white and black shirt ; Stores the low and high pointers for binary search ; Store the required answer ; Loop while low <= high ; Stor...
def numberofBoxes ( W , B , O ) : NEW_LINE INDENT low = 0 NEW_LINE high = min ( W , B ) NEW_LINE ans = 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( ( ( W >= mid ) and ( B >= mid ) ) and ( ( W - mid ) + ( B - mid ) + O ) >= mid ) : NEW_LINE INDENT ans = mid NEW_LINE lo...
Minimum swaps needed to convert given Binary Matrix A to Binary Matrix B | Function to count the minimum number of swaps required to convert matrix A to matrix B ; Stores number of cells such that matrix A contains 0 and matrix B contains 1 ; Stores number of cells such that matrix A contains 1 and matrix B contains 0 ...
def minSwaps ( N , M , A , B ) : NEW_LINE INDENT count01 = 0 NEW_LINE count10 = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , M ) : NEW_LINE INDENT if ( A [ i ] [ j ] != B [ i ] [ j ] ) : NEW_LINE INDENT if ( A [ i ] [ j ] == 1 ) : NEW_LINE INDENT count10 += 1 NEW_LINE DEDENT else : NEW_LIN...
Maximize X such that sum of numbers in range [ 1 , X ] is at most K | Function to count the elements with sum of the first that many natural numbers less than or equal to K ; If K equals to 0 ; Stores sum of first i natural numbers ; Stores the result ; Iterate over the range [ 1 , N ] ; Increment sum by i ; Is sum is ...
def Count ( N , K ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT sum = 0 NEW_LINE res = 0 NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT sum += i NEW_LINE if ( sum <= K ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return res ...
Remove last occurrence of a word from a given sentence string | Function to remove last occurrence of W from S ; If M is greater than N ; Iterate while i is greater than or equal to 0 ; of W has been found or not ; Iterate over the range [ 0 , M ] ; If S [ j + 1 ] is not equal to W [ j ] ; Mark flag true and break ; If...
def removeLastOccurrence ( S , W , N , M ) : NEW_LINE INDENT S = [ i for i in S ] NEW_LINE W = [ i for i in W ] NEW_LINE if ( M > N ) : NEW_LINE INDENT return S NEW_LINE DEDENT for i in range ( N - M , - 1 , - 1 ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( M ) : NEW_LINE INDENT if ( S [ j + i ] != W [ j ] ) :...
Rearrange the Array to maximize the elements which is smaller than both its adjacent elements | Function to rearrange array such that count of element that are smaller than their adjacent elements is maximum ; Stores the rearranged array ; Stores the maximum count of elements ; Sort the given array ; Place the smallest...
def maximumIndices ( arr , N ) : NEW_LINE INDENT temp = [ 0 ] * N NEW_LINE maxIndices = ( N - 1 ) // 2 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( maxIndices ) : NEW_LINE INDENT temp [ 2 * i + 1 ] = arr [ i ] NEW_LINE DEDENT j = 0 NEW_LINE i = maxIndices NEW_LINE while ( i < N ) : NEW_LINE INDENT if ( temp [ j ] ...
Check if given Strings can be made equal by inserting at most 1 String | Python3 program for the above approach ; Function to check whether two sentences can be made equal by inserting at most one sentence in one of them ; Size of sentence S1 ; Size of sentence S2 ; Check if S1 and S2 are of equal sizes ; If both sente...
from collections import deque NEW_LINE def areSimilar ( S1 , S2 ) : NEW_LINE INDENT S1 = [ i for i in S1 ] NEW_LINE S2 = [ i for i in S2 ] NEW_LINE N = len ( S1 ) NEW_LINE M = len ( S2 ) NEW_LINE if ( N == M ) : NEW_LINE INDENT if ( S1 == S2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT X...
Find the repeating element in an Array of size N consisting of first M natural numbers | Function to calculate the repeating character in a given permutation ; variables to store maximum element and sum of the array respectively . ; calculate sum of array ; calculate maximum element in the array ; calculating sum of pe...
def repeatingElement ( arr , N ) : NEW_LINE INDENT M = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE M = max ( M , arr [ i ] ) NEW_LINE DEDENT sum1 = M * ( M + 1 ) // 2 NEW_LINE ans = ( sum - sum1 ) // ( N - M ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main...
Maximize value at Kth index to create N size array with adjacent difference 1 and sum less than M | Function to calculate maximum value that can be placed at the Kth index in a distribution in which difference of adjacent elements is less than 1 and total sum of distribution is M . ; Variable to store final answer ; Va...
def calculateMax ( N , M , K ) : NEW_LINE INDENT ans = - 1 NEW_LINE low = 0 NEW_LINE high = M NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) / 2 NEW_LINE val = 0 NEW_LINE L = K - 1 NEW_LINE R = N - K NEW_LINE val += mid NEW_LINE if ( mid >= L ) : NEW_LINE INDENT val += ( L ) * ( 2 * mid - L - 1 )...
Minimum time required to color all edges of a Tree | Stores the required answer ; Stores the graph ; Function to add edges ; Function to calculate the minimum time required to color all the edges of a tree ; Starting from time = 0 , for all the child edges ; If the edge is not visited yet . ; Time of coloring of the cu...
ans = 0 NEW_LINE edges = [ [ ] for i in range ( 100000 ) ] NEW_LINE def Add_edge ( u , v ) : NEW_LINE INDENT global edges NEW_LINE edges [ u ] . append ( v ) NEW_LINE edges [ v ] . append ( u ) NEW_LINE DEDENT def minTimeToColor ( node , parent , arrival_time ) : NEW_LINE INDENT global ans NEW_LINE current_time = 0 NEW...
Largest number having both positive and negative values present in the array | Function to find the largest number k such that both k and - k are present in the array ; Stores the resultant value of K ; Sort the array arr [ ] ; Initialize two variables to use two pointers technique ; Iterate until the value of l is les...
def largestNum ( arr ) : NEW_LINE INDENT res = 0 NEW_LINE arr = sorted ( arr ) NEW_LINE l = 0 NEW_LINE r = len ( arr ) - 1 NEW_LINE while ( l < r ) : NEW_LINE INDENT sum = arr [ l ] + arr [ r ] NEW_LINE if ( sum == 0 ) : NEW_LINE INDENT res = max ( res , max ( arr [ l ] , arr [ r ] ) ) NEW_LINE return res NEW_LINE DEDE...
Find elements larger than half of the elements in an array | Set 2 | Function to find the element that are larger than half of elements of the array ; Find the value of mid ; Stores the maximum element ; Stores the frequency of each array element ; Traverse the array in the reverse order ; Decrement the value of count ...
def findLarger ( arr , n ) : NEW_LINE INDENT mid = ( n + 1 ) // 2 NEW_LINE mx = max ( arr ) NEW_LINE count = [ 0 ] * ( mx + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( mx , - 1 , - 1 ) : NEW_LINE INDENT while ( count [ i ] > 0 ) : NEW_LINE INDENT count [...
Probability of obtaining pairs from two arrays such that element from the first array is smaller than that of the second array | Function to find probability such that x < y and X belongs to arr1 [ ] and Y belongs to arr2 [ ] ; Stores the length of arr1 ; Stores the length of arr2 ; Stores the result ; Traverse the arr...
def probability ( arr1 , arr2 ) : NEW_LINE INDENT N = len ( arr1 ) NEW_LINE M = len ( arr2 ) NEW_LINE res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT y = 0 NEW_LINE for j in range ( M ) : NEW_LINE INDENT if ( arr2 [ j ] > arr1 [ i ] ) : NEW_LINE INDENT y += 1 NEW_LINE DEDENT DEDENT res += y NEW_LINE DEDENT res ...
Probability of obtaining pairs from two arrays such that element from the first array is smaller than that of the second array | Function to find probability such that x < y and X belongs to arr1 [ ] & Y belongs to arr2 [ ] ; Stores the length of arr1 ; Stores the length of arr2 ; Stores the result ; Sort the arr2 [ ] ...
def probability ( arr1 , arr2 ) : NEW_LINE INDENT n = len ( arr1 ) NEW_LINE m = len ( arr2 ) NEW_LINE res = 0 NEW_LINE arr2 . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT y = countGreater ( arr2 , arr1 [ i ] ) NEW_LINE res += y NEW_LINE DEDENT res /= ( n * m ) NEW_LINE return res NEW_LINE DEDENT def countGr...
Minimize cost to cover floor using tiles of dimensions 1 * 1 and 1 * 2 | Function to find the minimum cost of flooring with the given tiles ; Store the size of the 2d array ; Stores the minimum cost of flooring ; Traverse the 2d array row - wise ; If the current character is ' * ' , then skip it ; Choose the 1 * 1 tile...
def minCost ( arr , A , B ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE m = len ( arr [ 0 ] ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = 0 NEW_LINE while j < m : NEW_LINE INDENT if ( arr [ i ] [ j ] == ' * ' ) : NEW_LINE INDENT j += 1 NEW_LINE continue NEW_LINE DEDENT if ( j == m - 1 ) : NEW_LI...
Count inversions in a permutation of first N natural numbers | Python3 program for the above approach ; Function to count number of inversions in a permutation of first N natural numbers ; Store array elements in sorted order ; Store the count of inversions ; Traverse the array ; Store the index of first occurrence of ...
from bisect import bisect_left NEW_LINE def countInversions ( arr , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT itr = bisect_left ( v , arr [ i ] ) NEW_LINE ans += itr NEW_LINE v = v [ ...
Find all possible pairs with given Bitwise OR and Bitwise XOR values | Function to find pairs with XOR equal to A and OR equal to B ; Iterate from 1 to B ; Check if ( i OR y ) is B ; Driver Code
def findPairs ( A , B ) : NEW_LINE INDENT for i in range ( 1 , B + 1 ) : NEW_LINE INDENT y = A ^ i NEW_LINE if ( y > 0 and ( i y ) == B ) : NEW_LINE INDENT print ( i , " ▁ " , y ) NEW_LINE DEDENT DEDENT DEDENT A = 8 NEW_LINE B = 10 NEW_LINE findPairs ( A , B ) NEW_LINE
Count distinct elements from a range of a sorted sequence from a given frequency array | Function to find the first index with value is at least element ; Update the value of left ; Binary search for the element ; Find the middle element ; Check if the value lies between the elements at index mid - 1 and mid ; Check in...
def binarysearch ( array , right , element ) : NEW_LINE INDENT left = 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = ( left + right // 2 ) NEW_LINE if ( array [ mid ] == element ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( mid - 1 > 0 and array [ mid ] > element and array [ mid - 1 ] < element ) : NE...
Find Unique ID and Domain Name of a Website from a string | Function to check if a character is alphabet or not ; Function to check if a character is a numeric or not ; Function to find ID and Domain name from a given ; Stores ID and the domain names ; Stores the words of S ; Stores the temporary word ; Traverse the S ...
def ischar ( x ) : NEW_LINE INDENT if ( ( x >= ' A ' and x <= ' Z ' ) or ( x >= ' a ' and x <= ' z ' ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def isnum ( x ) : NEW_LINE INDENT if ( x >= '0' and x <= '9' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def findIdandDom...
Capacity To Ship Packages Within D Days | Function to check if the weights can be delivered in D days or not ; Stores the count of days required to ship all the weights if the maximum capacity is mx ; Traverse all the weights ; If total weight is more than the maximum capacity ; If days are more than D , then return fa...
def isValid ( weight , n , D , mx ) : NEW_LINE INDENT st = 1 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += weight [ i ] NEW_LINE if ( sum > mx ) : NEW_LINE INDENT st += 1 NEW_LINE sum = weight [ i ] NEW_LINE DEDENT if ( st > D ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True...
Find a point whose sum of distances from all given points on a line is K | Function to find the sum of distances of all points from a given point ; Stores sum of distances ; Traverse the array ; Return the sum ; Function to find such a point having sum of distances of all other points from this point equal to K ; If N ...
def findSum ( arr , N , pt ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += abs ( arr [ i ] - pt ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def findPoint ( arr , N , K ) : NEW_LINE INDENT left = 0 NEW_LINE if ( N % 2 ) : NEW_LINE INDENT left = arr [ N // 2 ] NEW_LINE DEDENT else : NE...
Generate an array consisting of most frequent greater elements present on the right side of each array element | Function to generate an array containing the most frequent greater element on the right side of each array element ; Stores the generated array ; Traverse the array arr [ ] ; Store the result for the current...
def findArray ( arr , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = - 1 NEW_LINE old_c = 0 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] > arr [ i ] ) : NEW_LINE INDENT curr_c = arr [ j : n + 1 ] . count ( arr [ j ] ) NEW_LINE if ( curr_c == old_c ) : NEW_L...
Smallest index that splits an array into two subarrays with equal product | Function to find the smallest index that splits the array into two subarrays with equal product ; Stores the product of the array ; Traverse the given array ; Stores the product of left and the right subarrays ; Traverse the given array ; Updat...
def prodEquilibrium ( arr , N ) : NEW_LINE INDENT product = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT product *= arr [ i ] NEW_LINE DEDENT left = 1 NEW_LINE right = product NEW_LINE for i in range ( N ) : NEW_LINE INDENT left = left * arr [ i ] NEW_LINE right = right // arr [ i ] NEW_LINE if ( left == right ) :...
Count triplets from a sorted array having difference between adjacent elements equal to D | Function to count the number of triplets having difference between adjacent elements equal to D ; Stores the frequency of array elements ; Stores the count of resultant triplets ; Traverse the array ; Check if arr [ i ] - D and ...
def countTriplets ( D , arr ) : NEW_LINE INDENT freq = { } NEW_LINE ans = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( ( ( arr [ i ] - D ) in freq ) and ( arr [ i ] - 2 * D ) in freq ) : NEW_LINE INDENT ans += ( freq [ arr [ i ] - D ] * freq [ arr [ i ] - 2 * D ] ) NEW_LINE DEDENT freq [ arr [ i ] ]...
Find the array element having equal sum of Prime Numbers on its left and right | Python3 program for the above approach ; Function to find an index in the array having sum of prime numbers to its left and right equal ; Stores the maximum value present in the array ; Stores all positive elements which are <= max_value ;...
from math import sqrt NEW_LINE def find_index ( arr , N ) : NEW_LINE INDENT max_value = - 10 ** 9 NEW_LINE for i in range ( N ) : NEW_LINE INDENT max_value = max ( max_value , arr [ i ] ) NEW_LINE DEDENT store = { } NEW_LINE for i in range ( 1 , max_value + 1 ) : NEW_LINE INDENT store [ i ] = store . get ( i , 0 ) + 1 ...
Convert an array to reduced form | Set 3 ( Binary Search ) | Function to find the reduced form of the given array arr [ ] ; Stores the sorted form of the the given array arr [ ] ; Sort the array brr [ ] ; Traverse the given array arr [ ] ; Perform the Binary Search ; Calculate the value of mid ; Prthe current index and...
def convert ( arr , n ) : NEW_LINE INDENT brr = [ i for i in arr ] NEW_LINE brr = sorted ( brr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT l , r , mid = 0 , n - 1 , 0 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = ( l + r ) // 2 NEW_LINE if ( brr [ mid ] == arr [ i ] ) : NEW_LINE INDENT print ( mid , end = " ▁...
Find the array element having equal count of Prime Numbers on its left and right | Python 3 program for the above approach ; Function to find the index of the array such that the count of prime numbers to its either ends are same ; Store the maximum value in the array ; Traverse the array arr [ ] ; / Stores all the num...
from collections import defaultdict NEW_LINE import sys NEW_LINE import math NEW_LINE def findIndex ( arr , N ) : NEW_LINE INDENT maxValue = - sys . maxsize - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT maxValue = max ( maxValue , arr [ i ] ) NEW_LINE DEDENT St = defaultdict ( int ) NEW_LINE for i in range ( 1 , ...
Numbers of pairs from an array whose average is also present in the array | Function to count the number of pairs from the array having sum S ; Stores the total count of pairs whose sum is 2 * S ; Generate all possible pairs and check their sums ; If the sum is S , then increment the count ; Return the total count of p...
def getCountPairs ( arr , N , S ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( arr ) ) : NEW_LINE INDENT if ( ( arr [ i ] + arr [ j ] ) == S ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT def countPairs ( ...
Sort array of strings after sorting each string after removing characters whose frequencies are not a powers of 2 | Python3 program for the above approach ; Function to check if N is power of 2 or not ; Base Case ; Return true if N is power of 2 ; Function to print array of strings in ascending order ; Sort strings in ...
from collections import defaultdict NEW_LINE import math NEW_LINE def isPowerOfTwo ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( math . ceil ( math . log2 ( n ) ) == math . floor ( math . log2 ( n ) ) ) NEW_LINE DEDENT def printArray ( res ) : NEW_LINE INDENT res . sort (...
Modify string by replacing all occurrences of given characters by specified replacing characters | Function to modify given string by replacing characters ; Store the size of string and the number of pairs ; Initialize 2 character arrays ; Traverse the string s Update arrays arr [ ] and brr [ ] ; Traverse the array of ...
def replaceCharacters ( s , p ) : NEW_LINE INDENT n , k = len ( s ) , len ( p ) NEW_LINE arr = [ 0 ] * 26 NEW_LINE brr = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ ord ( s [ i ] ) - ord ( ' a ' ) ] = s [ i ] NEW_LINE brr [ ord ( s [ i ] ) - ord ( ' a ' ) ] = s [ i ] NEW_LINE DEDENT for j in range ...
Smallest Semi | Python3 program for the above approach ; Function to find all the prime numbers using Sieve of Eratosthenes ; Set 0 and 1 as non - prime ; If p is a prime ; Set all multiples of p as non - prime ; Function to find the smallest semi - prime number having a difference between any of its two divisors at le...
MAX = 100001 NEW_LINE def SieveOfEratosthenes ( prime ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p < MAX : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , MAX , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DED...
Check if a number can be represented as product of two positive perfect cubes | Function to check if N can be represented as the product of two perfect cubes or not ; Stores the perfect cubes ; Traverse the Map ; Stores the first number ; Stores the second number ; Search the pair for the first number to obtain product...
def productOfTwoPerfectCubes ( N ) : NEW_LINE INDENT cubes = { } NEW_LINE i = 1 NEW_LINE while i * i * i <= N : NEW_LINE INDENT cubes [ i * i * i ] = i NEW_LINE i += 1 NEW_LINE DEDENT for itr in cubes : NEW_LINE INDENT firstNumber = itr NEW_LINE if ( N % itr == 0 ) : NEW_LINE INDENT secondNumber = N // itr NEW_LINE if ...
Check if a number can be represented as product of two positive perfect cubes | Function to check if the number N can be represented as the product of two perfect cubes or not ; If cube of cube_root is N ; Otherwise , prNo ; Driver Code
def productOfTwoPerfectCubes ( N ) : NEW_LINE INDENT cube_root = round ( ( N ) ** ( 1 / 3 ) ) NEW_LINE print ( cube_root ) NEW_LINE if ( cube_root * cube_root * cube_root == N ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DE...
Size of smallest square that contains N non | Function to check if side of square X can pack all the N rectangles or not ; Find the number of rectangle it can pack ; If val is atleast N , then return true ; Otherwise , return false ; Function to find the size of the smallest square that can contain N rectangles of dime...
def bound ( w , h , N , x ) : NEW_LINE INDENT val = ( x // w ) * ( x // h ) NEW_LINE if ( val >= N ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def FindSquare ( N , W , H ) : NEW_LINE INDENT i = 1 NEW_LINE j = W * H * N NEW_LINE while ( i < j ) : NEW_LINE IN...
Count integers up to N that are equal to at least 2 nd power of any integer exceeding 1 | Python 3 program for the above approach ; Function to count the integers up to N that can be represented as a ^ b , where a & b > 1 ; Initialize a HashSet ; Iterating over the range [ 2 , sqrt ( N ) ] ; Generate all possible power...
from math import sqrt NEW_LINE def printNumberOfPairs ( N ) : NEW_LINE INDENT st = set ( ) NEW_LINE for i in range ( 2 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT x = i NEW_LINE while ( x <= N ) : NEW_LINE INDENT x *= i NEW_LINE if ( x <= N ) : NEW_LINE INDENT st . add ( x ) NEW_LINE DEDENT DEDENT DEDENT print ( l...
Maximize product of lengths of strings having no common characters | Function to count the number of set bits in the integer n ; Stores the count of set bits in n ; Return the count ; Function to find the maximum product of pair of strings having no common characters ; Stores the integer equivalent of the strings ; Tra...
def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def maximumProduct ( words ) : NEW_LINE INDENT bits = [ 0 for i in range ( len ( words ) ) ] NEW_LINE for i in range ( len ( words ) ) : NEW_LINE IND...
Modify a sentence by reversing order of occurrences of all Palindrome Words | Function to check if a string S is a palindrome ; Function to print the modified string after reversing teh order of occurrences of all palindromic words in the sentence ; Stores the palindromic words ; Stores the words in the list ; Traversi...
def palindrome ( string ) : NEW_LINE INDENT if ( string == string [ : : - 1 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def printReverse ( sentence ) : NEW_LINE INDENT newlist = [ ] NEW_LINE lis = list ( sentence . split ( ) ) NEW_LINE for i in lis : NEW_...
Convert an array into another by repeatedly removing the last element and placing it at any arbitrary index | Function to count the minimum number of operations required to convert the array A [ ] into array B [ ] ; Stores the index in the first permutation A [ ] which is same as the subsequence in B [ ] ; Find the fir...
def minCount ( A , B , N ) : NEW_LINE INDENT i = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( A [ i ] == B [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT return N - i NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE B = [ 1 , 5 , 2 , 3 , 4 ] NEW_LIN...
Minimize maximum array element possible by at most K splits on the given array | Function to check if all array elements can be reduced to at most mid by at most K splits ; Stores the number of splits required ; Traverse the array arr [ ] ; Update count ; If possible , return true . Otherwise return false ; Function to...
def possible ( A , N , mid , K ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT count += ( A [ i ] - 1 ) // mid NEW_LINE DEDENT return count <= K NEW_LINE DEDENT def minimumMaximum ( A , N , K ) : NEW_LINE INDENT lo = 1 NEW_LINE hi = max ( A ) NEW_LINE while ( lo < hi ) : NEW_LINE INDENT mi...
Maximum value of X such that difference between any array element and X does not exceed K | Function to find maximum value of X such that | A [ i ] - X | a K ; Stores the smallest array element ; Store the possible value of X ; Traverse the array A [ ] ; If required criteria is not satisfied ; Update ans ; Print the re...
def maximumNumber ( arr , N , K ) : NEW_LINE INDENT minimum = min ( arr ) NEW_LINE ans = minimum + K NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( abs ( arr [ i ] - ans ) > K ) : NEW_LINE INDENT ans = - 1 NEW_LINE break NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LI...