text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Find the last remaining element after repeated removal of an element from pairs of increasing adjacent array elements | Function to print the last remaining array element after after performing given operations ; If size of the array is 1 ; Check for the condition ; If condition is not satisfied ; Driver Code ; Functio... | def canArrayBeReduced ( arr , N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( arr [ 0 ] ) NEW_LINE return NEW_LINE DEDENT if ( arr [ 0 ] < arr [ N - 1 ] ) : NEW_LINE INDENT print ( arr [ N - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT DEDENT if __name__ == " _... |
Minimum prefix increments required to make all elements of an array multiples of another array | Python3 program for the above approach ; Function to find minimum count of operations required to make A [ i ] multiple of B [ i ] by incrementing prefix subarray ; Stores minimum count of operations required to make A [ i ... | from math import ceil , floor NEW_LINE def MinimumMoves ( A , B , N ) : NEW_LINE INDENT totalOperations = 0 NEW_LINE carry = 0 NEW_LINE K = 0 NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT nearestMultiple = ceil ( ( A [ i ] + carry ) / B [ i ] ) * B [ i ] NEW_LINE K = nearestMultiple - ( A [ i ] + carr... |
Minimize deviation of an array by given operations | Function to find the minimum deviation of the array A [ ] ; Store all array elements in sorted order ; Odd number are transformed using 2 nd operation ; ( Maximum - Minimum ) ; Check if the size of set is > 0 and the maximum element is divisible by 2 ; Maximum elemen... | def minimumDeviation ( A , N ) : NEW_LINE INDENT s = set ( [ ] ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] % 2 == 0 ) : NEW_LINE INDENT s . add ( A [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT s . add ( 2 * A [ i ] ) NEW_LINE DEDENT DEDENT s = list ( s ) NEW_LINE diff = s [ - 1 ] - s [ 0 ] NEW_LINE... |
Maximize given integer by swapping pairs of unequal bits | Function to return the maximum possible value that can be obtained from the given integer by performing given operations ; Convert to equivalent binary representation ; Stores binary representation of the maximized value ; Store the count of 0 ' s β and β 1' s ... | def findMaxNum ( num ) : NEW_LINE INDENT binaryNumber = bin ( num ) [ 2 : ] NEW_LINE maxBinaryNumber = " " NEW_LINE count0 , count1 = 0 , 0 NEW_LINE N = len ( binaryNumber ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( binaryNumber [ i ] == '1' ) : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT else : NEW_LINE IND... |
Minimum deletions to convert given integer to an odd number whose sum of digits is even | Set 2 | Function to find minimum count of digits required to be remove to make N odd and the sum of digits of N even ; Stores count of even digits ; Stores count of odd digits ; Iterate over the digits of N ; If current digit is e... | def minOperations ( N ) : NEW_LINE INDENT even = 0 ; NEW_LINE odd = 0 ; NEW_LINE for it in N : NEW_LINE INDENT if ( int ( ord ( it ) - ord ( '0' ) ) % 2 == 0 ) : NEW_LINE INDENT even += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 ; NEW_LINE DEDENT DEDENT if ( odd == 0 or odd == 1 ) : NEW_LINE INDENT print ( " N... |
Find the player with least 0 s after emptying a Binary String by removing non | Function to find the player who wins the game ; Stores total count of 0 s in the string ; Stores count of consecutive 1 s ; Stores Nim - Sum on count of consecutive 1 s ; Stores length of the string ; Traverse the string ; If the current ch... | def FindwinnerOfGame ( S ) : NEW_LINE INDENT cntZero = 0 NEW_LINE cntConOne = 0 NEW_LINE nimSum = 0 NEW_LINE N = len ( S ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT cntConOne += 1 NEW_LINE DEDENT else : NEW_LINE INDENT nimSum ^= cntConOne NEW_LINE cntConOne = 0 NEW_LINE cnt... |
Place first N natural numbers at indices not equal to their values in an array | Function to place first N natural numbers in an array such that none of the values are equal to its indices ; Stores the required array ; Place N at the first position ; Iterate the range [ 1 , N ) ; Append elements to the sequence ; Print... | def generatepermutation ( N ) : NEW_LINE INDENT answer = [ ] NEW_LINE answer . append ( N ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT answer . append ( i ) NEW_LINE DEDENT print ( * answer ) NEW_LINE DEDENT N = 4 NEW_LINE generatepermutation ( N ) NEW_LINE |
Maximize element at index K in an array with at most sum M and difference between adjacent elements at most 1 | Function to calculate the maximum possible value at index K ; Stores the sum of elements in the left and right of index K ; Stores the maximum possible value at index K ; Prthe answer ; Driver Code ; Given N ... | def maxValueAtIndexK ( N , K , M ) : NEW_LINE INDENT S1 = 0 ; S2 = 0 ; NEW_LINE S1 = K * ( K + 1 ) // 2 ; NEW_LINE S2 = ( N - K - 1 ) * ( N - K ) // 2 ; NEW_LINE X = ( M + S1 + S2 ) // N ; NEW_LINE print ( X ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 ; K = 1 ; M = 7 ; NEW_LINE maxValueA... |
Farthest cell from a given cell in a Matrix | Function to find the farthest cell distance from the given cell ; From cell ( N , M ) ; From Cell ( 1 , 1 ) ; From cell ( N , 1 ) ; From cell ( 1 , M ) ; Finding out maximum ; Prthe answer ; Driver Code | def farthestCellDistance ( N , M , R , C ) : NEW_LINE INDENT d1 = N + M - R - C ; NEW_LINE d2 = R + C - 2 ; NEW_LINE d3 = N - R + C - 1 ; NEW_LINE d4 = M - C + R - 1 ; NEW_LINE maxDistance = max ( d1 , max ( d2 , max ( d3 , d4 ) ) ) ; NEW_LINE print ( maxDistance ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NE... |
Maximize every array element by repeatedly adding all valid i + a [ i ] th array element | Function to maximize value at every array index by performing given operations ; Traverse the array in reverse ; If the current index is a valid index ; Prthe array ; Driver Code ; Given array ; Size of the array | def maxSum ( arr , N ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT t = i ; NEW_LINE if ( t + arr [ i ] < N ) : NEW_LINE INDENT arr [ i ] += arr [ t + arr [ i ] ] ; NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE D... |
Path from the root node to a given node in an N | Python3 program for the above approach ; Function to find the path from root to N ; Stores the number of nodes at ( i + 1 ) - th level ; Stores the number of nodes ; Stores if the current level is even or odd ; If level is odd ; If level is even ; If level with node N i... | from bisect import bisect_left NEW_LINE def PrintPathNodes ( N ) : NEW_LINE INDENT arr = [ ] NEW_LINE arr . append ( 1 ) NEW_LINE k = 1 NEW_LINE flag = True NEW_LINE while ( k < N ) : NEW_LINE INDENT if ( flag == True ) : NEW_LINE INDENT k *= 2 NEW_LINE flag = False NEW_LINE DEDENT else : NEW_LINE INDENT k *= 4 NEW_LIN... |
Generate an N | Python3 program for the above approach ; Function to construct an array with given conditions ; Traverse the array arr [ ] ; Stores closest power of 2 less than or equal to arr [ i ] ; Stores R into brr [ i ] ; Prarray elements ; Driver Code ; Given array ; Size of the array ; Function Call | from math import log NEW_LINE def constructArray ( arr , N ) : NEW_LINE INDENT brr = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT K = int ( log ( arr [ i ] ) / log ( 2 ) ) NEW_LINE R = pow ( 2 , K ) NEW_LINE brr [ i ] = R NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( brr [ i ] , end = " β ... |
Find the element at specified index in a Spiral Matrix | Function to the find element at ( i , j ) index ; Driver Code ; Function Call | def findInGrid ( i , j ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return ( i * i - ( i - 1 ) ) NEW_LINE DEDENT elif ( i > j ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT return i * i - ( j - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( i - 1 ) * ( i - 1 ) + 1 + ( j - 1 ) ) NEW_LINE DEDENT DE... |
Make all array elements equal to 0 by replacing minimum subsequences consisting of equal elements | Function to find minimum count of operations required to convert all array elements to zero by replacing subsequence of equal elements to 0 ; Store distinct elements present in the array ; Traverse the array ; If arr [ i... | def minOpsToTurnArrToZero ( arr , N ) : NEW_LINE INDENT st = dict ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i in st . keys ( ) or arr [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT st [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT print ( len ( st ) ) NEW_LINE DEDENT arr = [ 3 ,... |
Split an array into equal length subsequences consisting of equal elements only | Python3 program for the above approach ; Function to find the GCD of two numbers a and b ; Function to check if it is possible to split the array into equal length subsequences such that all elements in the subsequence are equal ; Store f... | from collections import defaultdict NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def splitArray ( arr , N ) : NEW_LINE INDENT mp = defaultdict ( int ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 N... |
Minimize count of given operations required to be performed to make all array elements equal to 1 | Python 3 program to implement the above approach ; Function to check if all array elements are equal or not ; Traverse the array ; If all array elements are not equal ; Function to find minimum count of operation to make... | import math NEW_LINE def CheckAllEqual ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ 0 ] != arr [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def minCntOperations ( arr , N ) : NEW_LINE INDENT Max = max ( arr ) NEW_LINE isPower2 = not ( M... |
Largest number not exceeding N that does not contain any of the digits of S | Function to obtain the largest number not exceeding num which does not contain any digits present in S ; Stores digits of S ; Traverse the string S ; Set occurrence as true ; Traverse the string n ; All digits of num are not present in string... | def greatestReducedNumber ( num , s ) : NEW_LINE INDENT vis_s = [ False ] * 10 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE vis_s [ ( ord ) ( s [ i ] ) - 48 ] = True NEW_LINE n = len ( num ) NEW_LINE In = - 1 NEW_LINE for i in range ( n ) : NEW_LINE if ( vis_s [ ord ( num [ i ] ) - ord ( '0' ) ] ) : NEW_LINE INDENT... |
Generate an array of minimum sum whose XOR of same | Function to generate an array whose XOR with same - indexed elements of the given array is always a prime ; Traverse the array ; If current array element is 2 ; Print its XOR with 3 ; Otherwise ; Print its XOR with 2 ; Driver Code ; Given array ; Size of the array ; ... | def minXOR ( Arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if ( Arr [ i ] == 2 ) : NEW_LINE INDENT print ( Arr [ i ] ^ 3 , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( Arr [ i ] ^ 2 , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Arr =... |
Find the largest element in an array generated using the given conditions | Function to generate the required array ; Stores the array ; Base case ; Iterate over the indices ; If current index is even ; Otherwise ; Function to find and return the maximum array element ; If n is 0 ; If n is 1 ; Generates the required ar... | def findArray ( n ) : NEW_LINE INDENT Arr = [ 0 ] * ( n + 1 ) NEW_LINE Arr [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT Arr [ i ] = Arr [ i // 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT Arr [ i ] = ( Arr [ ( i - 1 ) // 2 ] + Arr [ ( i - 1 ) // 2 + 1 ] ) NEW_LINE ... |
Construct a graph using N vertices whose shortest distance between K pair of vertices is 2 | Function to construct the simple and connected graph such that the distance between exactly K pairs of vertices is 2 ; Stores maximum possible count of edges in a graph ; Base case ; Stores edges of a graph ; Connect all vertic... | def constGraphWithCon ( N , K ) : NEW_LINE INDENT Max = ( ( N - 1 ) * ( N - 2 ) ) // 2 NEW_LINE if ( K > Max ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT ans = [ ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N + 1 ) : NEW_LINE INDENT ans . append ( [ i , j ] ) NEW_L... |
Minimum steps required to visit all corners of an N * M grid | Python3 program to implement the above approach ; Function to find the minimum count of steps required to visit all the corners of the grid ; Stores corner of the grid ; Stores minimum count of steps required to visit the first corner of the grid ; Checking... | import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def min_steps_required ( n , m , r , c ) : NEW_LINE INDENT i = 0 ; j = 0 ; NEW_LINE corner_steps_req = INT_MAX ; NEW_LINE i = 1 ; NEW_LINE j = 1 ; NEW_LINE corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; NEW_LINE i = n ; NEW_LINE j = 1... |
Minimum replacements required to have at most K distinct elements in the array | Function to find minimum count of array elements required to be replaced such that count of distinct elements is at most K ; Store the frequency of each distinct element of the array ; Traverse the array ; Update frequency of arr [ i ] ; S... | def min_elements ( arr , N , K ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT Freq = [ ] NEW_LINE for it in mp : NEW_LINE INDENT i = it NEW_LINE Fre... |
Check if sum of the given array can be reduced to 0 by reducing array elements by K | Function to check if the sum can be made 0 or not ; Stores sum of array elements ; Traverse the array ; Driver Code ; Given array arr [ ] | def sumzero ( arr , N , K ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT elif ( sum > 0 ) : NEW_LINE INDENT if ( sum % K == 0 ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT el... |
Counts 1 s that can be obtained in an Array by performing given operations | Function to count total number of 1 s in array by performing given operations ; Stores count of 1 s in the array by performing the operations ; Iterate over the range [ 1 , N ] ; Flip all array elements whose index is multiple of i ; Update ar... | def cntOnesArrWithGivenOp ( arr , N ) : NEW_LINE INDENT cntOnes = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( i - 1 , N , i ) : NEW_LINE INDENT arr [ j ] = 1 if arr [ j ] == 0 else 0 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT cntO... |
Counts 1 s that can be obtained in an Array by performing given operations | Function to count total number of 1 s in array by performing the given operations ; Stores count of 1 s in the array by performing the operations ; Update cntOnes ; Driver Code | def cntOnesArrWithGivenOp ( arr , N ) : NEW_LINE INDENT cntOnes = 0 ; NEW_LINE cntOnes = int ( N ** ( 1 / 2 ) ) ; NEW_LINE return cntOnes ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 0 , 0 , 0 , 0 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( cntOnesArrWithGivenOp ( arr , N ) ) ; NE... |
Count Knights that can attack a given pawn in an N * N board | Function to count the knights that are attacking the pawn in an M * M board ; Stores count of knights that are attacking the pawn ; Traverse the knights array ; Stores absolute difference of X co - ordinate of i - th knight and pawn ; Stores absolute differ... | def cntKnightsAttackPawn ( knights , pawn , M ) : NEW_LINE INDENT cntKnights = 0 ; NEW_LINE for i in range ( M ) : NEW_LINE INDENT X = abs ( knights [ i ] [ 0 ] - pawn [ 0 ] ) ; NEW_LINE Y = abs ( knights [ i ] [ 1 ] - pawn [ 1 ] ) ; NEW_LINE if ( ( X == 1 and Y == 2 ) or ( X == 2 and Y == 1 ) ) : NEW_LINE INDENT cntKn... |
Find the winner of game of removing array elements having GCD equal to 1 | Function to find the winner of the game by removing array elements whose GCD is 1 ; mp [ i ] : Stores count of array elements whose prime factor is i ; Traverse the array ; Calculate the prime factors of arr [ i ] ; If arr [ i ] is divisible by ... | def findWinnerGameRemoveGCD ( arr , n ) : NEW_LINE INDENT mp = dict . fromkeys ( arr , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 2 , int ( arr [ i ] * ( 1 / 2 ) ) + 1 ) : NEW_LINE INDENT if ( arr [ i ] % j == 0 ) : NEW_LINE INDENT mp [ j ] += 1 ; NEW_LINE while ( arr [ i ] % j == 0 ) : NEW_... |
Maximum possible sum of K even multiples of 5 in a given range | Function to find the maximum sum of K even multiples of 5 in the range [ L , R ] ; Store the total number of even multiples of 5 in the range [ L , R ] ; Check if K > N ; If true , print - 1 and return ; Otherwise , divide R by 10 ; Store the sum using th... | def maxksum ( L , R , K ) : NEW_LINE INDENT N = ( R // 10 - L // 10 ) + 1 ; NEW_LINE if ( K > N ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE return ; NEW_LINE DEDENT R = R // 10 ; NEW_LINE X = R - K ; NEW_LINE sum = 10 * ( ( R * ( R + 1 ) ) // 2 - ( X * ( X + 1 ) ) // 2 ) ; NEW_LINE print ( sum ) ; NEW_LINE DEDENT if _... |
Minimum swaps of same | Function to count the minimum swaps of same - indexed elements from arrays arr1 and arr2 required to make the sum of both the arrays even ; Store the sum of elements of the array arr1 and arr2 respectively ; Store the array sum of both the arrays ; If both sumArr1 and sumArr2 are even , pr0 and ... | def minimumSwaps ( arr1 , arr2 , n ) : NEW_LINE INDENT sumArr1 = 0 ; sumArr2 = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sumArr1 += arr1 [ i ] ; NEW_LINE sumArr2 += arr2 [ i ] ; NEW_LINE DEDENT if ( sumArr1 % 2 == 0 and sumArr2 % 2 == 0 ) : NEW_LINE INDENT print ( 0 ) ; NEW_LINE return ; NEW_LINE DEDENT if ( ... |
Count of seats booked on each of the given N flights | Function to find the total of the seats booked in each of the flights ; Stores the resultant sequence ; Traverse the array ; Store the first booked flight ; Store the last booked flight ; Store the total number of seats booked in flights [ l , r ] ; Add K to the fl... | def corpFlightBookings ( Bookings , N ) : NEW_LINE INDENT res = [ 0 ] * N NEW_LINE for i in range ( len ( Bookings ) ) : NEW_LINE INDENT l = Bookings [ i ] [ 0 ] NEW_LINE r = Bookings [ i ] [ 1 ] NEW_LINE K = Bookings [ i ] [ 2 ] NEW_LINE res [ l - 1 ] = res [ l - 1 ] + K NEW_LINE if ( r <= len ( res ) - 1 ) : NEW_LINE... |
Bitwise XOR of all odd numbers from a given range | Function to calculate Bitwise XOR of odd numbers in the range [ 1 , N ] ; N & 3 is equivalent to n % 4 ; If n is multiple of 4 ; If n % 4 gives remainder 1 ; If n % 4 gives remainder 2 ; If n % 4 gives remainder 3 ; Function to find the XOR of odd numbers less than or... | def findXOR ( n ) : NEW_LINE INDENT if ( n % 4 == 0 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT elif ( n % 4 == 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( n % 4 == 2 ) : NEW_LINE INDENT return n + 1 ; NEW_LINE DEDENT elif ( n % 4 == 3 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT def findOddXOR ... |
Smallest number greater than or equal to N which is divisible by its non | Function to find the smallest number greater than or equal to N such that it is divisible by its non - zero digits ; Iterate in range [ N , N + 2520 ] ; To check if the current number satisfies the given condition ; Store the number in a tempora... | def findSmallestNumber ( n ) : NEW_LINE INDENT for i in range ( n , n + 2521 ) : NEW_LINE INDENT possible = 1 NEW_LINE temp = i NEW_LINE while ( temp ) : NEW_LINE INDENT if ( temp % 10 != 0 ) : NEW_LINE INDENT digit = temp % 10 NEW_LINE if ( i % digit != 0 ) : NEW_LINE INDENT possible = 0 NEW_LINE break NEW_LINE DEDENT... |
Print path from a node to root of given Complete Binary Tree | Function to print the path from node to root ; Iterate until root is reached ; Print the value of the current node ; Move to parent of the current node ; Driver Code | def path_to_root ( node ) : NEW_LINE INDENT while ( node >= 1 ) : NEW_LINE INDENT print ( node , end = " β " ) NEW_LINE node //= 2 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE path_to_root ( N ) NEW_LINE DEDENT |
Smallest number whose sum of digits is N and every digit occurring at most K times | Function to find the smallest number whose sum of digits is N and each digit occurring at most K times ; Maximum sum possible using each digit at most K times ; Append smallest number into the resultant string ; Iterate over the range ... | def findSmallestNumberPossible ( N , K ) : NEW_LINE INDENT if ( N > 45 * K ) : NEW_LINE INDENT print ( " - 1" , endl = " " ) ; NEW_LINE return ; NEW_LINE DEDENT res = " " ; NEW_LINE count = 0 ; NEW_LINE i = 9 ; NEW_LINE while i >= 1 : NEW_LINE INDENT if ( count == K ) : NEW_LINE INDENT i -= 1 ; NEW_LINE count = 0 ; NEW... |
Minimum sum of values subtracted from array elements to make all array elements equal | Function to find the sum of values removed to make all array elements equal ; Stores the minimum of the array ; Stores required sum ; Traverse the array ; Add the value subtracted from the current element ; Return the total sum ; Dr... | def minValue ( arr , n ) : NEW_LINE INDENT minimum = min ( arr ) NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + ( arr [ i ] - minimum ) NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print (... |
Smallest positive number made up of non | Function to find smallest positive number made up of non - repeating digits whose sum of its digits is equal to n ; No such number exists ; Stores the required answer ; Store the digit at unit 's place ; Iterate until n > digit ; Push digit at the start of res ; Decrement n by ... | def result ( n ) : NEW_LINE INDENT if ( n > 45 ) : NEW_LINE INDENT print ( - 1 , end = " " ) NEW_LINE return NEW_LINE DEDENT res = " " NEW_LINE digit = 9 NEW_LINE while ( n > digit ) : NEW_LINE INDENT res = str ( digit ) + res NEW_LINE n -= digit NEW_LINE digit -= 1 NEW_LINE DEDENT if ( n > 0 ) : NEW_LINE INDENT res = ... |
Count pair of integers having even sum | Python3 program for the above approach ; Function to count even pairs ; Stores count of pairs having even sum ; Stores count of even numbers up to N ; Stores count of odd numbers up to N ; Stores count of even numbers up to M ; Stores count of odd numbers up to M ; Return the co... | import math NEW_LINE def countEvenPairs ( N , M ) : NEW_LINE INDENT count = 0 ; NEW_LINE nEven = int ( math . floor ( N / 2 ) ) ; NEW_LINE nOdd = int ( math . ceil ( N / 2 ) ) ; NEW_LINE mEven = int ( math . floor ( M / 2 ) ) ; NEW_LINE mOdd = int ( math . ceil ( M / 2 ) ) ; NEW_LINE count = nEven * mEven + nOdd * mOdd... |
Generate an N | Function to generate a string of length N having longest palindromic substring of length K ; Fill first K characters with 'a ; Stores a non - palindromic sequence to be repeated for N - k slots ; PrN - k remaining characters ; Driver Code ; Given N and K | def string_palindrome ( N , K ) : NEW_LINE ' NEW_LINE INDENT for i in range ( K ) : NEW_LINE INDENT print ( " a " , end = " " ) NEW_LINE DEDENT s = " bcd " NEW_LINE for i in range ( N - K ) : NEW_LINE INDENT print ( s [ i % 3 ] , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , K... |
Last remaining character after repeated removal of the first character and flipping of characters of a Binary String | Function to find the last removed character from the string ; Stores length of the string ; Base Case : ; If the second last character is '0 ; If the second last character is '1 ; Driver Code | def lastRemovedCharacter ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return ord ( str [ 0 ] ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( str [ n - 2 ] == '0' ) : NEW_LINE INDENT return ( ord ( '1' ) - ord ( str [ n - 1 ] ) + ord ( '0' ) ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDEN... |
Find the triplet from given Bitwise XOR and Bitwise AND values of all its pairs | Function to find the triplet with given Bitwise XOR and Bitwise AND values of all possible pairs of the triplet ; Stores values of a triplet ; Stores a + b ; Stores a + c ; Stores b + c ; Calculate aSUMb ; Calculate aSUMc ; Calculate bSUM... | def findNumbers ( aXORb , aANDb , aXORc , aANDc , bXORc , bANDc ) : NEW_LINE INDENT a , b , c = 0 , 0 , 0 ; NEW_LINE aSUMb = 0 ; NEW_LINE aSUMc = 0 ; NEW_LINE bSUMc = 0 ; NEW_LINE aSUMb = aXORb + aANDb * 2 ; NEW_LINE aSUMc = aXORc + aANDc * 2 ; NEW_LINE bSUMc = bXORc + bANDc * 2 ; NEW_LINE a = ( aSUMb - bSUMc + aSUMc )... |
Find N distinct numbers whose Bitwise XOR is equal to K | Function to find N integers having Bitwise XOR equal to K ; Base Cases ; Assign values to P and Q ; Stores Bitwise XOR of the first ( N - 3 ) elements ; Print the first N - 3 elements ; Calculate Bitwise XOR of first ( N - 3 ) elements ; Driver Code ; Function C... | def findArray ( N , K ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( K , end = " β " ) NEW_LINE return NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT print ( "0" , end = " β " ) NEW_LINE print ( K , end = " β " ) NEW_LINE return NEW_LINE DEDENT P = N - 2 NEW_LINE Q = N - 1 NEW_LINE VAL = 0 NEW_LINE for i ... |
Flip consecutive set bits starting from LSB of a given number | Function to find the number after converting 1 s from end to 0 s ; Count of 1 s ; AND operation of N and 1 ; Left shift N by count ; Driver Code ; Function Call | def findNumber ( N ) : NEW_LINE INDENT count = 0 NEW_LINE while ( ( N & 1 ) == 1 ) : NEW_LINE INDENT N = N >> 1 NEW_LINE count += 1 NEW_LINE DEDENT return N << count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 39 NEW_LINE print ( findNumber ( N ) ) NEW_LINE DEDENT |
Flip consecutive set bits starting from LSB of a given number | Function to find the number after converting 1 s from end to 0 s ; Return the logical AND of N and ( N + 1 ) ; Driver Code ; Function Call | def findNumber ( N ) : NEW_LINE INDENT return N & ( N + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 39 NEW_LINE print ( findNumber ( N ) ) NEW_LINE DEDENT |
Count of substrings of a string containing another given string as a substring | Function to store all substrings of S ; Stores the substrings of S ; Pick start point in outer loop and lengths of different strings for a given starting point ; Return the array containing substrings of S ; Function to check if a is prese... | def subString ( s , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for len in range ( 1 , n - i + 1 ) : NEW_LINE INDENT find = s [ i : i + len ] NEW_LINE v . append ( find ) NEW_LINE DEDENT DEDENT return v NEW_LINE DEDENT def IsPresent ( str , target ) : NEW_LINE INDENT if ( target in str... |
Minimum flips of odd indexed elements from odd length subarrays to make two given arrays equal | Function to find the minimum flip of subarrays required at alternate index to make binary arrays equals ; Stores count of total operations ; Stores count of consecutive unequal elements ; Loop to run on odd positions ; Incr... | def minOperation ( X , Y , n ) : NEW_LINE INDENT C = 0 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( 1 , n , 2 ) : NEW_LINE INDENT if ( X [ i ] != Y [ i ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( count != 0 ) : NEW_LINE INDENT C += 1 ; NEW_LINE DEDENT count = 0 ; NEW_LINE DEDENT D... |
Minimum subarray reversals required to make given binary array alternating | Function to count minimum subarray reversal operations required to make array alternating ; Stores minimum count of operations required to make array alternating ; Traverse the array ; If arr [ i ] is greater than arr [ i + 1 ] ; Update cntOp ... | def minimumcntOperationReq ( arr , N ) : NEW_LINE INDENT cntOp = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT cntOp += 1 NEW_LINE DEDENT DEDENT return ( cntOp + 1 ) // 2 NEW_LINE DEDENT arr = [ 1 , 1 , 1 , 0 , 1 , 0 , 0 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE... |
Modify sequence of first N natural numbers to a given array by replacing pairs with their GCD | Function to check if array arr [ ] can be obtained from first N natural numbers or not ; Driver Code ; Function Call | def isSequenceValid ( B , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if ( ( i + 1 ) % B [ i ] != 0 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " Yes " ) NEW_LINE DEDENT N = 4 NEW_LINE arr = [ 1 , 2 , 3 , 2 ] NEW_LINE isSequenceValid ( arr , N ) NEW_LINE |
Construct an array of first N natural numbers such that every adjacent pair is coprime | Function to construct an arrary with adjacent elements as co - prime numbers ; Iterate over the range [ 1 , N ] ; Print i ; Driver Code | def ConstArrayAdjacentCoprime ( N ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE ConstArrayAdjacentCoprime ( N ) NEW_LINE DEDENT |
Minimum cost to convert one given string to another using swap , insert or delete operations | Function to find the minimum cost to convert a to b ; Stores the frequency of string a and b respectively ; Store the frequencies of characters in a ; Store the frequencies of characters in b ; Minimum cost to convert A to B ... | def minimumCost ( a , b ) : NEW_LINE INDENT fre1 = [ 0 ] * ( 256 ) NEW_LINE fre2 = [ 0 ] * ( 256 ) NEW_LINE for c in a : NEW_LINE INDENT fre1 [ ord ( c ) ] += 1 NEW_LINE DEDENT for c in b : NEW_LINE INDENT fre2 [ ord ( c ) ] += 1 NEW_LINE DEDENT mincost = 0 NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT mincost += a... |
Minimum cost required to move all elements to the same position | Function to find the minimum cost required to place all elements in the same position ; Stores the count of even and odd elements ; Traverse the array arr [ ] ; Count even elements ; Count odd elements ; Print the minimum count ; Driver Code ; Given arra... | def minCost ( arr ) : NEW_LINE INDENT odd = 0 NEW_LINE even = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT even += 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT DEDENT print ( min ( even , odd ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ ... |
Maximize array sum by alternating the signs of adjacent elements | Function to find the maximum sum by alternating the signs of adjacent elements of the array ; Stores count of negative elements in the array ; Stores maximum sum by alternating the signs of adjacent elements ; Stores smallest absolute value of array ele... | def findMaxSumByAlternatingSign ( arr , N ) : NEW_LINE INDENT cntNeg = 0 NEW_LINE MaxAltSum = 0 NEW_LINE SmValue = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT cntNeg += 1 NEW_LINE DEDENT sum += abs ( arr [ i ] ) NEW_LINE SmValue = min ( SmValue , abs ( arr [... |
Construct array with sum of product of same indexed elements in the given array equal to zero | Function to generate a new array with product of same indexed elements with arr [ ] equal to 0 ; Stores sum of same indexed array elements of arr and new array ; Traverse the array ; If i is an even number ; Insert arr [ i +... | def constructNewArraySumZero ( arr , N ) : NEW_LINE INDENT newArr = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT newArr [ i ] = arr [ i + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT newArr [ i ] = - arr [ i - 1 ] NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDE... |
Generate Bitonic Sequence of length N from integers in a given range | Python3 program for the above approach ; Function to construct bitonic sequence of length N from integers in the range [ L , R ] ; If sequence is not possible ; Store the resultant list ; If size of deque < n ; Add elements from start ; Print the st... | from collections import deque NEW_LINE def bitonicSequence ( num , lower , upper ) : NEW_LINE INDENT if ( num > ( upper - lower ) * 2 + 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT ans = deque ( ) NEW_LINE for i in range ( min ( upper - lower + 1 , num - 1 ) ) : NEW_LINE INDENT ans . append ( upp... |
Count substrings of same length differing by a single character from two given strings | Function to count the number of substrings of equal length which differ by a single character ; Stores the count of pairs of substrings ; Traverse the string s ; Traverse the string t ; Different character ; Increment the answer ; ... | def countSubstrings ( s , t ) : NEW_LINE INDENT answ = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT for j in range ( len ( t ) ) : NEW_LINE INDENT if t [ j ] != s [ i ] : NEW_LINE INDENT answ += 1 NEW_LINE k = 1 NEW_LINE z = - 1 NEW_LINE q = 1 NEW_LINE while ( j + z >= 0 <= i + z and s [ i + z ] == t [ j +... |
Minimum flips to make all 1 s in right and 0 s in left | Function to find the minimum count of flips required to make all 1 s on the right and all 0 s on the left of the given string ; Stores length of str ; Store count of 0 s in the string ; Traverse the string ; If current character is 0 ; Update zeros ; If count of ... | def minimumCntOfFlipsRequired ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE zeros = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT zeros += 1 ; NEW_LINE DEDENT DEDENT if ( zeros == 0 or zeros == n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT minFlips = 10000001 ; ... |
Maximize length of longest non | Function to find the length of the longest non - decreasing array that can be generated ; Stores the length of the longest non - decreasing array that can be generated from the array ; Stores index of start pointer ; Stores index of end pointer ; Stores previously inserted element into ... | def findLongestNonDecreasing ( A , N ) : NEW_LINE INDENT res = 0 ; NEW_LINE start = 0 ; NEW_LINE end = N - 1 ; NEW_LINE prev = - 1 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT if ( A [ start ] <= A [ end ] ) : NEW_LINE INDENT if ( prev == - 1 ) : NEW_LINE INDENT prev = A [ start ] ; NEW_LINE res += 1 NEW_LINE st... |
Non | Function to print all pairs whose sum of Bitwise OR and AND is N ; Iterate from i = 0 to N ; Print pairs ( i , N - i ) ; Driver code | def findPairs ( N ) : NEW_LINE INDENT for i in range ( 0 , N + 1 ) : NEW_LINE INDENT print ( " ( " , i , " , " , N - i , " ) , β " , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE findPairs ( N ) NEW_LINE DEDENT |
Minimum index to split array into subarrays with co | Function to find the GCD of 2 numbers ; Base Case ; Find the GCD recursively ; Function to find the minimum partition index K s . t . product of both subarrays around that partition are co - prime ; Stores the prefix and suffix array product ; Update the prefix arra... | def GCD ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return GCD ( b , a % b ) NEW_LINE DEDENT def findPartition ( nums , N ) : NEW_LINE INDENT prefix = [ 0 ] * N NEW_LINE suffix = [ 0 ] * N NEW_LINE prefix [ 0 ] = nums [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT pre... |
Minimum subarray reversals required such that sum of all pairs of adjacent elements is odd | Function to count reversals to separate elements with same parity ; Traverse the given array ; Count size of subarray having integers with same parity only ; Otherwise ; Reversals required is equal to one less than subarray siz... | def separate ( arr , n , parity ) : NEW_LINE INDENT count = 1 NEW_LINE res = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( ( ( arr [ i ] + parity ) & 1 ) and ( ( arr [ i - 1 ] + parity ) & 1 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( count > 1 ) : NEW_LINE INDENT res += co... |
Count prime pairs whose difference is also a Prime Number | Python3 program to implement the above approach ; Function to find all prime numbers in the range [ 1 , N ] ; isPrime [ i ] : Stores if i is a prime number or not ; Calculate all prime numbers up to Max using Sieve of Eratosthenes ; If P is a prime number ; Se... | from math import sqrt NEW_LINE def SieveOfEratosthenes ( N ) : NEW_LINE INDENT isPrime = [ True for i in range ( N + 1 ) ] NEW_LINE isPrime [ 0 ] = False NEW_LINE isPrime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT if ( isPrime [ p ] ) : NEW_LINE INDENT for i in range ( p ... |
Length of longest subsequence consisting of distinct adjacent elements | Function that finds the length of longest subsequence having different adjacent elements ; Stores the length of the longest subsequence ; Traverse the array ; If previous and current element are not same ; Increment the count ; Print the maximum l... | def longestSubsequence ( arr , N ) : NEW_LINE INDENT count = 1 NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i - 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 8 , 1 , 2 , 2 , 5 , 5... |
Count of substrings having the most frequent character in the string as first character | Python3 program for the above approach ; Function to find all substrings whose first character occurs maximum number of times ; Stores frequency of characters ; Stores character that appears maximum number of times max_char = ; St... | import sys NEW_LINE def substringCount ( s ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE DEDENT INDENT maxfreq = - sys . maxsize - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE if ( maxfreq < freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] ) ... |
Minimum sum possible by assigning every increasing / decreasing consecutive pair with values in that order | Function to print the minimum sum of values assigned to each element of the array as per given conditions ; Initialize vectors with value 1 ; Traverse from left to right ; Update if ans [ i ] > ans [ i - 1 ] ; T... | def minSum ( arr , n ) : NEW_LINE INDENT ans = [ 1 ] * ( n ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT ans [ i ] = max ( ans [ i ] , ans [ i - 1 ] + 1 ) NEW_LINE DEDENT DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1... |
Maximize sum of assigned weights by flipping at most K bits in given Binary String | Function to find maximum sum of weights of binary string after at most K flips ; Stores lengths of substrings of the form 1. . 00. . 1 s ; Stores the index of last 1 encountered in the string ; Stores the index of first 1 encountered ;... | def findMax ( s , n , k ) : NEW_LINE INDENT ans = 0 ; NEW_LINE l = 0 ; NEW_LINE ind = - 1 ; NEW_LINE indf = - 1 ; NEW_LINE ls = set ( [ ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT l += 1 NEW_LINE DEDENT elif ( s [ i ] == '1' and l > 0 and ans != 0 ) : NEW_LINE INDENT ls .... |
Minimum removal of consecutive similar characters required to empty a Binary String | Python3 program for the above approach ; Function to find minimum steps to make the empty ; Stores the modified string ; Size of string ; Removing substring of same character from modified string ; Print the minimum steps required ; D... | from math import ceil NEW_LINE def minSteps ( S ) : NEW_LINE INDENT new_str = " " NEW_LINE N = len ( S ) NEW_LINE i = 0 NEW_LINE while ( i < N ) : NEW_LINE INDENT new_str += S [ i ] NEW_LINE j = i NEW_LINE while ( i < N and S [ i ] == S [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT print ( ceil ( ( len ( new_... |
Count pairs with equal Bitwise AND and Bitwise OR value | Function to count pairs in an array whose bitwise AND equal to bitwise OR ; Store count of pairs whose bitwise AND equal to bitwise OR ; Stores frequency of distinct elements of array ; Traverse the array ; Increment the frequency of arr [ i ] ; Traverse map ; D... | def countPairs ( arr , N ) : NEW_LINE INDENT cntPairs = 0 NEW_LINE mp = { } NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] = mp [ arr [ i ] ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT for freq in mp : NEW_LINE INDENT... |
Minimum increments required to make given matrix palindromic | Function to evaluate minimum number of operation required to convert the matrix to a palindrome matrix ; Variable to store number of operations required ; Iterate over the first quadrant of the matrix ; Store positions of all four values from four quadrants... | def palindromeMatrix ( N , M , arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( ( N + 1 ) // 2 ) : NEW_LINE INDENT for j in range ( ( M + 1 ) // 2 ) : NEW_LINE INDENT s = { } NEW_LINE s [ ( i , j ) ] = 1 NEW_LINE s [ ( i , M - j - 1 ) ] = 1 NEW_LINE s [ ( N - i - 1 , j ) ] = 1 NEW_LINE s [ ( N - i - 1 , M - j ... |
Minimum division by 10 and multiplication by 2 required to reduce given number to 1 | Function to find the minimum number operations required to reduce N to 1 ; Stores count of powers of 2 and 5 ; Calculating the primefactors 2 ; Calculating the primefactors 5 ; If n is 1 and cnt2 <= cnt5 ; Return the minimum operation... | def minimumMoves ( n ) : NEW_LINE INDENT cnt2 = 0 NEW_LINE cnt5 = 0 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n //= 2 NEW_LINE cnt2 += 1 NEW_LINE DEDENT while ( n % 5 == 0 ) : NEW_LINE INDENT n //= 5 NEW_LINE cnt5 += 1 NEW_LINE DEDENT if ( n == 1 and cnt2 <= cnt5 ) : NEW_LINE INDENT return 2 * cnt5 - cnt2 NEW_LIN... |
Check if permutation of first N natural numbers exists having Bitwise AND of adjacent elements non | Function to check if a permutation of first N natural numbers exist with Bitwise AND of adjacent elements not equal to 0 ; If n is a power of 2 ; Driver Code | def check ( n ) : NEW_LINE INDENT if ( ( n & n - 1 ) != 0 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE check ( n ) NEW_LINE DEDENT |
Minimize adding odd and subtracting even numbers to make all array elements equal to K | Function to find the minimum operations required to make array elements equal to K ; Stores minimum count of operations ; Traverse the given array ; If K is greater than arr [ i ] ; If ( K - arr [ i ] ) is even ; Update cntOpe ; Up... | def MinOperation ( arr , N , K ) : NEW_LINE INDENT cntOpe = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( K > arr [ i ] ) : NEW_LINE INDENT if ( ( K - arr [ i ] ) % 2 == 0 ) : NEW_LINE INDENT cntOpe += 2 NEW_LINE DEDENT else : NEW_LINE INDENT cntOpe += 1 NEW_LINE DEDENT DEDENT elif ( K < arr [ i ] ) : NEW_LINE... |
Rearrange array to make Bitwise XOR of similar indexed elements of two arrays is same | Function to rearrange the array B [ ] such that A [ i ] ^ B [ i ] is same for each element ; Store frequency of elements ; Stores xor value ; Taking xor of all the values of both arrays ; Store frequency of B [ ] ; Find the array B ... | def rearrangeArray ( A , B , N ) : NEW_LINE INDENT m = { } NEW_LINE xor_value = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT xor_value ^= A [ i ] NEW_LINE xor_value ^= B [ i ] NEW_LINE if B [ i ] in m : NEW_LINE m [ B [ i ] ] = m [ B [ i ] ] + 1 NEW_LINE else : NEW_LINE m [ B [ i ] ] = 1 NEW_LINE DEDENT for i ... |
Count sequences of given length having non | Function to find the Binomial Coefficient C ( n , r ) ; Stores the value C ( n , r ) ; Update C ( n , r ) = C ( n , n - r ) ; Find C ( n , r ) iteratively ; Return the final value ; Function to find number of sequence whose prefix sum at each index is always non - negative ;... | def binCoff ( n , r ) : NEW_LINE INDENT val = 1 NEW_LINE if ( r > ( n - r ) ) : NEW_LINE INDENT r = ( n - r ) NEW_LINE DEDENT for i in range ( 0 , r ) : NEW_LINE INDENT val *= ( n - i ) NEW_LINE val //= ( i + 1 ) NEW_LINE DEDENT return val NEW_LINE DEDENT def findWays ( M ) : NEW_LINE INDENT n = M // 2 NEW_LINE a = bin... |
XOR of array elements whose modular inverse with a given number exists | Function to return the gcd of a & b ; Base Case ; Recursively calculate GCD ; Function to print the Bitwise XOR of elements of arr [ ] if gcd ( arr [ i ] , M ) is 1 ; Initialize xor ; Traversing the array ; GCD of M and arr [ i ] ; If GCD is 1 , u... | def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def countInverse ( arr , N , M ) : NEW_LINE INDENT XOR = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT gcdOfMandelement = gcd ( M , arr [ i ] ) NEW_LINE if ( gcdOfMandelement == ... |
Count positions in a chessboard that can be visited by the Queen which are not visited by the King | Function to print the number of cells only visited by the queen ; Find all the moves ; Find all moves for x + 1 , y + 1 ; Find all moves for x - 1 , y - 1 ; Find all moves for x - 1 , y + 1 ; Find all moves for x + 1 , ... | def Moves_Calculator ( x , y , row , col ) : NEW_LINE INDENT total_moves = 0 NEW_LINE if ( row - x ) > 0 and ( col - y ) > 0 : NEW_LINE INDENT total_moves += min ( ( row - x ) , ( col - y ) ) NEW_LINE DEDENT if ( y - 1 ) > 0 and ( x - 1 ) > 0 : NEW_LINE INDENT total_moves += min ( ( y - 1 ) , ( x - 1 ) ) NEW_LINE DEDEN... |
Nearest smaller number to N having multiplicative inverse under modulo N equal to that number | Function to find the nearest smaller number satisfying the condition ; Driver Code | def clstNum ( N ) : NEW_LINE INDENT return ( N - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 11 NEW_LINE print ( clstNum ( N ) ) NEW_LINE DEDENT |
Count array elements having modular inverse under given prime number P equal to itself | Function to get the count of elements that satisfy the given condition . ; Stores count of elements that satisfy the condition ; Traverse the given array . ; If square of current element is equal to 1 ; Driver Code | def equvInverse ( arr , N , P ) : NEW_LINE INDENT cntElem = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( ( arr [ i ] * arr [ i ] ) % P == 1 ) : NEW_LINE INDENT cntElem = cntElem + 1 NEW_LINE DEDENT DEDENT return cntElem NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 6 , 4 , ... |
Count ways to split array into K non | Function to get the value of pow ( K , M ) ; Stores value of pow ( K , M ) ; Calculate value of pow ( K , N ) ; If N is odd , update res ; Update M to M / 2 ; Update K ; Function to print total ways to split the array that satisfies the given condition ; Stores total ways that sat... | def power ( K , M ) : NEW_LINE INDENT res = 1 NEW_LINE while ( M > 0 ) : NEW_LINE INDENT if ( ( M & 1 ) == 1 ) : NEW_LINE INDENT res = ( res * K ) NEW_LINE DEDENT M = M >> 1 NEW_LINE K = ( K * K ) NEW_LINE DEDENT return res NEW_LINE DEDENT def cntWays ( arr , N , K ) : NEW_LINE INDENT cntways = 0 NEW_LINE M = 0 NEW_LIN... |
Minimize product of first N | Python3 program for the above approach ; Function to find the minimum product of 1 to N - 1 after performing the given operations ; Initialize ans with 1 ; Multiply ans with N - 2 ( ( N - 4 ) / 2 ) times ; Multiply ans with N - 1 and N - 2 once ; Print ans ; Driver Code ; Given number N ; ... | mod = 1e9 + 7 NEW_LINE def minProduct ( n ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , ( n - 4 ) // 2 + 1 ) : NEW_LINE INDENT ans = ( ans * ( n - 2 ) ) % mod NEW_LINE DEDENT ans = ( ans * ( n - 2 ) * ( n - 1 ) ) % mod NEW_LINE print ( int ( ans ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE... |
Bitwise XOR of all unordered pairs from a given array | Function to get bitwise XOR of all possible pairs of the given array ; Stores bitwise XOR of all possible pairs ; Generate all possible pairs and calculate bitwise XOR of all possible pairs ; Calculate bitwise XOR of each pair ; Driver code | def TotalXorPair ( arr , N ) : NEW_LINE INDENT totalXOR = 0 ; NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT totalXOR ^= arr [ i ] ^ arr [ j ] ; NEW_LINE DEDENT DEDENT return totalXOR ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , ... |
Count permutations of all integers upto N that can form an acyclic graph based on given conditions | Find the count of possible graphs ; Driver code | def possibleAcyclicGraph ( N ) : NEW_LINE INDENT print ( pow ( 2 , N - 1 ) ) NEW_LINE return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE possibleAcyclicGraph ( N ) NEW_LINE DEDENT |
Minimize positive product of two given numbers by at most N decrements | Function to minimize the product of two numbers ; Reducing X , N times , minimizes the product ; Reduce X to 1 and reduce remaining N from Y ; Reducing Y , N times , minimizes the product ; Reduce Y to 1 and reduce remaining N from X ; Driver Code | def minProd ( X , Y , N ) : NEW_LINE INDENT if ( X <= Y ) : NEW_LINE INDENT if ( N < X ) : NEW_LINE INDENT return ( X - N ) * Y NEW_LINE DEDENT else : NEW_LINE INDENT return max ( Y - ( N - X + 1 ) , 1 ) NEW_LINE DEDENT DEDENT if ( Y >= N ) : NEW_LINE INDENT return ( Y - N ) * X NEW_LINE DEDENT return max ( X - ( N - Y... |
Count pairs from an array having product of their sum and difference equal to 1 | Function to count the desired number of pairs ; Initialize oneCount ; Initialize the desiredPair ; Traverse the given array ; If 1 is encountered ; If 0 is encountered ; Update count of pairs ; Return the final count ; Driver Code ; Given... | def countPairs ( arr , n ) : NEW_LINE INDENT oneCount = 0 NEW_LINE desiredPair = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT oneCount += 1 NEW_LINE DEDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT desiredPair += oneCount NEW_LINE DEDENT DEDENT return desiredPair NEW_LINE DEDE... |
Smallest missing non | Function to prthe smallest missing non - negative integer up to every array indices ; Stores the smallest missing non - negative integers between start index to current index ; Store the boolean value to check smNonNeg present between start index to each index of the array ; Traverse the array ; ... | def smlstNonNeg ( arr , N ) : NEW_LINE INDENT smNonNeg = 0 NEW_LINE hash = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] >= 0 and arr [ i ] < N ) : NEW_LINE INDENT hash [ arr [ i ] ] = True NEW_LINE DEDENT while ( hash [ smNonNeg ] ) : NEW_LINE INDENT smNonNeg += 1 NEW_LINE DEDENT pri... |
Split array into two subsequences having minimum count of pairs with sum equal to X | Function to split the array into two subsequences ; Stores the two subsequences ; Flag to set / reset to split arrays elements alternately into two arrays ; Traverse the given array ; If 2 * arr [ i ] is less than X ; Push element int... | def solve ( arr , N , X ) : NEW_LINE INDENT A = [ ] NEW_LINE B = [ ] NEW_LINE c = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( ( 2 * arr [ i ] ) < X ) : NEW_LINE INDENT A . append ( arr [ i ] ) NEW_LINE DEDENT elif ( ( 2 * arr [ i ] ) > X ) : NEW_LINE INDENT B . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW... |
Split array into minimum number of subsets having maximum pair sum at most K | Function to get the minimum count of subsets that satisfy the given condition ; Store the minimum count of subsets that satisfy the given condition ; Stores start index of the sorted array . ; Stores end index of the sorted array ; Sort the ... | def cntMinSub ( arr , N , K ) : NEW_LINE INDENT res = 0 NEW_LINE start = 0 NEW_LINE end = N - 1 NEW_LINE arr = sorted ( arr ) NEW_LINE while ( end - start > 1 ) : NEW_LINE INDENT if ( arr [ start ] + arr [ end ] <= K ) : NEW_LINE INDENT start += 1 NEW_LINE DEDENT else : NEW_LINE INDENT res += 1 NEW_LINE end -= 1 NEW_LI... |
Count possible values of K such that X | Function to count integers K satisfying given equation ; Calculate the absoluter difference between a and b ; Iterate till sqrt of the difference ; Return the count ; Driver Code | def condition ( a , b ) : NEW_LINE INDENT d = abs ( a - b ) NEW_LINE count = 0 NEW_LINE for i in range ( 1 , d + 1 ) : NEW_LINE INDENT if i * i > d : NEW_LINE INDENT break NEW_LINE DEDENT if ( d % i == 0 ) : NEW_LINE INDENT if ( d // i == i ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += ... |
Count pairs in an array whose product is composite number | Function to check if a number is prime or not ; Check if N is multiple of i or not . ; If N is multiple of i . ; Function to get the count of pairs whose product is a composite number . ; Stores the count of pairs whose product is a composite number ; Generate... | def isComposite ( N ) : NEW_LINE INDENT for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT if ( N % i == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def compositePair ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ... |
Count N | Python3 program for the above approach ; Function for calculate ( x ^ y ) % mod in O ( log y ) ; Base Condition ; Transition state of power Function ; Function for counting total numbers that can be formed such that digits X , Y are present in each number ; Calculate the given expression ; Return the final an... | mod = 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 TotalNumber ( N ) : NEW_LINE INDENT a... |
Array obtained by repeatedly reversing array after every insertion from given array | Python3 program of the above approach ; Function to generate the array by inserting array elements one by one followed by reversing the array ; Doubly ended Queue ; Iterate over the array ; Push array elements alternately to the front... | from collections import deque NEW_LINE def generateArray ( arr , n ) : NEW_LINE INDENT ans = deque ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i & 1 != 0 ) : NEW_LINE INDENT ans . appendleft ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT ans . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT if ( n & 1 !=... |
Find the greater number closest to N having at most one non | Function to get closest greater number with at most non zero digit ; Stores the closest greater number with at most one non - zero digit ; Stores length of str ; Append 10 to the end of resultant String ; Append n - 1 times '0' to the end of resultant String... | def closestgtNum ( str ) : NEW_LINE INDENT res = " " ; NEW_LINE n = len ( str ) ; NEW_LINE if ( str [ 0 ] < '9' ) : NEW_LINE INDENT res += ( chr ) ( ord ( str [ 0 ] ) + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT res += ( chr ) ( '1' ) ; NEW_LINE res += ( chr ) ( '0' ) ; NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_... |
Count maximum non | Function to count maximum number of non - overlapping subarrays with sum equals to the target ; Stores the final count ; Next subarray should start from index >= availIdx ; Tracks the prefix sum ; Map to store the prefix sum for respective indices ; Check if cur_sum - target is present in the array ... | def maximumSubarrays ( arr , N , target ) : NEW_LINE INDENT ans = 0 NEW_LINE availIdx = - 1 NEW_LINE cur_sum = 0 NEW_LINE mp = { } NEW_LINE mp [ 0 ] = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cur_sum += arr [ i ] NEW_LINE if ( ( cur_sum - target ) in mp and mp [ cur_sum - target ] >= availIdx ) : NEW_LINE IN... |
Maximize array sum by replacing equal adjacent pairs by their sum and X respectively | Function to calculate x ^ y ; Base Case ; Find the value in temp ; If y is even ; Function that find the maximum possible sum of the array ; Print the result using the formula ; Driver Code ; Function call | def power ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT temp = power ( x , y // 2 ) NEW_LINE if ( y % 2 == 0 ) : NEW_LINE INDENT return temp * temp NEW_LINE DEDENT else : NEW_LINE INDENT return x * temp * temp NEW_LINE DEDENT DEDENT def maximumPossibleSum ( N , X ) : NEW_LINE INDE... |
Count ways to generate pairs having Bitwise XOR and Bitwise AND equal to X and Y respectively | Function to return the count of possible pairs of A and B whose Bitwise XOR is X and Y respectively ; Stores the count of pairs ; Iterate till any bit are set ; Extract i - th bit of X and Y ; Divide X and Y by 2 ; If Xi = 1... | def countOfPairs ( x , y ) : NEW_LINE INDENT counter = 1 NEW_LINE while ( x or y ) : NEW_LINE INDENT bit1 = x % 2 NEW_LINE bit2 = y % 2 NEW_LINE x >>= 1 NEW_LINE y >>= 1 NEW_LINE if ( bit1 == 1 and bit2 == 0 ) : NEW_LINE INDENT counter *= 2 NEW_LINE continue NEW_LINE DEDENT if ( bit1 & bit2 ) : NEW_LINE INDENT counter ... |
Make all array elements equal by repeated subtraction of absolute difference of pairs from their maximum | Function to return gcd of a and b ; Base Case ; Recursive call ; Function to find gcd of array ; Initialise the result ; Traverse the array arr [ ] ; Update result as gcd of the result and arr [ i ] ; Return the r... | def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def findGCD ( arr , N ) : NEW_LINE INDENT result = 0 NEW_LINE for element in arr : NEW_LINE INDENT result = gcd ( result , element ) NEW_LINE if ( result == 1 ) : NEW_LINE INDENT return ... |
Check if any permutation of array contains sum of every adjacent pair not divisible by 3 | Function to checks if any permutation of the array exists whose sum of adjacent pairs is not divisible by 3 ; Count remainder 0 ; Count remainder 1 ; Count remainder 2 ; Condition for valid arrangements ; Given array arr [ ] ; Fu... | def factorsOf3 ( arr , N ) : NEW_LINE INDENT a = 0 NEW_LINE b = 0 NEW_LINE c = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 3 == 0 ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT elif ( arr [ i ] % 3 == 1 ) : NEW_LINE INDENT b += 1 NEW_LINE DEDENT elif ( arr [ i ] % 3 == 2 ) : NEW_LINE INDENT c += 1 NE... |
Check if a number is a perfect square having all its digits as a perfect square | Python3 program for the above approach ; Function to check if digits of N is a perfect square or not ; Iterate over the digits ; Extract the digit ; Check if digit is a perfect square or not ; Divide N by 10 ; Return true ; Function to ch... | import math NEW_LINE def check_digits ( N ) : NEW_LINE INDENT while ( N > 0 ) : NEW_LINE INDENT n = N % 10 NEW_LINE if ( ( n != 0 ) and ( n != 1 ) and ( n != 4 ) and ( n != 9 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT N = N // 10 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def is_perfect ( N ) : NEW_LINE INDENT n = ma... |
Count substrings with different first and last characters | Function to count the substrings having different first & last character ; Stores frequency of each char ; Loop to store frequency of the characters in a Map ; To store final result ; Traversal of string ; Store answer for every iteration ; Map traversal ; Com... | def countSubstring ( s , n ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] in m : NEW_LINE INDENT m [ s [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ s [ i ] ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE if s [ i ] ... |
Maximize count of empty water bottles from N filled bottles | Function to find the maximum bottles that can be emptied ; Iterate until a is non - zero ; Add the number of bottles that are emptied ; Update a after exchanging empty bottles ; Stores the number of bottles left after the exchange ; Return the answer ; Drive... | def maxBottles ( n , e ) : NEW_LINE INDENT s = 0 NEW_LINE b = 0 NEW_LINE a = n NEW_LINE while ( a != 0 ) : NEW_LINE INDENT s = s + a NEW_LINE a = ( a + b ) // e NEW_LINE b = n - ( a * e ) NEW_LINE n = a + b NEW_LINE DEDENT return s NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 9 NEW_LINE e = 3 N... |
Count all N digit numbers whose digits are multiple of X | Function to calculate x ^ n using binary - exponentiation ; Stores the resultant power ; Stores the value of x ^ ( n / 2 ) ; Function to count aN - digit numbers whose digits are multiples of x ; Count adigits which are multiples of x ; Check if current number ... | def power ( x , n ) : NEW_LINE INDENT temp = [ ] NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT temp = power ( x , n // 2 ) NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT return temp * temp NEW_LINE DEDENT else : NEW_LINE INDENT return x * temp * temp NEW_LINE DEDENT DEDENT def count_Total_Numbers ( n ... |
Find the vertex diagonally opposite to the vertex M from an N | Function to return the required vertex ; Case 1 : ; Case 2 : ; Driver Code | def getPosition ( N , M ) : NEW_LINE INDENT if ( M > ( N // 2 ) ) : NEW_LINE INDENT return ( M - ( N // 2 ) ) NEW_LINE DEDENT return ( M + ( N // 2 ) ) NEW_LINE DEDENT N = 8 NEW_LINE M = 5 NEW_LINE print ( getPosition ( N , M ) ) NEW_LINE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.