text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Append digits to the end of duplicate strings to make all strings in an array unique | Function to replace duplicate strings by alphanumeric strings to make all strings in the array unique ; Store the frequency of strings ; Iterate over the array ; For the first occurrence , update the frequency count ; Otherwise ; App...
def replaceDuplicates ( names ) : NEW_LINE INDENT hash = { } NEW_LINE for i in range ( 0 , len ( names ) ) : NEW_LINE INDENT if names [ i ] not in hash : NEW_LINE INDENT hash [ names [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = hash [ names [ i ] ] NEW_LINE hash [ names [ i ] ] += 1 NEW_LINE names [ i ] +...
Minimum cost of flipping characters required to convert Binary String to 0 s only | Function to find the minimum cost to convert given string to 0 s only ; Length of string ; Stores the index of leftmost '1' in str ; Update the index of leftmost '1' in str ; Stores the index of rightmost '1' in str ; Update the index o...
def convert_to_allzeroes ( st , a , b ) : NEW_LINE INDENT length = len ( st ) NEW_LINE left_1 = 0 NEW_LINE i = 0 NEW_LINE while ( i < length and st [ i ] == '0' ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT left_1 = i NEW_LINE right_1 = 0 NEW_LINE i = length - 1 NEW_LINE while ( i >= 0 and st [ i ] == '0' ) : NEW_LINE IND...
Minimum distance to visit given K points on X | Python3 program to implement the above approach ; Function to find the minimum distance travelled to visit K point ; Stores minimum distance travelled to visit K point ; Stores distance travelled to visit points ; Traverse the array arr [ ] ; If arr [ i ] and arr [ i + K ...
import sys NEW_LINE def MinDistK ( arr , N , K ) : NEW_LINE INDENT res = sys . maxsize NEW_LINE dist = 0 NEW_LINE for i in range ( N - K + 1 ) : NEW_LINE INDENT if ( arr [ i ] >= 0 and arr [ i + K - 1 ] >= 0 ) : NEW_LINE INDENT dist = max ( arr [ i ] , arr [ i + K - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dist = (...
Maximize the minimum array element by M subarray increments of size S | Function to return index of minimum element in the array ; Initialize a [ 0 ] as minValue ; Traverse the array ; If a [ i ] < existing minValue ; Return the minimum index ; Function that maximize the minimum element of array after incrementing suba...
def min ( a , n ) : NEW_LINE INDENT minIndex = 0 NEW_LINE minValue = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] < minValue ) : NEW_LINE INDENT minValue = a [ i ] NEW_LINE minIndex = i NEW_LINE DEDENT DEDENT return minIndex NEW_LINE DEDENT def maximizeMin ( A , N , S , M ) : NEW_LINE INDENT...
Sum of nodes in the path from root to N | Python3 program for the above approach ; Function to find sum of all nodes from root to N ; If N is equal to 1 ; If N is equal to 2 or 3 ; 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 ...
from bisect import bisect_left , bisect NEW_LINE def sumOfPathNodes ( N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( N == 2 or N == 3 ) : NEW_LINE INDENT return N + 1 NEW_LINE DEDENT arr = [ ] NEW_LINE arr . append ( 1 ) NEW_LINE k = 1 NEW_LINE flag = True NEW_LINE while ( k < N )...
Check if given point lies in range of any of the given towers | Python3 program to implement the above approach ; Function to check if the point ( X , Y ) exists in the towers network - range or not ; Traverse the array arr [ ] ; Stores distance of the point ( X , Y ) from i - th tower ; If dist lies within the range o...
from math import sqrt NEW_LINE def checkPointRange ( arr , X , Y , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT dist = sqrt ( ( arr [ i ] [ 0 ] - X ) * ( arr [ i ] [ 0 ] - X ) + ( arr [ i ] [ 1 ] - Y ) * ( arr [ i ] [ 1 ] - Y ) ) NEW_LINE if ( dist <= arr [ i ] [ 2 ] ) : NEW_LINE INDENT return True NEW_...
Find the winner of the Game of removing odd or replacing even array elements | Function to evaluate the winner of the game ; Stores count of odd array elements ; Stores count of even array elements ; Traverse the array ; If array element is odd ; Otherwise ; If count of even is zero ; If count of odd is even ; If count...
def findWinner ( arr , N ) : NEW_LINE INDENT odd = 0 NEW_LINE even = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even += 1 NEW_LINE DEDENT DEDENT if ( even == 0 ) : NEW_LINE INDENT if ( odd % 2 == 0 ) : NEW_LINE INDENT pri...
Rearrange array to maximize count of local minima | Function to rearrange array elements to maximize count of local minima in the array ; Sort the array in ascending order ; Stores index of left pointer ; Stores index of right pointer ; Traverse the array elements ; if right is less than N ; Print array element ; Updat...
def rearrangeArrMaxcntMinima ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE left = 0 NEW_LINE right = N // 2 NEW_LINE while ( left < N // 2 or right < N ) : NEW_LINE INDENT if ( right < N ) : NEW_LINE INDENT print ( arr [ right ] , end = " ▁ " ) NEW_LINE right += 1 NEW_LINE DEDENT if ( left < N // 2 ) : NEW_LINE...
Minimum jumps required to make a group of persons sit together | Python3 program for the above approach ; Function to find the minimum jumps required to make the whole group sit adjacently ; Store the indexes ; Stores the count of occupants ; Length of the string ; Traverse the seats ; If current place is occupied ; Pu...
MOD = 10 ** 9 + 7 NEW_LINE def minJumps ( seats ) : NEW_LINE INDENT position = [ ] NEW_LINE count = 0 NEW_LINE lenn = len ( seats ) NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( seats [ i ] == ' x ' ) : NEW_LINE INDENT position . append ( i - count ) NEW_LINE count += 1 NEW_LINE DEDENT DEDENT if ( count == le...
Count pairs whose product contains single distinct prime factor | Function to find a single distinct prime factor of N ; Stores distinct prime factors of N ; Calculate prime factor of N ; Calculate distinct prime factor ; Insert i into disPrimeFact ; Update N ; If N is not equal to 1 ; Insert N into disPrimeFact ; If N...
def singlePrimeFactor ( N ) : NEW_LINE INDENT disPrimeFact = { } NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT while ( N % i == 0 ) : NEW_LINE INDENT disPrimeFact [ i ] = 1 NEW_LINE N //= i NEW_LINE DEDENT DEDENT if ( N != 1 ) : NEW_LINE INDENT disPrimeFact...
Minimize replacements or swapping of same indexed characters required to make two given strings palindromic | Function to find minimum operations to make both the strings palindromic ; Stores index of the left pointer ; Stores index of the right pointer ; Stores count of minimum operations to make both the strings pali...
def MincntBothPalin ( str1 , str2 , N ) : NEW_LINE INDENT i = 0 NEW_LINE j = N - 1 NEW_LINE cntOp = 0 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( str1 [ i ] == str1 [ j ] and str2 [ i ] != str2 [ j ] ) : NEW_LINE INDENT cntOp += 1 NEW_LINE DEDENT elif ( str1 [ i ] != str1 [ j ] and str2 [ i ] == str2 [ j ] ) : NEW_...
Find an integral solution of the non | Python3 program to implement the above approach ; Function to find the value of power ( X , N ) ; Stores the value of ( X ^ N ) ; Calculate the value of power ( x , N ) ; If N is odd ; Update res ; Update x ; Update N ; Function to find the value of X and Y that satisfy the condit...
from math import log2 NEW_LINE def power ( x , N ) : NEW_LINE INDENT res = 1 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N & 1 ) : NEW_LINE INDENT res = ( res * x ) NEW_LINE DEDENT x = ( x * x ) NEW_LINE N = N >> 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def findValX_Y ( N ) : NEW_LINE INDENT if ( N <= 1 ) : NEW...
Count pairs from two arrays with difference exceeding K | set 2 | Python3 program for the above approach ; Function to count pairs that satisfy the given conditions ; Stores the count of pairs ; If v1 [ ] is smaller than v2 [ ] ; Sort the array v1 [ ] ; Traverse the array v2 [ ] ; Returns the address of the first numbe...
from bisect import bisect_left , bisect_right NEW_LINE def countPairs ( v1 , v2 , n , m , k ) : NEW_LINE INDENT count = 0 NEW_LINE if ( n <= m ) : NEW_LINE INDENT v1 = sorted ( v1 ) NEW_LINE for j in range ( m ) : NEW_LINE INDENT index = bisect_left ( v1 , v2 [ j ] - k ) NEW_LINE count += index NEW_LINE DEDENT DEDENT e...
Maximum sum subarray of size K with sum less than X | Function to calculate maximum sum among all subarrays of size K with the sum less than X ; Initialize sum_K to 0 ; Calculate sum of first K elements ; If sum_K is less than X ; Initialize MaxSum with sum_K ; Iterate over the array from ( K + 1 ) - th index ; Subtrac...
def maxSumSubarr ( A , N , K , X ) : NEW_LINE INDENT sum_K = 0 NEW_LINE for i in range ( 0 , K ) : NEW_LINE INDENT sum_K += A [ i ] NEW_LINE DEDENT Max_Sum = 0 NEW_LINE if ( sum_K < X ) : NEW_LINE INDENT Max_Sum = sum_K NEW_LINE DEDENT for i in range ( K , N ) : NEW_LINE INDENT sum_K -= ( A [ i - K ] - A [ i ] ) NEW_LI...
Rearrange array to make sum of all subarrays starting from first index non | Function to rearrange the array such that sum of all elements of subarrays from the 1 st index is non - zero ; Initialize sum of subarrays ; Sum of all elements of array ; If sum is 0 , the required array could never be formed ; If sum is non ...
def rearrangeArray ( a , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT sum = 0 NEW_LINE b = 0 NEW_LINE a = sorted ( a ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum +=...
Length of smallest subarray to be removed to make sum of remaining elements divisible by K | Python3 program for the above approach ; Function to find the length of the smallest subarray to be removed such that sum of elements is divisible by K ; Stores the remainder of each arr [ i ] when divided by K ; Stores total s...
import sys NEW_LINE def removeSmallestSubarray ( arr , n , k ) : NEW_LINE INDENT mod_arr = [ 0 ] * n NEW_LINE total_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mod_arr [ i ] = ( arr [ i ] + k ) % k NEW_LINE total_sum += arr [ i ] NEW_LINE DEDENT target_remainder = total_sum % k NEW_LINE if ( target_remainde...
Queries to flip characters of a binary string in given range | Function to find the binary by performing all the given queries ; Stores length of the string ; prefixCnt [ i ] : Stores number of times strr [ i ] toggled by performing all the queries ; Update prefixCnt [ Q [ i ] [ 0 ] ] ; Update prefixCnt [ Q [ i ] [ 1 ]...
def toggleQuery ( strr , Q , M ) : NEW_LINE INDENT strr = [ i for i in strr ] NEW_LINE N = len ( strr ) NEW_LINE prefixCnt = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT prefixCnt [ Q [ i ] [ 0 ] ] += 1 NEW_LINE prefixCnt [ Q [ i ] [ 1 ] + 1 ] -= 1 NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW...
Maximum length possible by cutting N given woods into at least K pieces | Function to check if it is possible to cut woods into K pieces of length len ; Stores count of pieces having length equal to K ; Traverse wood [ ] array ; Update count ; Function to find the maximum value of L ; Stores minimum possible of L ; Sto...
def isValid ( wood , N , len , K ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT count += wood [ i ] // len NEW_LINE DEDENT return ( count >= K ) NEW_LINE DEDENT def findMaxLen ( wood , N , K ) : NEW_LINE INDENT left = 1 NEW_LINE right = max ( wood ) NEW_LINE while ( left <= right ) : NEW_...
Count quadruplets with sum K from given array | Function to return the number of quadruplets with the given sum ; Initialize answer ; All possible first elements ; All possible second elements ; All possible third elements ; All possible fourth elements ; Increment counter by 1 if quadruplet sum is S ; Return the final...
def countSum ( a , n , sum ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n - 3 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 2 ) : NEW_LINE INDENT for k in range ( j + 1 , n - 1 ) : NEW_LINE INDENT for l in range ( k + 1 , n ) : NEW_LINE INDENT if ( a [ i ] + a [ j ] + a [ k ] + a [ l ] == sum ) : NEW_LINE...
Minimum adjacent swaps to group similar characters together | Function to find minimum adjacent swaps required to make all the same character adjacent ; Initialize answer ; Create a 2D array of size 26 ; Traverse the string ; Get character ; Append the current index in the corresponding vector ; Traverse each character...
def minSwaps ( S , n ) : NEW_LINE INDENT swaps = 0 NEW_LINE arr = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT pos = ord ( S [ i ] ) - ord ( ' a ' ) NEW_LINE arr [ pos ] . append ( i ) NEW_LINE DEDENT for ch in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT pos = ch - ord...
Construct a graph which does not contain any pair of adjacent nodes with same value | Function that prints the edges of the generated graph ; First print connections stored in store [ ] ; Check if there is more than one occurrence of 1 st unique element ; Print all other occurrence of 1 st unique element with second un...
def printConnections ( store , ind , ind1 ) : NEW_LINE INDENT for pr in store : NEW_LINE INDENT print ( pr [ 0 ] , pr [ 1 ] ) NEW_LINE DEDENT if ( len ( ind ) != 0 ) : NEW_LINE INDENT for x in ind : NEW_LINE INDENT print ( ind1 , x + 1 ) NEW_LINE DEDENT DEDENT DEDENT def constructGraph ( arr , N ) : NEW_LINE INDENT ind...
Minimum substring flips required to convert given binary string to another | Function that finds the minimum number of operations required such that string A and B are the same ; Stores the count of steps ; Stores the last index whose bits are not same ; Iterate until both string are unequal ; Check till end of string ...
def findMinimumOperations ( a , b ) : NEW_LINE INDENT step = 0 NEW_LINE last_index = 0 NEW_LINE while ( a != b ) : NEW_LINE INDENT a = [ i for i in a ] NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT if ( a [ i ] != b [ i ] ) : NEW_LINE INDENT last_index = i NEW_LINE DEDENT DEDENT for i in range ( last_index + ...
Count all disjoint pairs having absolute difference at least K from a given array | Function to check if it is possible to form M pairs with abs diff at least K ; Traverse the array over [ 0 , M ] ; If valid index ; Return 1 ; Function to count distinct pairs with absolute difference atleasr K ; Stores the count of all...
def isValid ( arr , n , m , d ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT if ( abs ( arr [ n - m + i ] - arr [ i ] ) < d ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def countPairs ( arr , N , K ) : NEW_LINE INDENT ans = 0 NEW_LINE left = 0 NEW_LINE right = N // 2 + 1 NEW_...
Minimum common element in subarrays of all possible lengths | Function to find maximum distance between every two element ; Stores index of last occurence of each array element ; Initialize temp [ ] with - 1 ; Traverse the array ; If array element has not occurred previously ; Update index in temp ; Otherwise ; Compare...
def max_distance ( a , temp , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT temp [ i ] = - 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] not in mp ) : NEW_LINE INDENT temp [ a [ i ] ] = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp [ a [ i ] ] = max (...
Find a triplet in an array such that arr [ i ] arr [ k ] and i < j < k | Function to find a triplet that satisfy the conditions ; Traverse the given array ; Stores current element ; Stores element just before the current element ; Stores element just after the current element ; Check the given conditions ; Print a trip...
def FindTrip ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N - 1 ) : NEW_LINE INDENT p = arr [ i - 1 ] NEW_LINE q = arr [ i ] NEW_LINE r = arr [ i + 1 ] NEW_LINE if ( p < q and q > r ) : NEW_LINE INDENT print ( i - 1 , i , i + 1 ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( - 1 ) NEW_LINE DEDENT if __name__ == ...
Count subarrays having each distinct element occurring at least twice | Python3 program to implement the above approach ; Function to get the count of subarrays having each element occurring at least twice ; Stores count of subarrays having each distinct element occurring at least twice ; Stores count of unique element...
from collections import defaultdict NEW_LINE def cntSubarrays ( arr , N ) : NEW_LINE INDENT cntSub = 0 NEW_LINE cntUnique = 0 NEW_LINE cntFreq = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i , N ) : NEW_LINE INDENT cntFreq [ arr [ j ] ] += 1 NEW_LINE if ( cntFreq [ arr [ ...
Check if permutation of a given string can be made palindromic by removing at most K characters | Function to check if the satisfies the given conditions or not ; Stores length of given string ; Stores frequency of each character of str ; Update frequency of current character ; Stores count of distinct character whose ...
def checkPalinK ( str , K ) : NEW_LINE INDENT N = len ( str ) NEW_LINE cntFreq = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cntFreq [ ord ( str [ i ] ) ] += 1 NEW_LINE DEDENT cntOddFreq = 0 NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT if ( cntFreq [ i ] % 2 == 1 ) : NEW_LINE INDENT cntOddFreq += 1...
Maximum number of elements that can be removed such that MEX of the given array remains unchanged | Function to find the maximum number of elements that can be removed ; Initialize hash [ ] with 0 s ; Initialize MEX ; Set hash [ i ] = 1 , if i is present in arr [ ] ; Find MEX from the hash ; Print the maximum numbers t...
def countRemovableElem ( arr , N ) : NEW_LINE INDENT hash = [ 0 ] * ( N + 1 ) NEW_LINE mex = N + 1 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] <= N ) : NEW_LINE INDENT hash [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( hash [ i ] == 0 ) : NEW_LINE IN...
Print all positions of a given string having count of smaller characters equal on both sides | Function to find indexes of the given that satisfy the condition ; Stores length of given string ; Stores frequency of each character of strr ; Update frequency of current character ; cntLeftFreq [ i ] Stores frequency of cha...
def printIndexes ( strr ) : NEW_LINE INDENT N = len ( strr ) NEW_LINE cntFreq = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cntFreq [ ord ( strr [ i ] ) ] += 1 NEW_LINE DEDENT cntLeftFreq = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cntLeft = 0 NEW_LINE cntRight = 0 NEW_LINE for j in ra...
Count three | Function to count three - digit numbers having difference x with its reverse ; If x is not multiple of 99 ; No solution exists ; Generate all possible pairs of digits [ 1 , 9 ] ; If any pair is obtained with difference x / 99 ; Increase count ; Return the count ; Driver Code
def Count_Number ( x ) : NEW_LINE INDENT ans = 0 ; NEW_LINE if ( x % 99 != 0 ) : NEW_LINE INDENT ans = - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT diff = x / 99 ; NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT for j in range ( 1 , 10 ) : NEW_LINE INDENT if ( ( i - j ) == diff ) : NEW_LINE INDENT ans += 10 ; NEW_...
Check if a point having maximum X and Y coordinates exists or not | Python3 program for the above approach ; Initialize INF as inifnity ; Function to return the pohaving maximum X and Y coordinates ; Base Case ; Stores if valid poexists ; If poarr [ i ] is valid ; Check for the same point ; Check for a valid point ; If...
import sys NEW_LINE INF = sys . maxsize ; NEW_LINE def findMaxPoint ( arr , i , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return [ INF , INF ] NEW_LINE DEDENT flag = True ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( j == i ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( arr [ j ] [ 0 ] >= arr ...
Check if a point having maximum X and Y coordinates exists or not | Python3 program for the above approach ; Function to find the pohaving max X and Y coordinates ; Initialize maxX and maxY ; Length of the given array ; Get maximum X & Y coordinates ; Check if the required point i . e . , ( maxX , maxY ) is present ; I...
import sys ; NEW_LINE def findMaxPoint ( arr ) : NEW_LINE INDENT maxX = - sys . maxsize ; NEW_LINE maxY = - sys . maxsize ; NEW_LINE n = len ( arr ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxX = max ( maxX , arr [ i ] [ 0 ] ) ; NEW_LINE maxY = max ( maxY , arr [ i ] [ 1 ] ) ; NEW_LINE DEDENT for i in range (...
Search insert position of K in a sorted array | Function to find insert position of K ; Traverse the array ; If K is found ; If arr [ i ] exceeds K ; If all array elements are smaller ; Driver Code
def find_index ( arr , n , K ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] == K : NEW_LINE INDENT return i NEW_LINE DEDENT elif arr [ i ] > K : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return n NEW_LINE DEDENT arr = [ 1 , 3 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE K = 2 NEW_LINE prin...
Count subarrays for every array element in which they are the minimum | Set 2 | Function to calculate total number of sub - arrays for each element where that element is occurring as the minimum element ; Map for storing the number of sub - arrays for each element ; Traverse over all possible subarrays ; Minimum in eac...
def minSubarray ( arr , N ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT mini = 10 ** 9 NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT mini = min ( mini , arr [ j ] ) NEW_LINE m [ mini ] = m . get ( mini , 0 ) + 1 NEW_LINE DEDENT DEDENT for i in arr : NEW_LINE INDENT print ( m [ i ] , ...
Count subarrays for every array element in which they are the minimum | Set 2 | Function to count subarrays for each element where it is the minimum ; For the length of strictly larger numbers on the left of A [ i ] ; Storing x in result [ i ] ; For the length of strictly larger numbers on the right of A [ i ] ; Store ...
def minSubarray ( arr , N ) : NEW_LINE INDENT result = [ 0 ] * N NEW_LINE l = [ ] NEW_LINE r = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT count = 1 ; NEW_LINE while ( len ( l ) != 0 and l [ - 1 ] [ 0 ] > arr [ i ] ) : NEW_LINE INDENT count += l [ - 1 ] [ 1 ] NEW_LINE l . pop ( ) NEW_LINE DEDENT l . append ( [ ...
Count Full Prime numbers in a given range | Function to check if a number is prime or not ; If a divisor of n exists ; Function to check if a number is Full Prime or not ; If n is not a prime ; Otherwise ; Extract digit ; If any digit of n is non - prime ; Function to prcount of Full Primes in a range [ L , R ] ; Store...
def isPrime ( num ) : NEW_LINE INDENT if ( num <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , num + 1 ) : NEW_LINE INDENT if i * i > num : NEW_LINE INDENT break NEW_LINE DEDENT if ( num % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isFulPrim...
Print alternate elements of an array | Function to print Alternate elements of the given array ; Print elements at odd positions ; If currIndex stores even index or odd position ; Driver Code
def printAlter ( arr , N ) : NEW_LINE INDENT for currIndex in range ( 0 , N ) : NEW_LINE INDENT if ( currIndex % 2 == 0 ) : NEW_LINE INDENT print ( arr [ currIndex ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_L...
Minimize deletions in a Binary String to remove all subsequences of the form "0101" | Function to find minimum characters to be removed such that no subsequence of the form "0101" exists in the string ; Stores the partial sums ; Calculate partial sums ; Setting endpoints and deleting characters indices . ; Return count...
def findmin ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE maximum = 0 NEW_LINE incr = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT incr [ i + 1 ] = incr [ i ] NEW_LINE if ( s [ i ] == '0' ) : NEW_LINE INDENT incr [ i + 1 ] = incr [ i + 1 ] + 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , n + 1 ...
Length of longest subarray with product equal to a power of 2 | Function to check whether a number is power of 2 or not ; Function to find maximum length subarray having product of element as a perfect power of 2 ; Stores current subarray length ; Stores maximum subarray length ; Traverse the given array ; If arr [ i ]...
def isPower ( x ) : NEW_LINE INDENT if ( x != 0 and ( x & ( x - 1 ) ) == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def maximumlength ( arr , N ) : NEW_LINE INDENT max_length = 0 ; NEW_LINE max_len_subarray = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( isPower ( arr ...
Length of smallest subarray to be removed such that the remaining array is sorted | Python3 program for the above approach ; Find the length of the shortest subarray ; To store the result ; Calculate the possible length of the sorted subarray from left ; Array is sorted ; Calculate the possible length of the sorted sub...
import sys NEW_LINE def findLengthOfShortestSubarray ( arr ) : NEW_LINE INDENT minlength = sys . maxsize NEW_LINE left = 0 NEW_LINE right = len ( arr ) - 1 NEW_LINE while left < right and arr [ left + 1 ] >= arr [ left ] : NEW_LINE INDENT left += 1 NEW_LINE DEDENT if left == len ( arr ) - 1 : NEW_LINE INDENT return 0 N...
Smallest number to be subtracted to convert given number to a palindrome | Function to evaluate minimum subtraction required to make a number palindrome ; Counts number of subtractions required ; Run a loop till N >= 0 ; Store the current number ; Store reverse of current number ; Reverse the number ; Check if N is pal...
def minSub ( N ) : NEW_LINE INDENT count = 0 NEW_LINE while ( N >= 0 ) : NEW_LINE INDENT num = N NEW_LINE rev = 0 NEW_LINE while ( num != 0 ) : NEW_LINE INDENT digit = num % 10 NEW_LINE rev = ( rev * 10 ) + digit NEW_LINE num = num // 10 NEW_LINE DEDENT if ( N == rev ) : NEW_LINE INDENT break NEW_LINE DEDENT count += 1...
Count subarrays of atleast size 3 forming a Geometric Progression ( GP ) | Function to count all the subarrays of size at least 3 forming GP ; If array size is less than 3 ; Stores the count of subarray ; Stores the count of subarray for each iteration ; Traverse the array ; Check if L [ i ] forms GP ; Otherwise , upda...
def numberOfGP ( L , N ) : NEW_LINE INDENT if ( N <= 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 0 NEW_LINE res = 0 NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT if ( L [ i - 1 ] * L [ i - 1 ] == L [ i ] * L [ i - 2 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = 0 NEW_L...
Count even length subarrays having bitwise XOR equal to 0 | Function to count the number of even - length subarrays having Bitwise XOR equal to 0 ; Stores the count of required subarrays ; Stores prefix - XOR of arr [ i , i + 1 , ... N - 1 ] ; Traverse the array ; Calculate the prefix - XOR of current subarray ; Check ...
def cntSubarr ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE prefixXor = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT prefixXor = arr [ i ] NEW_LINE for j in range ( i + 1 , N ) : NEW_LINE INDENT prefixXor ^= arr [ j ] NEW_LINE if ( prefixXor == 0 and ( j - i + 1 ) % 2 == 0 ) : NEW_LINE INDENT res += 1 NEW_LIN...
Count even length subarrays having bitwise XOR equal to 0 | Python3 program to implement the above approach ; Function to get the count of even length subarrays having bitwise xor 0 ; Stores prefix - xor of the given array ; Stores prefix - xor at even index of the array . ; Stores prefix - xor at odd index of the arra...
M = 1000000 ; NEW_LINE def cntSubXor ( arr , N ) : NEW_LINE INDENT prefixXor = 0 ; NEW_LINE Even = [ 0 ] * M ; NEW_LINE Odd = [ 0 ] * M ; NEW_LINE cntSub = 0 ; NEW_LINE Odd [ 0 ] = 1 ; NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT prefixXor ^= arr [ i ] ; NEW_LINE if ( i % 2 == 1 ) : NEW_LINE INDENT cntSub += Odd...
Maximize sum of array elements removed by performing the given operations | Function to find the maximum sum of the array arr [ ] where each element can be reduced to at most min [ i ] ; Stores the pair of arr [ i ] & min [ i ] ; Sorting vector of pairs ; Traverse the vector of pairs ; Add to the value of S ; Update K ...
def findMaxSum ( arr , n , min , k , S ) : NEW_LINE INDENT A = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT A . append ( ( arr [ i ] , min [ i ] ) ) NEW_LINE DEDENT A = sorted ( A ) NEW_LINE A = A [ : : - 1 ] NEW_LINE K = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT S += max ( A [ i ] [ 0 ] - K , A [ i ] [ ...
Length of smallest substring of a given string which contains another string as subsequence | Python3 program to implement the above approach ; Function to find the length of smallest substring of a having string b as a subsequence ; Stores the characters present in string b ; Find index of characters of a that are als...
import sys NEW_LINE def minLength ( a , b ) : NEW_LINE INDENT Char = { } NEW_LINE for i in range ( len ( b ) ) : NEW_LINE INDENT Char [ b [ i ] ] = Char . get ( b [ i ] , 0 ) + 1 NEW_LINE DEDENT CharacterIndex = { } NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT x = a [ i ] NEW_LINE if ( x in Char ) : NEW_LINE...
Count smaller primes on the right of each array element | Function to check if a number is prime or not ; Function to find the count of smaller primes on the right of each array element ; Stores the count of smaller primes ; If A [ j ] <= A [ i ] and A [ j ] is prime ; Increase count ; Print the count for the current e...
def is_prime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT 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 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def countSmallerPrimes ( ar , N )...
Check if a string is concatenation of another given string | Function to check if a is concatenation of another string ; Stores the length of str2 ; Stores the length of str1 ; If M is not multiple of N ; Traverse both the strings ; If str1 is not concatenation of str2 ; Driver Code
def checkConcat ( str1 , str2 ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE M = len ( str2 ) NEW_LINE if ( N % M != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ i % M ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DED...
Minimize length of string by replacing K pairs of distinct adjacent characters | Function to minimize the length of the by replacing distinct pairs of adjacent characters ; Stores the length of the given string ; Stores the index of the given string ; Traverse the given string ; If two adjacent haracters are distinct ;...
def MinLen ( str , K ) : NEW_LINE INDENT N = len ( str ) NEW_LINE i = 0 NEW_LINE while ( i < N - 1 ) : NEW_LINE INDENT if ( str [ i ] != str [ i + 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( i == N - 1 ) : NEW_LINE INDENT return N NEW_LINE DEDENT return max ( 1 , N - K ) NEW_LINE DEDENT if...
Length of smallest sequence having sum X and product Y | Python3 program for the above approach ; Function for checking valid or not ; Function for checking boundary of binary search ; Function to calculate the minimum sequence size using binary search ; Initialize high and low ; Base case ; Print - 1 if a sequence can...
from math import floor , exp NEW_LINE def temp ( n , x ) : NEW_LINE INDENT return pow ( x * 1 / n , n ) NEW_LINE DEDENT def check ( n , y , x ) : NEW_LINE INDENT v = temp ( n , x ) NEW_LINE return ( v >= y ) NEW_LINE DEDENT def find ( x , y ) : NEW_LINE INDENT high = floor ( x / exp ( 1.0 ) ) NEW_LINE low = 1 NEW_LINE ...
Print the middle nodes of each level of a Binary Tree | Structure Node of Binary Tree ; Function to create a new node ; Return the created node ; Function that performs the DFS traversal on Tree to store all the nodes at each level in map M ; Base Case ; Push the current level node ; Left Recursion ; Right Recursion ; ...
class node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newnode ( d ) : NEW_LINE INDENT temp = node ( d ) NEW_LINE return temp NEW_LINE DEDENT def dfs ( root , l , M ) : NEW_LINE INDENT if ( root =...
Smallest array that can be obtained by replacing adjacent pairs with their products | Function to minimize the size of array by performing given operations ; If all array elements are not same ; If all array elements are same ; Driver Code ; Function call
def minLength ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ 0 ] != arr [ i ] ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return N NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 1 , 3 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minLength ( ...
Subarrays whose sum is a perfect square | Python3 program to implement the above approach ; Function to print the start and end indices of all subarrays whose sum is a perfect square ; Stores the current subarray sum ; Update current subarray sum ; Stores the square root of currSubSum ; Check if currSubSum is a perfect...
import math NEW_LINE def PrintIndexes ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT currSubSum = 0 NEW_LINE for j in range ( i , N , 1 ) : NEW_LINE INDENT currSubSum += arr [ j ] NEW_LINE sq = int ( math . sqrt ( currSubSum ) ) NEW_LINE if ( sq * sq == currSubSum ) : NEW_LINE INDENT print ( " ( "...
Count positions in Binary Matrix having equal count of set bits in corresponding row and column | Function to return the count of indices in from the given binary matrix having equal count of set bits in its row and column ; Stores count of set bits in corresponding column and row ; Traverse matrix ; Since 1 contains a...
def countPosition ( mat ) : NEW_LINE INDENT n = len ( mat ) NEW_LINE m = len ( mat [ 0 ] ) NEW_LINE row = [ 0 ] * n NEW_LINE col = [ 0 ] * m 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 col [ j ] += 1 NEW_LINE row [ i ] += 1 NEW_LIN...
Maximum value at each level in an N | Function to find the maximum value at each level of N - ary tree ; Stores the adjacency list ; Create the adjacency list ; Perform level order traversal of nodes at each level ; Push the root node ; Iterate until queue is empty ; Get the size of queue ; Iterate for : all the nodes ...
def maxAtLevel ( N , M , Value , Edges ) : NEW_LINE INDENT adj = [ [ ] for i in range ( N ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT u = Edges [ i ] [ 0 ] NEW_LINE v = Edges [ i ] [ 1 ] NEW_LINE adj [ u ] . append ( v ) NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( 0 ) NEW_LINE while ( len ( q ) ) : NEW_LINE I...
Rearrange array to maximize count of triplets ( i , j , k ) such that arr [ i ] > arr [ j ] < arr [ k ] and i < j < k | Function to rearrange the array to maximize the count of triplets ; Sort the given array ; Stores the permutations of the given array ; Stores the index of the given array ; Place the first half of th...
def ctTriplets ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE temp = [ 0 ] * N NEW_LINE index = 0 NEW_LINE for i in range ( 1 , N , 2 ) : NEW_LINE INDENT temp [ i ] = arr [ index ] NEW_LINE index += 1 NEW_LINE DEDENT for i in range ( 0 , N , 2 ) : NEW_LINE INDENT temp [ i ] = arr [ index ] NEW_LINE index += 1 NE...
Rearrange array to make it non | Python3 program for above approach ; Function to check if the array can be made non - decreasing ; Iterate till N ; Find the minimum element ; Sort the array ; Iterate till N ; Check if the element is at its correct position ; Return the answer ; Driver Code ; Print the answer
import sys NEW_LINE def check ( a , n ) : NEW_LINE INDENT b = [ None ] * n NEW_LINE minElement = sys . maxsize NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT b [ i ] = a [ i ] NEW_LINE minElement = min ( minElement , a [ i ] ) NEW_LINE DEDENT b . sort ( ) NEW_LINE k = 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE...
Count 1 s in binary matrix having remaining indices of its row and column filled with 0 s | Function to count required 1 s from the given matrix ; Stores the dimensions of the mat ; Calculate sum of rows ; Calculate sum of columns ; Stores required count of 1 s ; If current cell is 1 and sum of row and column is 1 ; In...
def numSpecial ( mat ) : NEW_LINE INDENT m = len ( mat ) NEW_LINE n = len ( mat [ 0 ] ) NEW_LINE rows = [ 0 ] * m NEW_LINE cols = [ 0 ] * n NEW_LINE i , j = 0 , 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT rows [ i ] = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT rows [ i ] += mat [ i ] [ j ] NEW_LINE DEDENT ...
Find all matrix elements which are minimum in their row and maximum in their column | Python3 program for the above approach ; Functionto find all the matrix elements which are minimum in its row and maximum in its column ; Initialize unordered set ; Traverse the matrix ; Update the minimum element of current row ; Ins...
import sys NEW_LINE def minmaxNumbers ( matrix , res ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 0 , len ( matrix ) , 1 ) : NEW_LINE INDENT minr = sys . maxsize NEW_LINE for j in range ( 0 , len ( matrix [ i ] ) , 1 ) : NEW_LINE INDENT minr = min ( minr , matrix [ i ] [ j ] ) NEW_LINE DEDENT s . add ( min...
Node whose removal minimizes the maximum size forest from an N | Python3 program to implement the above approach ; Function to create the graph ; Function to traverse the graph and find the minimum of maximum size forest after removing a Node ; Traversing every child subtree except the parent Node ; Traverse all subtre...
mini = 105 ; NEW_LINE ans = 0 ; NEW_LINE n = 0 ; NEW_LINE g = [ ] ; NEW_LINE size = [ 0 ] * 100 ; NEW_LINE def create_graph ( ) : NEW_LINE INDENT g [ 1 ] . append ( 2 ) ; NEW_LINE g [ 2 ] . append ( 1 ) ; NEW_LINE g [ 1 ] . append ( 3 ) ; NEW_LINE g [ 3 ] . append ( 1 ) ; NEW_LINE g [ 1 ] . append ( 4 ) ; NEW_LINE g [ ...
Smallest prefix to be deleted such that remaining array can be rearranged to form a sorted array | Function to find the minimum length of prefix required to be deleted ; Stores index to be returned ; Iterate until previous element is <= current index ; Decrementing index ; Return index ; Driver code ; Given arr ; Funct...
def findMinLength ( arr ) : NEW_LINE INDENT index = len ( arr ) - 1 ; NEW_LINE while ( index > 0 and arr [ index ] >= arr [ index - 1 ] ) : NEW_LINE INDENT index -= 1 ; NEW_LINE DEDENT return index ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 8 , 5 , 0 , - 1 , - 1 , 0 , 1 , 2 , 3 , 4 ...
Count array elements exceeding sum of preceding K elements | Function to count array elements exceeding sum of preceding K elements ; Iterate over the array ; Update prefix sum ; Check if arr [ K ] > arr [ 0 ] + . . + arr [ K - 1 ] ; Increment count ; Check if arr [ i ] > arr [ i - K - 1 ] + . . + arr [ i - 1 ] ; Incre...
def countPrecedingK ( a , n , K ) : NEW_LINE INDENT prefix = [ 0 ] * n NEW_LINE prefix [ 0 ] = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + a [ i ] NEW_LINE DEDENT ctr = 0 NEW_LINE if ( prefix [ K - 1 ] < a [ K ] ) : NEW_LINE INDENT ctr += 1 NEW_LINE DEDENT for i in rang...
Count minimum moves required to convert A to B | Function to find minimum number of moves to obtained B from A ; Stores the minimum number of moves ; Absolute difference ; K is in range [ 0 , 10 ] ; Print the required moves ; Driver Code
def convertBfromA ( a , b ) : NEW_LINE INDENT moves = 0 NEW_LINE x = abs ( a - b ) NEW_LINE for i in range ( 10 , 0 , - 1 ) : NEW_LINE INDENT moves += x // i NEW_LINE x = x % i NEW_LINE DEDENT print ( moves , end = " ▁ " ) NEW_LINE DEDENT A = 188 NEW_LINE B = 4 NEW_LINE convertBfromA ( A , B ) NEW_LINE
Count N digits numbers with sum divisible by K | Function to count the N digit numbers whose sum is divisible by K ; Base case ; If already computed subproblem occurred ; Store the count of N digit numbers whoe sum is divisible by K ; Check if the number does not contain any leading 0. ; Recurrence relation ; Driver co...
def countNum ( N , sum , K , st , dp ) : NEW_LINE INDENT if ( N == 0 and sum == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( N < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ N ] [ sum ] [ st ] != - 1 ) : NEW_LINE INDENT return dp [ N ] [ sum ] [ st ] NEW_LINE DEDENT res = 0 NEW_LINE start = 1 NEW_LIN...
Minimize Nth term of an Arithmetic progression ( AP ) | Python3 program to implement the above approach ; Function to find the smallest Nth term of an AP possible ; Stores the smallest Nth term ; Check if common difference of AP is an integer ; Store the common difference ; Store the First Term of that AP ; Store the N...
import sys NEW_LINE def smallestNth ( A , B , N ) : NEW_LINE INDENT res = sys . maxsize NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( N , i , - 1 ) : NEW_LINE INDENT if ( ( B - A ) % ( j - i ) == 0 ) : NEW_LINE INDENT D = ( B - A ) // ( j - i ) NEW_LINE FirstTerm = A - ( i - 1 ) * D NEW_LINE NthT...
Subarray of size K with prime sum | Generate all prime numbers in the range [ 1 , 1000000 ] ; Set all numbers as prime initially ; Mark 0 and 1 as non - prime ; If current element is prime ; Mark all its multiples as non - prime ; Function to prthe subarray whose sum of elements is prime ; Store the current subarray of...
def sieve ( prime ) : NEW_LINE INDENT for i in range ( 1000000 ) : NEW_LINE INDENT prime [ i ] = True NEW_LINE DEDENT prime [ 0 ] = prime [ 1 ] = False NEW_LINE for i in range ( 2 , 1000 + 1 ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , 1000000 , i ) : NEW_LINE INDENT prime [ j ] = F...
Minimum characters required to be removed to sort binary string in ascending order | Function to find the minimum count of characters to be removed to make the string sorted in ascending order ; Length of given string ; Stores the first occurrence of '1 ; Stores the last occurrence of '0 ; Traverse the string to find t...
def minDeletion ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE DEDENT ' NEW_LINE INDENT firstIdx1 = - 1 NEW_LINE DEDENT ' NEW_LINE INDENT lastIdx0 = - 1 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT firstIdx1 = i NEW_LINE break NEW_LINE DEDENT DED...
Maximum score assigned to a subsequence of numerically consecutive and distinct array elements | Function to find the maximum score with unique element in the subset ; Base Case ; Check if the previously picked element differs by 1 from the current element ; Calculate score by including the current element ; Calculate ...
def maximumSum ( a , b , n , index , lastpicked ) : NEW_LINE INDENT if ( index == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT option1 = 0 NEW_LINE option2 = 0 NEW_LINE if ( lastpicked == - 1 or a [ lastpicked ] != a [ index ] ) : NEW_LINE INDENT option1 = b [ index ] + maximumSum ( a , b , n , index + 1 , index ) NE...
Replace every element in a circular array by sum of next K elements | Function to print required resultant array ; Reverse the array ; Traverse the range ; Store prefix sum ; Find the prefix sum ; Store the answer ; Calculate the answers ; Count of remaining elements ; Add the sum of all elements y times ; Add the rema...
def sumOfKElements ( arr , n , k ) : NEW_LINE INDENT rev = False ; NEW_LINE if ( k < 0 ) : NEW_LINE INDENT rev = True ; NEW_LINE k *= - 1 ; NEW_LINE l = 0 ; NEW_LINE r = n - 1 ; NEW_LINE while ( l < r ) : NEW_LINE INDENT tmp = arr [ l ] ; NEW_LINE arr [ l ] = arr [ r ] ; NEW_LINE arr [ r ] = tmp ; NEW_LINE l += 1 ; NEW...
Count subarrays for every array element in which they are the minimum | Function to find the boundary of every element within which it is minimum ; Perform Binary Search ; Find mid m ; Update l ; Update r ; Inserting the index ; Function to required count subarrays ; Stores the indices of element ; Initialize the outpu...
def binaryInsert ( boundary , i ) : NEW_LINE INDENT l = 0 NEW_LINE r = len ( boundary ) - 1 NEW_LINE while l <= r : NEW_LINE INDENT m = ( l + r ) // 2 NEW_LINE if boundary [ m ] < i : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE DEDENT DEDENT boundary . insert ( l , i ) NEW_LINE r...
Check if digit cube limit of an integer arrives at fixed point or a limit cycle | Define the limit ; Function to get the sum of cube of digits of a number ; Convert to string to get sum of the cubes of its digits ; Return sum ; Function to check if the number arrives at a fixed point or a cycle ; Stores the values obta...
LIMIT = 1000000000 NEW_LINE def F ( N : int ) -> int : NEW_LINE INDENT string = str ( N ) NEW_LINE sum = 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT val = int ( ord ( string [ i ] ) - ord ( '0' ) ) NEW_LINE sum += val * val * val NEW_LINE DEDENT return sum NEW_LINE DEDENT def findDestination ( N : in...
Count quadruples ( i , j , k , l ) in an array such that i < j < k < l and arr [ i ] = arr [ k ] and arr [ j ] = arr [ l ] | Function to count total number of required tuples ; Initialize unordered map ; Find the pairs ( j , l ) such that arr [ j ] = arr [ l ] and j < l ; Elements are equal ; Update the count ; Add the...
def countTuples ( arr , N ) : NEW_LINE INDENT ans = 0 NEW_LINE val = 0 NEW_LINE freq = { } NEW_LINE for j in range ( N - 2 ) : NEW_LINE INDENT val = 0 NEW_LINE for l in range ( j + 1 , N ) : NEW_LINE INDENT if ( arr [ j ] == arr [ l ] ) : NEW_LINE INDENT ans += val NEW_LINE DEDENT if arr [ l ] in freq : NEW_LINE INDENT...
Minimize subarray increments / decrements required to reduce all array elements to 0 | Python3 program of the above approach ; Function to count the minimum number of operations required ; Traverse the array ; If array element is negative ; Update minimum negative ; Update maximum position ; Return minOp ; Driver code
import sys NEW_LINE def minOperation ( arr ) : NEW_LINE INDENT minOp = sys . maxsize NEW_LINE minNeg = 0 NEW_LINE maxPos = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT if ( arr [ i ] < minNeg ) : NEW_LINE INDENT minNeg = arr [ i ] NEW_LINE DEDENT DEDENT else : NEW_L...
Pair of integers having least GCD among all given pairs having GCD exceeding K | Function to calculate the GCD of two numbers ; Function to print the pair having a gcd value just greater than the given integer ; Initialize variables ; Iterate until low less than equal to high ; Calculate mid ; Reducing the search space...
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 GcdPair ( arr , k ) : NEW_LINE INDENT lo = 0 NEW_LINE hi = len ( arr ) - 1 NEW_LINE ans = [ - 1 , 0 ] NEW_LINE while ( lo <= hi ) : NEW_LINE INDENT mid = lo + ( hi - lo ) // 2 NEW_LI...
Check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array | Python3 implementation of the above approach ; Function to check if it is possible to sort array or not ; Store the smallest element ; Copy the original array ; Iterate over the given array ; Update smallest element ;...
import sys NEW_LINE def isPossible ( arr , N ) : NEW_LINE INDENT mn = sys . maxsize ; NEW_LINE B = [ 0 ] * N ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT mn = min ( mn , arr [ i ] ) ; NEW_LINE B [ i ] = arr [ i ] ; NEW_LINE DEDENT arr . sort ( ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] != B...
Check if every vertex triplet in graph contains two vertices connected to third vertex | Function to add edge into the graph ; Finding the maximum and minimum values in each component ; Function for checking whether the given graph is valid or not ; Checking for intersecting intervals ; If intersection is found ; Graph...
def addEdge ( adj , u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE return adj NEW_LINE DEDENT def DFSUtil ( u , adj , visited , componentMin , componentMax ) : NEW_LINE INDENT visited [ u ] = True NEW_LINE componentMax = max ( componentMax , u ) NEW_LINE componentMin = min...
Check if all array elements are present in a given stack or not | Function to check if all array elements is present in the stack ; Store the frequency of array elements ; Loop while the elements in the stack is not empty ; Condition to check if the element is present in the stack ; Driver Code
def checkArrInStack ( s , arr ) : NEW_LINE INDENT freq = { } NEW_LINE for ele in arr : NEW_LINE INDENT freq [ ele ] = freq . get ( ele , 0 ) + 1 NEW_LINE DEDENT while s : NEW_LINE INDENT poppedEle = s . pop ( ) NEW_LINE if poppedEle in freq : NEW_LINE freq [ poppedEle ] -= 1 NEW_LINE if not freq [ poppedEle ] : NEW_LIN...
Length of longest substring to be deleted to make a string equal to another string | Function to prthe length of longest substring to be deleted ; Stores the length of string ; Store the position of previous matched character of str1 ; Store the position of first occurrence of str2 in str1 ; Find the position of the fi...
def longDelSub ( str1 , str2 ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE M = len ( str2 ) NEW_LINE prev_pos = 0 NEW_LINE pos = [ 0 ] * M NEW_LINE for i in range ( M ) : NEW_LINE INDENT index = prev_pos NEW_LINE while ( index < N and str1 [ index ] != str2 [ i ] ) : NEW_LINE INDENT index += 1 NEW_LINE DEDENT pos [ i ]...
Maximized partitions of a string such that each character of the string appears in one substring | Function to print all the substrings ; Stores the substrings ; Stores last index of characters of string s ; Find the last position of each character in the string ; Update the last index ; Iterate the given string ; Get ...
def print_substring ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE str = " " NEW_LINE ans = [ ] NEW_LINE if ( n == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT last_pos = [ - 1 ] * 26 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( last_pos [ ord ( s [ i ] ) - ord ( ' a ' ...
Lengths of maximized partitions of a string such that each character of the string appears in one substring | Function to find the length of all partitions oof a string such that each characters occurs in a single substring ; Stores last index of string s ; Find the last position of each letter in the string ; Update t...
def partitionString ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = [ ] NEW_LINE if ( n == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT last_pos = [ - 1 ] * 26 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( last_pos [ ord ( s [ i ] ) - ord ( ' a ' ) ] == - 1 ) : NEW_...
Find the maximum occurring character after performing the given operations | Function to find the maximum occurring character ; Initialize count of zero and one ; Iterate over the given string ; Count the zeros ; Count the ones ; Iterate over the given string ; Check if character is * then continue ; Check if first cha...
def solve ( S ) : NEW_LINE INDENT count_0 = 0 NEW_LINE count_1 = 0 NEW_LINE prev = - 1 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT count_0 += 1 NEW_LINE DEDENT elif ( S [ i ] == '1' ) : NEW_LINE INDENT count_1 += 1 NEW_LINE DEDENT DEDENT for i in range ( len ( S ) ) :...
Arithmetic Progression containing X and Y with least possible first term | Python3 program for the approach ; Function that finds the minimum positive first term including X with given common difference and the number of terms ; Stores the first term ; Initialize the low and high ; Perform binary search ; Find the mid ...
import sys NEW_LINE def minFirstTerm ( X , diff , N ) : NEW_LINE INDENT first_term_1 = sys . maxsize NEW_LINE low = 0 NEW_LINE high = N NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( X - mid * diff > 0 ) : NEW_LINE INDENT first_term_1 = X - mid * diff NEW_LINE low = mid + 1 NEW...
Check if a number can be represented as sum of two consecutive perfect cubes | Function to check if a number can be expressed as the sum of cubes of two consecutive numbers ; Driver Code
def isCubeSum ( n ) : NEW_LINE INDENT for i in range ( 1 , int ( pow ( n , 1 / 3 ) ) + 1 ) : NEW_LINE INDENT if ( i * i * i + ( i + 1 ) * ( i + 1 ) * ( i + 1 ) == n ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 35 ; NEW_LINE...
Check if a number can be represented as sum of two consecutive perfect cubes | Function to check that a number is the sum of cubes of 2 consecutive numbers or not ; Condition to check if a number is the sum of cubes of 2 consecutive numbers or not ; Driver Code ; Function call
def isSumCube ( N ) : NEW_LINE INDENT a = int ( pow ( N , 1 / 3 ) ) NEW_LINE b = a - 1 NEW_LINE ans = ( ( a * a * a + b * b * b ) == N ) NEW_LINE return ans NEW_LINE DEDENT i = 35 NEW_LINE if ( isSumCube ( i ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Maximize sum of remaining elements after every removal of the array half with greater sum | Function to find the maximum sum ; Base case len of array is 1 ; Stores the final result ; Traverse the array ; Store left prefix sum ; Store right prefix sum ; Compare the left and right ; If both are equal apply the optimal me...
def maxweight ( s , e , pre ) : NEW_LINE INDENT if s == e : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( s , e ) : NEW_LINE INDENT left = pre [ i ] - pre [ s - 1 ] NEW_LINE right = pre [ e ] - pre [ i ] NEW_LINE if left < right : NEW_LINE INDENT ans = max ( ans , left + maxweight ( s , i ,...
Maximum time in HH : MM : SS format that can be represented by given six digits | Function to return the maximum possible time in 24 - Hours format that can be represented by array elements ; Stores the frequency of the array elements ; Maximum possible time ; Iterate to minimum possible time ; Conditions to reduce the...
def largestTimeFromDigits ( A ) : NEW_LINE INDENT mp1 = { } NEW_LINE mp2 = { } NEW_LINE for x in A : NEW_LINE INDENT mp1 [ x ] = mp1 . get ( x , 0 ) + 1 NEW_LINE DEDENT mp2 = mp1 . copy ( ) NEW_LINE hr = 23 NEW_LINE m = 59 NEW_LINE s = 59 NEW_LINE while ( hr >= 0 ) : NEW_LINE INDENT h0 = hr // 10 NEW_LINE h1 = hr % 10 ...
Minimum size substring to be removed to make a given string palindromic | Function to find palindromic prefix of maximum length ; Finding palindromic prefix of maximum length ; Checking if curr substring is palindrome or not . ; Condition to check if the prefix is a palindrome ; if no palindrome exist ; Function to fin...
def palindromePrefix ( S ) : NEW_LINE INDENT n = len ( S ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT curr = S [ 0 : i + 1 ] NEW_LINE l = 0 NEW_LINE r = len ( curr ) - 1 NEW_LINE is_palindrome = 1 NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( curr [ l ] != curr [ r ] ) : NEW_LINE INDENT is_palind...
Count numbers from a given range that contains a given number as the suffix | Python3 program of the above approach ; Function to count the number ends with given number in range ; Find number of digits in A ; Find the power of 10 ; Incrementing the A ; Driver Code ; Function call
from math import log10 NEW_LINE def countNumEnds ( A , L , R ) : NEW_LINE INDENT count = 0 NEW_LINE digits = int ( log10 ( A ) + 1 ) NEW_LINE temp = int ( pow ( 10 , digits ) ) NEW_LINE cycle = temp NEW_LINE while ( temp <= R ) : NEW_LINE INDENT if ( temp >= L ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT temp += cycl...
Minimize replacement of characters to its nearest alphabet to make a string palindromic | Function to find the minimum number of operations required to convert th given string into palindrome ; Iterate till half of the string ; Find the absolute difference between the characters ; Adding the minimum difference of the t...
def minOperations ( s ) : NEW_LINE INDENT length = len ( s ) NEW_LINE result = 0 NEW_LINE for i in range ( length // 2 ) : NEW_LINE INDENT D1 = ( ord ( max ( s [ i ] , s [ length - 1 - i ] ) ) - ord ( min ( s [ i ] , s [ length - 1 - i ] ) ) ) NEW_LINE D2 = 26 - D1 NEW_LINE result += min ( D1 , D2 ) NEW_LINE DEDENT ret...
Check if all the pairs of an array are coprime with each other | Function to store and check the factors ; Check if factors are equal ; Check if the factor is already present ; Insert the factor in set ; Check if the factor is already present ; Insert the factors in set ; Function to check if all the pairs of array ele...
def findFactor ( value , factors ) : NEW_LINE INDENT factors . add ( value ) NEW_LINE i = 2 NEW_LINE while ( i * i <= value ) : NEW_LINE if value % i == 0 : NEW_LINE INDENT if value // i == i : NEW_LINE if i in factors : NEW_LINE INDENT return bool ( True ) NEW_LINE DEDENT else : NEW_LINE INDENT factors . add ( i ) NEW...
Count subsequences which contains both the maximum and minimum array element | Function to calculate the count of subsequences ; Find the maximum from the array ; Find the minimum from the array ; If array contains only one distinct element ; Find the count of maximum ; Find the count of minimum ; Finding the result wi...
def countSubSequence ( arr , n ) : NEW_LINE INDENT maximum = max ( arr ) NEW_LINE minimum = min ( arr ) NEW_LINE if maximum == minimum : NEW_LINE INDENT return pow ( 2 , n ) - 1 NEW_LINE DEDENT i = arr . count ( maximum ) NEW_LINE j = arr . count ( minimum ) NEW_LINE res = ( pow ( 2 , i ) - 1 ) * ( pow ( 2 , j ) - 1 ) ...
Minimize elements to be added to a given array such that it contains another given array as its subsequence | Function that finds the minimum number of the element must be added to make A as a subsequence in B ; Base Case ; dp [ i ] [ j ] indicates the length of LCS of A of length i & B of length j ; If there are no el...
def transformSubsequence ( n , m , A , B ) : NEW_LINE INDENT if B is None or len ( B ) == 0 : NEW_LINE INDENT return n NEW_LINE DEDENT dp = [ [ 0 for col in range ( m + 1 ) ] for row in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( m + 1 ) : NEW_LINE INDENT if i == 0 or j == 0 :...
Check if the sum of a subarray within a given range is a perfect square or not | Function to calculate the square root of the sum of a subarray in a given range ; Calculate the sum of array elements within a given range ; Finding the square root ; If a perfect square is found ; Reduce the search space if the value is g...
def checkForPerfectSquare ( arr , i , j ) : NEW_LINE INDENT mid , sum = 0 , 0 NEW_LINE for m in range ( i , j + 1 ) : NEW_LINE INDENT sum += arr [ m ] NEW_LINE DEDENT low = 0 NEW_LINE high = sum // 2 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( mid * mid == sum ) : NEW_...
Count of subarrays forming an Arithmetic Progression ( AP ) | Function to find the total count of subarrays ; Iterate over each subarray ; Difference between first two terms of subarray ; Iterate over the subarray from i to j ; Check if the difference of all adjacent elements is same ; Driver Code ; Given array ; Funct...
def calcSubarray ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT flag = True NEW_LINE comm_diff = A [ i + 1 ] - A [ i ] NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT if ( A [ k + 1 ] - A [ k ] == comm_diff ) : NEW_LINE INDENT con...
Largest Sum Contiguous Subarray having unique elements | Function to calculate required maximum subarray sum ; Initialize two pointers ; Stores the unique elements ; Insert the first element ; Current max sum ; Global maximum sum ; Update sum & increment j ; Add the current element ; Update sum and increment i and remo...
def maxSumSubarray ( arr ) : NEW_LINE INDENT i = 0 NEW_LINE j = 1 NEW_LINE set = { } NEW_LINE set [ arr [ 0 ] ] = 1 NEW_LINE sum = arr [ 0 ] NEW_LINE maxsum = sum NEW_LINE while ( i < len ( arr ) - 1 and j < len ( arr ) ) : NEW_LINE INDENT if arr [ j ] not in set : NEW_LINE INDENT sum = sum + arr [ j ] NEW_LINE maxsum ...
Count of numbers having only one unset bit in a range [ L , R ] | Python3 program for the above approach ; Function to count numbers in the range [ l , r ] having exactly one unset bit ; Stores the required count ; Iterate over the range ; Calculate number of bits ; Calculate number of set bits ; If count of unset bits...
from math import log2 NEW_LINE def count_numbers ( L , R ) : NEW_LINE INDENT ans = 0 NEW_LINE for n in range ( L , R + 1 ) : NEW_LINE INDENT no_of_bits = int ( log2 ( n ) + 1 ) NEW_LINE no_of_set_bits = bin ( n ) . count ( '1' ) NEW_LINE if ( no_of_bits - no_of_set_bits == 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT...
Count of numbers having only one unset bit in a range [ L , R ] | Python3 program for the above approach ; Function to count numbers in the range [ L , R ] having exactly one unset bit ; Stores the count elements having one zero in binary ; Stores the maximum number of bits needed to represent number ; Loop over for ze...
import math NEW_LINE def count_numbers ( L , R ) : NEW_LINE INDENT ans = 0 ; NEW_LINE LogR = ( int ) ( math . log ( R ) + 1 ) ; NEW_LINE for zero_bit in range ( LogR ) : NEW_LINE INDENT cur = 0 ; NEW_LINE for j in range ( zero_bit ) : NEW_LINE INDENT cur |= ( 1 << j ) ; NEW_LINE DEDENT for j in range ( zero_bit + 1 , L...
Sum of all distances between occurrences of same characters in a given string | Function to calculate the sum of distances between occurrences of same characters in a string ; If similar characters are found ; Add the difference of their positions ; Return the answer ; Driver Code
def findSum ( s ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT sum += ( j - i ) NEW_LINE DEDENT DEDENT DEDENT return sum NEW_LINE DEDENT s = " ttt " NEW_LINE print ( findSum ( s ) ) NE...
Count array elements that can be represented as sum of at least two consecutive array elements | Function to find the number of array elements that can be represented as the sum of two or more consecutive array elements ; Stores the frequencies of array elements ; Stores required count ; Update frequency of each array ...
def countElements ( a , n ) : NEW_LINE INDENT cnt = [ 0 ] * ( n + 1 ) NEW_LINE ans = 0 NEW_LINE for k in a : NEW_LINE INDENT cnt [ k ] += 1 NEW_LINE DEDENT for l in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for r in range ( l , n ) : NEW_LINE INDENT sum += a [ r ] NEW_LINE if ( l == r ) : NEW_LINE INDENT continue ...
Maximum GCD among all pairs ( i , j ) of first N natural numbers | Python3 program for the above approach ; Function to find maximum gcd of all pairs possible from first n natural numbers ; Stores maximum gcd ; Iterate over all possible pairs ; Update maximum GCD ; Driver Code
def __gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT else : NEW_LINE INDENT return __gcd ( b , a % b ) ; NEW_LINE DEDENT DEDENT def maxGCD ( n ) : NEW_LINE INDENT maxHcf = - 2391734235435 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n + 1...