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