text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Maximum GCD among all pairs ( i , j ) of first N natural numbers | Function to find the maximum GCD among all the pairs from first n natural numbers ; Return max GCD ; Driver code | def maxGCD ( n ) : NEW_LINE INDENT return ( n // 2 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE print ( maxGCD ( n ) ) ; NEW_LINE DEDENT |
Remove odd indexed characters from a given string | Function to remove the odd indexed characters from a given string ; Stores the resultant string ; If the current index is odd ; Skip the character ; Otherwise , append the character ; Return the modified string ; Driver Code ; Remove the characters which have odd inde... | def removeOddIndexCharacters ( s ) : NEW_LINE INDENT new_s = " " NEW_LINE i = 0 NEW_LINE while i < len ( s ) : NEW_LINE INDENT if ( i % 2 == 1 ) : NEW_LINE INDENT i += 1 NEW_LINE continue NEW_LINE DEDENT new_s += s [ i ] NEW_LINE i += 1 NEW_LINE DEDENT return new_s NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_... |
Longest subarray forming a Geometic Progression ( GP ) | Function to return the length of the longest subarray forming a GP in a sorted array ; Base Case ; Stores the length of GP and the common ratio ; Stores the maximum length of the GP ; Traverse the array ; Check if the common ratio is valid for GP ; If the current... | def longestGP ( A , N ) : NEW_LINE INDENT if ( N < 2 ) : NEW_LINE INDENT return N NEW_LINE DEDENT length = 1 NEW_LINE common_ratio = 1 NEW_LINE maxlength = 1 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i + 1 ] % A [ i ] == 0 ) : NEW_LINE INDENT if ( A [ i + 1 ] // A [ i ] == common_ratio ) : NEW_LINE I... |
Maximum number of uncrossed lines between two given arrays | Function to count maximum number of uncrossed lines between the two given arrays ; Stores the length of lcs obtained upto every index ; Iterate over first array ; Iterate over second array ; Update value in dp table ; If both characters are equal ; Update the... | def uncrossedLines ( a , b , n , m ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( m + 1 ) ] for y 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 ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT elif ( a [ i - 1 ] == b [ j ... |
Minimize flips required to make all shortest paths from top | Function to count the minimum number of flips required ; Dimensions of matrix ; Stores the count the flips ; Check if element is same or not ; Return the final count ; Given Matrix ; Given path as a string ; Function call | def minFlips ( mat , s ) : NEW_LINE INDENT N = len ( mat ) NEW_LINE M = len ( mat [ 0 ] ) NEW_LINE count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != ord ( s [ i + j ] ) - ord ( '0' ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT retur... |
Generate a pair of integers from a range [ L , R ] whose LCM also lies within the range | Python3 implementation of the above approach ; Checking if any pair is possible or not in range ( l , r ) ; If not possible print ( - 1 ) ; Print LCM pair ; Driver Code ; Function call | def lcmpair ( l , r ) : NEW_LINE INDENT x = l NEW_LINE y = 2 * l NEW_LINE if ( y > r ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " X β = β { } β Y β = β { } " . format ( x , y ) ) NEW_LINE DEDENT DEDENT l = 13 NEW_LINE r = 69 NEW_LINE lcmpair ( l , r ) NEW_LINE |
Print all possible shortest chains to reach a target word | Python Program to implement the above approach ; Function to print all possible shortest sequences starting from start to target . ; Find words differing by a single character with word ; Find next word in dict by changing each element from ' a ' to 'z ; Funct... | from collections import deque NEW_LINE from typing import Deque , List , Set NEW_LINE def displaypath ( res : List [ List [ str ] ] ) : NEW_LINE INDENT for i in res : NEW_LINE INDENT print ( " [ β " , end = " " ) for j in i : print ( j , end = " , β " ) print ( " ] " ) NEW_LINE DEDENT DEDENT def addWord ( word : str , ... |
Count non | Function to reverse a number ; Store the reverse of N ; Return reverse of N ; Function to get the count of non - palindromic numbers having same first and last digit ; Store the required count ; Traverse the array ; Store reverse of arr [ i ] ; Check for palindrome ; IF non - palindromic ; Check if first an... | def revNum ( N ) : NEW_LINE INDENT x = 0 NEW_LINE while ( N ) : NEW_LINE INDENT x = x * 10 + N % 10 NEW_LINE N = N // 10 NEW_LINE DEDENT return x NEW_LINE DEDENT def ctNonPalin ( arr , N ) : NEW_LINE INDENT Res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = revNum ( arr [ i ] ) NEW_LINE if ( x == arr [ i ] ) :... |
Smallest subarray from a given Array with sum greater than or equal to K | Set 2 | Python3 program for the above approach ; Function to find the smallest subarray with sum greater than or equal target ; DP table to store the computed subproblems ; Initialize first column with 0 ; Initialize first row with 0 ; Check for... | import sys NEW_LINE def minlt ( arr , target , n ) : NEW_LINE INDENT dp = [ [ - 1 for _ in range ( target + 1 ) ] \ for _ in range ( len ( arr ) + 1 ) ] NEW_LINE for i in range ( len ( arr ) + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 0 NEW_LINE DEDENT for j in range ( target + 1 ) : NEW_LINE INDENT dp [ 0 ] [ j ] = sys .... |
Minimum absolute difference of server loads | Function which returns the minimum difference of loads ; Compute the overall server load ; Stores the results of subproblems ; Fill the partition table in bottom up manner ; If i - th server is included ; If i - th server is excluded ; Server A load : total_sum - ans Server... | def minServerLoads ( n , servers ) : NEW_LINE INDENT totalLoad = sum ( servers ) NEW_LINE requiredLoad = totalLoad // 2 NEW_LINE dp = [ [ 0 for col in range ( requiredLoad + 1 ) ] for row in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , requiredLoad + 1 ) : NEW_LINE INDE... |
Length of longest subarray with positive product | Function to find the length of longest subarray whose product is positive ; Stores the length of current subarray with positive product ; Stores the length of current subarray with negative product ; Stores the length of the longest subarray with positive product ; Res... | def maxLenSub ( arr , N ) : NEW_LINE INDENT Pos = 0 NEW_LINE Neg = 0 NEW_LINE res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT Pos = Neg = 0 NEW_LINE DEDENT elif ( arr [ i ] > 0 ) : NEW_LINE INDENT Pos += 1 NEW_LINE if ( Neg != 0 ) : NEW_LINE INDENT Neg += 1 NEW_LINE DEDEN... |
Print all strings of maximum length from an array of strings | Python3 program to implement the above approach ; Function to find the length of the longest string from the given array of strings ; Traverse the array ; Stores the length of current string ; Update maximum length ; Return the maximum length ; Function to ... | import sys NEW_LINE def maxLength ( arr ) : NEW_LINE INDENT lenn = - sys . maxsize - 1 NEW_LINE N = len ( arr ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT l = len ( arr [ i ] ) NEW_LINE if ( lenn < l ) : NEW_LINE INDENT lenn = l NEW_LINE DEDENT DEDENT return lenn NEW_LINE DEDENT def maxStrings ( arr , lenn ) : NEW... |
Minimize count of flips required such that no substring of 0 s have length exceeding K | Function to return minimum number of flips required ; Base Case ; Stores the count of minimum number of flips ; Stores the count of zeros in current sub ; If current character is 0 ; Continue ongoing sub ; Start a new sub ; If k co... | def min_flips ( strr , k ) : NEW_LINE INDENT if ( len ( strr ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 0 NEW_LINE cnt_zeros = 0 NEW_LINE for ch in strr : NEW_LINE INDENT if ( ch == '0' ) : NEW_LINE INDENT cnt_zeros += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt_zeros = 0 NEW_LINE DEDENT if ( cnt_zeros ... |
Find all possible subarrays having product less than or equal to K | Function to return all possible subarrays having product less than or equal to K ; Store the required subarrays ; Stores the product of current subarray ; Stores the starting index of the current subarray ; Check for empty array ; Iterate over the arr... | def maxSubArray ( arr , n , K ) : NEW_LINE INDENT solution = [ ] NEW_LINE multi = 1 NEW_LINE start = 0 NEW_LINE if ( n <= 1 or K < 0 ) : NEW_LINE INDENT return solution NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT multi = multi * arr [ i ] NEW_LINE while ( multi > K ) : NEW_LINE INDENT multi = multi // arr [ ... |
Count of collisions at a point ( X , Y ) | Function to find the count of possible pairs of collisions ; Stores the time at which points reach the origin ; Calculate time for each point ; Sort the times ; Counting total collisions ; Count of elements arriving at a given point at the same time ; Driver Code ; Given set o... | def solve ( D , N , X , Y ) : NEW_LINE INDENT T = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = D [ i ] [ 0 ] NEW_LINE y = D [ i ] [ 1 ] NEW_LINE speed = D [ i ] [ 2 ] NEW_LINE time = ( ( x * x - X * X ) + ( y * y - Y * Y ) ) / ( speed * speed ) NEW_LINE T . append ( time ) NEW_LINE DEDENT T . sort ( ) NEW_LI... |
Longest subarray forming an Arithmetic Progression ( AP ) | Function to return the length of longest subarray forming an AP ; Minimum possible length of required subarray is 2 ; Stores the length of the current subarray ; Stores the common difference of the current AP ; Stores the common difference of the previous AP ;... | def getMaxLength ( arr , N ) : NEW_LINE INDENT res = 2 NEW_LINE dist = 2 NEW_LINE curradj = ( arr [ 1 ] - arr [ 0 ] ) NEW_LINE prevadj = ( arr [ 1 ] - arr [ 0 ] ) NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT curradj = arr [ i ] - arr [ i - 1 ] NEW_LINE if ( curradj == prevadj ) : NEW_LINE INDENT dist += 1 NEW_LI... |
Minimize cost to empty a given string by removing characters alphabetically | Function to find the minimum cost required to remove each character of the string in alphabetical order ; Stores the frequency of characters of the string ; Iterate through the string ; Count the number of characters smaller than the present ... | def minSteps ( str , N ) : NEW_LINE INDENT cost = 0 NEW_LINE f = [ 0 ] * 26 NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr_ele = ord ( str [ i ] ) - ord ( ' a ' ) NEW_LINE smaller = 0 NEW_LINE for j in range ( curr_ele + 1 ) : NEW_LINE INDENT if ( f [ j ] ) : NEW_LINE INDENT smaller += f [ j ] NEW_LINE DEDENT DED... |
Count of Rectangles with area K made up of only 1 s from given Binary Arrays | Function to find the subarrays of all possible lengths made up of only 1 s ; Stores the frequency of the subarrays ; Check if the previous value was also 0 ; If the previous value was 1 ; Find the subarrays of each size from 1 to count ; If ... | def findSubarrays ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE freq = [ 0 ] * ( n + 1 ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT if ( count == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT value = count NEW_LINE for j in range ( 1... |
Print Longest Bitonic subsequence ( Space Optimized Approach ) | Function to print the longest bitonic subsequence ; Function to generate the longest bitonic subsequence ; Store the lengths of LIS ending at every index ; Store the lengths of LDS ending at every index ; Compute LIS for all indices ; Compute LDS for all ... | def printRes ( res ) : NEW_LINE INDENT n = len ( res ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( res [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def printLBS ( arr , N ) : NEW_LINE INDENT lis = [ 0 ] * N NEW_LINE lds = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT lis [ i ] = lds [ i ] = 1 NE... |
Minimum possible value T such that at most D Partitions of the Array having at most sum T is possible | Function to check if the array can be partitioned into atmost d subarray with sum atmost T ; Initial partition ; Current sum ; If current sum exceeds T ; Create a new partition ; If count of partitions exceed d ; Fun... | def possible ( T , arr , n , d ) : NEW_LINE INDENT partition = 1 ; NEW_LINE total = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT total = total + arr [ i ] ; NEW_LINE if ( total > T ) : NEW_LINE INDENT partition = partition + 1 ; NEW_LINE total = arr [ i ] ; NEW_LINE if ( partition > d ) : NEW_LINE INDENT return ... |
Minimize splits to generate monotonous Substrings from given String | Function to return final result ; Initialize variable to keep track of ongoing sequence ; If current sequence is neither increasing nor decreasing ; If prev char is greater ; If prev char is same ; Otherwise ; If current sequence is Non - Decreasing ... | def minReqSubstring ( s , n ) : NEW_LINE INDENT ongoing = ' N ' NEW_LINE count , l = 0 , len ( s ) NEW_LINE for i in range ( 1 , l ) : NEW_LINE INDENT if ongoing == ' N ' : NEW_LINE INDENT if s [ i ] < s [ i - 1 ] : NEW_LINE INDENT ongoing = ' D ' NEW_LINE DEDENT elif s [ i ] == s [ i - 1 ] : NEW_LINE INDENT ongoing = ... |
Minimum decrements required such that sum of all adjacent pairs in an Array does not exceed K | Function to calculate the minimum number of operations required ; Stores the total number of operations ; Iterate over the array ; If the sum of pair of adjacent elements exceed k . ; If current element exceeds k ; Reduce ar... | def minimum_required_operations ( arr , n , k ) : NEW_LINE INDENT answer = 0 NEW_LINE mod = 10 ** 9 + 7 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if arr [ i ] + arr [ i + 1 ] > k : NEW_LINE INDENT if arr [ i ] > k : NEW_LINE INDENT answer += ( arr [ i ] - k ) NEW_LINE arr [ i ] = k NEW_LINE DEDENT answer += (... |
Lexicographic smallest permutation of a String containing the second String as a Substring | Function to print the desired lexicographic smaller string ; Calculate length of the string ; Stores the frequencies of characters of string str1 ; Stores the frequencies of characters of string str2 ; Decrease the frequency of... | def findSmallestString ( str1 , str2 ) : NEW_LINE INDENT freq1 = [ 0 ] * 26 NEW_LINE freq2 = [ 0 ] * 26 NEW_LINE n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT freq1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( n2 ) : NEW_LINE INDENT freq2 [... |
Restore original String from given Encrypted String by the given operations | Function to decrypt and print the original strings ; If length is exceeded ; Reverse the string ; Driver Code | def decryptString ( s , N ) : NEW_LINE INDENT for i in range ( 0 , len ( s ) , 2 * N ) : NEW_LINE INDENT if ( i + N < len ( s ) ) : NEW_LINE INDENT end = s [ i + N ] NEW_LINE DEDENT if ( i + N > len ( s ) ) : NEW_LINE INDENT end = s [ - 1 ] NEW_LINE DEDENT if ( i == 0 ) : NEW_LINE INDENT s = s [ i + N - 1 : : - 1 ] + s... |
Determine the winner of a game of deleting Characters from a String | Function to find the winner of the game when both players play optimally ; Stores the frequency of all digit ; Stores the scores of player1 and player2 respectively ; Iterate to store frequencies ; Turn for the player1 ; Add score of player1 ; Add sc... | def determineWinner ( str ) : NEW_LINE INDENT A = [ 0 for i in range ( 9 ) ] ; NEW_LINE sum1 = 0 ; sum2 = 0 ; NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT A [ int ( str [ i ] ) ] += 1 ; NEW_LINE DEDENT for i in range ( 0 , 9 ) : NEW_LINE INDENT if ( i % 2 != 0 ) : NEW_LINE INDENT sum1 = sum1 + A [ i ] ... |
Generate a String from given Strings P and Q based on the given conditions | Function to generate a string S from string P and Q according to the given conditions ; Stores the frequencies ; Counts occurrences of each characters ; Reduce the count of the character which is also present in Q ; Stores the resultant string... | def manipulateStrings ( P , Q ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] ; NEW_LINE for i in range ( len ( P ) ) : NEW_LINE INDENT freq [ ord ( P [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( len ( Q ) ) : NEW_LINE INDENT freq [ ord ( Q [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE DEDENT sb = "... |
Minimum moves required to type a word in QWERTY based keyboard | Function that calculates the moves required to prthe current String ; row1 has qwertyuiop , row2 has asdfghjkl , and row3 has zxcvbnm Store the row number of each character ; String length ; Initialise move to 1 ; Traverse the String ; If current row numb... | def numberMoves ( s ) : NEW_LINE INDENT row = [ 2 , 3 , 3 , 2 , 1 , 2 , 2 , 2 , 1 , 2 , 2 , 2 , 3 , 3 , 1 , 1 , 1 , 1 , 2 , 1 , 1 , 3 , 1 , 3 , 1 , 3 ] ; NEW_LINE n = len ( s ) ; NEW_LINE move = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE if ( row [ ord ( s [ i ] ) - ord ( ' a ' ) ] != row [ ord ( s [ i - 1 ] ) - ... |
Count of distinct Strings possible by swapping prefixes of pairs of Strings from the Array | Python3 program to implement the above approach ; Function to count the distinct strings possible after swapping the prefixes between two possible strings of the array ; Stores the count of unique characters for each index ; St... | from collections import defaultdict NEW_LINE mod = 1000000007 NEW_LINE def countS ( string : list , n : int , m : int ) -> int : NEW_LINE INDENT counts = defaultdict ( lambda : set ( ) ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = string [ i ] NEW_LINE for j in range ( m ) : NEW_LINE INDENT counts [ j ] . add (... |
Longest Subarrays having each Array element as the maximum | Function to find the maximum length of Subarrays for each element of the array having it as the maximum ; Initialise the bounds ; Iterate to find greater element on the left ; If greater element is found ; Decrement left pointer ; If boundary is exceeded ; It... | def solve ( n , arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT left = max ( i - 1 , 0 ) NEW_LINE right = min ( n - 1 , i + 1 ) NEW_LINE while left >= 0 : NEW_LINE INDENT if arr [ left ] > arr [ i ] : NEW_LINE INDENT left += 1 NEW_LINE break NEW_LINE DEDENT left -= 1 NEW_LINE DEDENT if l... |
Count of Substrings having Sum equal to their Length | Python3 program to implement the above approach ; Function to count the number of substrings with sum equal to length ; Stores the count of substrings ; Add character to sum ; Add count of substrings to result ; Increase count of subarrays ; Return count ; Driver c... | from collections import defaultdict NEW_LINE def countSubstrings ( s , n ) : NEW_LINE INDENT count , sum = 0 , 0 NEW_LINE mp = defaultdict ( lambda : 0 ) NEW_LINE mp [ 0 ] += 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ord ( s [ i ] ) - ord ( '0' ) NEW_LINE count += mp [ sum - ( i + 1 ) ] NEW_LINE mp [ sum... |
Count of ways to split an Array into three contiguous Subarrays having increasing Sum | Function to count the number of ways to split array into three contiguous subarrays of the required type ; Stores the prefix sums ; Stores the suffix sums ; Traverse the given array ; Updating curr_subarray_sum until it is less than... | def findCount ( arr , n ) : NEW_LINE INDENT prefix_sum = [ 0 for x in range ( n ) ] NEW_LINE prefix_sum [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i ] NEW_LINE DEDENT suffix_sum = [ 0 for x in range ( n ) ] NEW_LINE suffix_sum [ n - 1 ] = arr [ ... |
Minimum number of operations required to maximize the Binary String | Function to find the number of operations required ; Count of 1 's ; Count of 0 's upto (cnt1)-th index ; Return the answer ; Driver Code | def minOperation ( s , n ) : NEW_LINE INDENT cnt1 = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ord ( s [ i ] ) == ord ( '1' ) ) : NEW_LINE INDENT cnt1 += 1 ; NEW_LINE DEDENT DEDENT cnt0 = 0 ; NEW_LINE for i in range ( 0 , cnt1 ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT cnt0 += 1 ; NEW_LIN... |
Minimum number of operations required to maximize the Binary String | Function to find the number of operations required ; Swap 0 ' s β and β 1' s ; Return the answer ; Driver code | def minOperation ( s , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE i = 0 ; j = n - 1 ; NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( s [ i ] == '0' and s [ j ] == '1' ) : NEW_LINE INDENT ans += 1 ; NEW_LINE i += 1 ; NEW_LINE j -= 1 ; NEW_LINE continue ; NEW_LINE DEDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT i += 1 ; NE... |
Count of N digit Numbers having no pair of equal consecutive Digits | Function to count the number of N - digit numbers with no equal pair of consecutive digits ; Base Case ; Calculate the total count of valid ( i - 1 ) - digit numbers ; Update dp table ; Calculate the count of required N - digit numbers ; Driver Code | def count ( N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( 10 ) ; NEW_LINE return ; NEW_LINE DEDENT dp = [ [ 0 for i in range ( 10 ) ] for j in range ( N ) ] NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 ; NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT temp = 0 ; NEW... |
Count of N digit Numbers having no pair of equal consecutive Digits | Iterative Function to calculate ( x ^ y ) % mod in O ( log y ) ; Initialize result ; Update x if x >= mod ; If x is divisible by mod ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Function to count the number of N - digit num... | def power ( x , y , mod ) : NEW_LINE INDENT res = 1 ; NEW_LINE x = x % mod ; NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) == 1 ) : NEW_LINE INDENT res = ( res * x ) % mod ; NEW_LINE DEDENT y = y >> 1 ; NEW_LINE x = ( x * x ) % mod ; NEW_LINE DEDENT... |
Smallest String consisting of a String S exactly K times as a Substring | KMP algorithm ; Function to return the required string ; Finding the longest proper prefix which is also suffix ; ans string ; Update ans appending the substring K - 1 times ; Append the original string ; Returning min length string which contain... | def kmp ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE lps = [ None ] * n NEW_LINE lps [ 0 ] = 0 NEW_LINE i , Len = 1 , 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( s [ i ] == s [ Len ] ) : NEW_LINE INDENT Len += 1 NEW_LINE lps [ i ] = Len NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( Len != 0 ) : NE... |
Check if an Array can be Sorted by picking only the corner Array elements | Function to check if an array can be sorted using given operations ; If sequence becomes increasing after an already non - decreasing to non - increasing pattern ; If a decreasing pattern is observed ; Driver Code | def check ( arr , n ) : NEW_LINE INDENT g = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] > 0 and g == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( arr [ i ] - arr [ i ] < 0 ) : NEW_LINE INDENT g = 1 NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 2 , 3 , 4 ,... |
Queries to find the count of connected Non | Count of connected cells ; Function to return the representative of the Set to which x belongs ; If x is parent of itself ; x is representative of the Set ; Otherwise ; Path Compression ; Unites the set that includes x and the set that includes y ; Find the representatives (... | ctr = 0 NEW_LINE def find ( parent , x ) : NEW_LINE INDENT if ( parent [ x ] == x ) : NEW_LINE INDENT return x NEW_LINE DEDENT parent [ x ] = find ( parent , parent [ x ] ) NEW_LINE return parent [ x ] NEW_LINE DEDENT def setUnion ( parent , rank , x , y ) : NEW_LINE INDENT global ctr NEW_LINE parentx = find ( parent ,... |
Minimum Sum of a pair at least K distance apart from an Array | Python3 program to implement the above approach ; Function to find the minimum sum of two elements that are atleast K distance apart ; Length of the array ; Find the suffix array ; Iterate in the array ; Update minimum sum ; Print the answer ; Driver Code | import sys NEW_LINE def findMinSum ( A , K ) : NEW_LINE INDENT n = len ( A ) ; NEW_LINE suffix_min = [ 0 ] * n ; NEW_LINE suffix_min [ n - 1 ] = A [ n - 1 ] ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffix_min [ i ] = min ( suffix_min [ i + 1 ] , A [ i ] ) ; NEW_LINE DEDENT min_sum = sys . maxsi... |
Maximum number of envelopes that can be put inside other bigger envelopes | Function that returns the maximum number of envelopes that can be inserted into another envelopes ; Number of envelopes ; Sort the envelopes in non - decreasing order ; Initialize dp [ ] array ; To store the result ; Loop through the array ; Fi... | def maxEnvelopes ( envelopes ) : NEW_LINE INDENT N = len ( envelopes ) NEW_LINE if ( N == 0 ) : NEW_LINE INDENT return N NEW_LINE DEDENT envelopes = sorted ( envelopes ) NEW_LINE dp = [ 0 ] * N NEW_LINE max_envelope = 1 NEW_LINE dp [ 0 ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE for ... |
Maximize difference between the Sum of the two halves of the Array after removal of N elements | Function to print the maximum difference possible between the two halves of the array ; Stores n maximum values from the start ; Insert first n elements ; Update sum of largest n elements from left ; For the remaining eleme... | def FindMaxDif ( a , m ) : NEW_LINE INDENT n = m // 3 NEW_LINE l = [ 0 ] * ( m + 5 ) NEW_LINE r = [ 0 ] * ( m + 5 ) NEW_LINE s = [ ] NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( i <= n ) : NEW_LINE INDENT l [ i ] = a [ i - 1 ] + l [ i - 1 ] NEW_LINE s . append ( a [ i - 1 ] ) NEW_LINE DEDENT else : NEW_... |
Check if each element of an Array is the Sum of any two elements of another Array | Function to check if each element of B [ ] can be formed by adding two elements of array A [ ] ; Store each element of B [ ] ; Traverse all possible pairs of array ; If A [ i ] + A [ j ] is present in the set ; Remove A [ i ] + A [ j ] ... | def checkPossible ( A , B , n ) : NEW_LINE INDENT values = set ( [ ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT values . add ( B [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ( A [ i ] + A [ j ] ) in values ) : NEW_LINE INDENT values . remove ( A [ i ]... |
Count of Array elements greater than or equal to twice the Median of K trailing Array elements | Python3 program to implement the above approach ; Function to find the count of array elements >= twice the median of K trailing array elements ; Stores frequencies ; Stores the array elements ; Count the frequencies of the... | import math NEW_LINE N = 200000 NEW_LINE V = 500 NEW_LINE def solve ( n , d , input1 ) : NEW_LINE INDENT a = [ 0 ] * N NEW_LINE cnt = [ 0 ] * ( V + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] = input1 [ i ] NEW_LINE DEDENT answer = 0 NEW_LINE for i in range ( d ) : NEW_LINE INDENT cnt [ a [ i ] ] += 1 N... |
Smallest positive integer X satisfying the given equation | Python3 program to implement the above approach ; Function to find out the smallest positive integer for the equation ; Stores the minimum ; Iterate till K ; Check if n is divisible by i ; Return the answer ; Driver Code | import sys NEW_LINE def findMinSoln ( n , k ) : NEW_LINE INDENT minSoln = sys . maxsize ; NEW_LINE for i in range ( 1 , k ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT minSoln = min ( minSoln , ( n // i ) * k + i ) ; NEW_LINE DEDENT DEDENT return minSoln ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW... |
Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree | Function to calculate and return the sum of arr [ 0. . index ] ; Traverse ancestors of BITree [ index ] ; Update the sum of current element of BIT to ans ; Update index to that of the parent node in getSum ( ) view by subtracti... | def getSum ( BITree , index ) : NEW_LINE INDENT ans = 0 NEW_LINE index += 1 NEW_LINE while ( index > 0 ) : NEW_LINE INDENT ans += BITree [ index ] NEW_LINE index -= index & ( - index ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def updateBIT ( BITree , n , index , val ) : NEW_LINE INDENT index = index + 1 NEW_LINE whil... |
Minimum number of leaves required to be removed from a Tree to satisfy the given condition | Stores the count of safe nodes ; Function to perform DFS on the Tree to obtain the count of vertices that are not required to be deleted ; Update cost to reach the vertex ; If the vertex does not satisfy the condition ; Otherwi... | cnt = 0 NEW_LINE def dfs ( val , cost , tr , u , s ) : NEW_LINE INDENT global cnt NEW_LINE s = s + cost [ u ] NEW_LINE if ( s < 0 ) : NEW_LINE INDENT s = 0 NEW_LINE DEDENT if ( s > val [ u ] ) : NEW_LINE INDENT return NEW_LINE DEDENT cnt += 1 NEW_LINE for i in range ( 0 , len ( tr [ u ] ) ) : NEW_LINE INDENT dfs ( val ... |
Check if an Array is made up of Subarrays of continuous repetitions of every distinct element | Function to check if the array is made up of subarrays of repetitions ; Base Case ; Stores the size of current subarray ; If a different element is encountered ; If the previous subarray was a single element ; Reset to new s... | def ContinuousElements ( a , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT curr = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] != a [ i - 1 ] ) : NEW_LINE if ( curr == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT curr = 0 NEW_LINE c... |
Size of all connected non | Python3 program to implement the above approach ; Function to find size of all the islands from the given matrix ; Initialize a queue for the BFS traversal ; Iterate until the queue is empty ; Top element of queue ; Pop the element Q . pop ( ) ; ; Check for boundaries ; Check if current elem... | from collections import deque NEW_LINE def BFS ( mat , row , col ) : NEW_LINE INDENT area = 0 NEW_LINE Q = deque ( ) NEW_LINE Q . append ( [ row , col ] ) NEW_LINE while ( len ( Q ) > 0 ) : NEW_LINE INDENT it = Q . popleft ( ) NEW_LINE r , c = it [ 0 ] , it [ 1 ] NEW_LINE if ( r < 0 or c < 0 or r > 4 or c > 4 ) : NEW_L... |
Find a pair in Array with second largest product | Function to find second largest product pair in arr [ 0. . n - 1 ] ; No pair exits ; Sort the array ; Initialize smallest element of the array ; Initialize largest element of the array ; Prsecond largest product pair ; Driver Code ; Given array ; Function Call | def maxProduct ( arr , N ) : NEW_LINE INDENT if ( N < 3 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT arr . sort ( ) ; NEW_LINE smallest1 = arr [ 0 ] ; NEW_LINE smallest3 = arr [ 2 ] ; NEW_LINE largest1 = arr [ N - 1 ] ; NEW_LINE largest3 = arr [ N - 3 ] ; NEW_LINE if ( smallest1 * smallest3 >= largest1 * largest3 ) : N... |
Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | Function to find the maximum subarray length of ones ; Stores the length , starting index and ending index of the subarrays ; S : starting index of the sub - array ; Traverse only continuous 1 s ; Calculate length of the sub - a... | def maxLen ( A , N ) : NEW_LINE INDENT v = [ ] NEW_LINE i = 0 NEW_LINE while i < N : NEW_LINE INDENT if ( A [ i ] == 1 ) : NEW_LINE INDENT s = i NEW_LINE while ( i < N and A [ i ] == 1 ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT le = i - s NEW_LINE v . append ( [ le , s , i - 1 ] ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT... |
Detect cycle in Directed Graph using Topological Sort | Python3 program to implement the above approach ; Stack to store the visited vertices in the Topological Sort ; Store Topological Order ; Adjacency list to store edges ; To ensure visited vertex ; Function to perform DFS ; Set the vertex as visited ; Visit connect... | t = 0 NEW_LINE n = 0 NEW_LINE m = 0 NEW_LINE a = 0 NEW_LINE s = [ ] NEW_LINE tsort = [ ] NEW_LINE adj = [ [ ] for i in range ( 100001 ) ] NEW_LINE visited = [ False for i in range ( 100001 ) ] NEW_LINE def dfs ( u ) : NEW_LINE INDENT visited [ u ] = 1 NEW_LINE for it in adj [ u ] : NEW_LINE INDENT if ( visited [ it ] =... |
Rearrange an Array such that Sum of same | Function to rearrange the array such that no same - indexed subset have sum equal to that in the original array ; Initialize a vector ; Iterate the array ; Sort the vector ; Shift of elements to the index of its next cyclic element ; Print the answer ; Driver Code | def printNewArray ( a , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT v . append ( ( a [ i ] , i ) ) NEW_LINE DEDENT v . sort ( ) NEW_LINE ans = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans [ v [ ( i + 1 ) % n ] [ 1 ] ] = v [ i ] [ 0 ] NEW_LINE DEDENT for i in range ( n ... |
Minimize count of array elements to be removed to maximize difference between any pair up to K | Python3 program to implement the above approach ; Function to count the number of elements to be removed from the array based on the given condition ; Sort the array ; Initialize the variable ; Iterate for all possible pair... | import sys NEW_LINE def min_remove ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if ( arr [ j ] - arr [ i ] <= k ) : NEW_LINE INDENT ans = min ( ans , n - j + i - 1 ) NEW_LINE DEDENT DEDENT DEDENT ... |
Reduce a given Binary Array to a single element by removal of Triplets | Function to check if it is possible to reduce the array to a single element ; Stores frequency of 0 's ; Stores frequency of 1 's ; Condition for array to be reduced ; Otherwise ; Driver Code | def solve ( arr , n ) : NEW_LINE INDENT countzeroes = 0 ; NEW_LINE countones = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT countzeroes += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT countones += 1 ; NEW_LINE DEDENT DEDENT if ( abs ( countzeroes - countones ) == 1 ) : NEW_L... |
Nearest smaller character to a character K from a Sorted Array | Function to return the nearest smaller character ; Stores the nearest smaller character ; Iterate till starts cross end ; Find the mid element ; Check if K is found ; Check if current character is less than K ; Increment the start ; Otherwise ; Increment ... | def bs ( a , n , ele ) : NEW_LINE INDENT start = 0 NEW_LINE end = n - 1 NEW_LINE ch = ' @ ' NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = start + ( end - start ) // 2 ; NEW_LINE if ( ar [ mid ] == ele ) : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT elif ( ar [ mid ] < ele ) : NEW_LINE INDENT ch = ar [ mid ]... |
Largest possible Subset from an Array such that no element is K times any other element in the Subset | Function to find the maximum size of the required subset ; Size of the array ; Sort the array ; Stores which index is included or excluded ; Stores the indices of array elements ; Count of pairs ; Iterate through all... | def findMaxLen ( a , k ) : NEW_LINE INDENT n = len ( a ) NEW_LINE a . sort ( ) NEW_LINE vis = [ 0 ] * n NEW_LINE mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ a [ i ] ] = i NEW_LINE DEDENT c = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( vis [ i ] == False ) : NEW_LINE INDENT check = a [ i ] *... |
Minimize length of prefix of string S containing all characters of another string T | Python3 program for the above approach ; Base Case - if T is empty , it matches 0 length prefix ; Convert strings to lower case for uniformity ; Update dictCount to the letter count of T ; If new character is found , initialize its en... | def getPrefixLength ( srcStr , targetStr ) : NEW_LINE INDENT if ( len ( targetStr ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT srcStr = srcStr . lower ( ) NEW_LINE targetStr = targetStr . lower ( ) NEW_LINE dictCount = dict ( [ ] ) NEW_LINE nUnique = 0 NEW_LINE for ch in targetStr : NEW_LINE INDENT if ( ch not i... |
Minimize length of Substrings containing at least one common Character | Function to check and return if substrings of length mid has a common character a ; Length of the string ; Initialise the first occurrence of character a ; Check that distance b / w the current and previous occurrence of character a is less than o... | def check ( st , mid , a ) : NEW_LINE INDENT n = len ( st ) NEW_LINE previous = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( st [ i ] == chr ( a ) ) : NEW_LINE INDENT if ( i - previous > mid ) : NEW_LINE INDENT return False NEW_LINE DEDENT previous = i NEW_LINE DEDENT DEDENT if ( i - previous > mid ) : NEW_... |
Maximize product of absolute index difference with K | Function returns maximum possible value of k ; Pointer i make sure that A [ i ] will result in max k ; Stores maximum possible k ; Possible value of k for current pair ( A [ i ] and A [ j ] ) ; If current value exceeds k ; Update the value of k ; Update pointer i ;... | def solve ( A , N ) : NEW_LINE INDENT i = 0 NEW_LINE k = 0 NEW_LINE for j in range ( 1 , N ) : NEW_LINE INDENT tempK = ( min ( A [ i ] , A [ j ] ) // ( j - i ) ) NEW_LINE if ( tempK > k ) : NEW_LINE INDENT k = tempK NEW_LINE DEDENT if ( A [ j ] >= A [ i ] // ( j - i ) ) : NEW_LINE INDENT i = j NEW_LINE DEDENT DEDENT re... |
Split Array into min number of subsets with difference between each pair greater than 1 | Function to Split the array into minimum number of subsets with difference strictly > 1 ; Sort the array ; Traverse through the sorted array ; Check the pairs of elements with difference 1 ; If we find even a single pair with diff... | def split ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE count = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] == 1 ) : NEW_LINE INDENT count = 2 NEW_LINE break NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ ... |
Check if a Palindromic String can be formed by concatenating Substrings of two given Strings | Function to check if a palindromic string can be formed from the substring of given strings ; Boolean array to mark presence of characters ; Check if any of the character of str2 is already marked ; If a common character is f... | def check ( str1 , str2 ) : NEW_LINE INDENT mark = [ False for i in range ( 26 ) ] NEW_LINE n = len ( str1 ) NEW_LINE m = len ( str2 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mark [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT if ( mark [ ord ( str2 [ i ] ) ... |
Generate K co | Python3 implementation of the above approach ; Function prints the required pairs ; First co - prime pair ; As a pair ( 1 n ) has already been Printed ; If i is a factor of N ; Since ( i , i ) won 't form a coprime pair ; Driver Code | from math import sqrt NEW_LINE def FindPairs ( n , k ) : NEW_LINE INDENT print ( 1 , n ) NEW_LINE k -= 1 NEW_LINE for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT print ( 1 , i ) NEW_LINE k -= 1 NEW_LINE if ( k == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( i != n... |
Count of subarrays which forms a permutation from given Array elements | Function returns the required count ; Store the indices of the elements present in A [ ] . ; Store the maximum and minimum index of the elements from 1 to i . ; Update maxi and mini , to store minimum and maximum index for permutation of elements ... | def PermuteTheArray ( A , n ) : NEW_LINE INDENT arr = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ A [ i ] - 1 ] = i NEW_LINE DEDENT mini = n NEW_LINE maxi = 0 NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mini = min ( mini , arr [ i ] ) NEW_LINE maxi = max ( maxi , arr [ i ] ) N... |
Find Second largest element in an array | Set 2 | Function to find the largest element in the array arr [ ] ; Base Condition ; Initialize an empty list ; Divide the array into two equal length subarrays and recursively find the largest among the two ; Store length of compared1 [ ] in the first index ; Store the maximum... | def findLargest ( beg , end , arr , n ) : NEW_LINE INDENT if ( beg == end ) : NEW_LINE INDENT compared = [ 0 ] * n NEW_LINE compared [ 0 ] = 1 NEW_LINE compared [ 1 ] = arr [ beg ] NEW_LINE return compared NEW_LINE DEDENT compared1 = findLargest ( beg , ( beg + end ) // 2 , arr , n ) NEW_LINE compared2 = findLargest ( ... |
Count of Reverse Bitonic Substrings in a given String | Function to calculate the number of reverse bitonic substrings ; Stores the count ; All possible lengths of substrings ; Starting poof a substring ; Ending poof a substring ; Condition for reverse bitonic substrings of length 1 ; Check for decreasing sequence ; If... | def CountsubString ( strr , n ) : NEW_LINE INDENT c = 0 NEW_LINE for len in range ( n + 1 ) : NEW_LINE INDENT for i in range ( n - len ) : NEW_LINE INDENT j = i + len - 1 NEW_LINE temp = strr [ i ] NEW_LINE f = 0 NEW_LINE if ( j == i ) : NEW_LINE INDENT c += 1 NEW_LINE continue NEW_LINE DEDENT k = i + 1 NEW_LINE while ... |
Maximum subsequence sum from a given array which is a perfect square | Python3 program to implement the above approach ; If sum is 0 , then answer is true ; If sum is not 0 and arr [ ] is empty , then answer is false ; Fill the subset table in bottom up manner ; Function to find the sum ; Find sum of all values ; Retur... | import math NEW_LINE def isSubsetSum ( arr , n , sum ) : NEW_LINE INDENT subset = [ [ True for x in range ( sum + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT subset [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , sum + 1 ) : NEW_LINE INDENT subset [ 0 ] [ i ] = False NEW... |
Smallest subarray whose product leaves remainder K when divided by size of the array | Function to find the subarray of minimum length ; Initialize the minimum subarray size to N + 1 ; Generate all possible subarray ; Initialize the product ; Find the product ; Return the minimum size of subarray ; Driver code ; Given ... | def findsubArray ( arr , N , K ) : NEW_LINE INDENT res = N + 1 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT curr_prad = 1 NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT curr_prad = curr_prad * arr [ j ] NEW_LINE if ( curr_prad % N == K and res > ( j - i + 1 ) ) : NEW_LINE INDENT res = min ( res , j - i + 1 ... |
Count of array elements whose order of deletion precedes order of insertion | Python3 Program to implement the above approach ; Function returns maximum number of required elements ; Insert the elements of array B in the queue and set ; Stores the answer ; If A [ i ] is already processed ; Until we find A [ i ] in the ... | import queue NEW_LINE def maximumCount ( A , B , n ) : NEW_LINE INDENT q = queue . Queue ( ) NEW_LINE s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( B [ i ] ) NEW_LINE q . put ( B [ i ] ) NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( A [ i ] not in s ) : NEW_LINE ... |
Check if a Matrix is Bitonic or not | Python3 program to check if a matrix is Bitonic or not ; Function to check if an array is Bitonic or not ; Check for increasing sequence ; Check for decreasing sequence ; Function to check whether given matrix is bitonic or not ; Check row wise ; Check column wise ; Generate an arr... | N = 3 NEW_LINE M = 3 NEW_LINE def checkBitonic ( arr , n ) : NEW_LINE INDENT i , j , f = 0 , 0 , 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_L... |
Maximum possible GCD for a pair of integers with product N | Python3 program to implement the above approach ; Function to return the maximum GCD ; To find all divisors of N ; If i is a factor ; Store the pair of factors ; Store the maximum GCD ; Return the maximum GCD ; Driver Code | import sys NEW_LINE import math NEW_LINE def getMaxGcd ( N ) : NEW_LINE INDENT maxGcd = - sys . maxsize - 1 NEW_LINE for i in range ( 1 , int ( math . sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT A = i NEW_LINE B = N // i NEW_LINE maxGcd = max ( maxGcd , math . gcd ( A , B ) ) NEW_LINE DEDEN... |
Maximum of minimum difference of all pairs from subsequences of given size | Function to check a subsequence can be formed with min difference mid ; If a subsequence of size B with min diff = mid is possible return true else false ; Function to find the maximum of all minimum difference of pairs possible among the subs... | def can_place ( A , n , B , mid ) : NEW_LINE INDENT count = 1 NEW_LINE last_position = A [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( A [ i ] - last_position >= mid ) : NEW_LINE INDENT last_position = A [ i ] NEW_LINE count = count + 1 NEW_LINE if ( count == B ) : NEW_LINE INDENT return bool ( True ) ... |
Count of triplets in an Array such that A [ i ] * A [ j ] = A [ k ] and i < j < k | Python3 program for the above approach ; Returns total number of valid triplets possible ; Stores the count ; Map to store frequency of array elements ; Increment the frequency of A [ j + 1 ] as it can be a valid A [ k ] ; If target exi... | from collections import defaultdict NEW_LINE def countTriplets ( A , N ) : NEW_LINE INDENT ans = 0 NEW_LINE map = defaultdict ( lambda : 0 ) NEW_LINE for j in range ( N - 2 , 0 , - 1 ) : NEW_LINE INDENT map [ A [ j + 1 ] ] += 1 NEW_LINE for i in range ( j ) : NEW_LINE INDENT target = A [ i ] * A [ j ] NEW_LINE if ( tar... |
Missing vertex among N axis | Python3 program for the above approach ; Driver code ; Number of rectangles ; Stores the coordinates ; Insert the coordinates | from collections import defaultdict NEW_LINE def MissingPoint ( V , N ) : NEW_LINE INDENT mp = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( len ( V ) ) : NEW_LINE INDENT mp [ V [ i ] [ 0 ] ] += 1 NEW_LINE DEDENT for it in mp . keys ( ) : NEW_LINE INDENT if ( mp [ it ] % 2 == 1 ) : NEW_LINE INDENT x = it NEW_LIN... |
Longest alternating subsequence with maximum sum | Set 2 | Function to check the sign of the element ; Function to calculate and return the maximum sum of longest alternating subsequence ; Iterate through the array ; Stores the first element of a sequence of same sign ; Traverse until an element with opposite sign is e... | def sign ( x ) : NEW_LINE INDENT if ( x > 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT def findMaxSum ( arr , size ) : NEW_LINE INDENT max_sum = 0 NEW_LINE i = 0 NEW_LINE while i < size : NEW_LINE INDENT pres = arr [ i ] NEW_LINE j = i NEW_LINE while ( j < size... |
Check if an array can be split into subsets of K consecutive elements | Python3 program to implement the above approach ; Function to check if a given array can be split into subsets of K consecutive elements ; Stores the frequencies of array elements ; Traverse the map ; Check if all its occurrences can be grouped int... | from collections import defaultdict NEW_LINE def groupInKConsecutive ( arr , K ) : NEW_LINE INDENT count = defaultdict ( int ) NEW_LINE for h in arr : NEW_LINE INDENT count [ h ] += 1 NEW_LINE DEDENT for key , value in count . items ( ) : NEW_LINE INDENT cur = key NEW_LINE n = value NEW_LINE if ( n > 0 ) : NEW_LINE IND... |
Count of substrings of a given Binary string with all characters same | Function to count number of sub - strings of a given binary string that contains only 1 ; Iterate untill L and R cross each other ; Check if reached the end of string ; Check if encountered '1' then extend window ; Check if encountered '0' then add... | def countSubAllOnes ( s ) : NEW_LINE INDENT l , r , ans = 0 , 0 , 0 NEW_LINE while ( l <= r ) : NEW_LINE INDENT if ( r == len ( s ) ) : NEW_LINE INDENT ans += ( ( r - l ) * ( r - l + 1 ) ) // 2 NEW_LINE break NEW_LINE DEDENT if ( s [ r ] == '1' ) : NEW_LINE INDENT r += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( ... |
Count of primes in a given range that can be expressed as sum of perfect squares | Function to check if a prime number satisfies the condition to be expressed as sum of two perfect squares ; Function to check if a number is prime or not ; Corner cases ; Function to return the count of primes in the range which can be e... | def sumsquare ( p ) : NEW_LINE INDENT return ( p - 1 ) % 4 == 0 NEW_LINE DEDENT def isprime ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if n <= 3 : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 ) or ( n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NE... |
Count of array elements which are greater than all elements on its left | Function to return the count of array elements with all elements to its left smaller than it ; Stores the count ; Stores the maximum ; Iterate over the array ; If an element greater than maximum is obtained ; Increase count ; Update maximum ; Dri... | def count_elements ( arr ) : NEW_LINE INDENT count = 1 NEW_LINE max = arr [ 0 ] NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT if arr [ i ] > max : NEW_LINE INDENT count += 1 NEW_LINE max = arr [ i ] NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 2 , 1 , 4 , 6 , 3 ] NEW_LINE print ( count_el... |
Count of bitonic substrings from the given string | Function to find all the bitonic sub strings ; Pick starting po ; Iterate till length of the string ; Pick ending pofor string ; Substring from i to j is obtained ; Substrings of length 1 ; Increase count ; For increasing sequence ; Check for strictly increasing ; Inc... | def subString ( str , n ) : NEW_LINE INDENT c = 0 ; NEW_LINE for len in range ( 1 , n + 1 ) : NEW_LINE INDENT for i in range ( 0 , n - len + 1 ) : NEW_LINE INDENT j = i + len - 1 ; NEW_LINE temp = str [ i ] NEW_LINE f = 0 ; NEW_LINE if ( j == i ) : NEW_LINE INDENT c += 1 NEW_LINE continue ; NEW_LINE DEDENT k = i + 1 ; ... |
Check if ceil of number divided by power of two exist in sorted array | Function to find there exist a number or not in the array ; Loop to check if there exist a number by divided by power of 2 ; Binary Search ; Condition to check the number is found in the array or not ; Otherwise divide the number by increasing the ... | def findNumberDivByPowerofTwo ( ar , k , n ) : NEW_LINE INDENT found = - 1 NEW_LINE m = k NEW_LINE while ( m > 0 ) : NEW_LINE INDENT l = 0 NEW_LINE r = n - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT mid = ( l + r ) // 2 NEW_LINE if ( ar [ mid ] == m ) : NEW_LINE INDENT found = m NEW_LINE break NEW_LINE DEDENT elif (... |
Largest subset having with sum less than equal to sum of respective indices | Function to find the length of the longest subset ; Stores the sum of differences between elements and their respective index ; Stores the size of the subset ; Iterate over the array ; If an element which is smaller than or equal to its index... | def findSubset ( a , n ) : NEW_LINE INDENT sum = 0 NEW_LINE cnt = 0 NEW_LINE v = [ ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( a [ i - 1 ] - i <= 0 ) : NEW_LINE INDENT sum += a [ i - 1 ] - i NEW_LINE cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( a [ i - 1 ] - i ) NEW_LINE DEDENT DEDENT... |
Queries for count of array elements with values in given range with updates | Python3 code for queries for number of elements that lie in range [ l , r ] ( with updates ) ; Function to set arr [ index ] = x ; Function to get count of elements that lie in range [ l , r ] ; Traverse array ; If element lies in the range [... | from typing import Generic , List , TypeVar NEW_LINE T = TypeVar ( ' T ' ) NEW_LINE V = TypeVar ( ' V ' ) NEW_LINE class Pair ( Generic [ V , T ] ) : NEW_LINE INDENT def __init__ ( self , first : V , second : T ) -> None : NEW_LINE INDENT self . first = first NEW_LINE self . second = second NEW_LINE DEDENT DEDENT def s... |
Construct a sequence from given frequencies of N consecutive integers with unit adjacent difference | Function generates the sequence ; Map to store the frequency of numbers ; Sum of all frequencies ; Try all possibilities for the starting element ; If the frequency of current element is non - zero ; vector to store th... | def generateSequence ( freq , n ) : NEW_LINE INDENT m = { } NEW_LINE total = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ i ] = freq [ i ] NEW_LINE total += freq [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( m [ i ] ) : NEW_LINE INDENT sequence = [ ] NEW_LINE mcopy = { } NEW_LINE for j in m... |
Minimum distance between any most frequent and least frequent element of an array | Python3 implementation of the approach ; Function to find the minimum distance between any two most and least frequent element ; Initialize sets to store the least and the most frequent elements ; Initialize variables to store max and m... | import sys NEW_LINE def getMinimumDistance ( a , n ) : NEW_LINE INDENT min_set = { } NEW_LINE max_set = { } NEW_LINE max , min = 0 , sys . maxsize + 1 NEW_LINE frequency = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT frequency [ a [ i ] ] = frequency . get ( a [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( n )... |
Construct a string that has exactly K subsequences from given string | Python3 program for the above approach ; Function that computes the string s ; Length of the given string str ; List that stores all the prime factors of given k ; Find the prime factors ; Initialize the count of each character position as 1 ; Loop ... | import math NEW_LINE def printSubsequenceString ( st , k ) : NEW_LINE INDENT n = len ( st ) NEW_LINE factors = [ ] NEW_LINE sqt = ( int ( math . sqrt ( k ) ) ) NEW_LINE for i in range ( 2 , sqt + 1 ) : NEW_LINE INDENT while ( k % i == 0 ) : NEW_LINE INDENT factors . append ( i ) NEW_LINE k //= i NEW_LINE DEDENT DEDENT ... |
Replace each element of Array with it 's corresponding rank | Function to assign rank to array elements ; Copy input array into newArray ; Sort newArray [ ] in ascending order ; Dictionary to store the rank of the array element ; Update rank of element ; Assign ranks to elements ; Driver Code ; Given array arr [ ] ; Fu... | def changeArr ( input1 ) : NEW_LINE INDENT newArray = input1 . copy ( ) NEW_LINE newArray . sort ( ) NEW_LINE ranks = { } NEW_LINE rank = 1 NEW_LINE for index in range ( len ( newArray ) ) : NEW_LINE INDENT element = newArray [ index ] ; NEW_LINE if element not in ranks : NEW_LINE INDENT ranks [ element ] = rank NEW_LI... |
Find pairs in array whose sum does not exist in Array | Function to print all pairs with sum not present in the array ; Corner Case ; Stores the distinct array elements ; Generate all possible pairs ; Calculate sum of current pair ; Check if the sum exists in the HashSet or not ; Driver Code | def findPair ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT hashMap = [ ] NEW_LINE for k in arr : NEW_LINE INDENT hashMap . append ( k ) NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT sum = arr [ i ] + arr [ j ] NE... |
Largest subset with M as smallest missing number | Function to find and return the length of the longest subset whose smallest missing value is M ; Initialize a set ; If array element is not equal to M ; Insert into set ; Increment frequency ; Stores minimum missing number ; Iterate to find the minimum missing integer ... | def findLengthOfMaxSubset ( arr , n , m ) : NEW_LINE INDENT s = [ ] ; NEW_LINE answer = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT tmp = arr [ i ] ; NEW_LINE if ( tmp != m ) : NEW_LINE INDENT s . append ( tmp ) ; NEW_LINE answer += 1 ; NEW_LINE DEDENT DEDENT min = 1 ; NEW_LINE while ( s . count ( min ) ) : NEW... |
Count of submatrix with sum X in a given Matrix | Size of a column ; Function to find the count of submatrix whose sum is X ; Copying arr to dp and making it indexed 1 ; Precalculate and store the sum of all rectangles with upper left corner at ( 0 , 0 ) ; ; Calculating sum in a 2d grid ; Stores the answer ; Minimum le... | m = 5 NEW_LINE def countSubsquare ( arr , n , X ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( m + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT dp [ i + 1 ] [ j + 1 ] = arr [ i ] [ j ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_L... |
Check if two arrays can be made equal by reversing any subarray once | Function to check whether two arrays can be made equal by reversing a sub - array only once ; Integer variable for storing the required starting and ending indices in the array ; Finding the smallest index for which A [ i ] != B [ i ] i . e the star... | def checkArray ( A , B , N ) : NEW_LINE INDENT start = 0 NEW_LINE end = N - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] ) : NEW_LINE INDENT start = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] ) : NEW_LINE INDENT end... |
Count of substrings having all distinct characters | Function to count total number of valid substrings ; Stores the count of substrings ; Stores the frequency of characters ; Initialised both pointers to beginning of the string ; If all characters in substring from index i to j are distinct ; Increment count of j - th... | def countSub ( Str ) : NEW_LINE INDENT n = len ( Str ) NEW_LINE ans = 0 NEW_LINE cnt = 26 * [ 0 ] NEW_LINE i , j = 0 , 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( j < n and ( cnt [ ord ( Str [ j ] ) - ord ( ' a ' ) ] == 0 ) ) : NEW_LINE INDENT cnt [ ord ( Str [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE ans += ( j - i... |
Find largest factor of N such that N / F is less than K | Function to find the largest factor of N which is less than or equal to K ; Initialise the variable to store the largest factor of N <= K ; Loop to find all factors of N ; Check if j is a factor of N or not ; Check if j <= K If yes , then store the larger value ... | def solve ( n , k ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( j * j > n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT if ( n % j == 0 ) : NEW_LINE INDENT if ( j <= k ) : NEW_LINE INDENT ans = max ( ans , j ) ; NEW_LINE DEDENT if ( n // j <= k ) : NEW_LINE INDENT ans = max ( ... |
Maximum sum subarray of size range [ L , R ] | Python3 program to find maximum sum subarray of size between L and R . ; Function to find maximum sum subarray of size between L and R ; Calculating prefix sum ; Maintain 0 for initial values of i upto R Once i = R , then we need to erase that 0 from our multiset as our fi... | import sys NEW_LINE def max_sum_subarray ( arr , L , R ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE pre = n * [ 0 ] NEW_LINE pre [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + arr [ i ] NEW_LINE DEDENT s1 = [ ] NEW_LINE s1 . append ( 0 ) NEW_LINE ans = - sys . maxsize ... |
Count of ways to select K consecutive empty cells from a given Matrix | Function to Traverse the matrix row wise ; Initialize ans ; Traverse row wise ; Initialize no of consecutive empty cells ; Check if blocked cell is encountered then reset countcons to 0 ; Check if empty cell is encountered , then increment countcon... | def rowWise ( v , n , m , k ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT countcons = 0 NEW_LINE for j in range ( m ) : NEW_LINE INDENT if ( v [ i ] [ j ] == '1' ) : NEW_LINE INDENT countcons = 0 NEW_LINE DEDENT else : NEW_LINE INDENT countcons += 1 NEW_LINE DEDENT if ( countcons >= k ) : ... |
Check if the count of inversions of two given types on an Array are equal or not | Python3 program to implement the above approach ; Function to check if the count of inversion of two types are same or not ; If maximum value is found to be greater than a [ j ] , then that pair of indices ( i , j ) will add extra value ... | import sys NEW_LINE def solve ( a , n ) : NEW_LINE INDENT mx = - sys . maxsize - 1 NEW_LINE for j in range ( 1 , n ) : NEW_LINE INDENT if ( mx > a [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT mx = max ( mx , a [ j - 1 ] ) NEW_LINE DEDENT return True NEW_LINE DEDENT a = [ 1 , 0 , 2 ] NEW_LINE n = len ( a ) NEW... |
How to validate an IP address using ReGex | Python3 program to validate IP address using Regex ; Function for Validating IP ; Regex expression for validating IPv4 ; Regex expression for validating IPv6 ; Checking if it is a valid IPv4 addresses ; Checking if it is a valid IPv6 addresses ; Return Invalid ; IP addresses ... | import re NEW_LINE def Validate_It ( IP ) : NEW_LINE INDENT regex = " ( ( [ 0-9 ] β [ 1-9 ] [ 0-9 ] β 1[0-9 ] [ 0-9 ] β " \ "2[0-4 ] [ 0-9 ] β 25[0-5 ] ) \\ . ) { 3 } " " ( [0-9 ] β [ 1-9 ] [ 0-9 ] β 1[0-9 ] [ 0-9 ] β " \ "2[0-4 ] [ 0-9 ] β 25[0-5 ] ) " NEW_LINE regex1 = " ( ( ( [0-9a - fA - F ] ) { 1,4 } ) \\ : ) { 7 ... |
Count of prime factors of N to be added at each step to convert N to M | Array to store shortest prime factor of every integer ; Function to precompute shortest prime factors ; Function to append distinct prime factors of every integer into a set ; Store distinct prime factors ; Function to return minimum steps using B... | spf = [ - 1 for i in range ( 100009 ) ] ; NEW_LINE def sieve ( ) : NEW_LINE INDENT i = 2 NEW_LINE while ( i * i <= 100006 ) : NEW_LINE INDENT for j in range ( i , 100006 , i ) : NEW_LINE INDENT if ( spf [ j ] == - 1 ) : NEW_LINE INDENT spf [ j ] = i ; NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def findPrimeFa... |
Count of elements which is product of a pair or an element square | Python3 program to implement the above approach ; Stores all factors a number ; Function to calculate and store in a vector ; Function to return the count of array elements which are a product of two array elements ; Copy elements into a a duplicate ar... | import math NEW_LINE v = [ [ ] for i in range ( 100000 ) ] NEW_LINE def div ( n ) : NEW_LINE INDENT global v NEW_LINE for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT v [ n ] . append ( i ) NEW_LINE DEDENT DEDENT DEDENT def prodof2elements ( arr , n ) : NEW_LINE... |
Largest subarray with frequency of all elements same | Function to find maximum subarray size ; Generating all subarray i -> starting index j -> end index ; Map 1 to hash frequency of all elements in subarray ; Map 2 to hash frequency of all frequencies of elements ; Finding previous frequency of arr [ j ] in map 1 ; I... | def max_subarray_size ( N , arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT map1 = { } NEW_LINE map2 = { } NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT if ( arr [ j ] not in map1 ) : NEW_LINE INDENT ele_count = 0 NEW_LINE DEDENT else : NEW_LINE INDENT ele_count = map1 [ arr [ j ] ... |
Longest substring consisting of vowels using Binary Search | Function to check if a character is vowel or not ; 0 - a 1 - b 2 - c and so on 25 - z ; Function to check if any substring of length k exists which contains only vowels ; Applying sliding window to get all substrings of length K ; Remove the occurence of ( i ... | def vowel ( vo ) : NEW_LINE INDENT if ( vo == 0 or vo == 4 or vo == 8 or vo == 14 or vo == 20 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def check ( s , k ) : NEW_LINE INDENT cnt = [ 0 ] * 26 NEW_LINE for i in range ( k - 1 ) : NEW_LINE INDENT cnt [ ord ( ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.