text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Find a valid parenthesis sequence of length K from a given valid parenthesis sequence | Function to find the subsequence of length K forming valid sequence ; Stores the resultant string ; Check whether character at index i is visited or not ; Traverse the string ; Push index of open bracket ; Pop and mark visited ; Increment count by 2 ; Append the characters and create the resultant string ; Return the resultant string ; Driver Code ; Function call | def findString ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = " " NEW_LINE st = [ ] NEW_LINE vis = [ False ] * n NEW_LINE count = 0 NEW_LINE List < bool > vis ( n , false ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT st . append ( i ) NEW_LINE DEDENT if ( count < k and s [ i ] == ' ) ' ) : NEW_LINE INDENT vis [ st [ - 1 ] ] = 1 NEW_LINE del st [ - 1 ] NEW_LINE vis [ i ] = True NEW_LINE count += 2 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( vis [ i ] == True ) : NEW_LINE INDENT ans += s [ i ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " ( ) ( ) ( ) " NEW_LINE K = 2 NEW_LINE print ( findString ( s , K ) ) NEW_LINE DEDENT |
Node having maximum number of nodes less than its value in its subtree | Stores the nodes to be deleted ; Structure of a Tree node ; Function to compare the current node key with keys received from it left & right tree by Post Order traversal ; Base Case ; Find nodes lesser than the current root in the left subtree ; Find nodes lesser than the current root in the right subtree ; Stores all the nodes less than the current node 's ; Add the nodes which are less than current node in left [ ] ; Add the nodes which are less than current node in right [ ] ; Create a combined vector for pass to it 's parent ; Stores key that has maximum nodes ; Return the vector of nodes ; Driver Code ; Given Tree ; Function Call ; Print the node value | max_v = 0 NEW_LINE rootIndex = 0 NEW_LINE mp = { } NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def findNodes ( root ) : NEW_LINE INDENT global max_v NEW_LINE global rootIndex NEW_LINE global mp NEW_LINE if ( root == None ) : NEW_LINE INDENT return [ ] NEW_LINE DEDENT left = findNodes ( root . left ) NEW_LINE right = findNodes ( root . right ) NEW_LINE combined = [ ] NEW_LINE count = 0 NEW_LINE for i in range ( len ( left ) ) : NEW_LINE INDENT if ( left [ i ] < root . key ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT combined . append ( left [ i ] ) NEW_LINE DEDENT for i in range ( len ( right ) ) : NEW_LINE INDENT if ( right [ i ] < root . key ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT combined . append ( right [ i ] ) NEW_LINE DEDENT combined . append ( root . key ) NEW_LINE if ( count > max_v ) : NEW_LINE INDENT rootIndex = root . key NEW_LINE max_v = count NEW_LINE DEDENT return combined NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = newNode ( 3 ) NEW_LINE root . left = newNode ( 4 ) NEW_LINE root . right = newNode ( 6 ) NEW_LINE root . right . left = newNode ( 4 ) NEW_LINE root . right . right = newNode ( 5 ) NEW_LINE root . left . left = newNode ( 10 ) NEW_LINE root . left . right = newNode ( 2 ) NEW_LINE max_v = 0 NEW_LINE rootIndex = - 1 NEW_LINE findNodes ( root ) NEW_LINE print ( rootIndex ) NEW_LINE DEDENT |
Maximum sum path in a matrix from top | Function to find the maximum sum path in the grid ; Dimensions of grid [ ] [ ] ; Stores maximum sum at each cell sum [ i ] [ j ] from cell sum [ 0 ] [ 0 ] ; Iterate to compute the maximum sum path in the grid ; Update the maximum path sum ; Return the maximum sum ; Driver Code | def MaximumPath ( grid ) : NEW_LINE INDENT N = len ( grid ) NEW_LINE M = len ( grid [ 0 ] ) NEW_LINE sum = [ [ 0 for i in range ( M + 1 ) ] for i in range ( N + 1 ) ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , M + 1 ) : NEW_LINE INDENT sum [ i ] [ j ] = ( max ( sum [ i - 1 ] [ j ] , sum [ i ] [ j - 1 ] ) + grid [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT return sum [ N ] [ M ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT grid = [ [ 1 , 2 ] , [ 3 , 5 ] ] NEW_LINE print ( MaximumPath ( grid ) ) NEW_LINE DEDENT |
Maximize cost of deletions to obtain string having no pair of similar adjacent characters | Function to find maximum cost to remove consecutive characters ; Initialize the count ; Maximum cost ; Traverse from 0 to len ( s ) - 2 ; If characters are identical ; Add cost [ i ] if its maximum ; Add cost [ i + 1 ] if its maximum ; Increment i ; Return the final max count ; Given string s ; Given cost of removal ; Function Call | def Maxcost ( s , cost ) : NEW_LINE INDENT count = 0 NEW_LINE maxcost = 0 NEW_LINE i = 0 NEW_LINE while i < len ( s ) - 1 : NEW_LINE INDENT if s [ i ] == s [ i + 1 ] : NEW_LINE INDENT if cost [ i ] > cost [ i + 1 ] : NEW_LINE INDENT maxcost += cost [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT maxcost += cost [ i + 1 ] NEW_LINE cost [ i + 1 ] = cost [ i ] NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return maxcost NEW_LINE DEDENT s = " abaac " NEW_LINE cost = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE print ( Maxcost ( s , cost ) ) NEW_LINE |
Maximum count of values of S modulo M lying in a range [ L , R ] after performing given operations on the array | Lookup table ; Function to count the value of S after adding arr [ i ] or arr [ i - 1 ] to the sum S at each time ; Base Case ; Store the mod value ; If the mod value lies in the range then return 1 ; Else return 0 ; Store the current state ; If already computed , return the computed value ; Recursively adding the elements to the sum adding ai value ; Adding arr [ i ] - 1 value ; Return the maximum count to check for root value as well ; Avoid counting idx = 0 as possible solution we are using idx != 0 ; Return the value of current state ; Driver Code | dp = { } NEW_LINE def countMagicNumbers ( idx , sum , a , n , m , l , r ) : NEW_LINE INDENT if ( idx == n ) : NEW_LINE INDENT temp = sum % m NEW_LINE if ( temp == l or temp == r or ( temp > l and temp < r ) ) : NEW_LINE INDENT dp [ ( idx , sum ) ] = 1 NEW_LINE return dp [ ( idx , sum ) ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ ( idx , sum ) ] = 0 NEW_LINE return dp [ ( idx , sum ) ] NEW_LINE DEDENT DEDENT curr = ( idx , sum ) NEW_LINE if ( curr in dp ) : NEW_LINE INDENT return dp [ curr ] NEW_LINE DEDENT ls = countMagicNumbers ( idx + 1 , sum + a [ idx ] , a , n , m , l , r ) NEW_LINE rs = countMagicNumbers ( idx + 1 , sum + ( a [ idx ] - 1 ) , a , n , m , l , r ) NEW_LINE temp1 = max ( ls , rs ) NEW_LINE temp = sum % m NEW_LINE if ( ( temp == l or temp == r or ( temp > l and temp < r ) ) and idx != 0 ) : NEW_LINE INDENT temp1 += 1 NEW_LINE DEDENT dp [ ( idx , sum ) ] = temp1 NEW_LINE return dp [ ( idx , sum ) ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE M = 22 NEW_LINE L = 14 NEW_LINE R = 16 NEW_LINE arr = [ 17 , 11 , 10 , 8 , 15 ] NEW_LINE print ( countMagicNumbers ( 0 , 0 , arr , N , M , L , R ) ) NEW_LINE DEDENT |
Check if a path exists for a cell valued 1 to reach the bottom right corner of a Matrix before any cell valued 2 | Python3 program for the above approach ; Function to check if cell with value 1 doesn 't reaches the bottom right cell or not ; Number of rows and columns ; Initialise the deque ; Traverse the matrix ; Push 1 to front of queue ; Push 2 to back of queue ; Store all the possible direction of the current cell ; Run multi - source BFS ; Get the front element ; If 1 reached corner first ; Insert new poin queue ; If 1 can 't reach the bottom right then return false ; Driver Code ; Given matrix ; Function call | from collections import deque NEW_LINE def reachesBottom ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( a [ 0 ] ) NEW_LINE q = deque ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( a [ i ] [ j ] == 1 ) : NEW_LINE INDENT q . appendleft ( [ i , j , 1 ] ) NEW_LINE DEDENT elif ( a [ i ] [ j ] == 2 ) : NEW_LINE INDENT q . append ( [ i , j , 2 ] ) NEW_LINE DEDENT a [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT dx = [ - 1 , 0 , 1 , 0 ] NEW_LINE dy = [ 0 , 1 , 0 , - 1 ] NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT front = q . popleft ( ) NEW_LINE i = front [ 0 ] NEW_LINE j = front [ 1 ] NEW_LINE t = front [ 2 ] NEW_LINE if ( a [ i ] [ j ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT a [ i ] [ j ] = 1 NEW_LINE if ( t == 1 and ( i == n - 1 and j == m - 1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT for d in range ( 4 ) : NEW_LINE INDENT ni = i + dx [ d ] NEW_LINE nj = j + dy [ d ] NEW_LINE if ( ni >= 0 and ni < n and nj >= 0 and nj < m ) : NEW_LINE INDENT q . append ( [ ni , nj , t ] ) NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT matrix = [ [ 0 , 2 , 0 ] , [ 0 , 1 , 0 ] , [ 0 , 2 , 0 ] ] NEW_LINE if ( reachesBottom ( matrix ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Smallest element from all square submatrices of size K from a given Matrix | Python3 program for the above approach ; Function to returns a smallest elements of all KxK submatrices of a given NxM matrix ; Stores the dimensions of the given matrix ; Stores the required smallest elements ; Update the smallest elements row - wise ; Update the minimum column - wise ; Store the final submatrix with required minimum values ; Return the resultant matrix ; Function call ; Print resultant matrix with the minimum values of KxK sub - matrix ; Given matrix ; Given K | import sys NEW_LINE def matrixMinimum ( nums , K ) : NEW_LINE INDENT N = len ( nums ) NEW_LINE M = len ( nums [ 0 ] ) NEW_LINE res = [ [ 0 for x in range ( M - K + 1 ) ] for y in range ( N - K + 1 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M - K + 1 ) : NEW_LINE INDENT mn = sys . maxsize NEW_LINE for k in range ( j , j + K ) : NEW_LINE INDENT mn = min ( mn , nums [ i ] [ k ] ) NEW_LINE DEDENT nums [ i ] [ j ] = mn NEW_LINE DEDENT DEDENT for j in range ( M ) : NEW_LINE INDENT for i in range ( N - K + 1 ) : NEW_LINE INDENT mn = sys . maxsize NEW_LINE for k in range ( i , i + K ) : NEW_LINE INDENT mn = min ( mn , nums [ k ] [ j ] ) NEW_LINE DEDENT nums [ i ] [ j ] = mn NEW_LINE DEDENT DEDENT for i in range ( N - K + 1 ) : NEW_LINE INDENT for j in range ( M - K + 1 ) : NEW_LINE INDENT res [ i ] [ j ] = nums [ i ] [ j ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def smallestinKsubmatrices ( arr , K ) : NEW_LINE INDENT res = matrixMinimum ( arr , K ) NEW_LINE for i in range ( len ( res ) ) : NEW_LINE INDENT for j in range ( len ( res [ 0 ] ) ) : NEW_LINE INDENT print ( res [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT arr = [ [ - 1 , 5 , 4 , 1 , - 3 ] , [ 4 , 3 , 1 , 1 , 6 ] , [ 2 , - 2 , 5 , 3 , 1 ] , [ 8 , 5 , 1 , 9 , - 4 ] , [ 12 , 3 , 5 , 8 , 1 ] ] NEW_LINE K = 3 NEW_LINE smallestinKsubmatrices ( arr , K ) NEW_LINE |
Queries to find Kth greatest character in a range [ L , R ] from a string with updates | Python3 Program to implement the above approach Function to find the kth greatest character from the string ; Sorting the in non - increasing Order ; Function to prthe K - th character from the subS [ l ] . . S [ r ] ; 0 - based indexing ; Subof strr from the indices l to r . ; Extract kth Largest character ; Function to replace character at pos of strr by the character s ; Index of S to be updated . ; Character to be replaced at index in S ; Driver Code ; Given string ; Count of queries ; Queries | def find_kth_largest ( strr , k ) : NEW_LINE INDENT strr = sorted ( strr ) NEW_LINE strr = strr [ : : - 1 ] NEW_LINE return strr [ k - 1 ] NEW_LINE DEDENT def printCharacter ( strr , l , r , k ) : NEW_LINE INDENT l = l - 1 NEW_LINE r = r - 1 NEW_LINE temp = strr [ l : r - l + 1 ] NEW_LINE ans = find_kth_largest ( temp , k ) NEW_LINE return ans NEW_LINE DEDENT def updateString ( strr , pos , s ) : NEW_LINE INDENT index = pos - 1 NEW_LINE c = s NEW_LINE strr [ index ] = c NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " abcddef " NEW_LINE strr = [ i for i in strr ] NEW_LINE Q = 3 NEW_LINE print ( printCharacter ( strr , 1 , 2 , 2 ) ) NEW_LINE updateString ( strr , 4 , ' g ' ) NEW_LINE print ( printCharacter ( strr , 1 , 5 , 4 ) ) NEW_LINE DEDENT |
Split array into two subarrays such that difference of their sum is minimum | Python3 program for the above approach ; Function to return minimum difference between sum of two subarrays ; To store total sum of array ; Calculate the total sum of the array ; Stores the prefix sum ; Stores the minimum difference ; Traverse the given array ; To store minimum difference ; Update minDiff ; Return minDiff ; Given array ; Length of the array | import sys NEW_LINE def minDiffSubArray ( arr , n ) : NEW_LINE INDENT total_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT total_sum += arr [ i ] NEW_LINE DEDENT prefix_sum = 0 NEW_LINE minDiff = sys . maxsize NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT prefix_sum += arr [ i ] NEW_LINE diff = abs ( ( total_sum - prefix_sum ) - prefix_sum ) NEW_LINE if ( diff < minDiff ) : NEW_LINE INDENT minDiff = diff NEW_LINE DEDENT DEDENT return minDiff NEW_LINE DEDENT arr = [ 7 , 9 , 5 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minDiffSubArray ( arr , n ) ) NEW_LINE |
Maximize count of non | Function to count the maximum number of subarrays with sum K ; Stores all the distinct prefixSums obtained ; Stores the prefix sum of the current subarray ; Stores the count of subarrays with sum K ; If a subarray with sum K is already found ; Increase count ; Reset prefix sum ; Clear the set ; Insert the prefix sum ; Driver Code | def CtSubarr ( arr , N , K ) : NEW_LINE INDENT st = set ( ) NEW_LINE prefixSum = 0 NEW_LINE st . add ( prefixSum ) NEW_LINE res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT prefixSum += arr [ i ] NEW_LINE if ( ( prefixSum - K ) in st ) : NEW_LINE INDENT res += 1 NEW_LINE prefixSum = 0 NEW_LINE st . clear ( ) NEW_LINE st . add ( 0 ) NEW_LINE DEDENT st . add ( prefixSum ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ - 2 , 6 , 6 , 3 , 5 , 4 , 1 , 2 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE K = 10 NEW_LINE print ( CtSubarr ( arr , N , K ) ) NEW_LINE |
Count of subarrays consisting of only prime numbers | Function to check if a number is prime or not . ; If n has any factor other than 1 , then n is non - prime . ; Function to return the count of subarrays made up of prime numbers only ; Stores the answer ; Stores the count of continuous prime numbers in an array ; If the current array element is prime ; Increase the count ; Update count of subarrays ; If the array ended with a continuous prime sequence ; Driver Code | def is_prime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i = 2 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def count_prime_subarrays ( ar , n ) : NEW_LINE INDENT ans = 0 NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( is_prime ( ar [ i ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( count ) : NEW_LINE INDENT ans += count * ( count + 1 ) // 2 NEW_LINE count = 0 NEW_LINE DEDENT DEDENT DEDENT if ( count ) : NEW_LINE INDENT ans += count * ( count + 1 ) // 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 10 NEW_LINE ar = [ 2 , 3 , 5 , 6 , 7 , 11 , 3 , 5 , 9 , 3 ] NEW_LINE print ( count_prime_subarrays ( ar , N ) ) NEW_LINE |
Minimum Subarray flips required to convert all elements of a Binary Array to K | Function to count the minimum number of subarray flips required ; Iterate the array ; If arr [ i ] and flag are equal ; Return the answer ; Driver Code | def minSteps ( arr , n , k ) : NEW_LINE INDENT cnt = 0 NEW_LINE if ( k == 1 ) : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == flag ) : NEW_LINE INDENT cnt += 1 NEW_LINE flag = ( flag + 1 ) % 2 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT arr = [ 1 , 0 , 1 , 0 , 0 , 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE k = 1 NEW_LINE print ( minSteps ( arr , n , k ) ) NEW_LINE |
Minimize Sum of an Array by at most K reductions | Function to obtain the minimum possible sum from the array by K reductions ; ; Insert elements into the MaxHeap ; Remove the maximum ; Insert maximum / 2 ; Stores the sum of remaining elements ; Driver code | def minSum ( a , n , k ) : NEW_LINE ' TABSYMBOL TABSYMBOL Implements β the β MaxHeap ' ' ' NEW_LINE INDENT q = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT q . append ( a [ i ] ) NEW_LINE DEDENT q = sorted ( q ) NEW_LINE while ( len ( q ) > 0 and k > 0 ) : NEW_LINE INDENT top = q [ - 1 ] // 2 NEW_LINE del q [ - 1 ] NEW_LINE q . append ( top ) NEW_LINE k -= 1 NEW_LINE q = sorted ( q ) NEW_LINE DEDENT sum = 0 NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT sum += q [ - 1 ] NEW_LINE del q [ - 1 ] NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE k = 3 NEW_LINE a = [ 20 , 7 , 5 , 4 ] NEW_LINE print ( minSum ( a , n , k ) ) NEW_LINE DEDENT |
Sum of indices of Characters removed to obtain an Empty String based on given conditions | Python3 program to implement the above approach ; Function to add index of the deleted character ; If index is beyond the range ; Insert the index of the deleted characeter ; Search over the subtrees to find the desired index ; Function to return count of deleted indices which are to the left of the current index ; Function to generate the sum of indices ; Stores the original index of the characters in sorted order of key ; Traverse the map ; Extract smallest index of smallest character ; Delete the character from the map if it has no remaining occurrence ; Stores the original index ; Count of elements removed to the left of current character ; Current index of the current character ; For 1 - based indexing ; Insert the deleted index in the segment tree ; Final answer ; Driver Code | import math , collections NEW_LINE def add_seg ( seg , start , end , current , index ) : NEW_LINE INDENT if ( index > end or index < start ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( start == end ) : NEW_LINE INDENT seg [ current ] = 1 NEW_LINE return NEW_LINE DEDENT mid = int ( ( start + end ) / 2 ) NEW_LINE add_seg ( seg , start , mid , 2 * current + 1 , index ) NEW_LINE add_seg ( seg , mid + 1 , end , 2 * current + 2 , index ) NEW_LINE seg [ current ] = seg [ 2 * current + 1 ] + seg [ 2 * current + 2 ] NEW_LINE DEDENT def deleted ( seg , l , r , start , end , current ) : NEW_LINE INDENT if ( end < l or start > r ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( start >= l and end <= r ) : NEW_LINE INDENT return seg [ current ] NEW_LINE DEDENT mid = int ( ( start + end ) / 2 ) NEW_LINE return deleted ( seg , l , r , start , mid , 2 * current + 1 ) + deleted ( seg , l , r , mid + 1 , end , 2 * current + 2 ) NEW_LINE DEDENT def sumOfIndices ( s ) : NEW_LINE INDENT N = len ( s ) NEW_LINE x = ( int ) ( math . ceil ( math . log ( N ) / math . log ( 2 ) ) ) NEW_LINE seg_size = 2 * pow ( 2 , x ) - 1 NEW_LINE segment = [ 0 ] * ( seg_size ) NEW_LINE count = 4 NEW_LINE fre = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT key = ( ord ) ( s [ i ] ) NEW_LINE if key in fre : NEW_LINE INDENT que = fre [ key ] NEW_LINE DEDENT else : NEW_LINE INDENT que = collections . deque ( [ ] ) NEW_LINE DEDENT que . append ( i ) NEW_LINE fre [ key ] = que NEW_LINE DEDENT while len ( fre ) > 0 : NEW_LINE INDENT it = list ( fre . keys ( ) ) [ 0 ] NEW_LINE if len ( fre [ it ] ) == 0 : NEW_LINE INDENT del fre [ it ] NEW_LINE DEDENT else : NEW_LINE INDENT que = fre [ it ] NEW_LINE original_index = que [ 0 ] NEW_LINE curr_index = deleted ( segment , 0 , original_index - 1 , 0 , N - 1 , 0 ) NEW_LINE new_index = original_index - curr_index NEW_LINE count += new_index + 1 NEW_LINE add_seg ( segment , 0 , N - 1 , 0 , original_index ) NEW_LINE que . popleft ( ) NEW_LINE fre [ it ] = que NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE sumOfIndices ( s ) NEW_LINE |
Maximum Length of Sequence of Sums of prime factors generated by the given operations | Python3 program to implement the above approach ; Smallest prime factor array ; Stores if a number is prime or not ; Function to compute all primes using Sieve of Eratosthenes ; Function for finding smallest prime factors for every integer ; Function to find the sum of prime factors of number ; Add smallest prime factor to the sum ; Reduce N ; Return the answer ; Function to return the length of sequence of for the given number ; If the number is prime ; If a previously computed subproblem occurred ; Calculate the sum of prime factors ; Function to return the maximum length of sequence for the given range ; Pre - calculate primes ; Precalculate smallest prime factors ; Iterate over the range ; Update maximum length ; Driver Code | import sys NEW_LINE spf = [ 0 ] * 100005 NEW_LINE prime = [ False ] * 100005 NEW_LINE dp = [ 0 ] * 100005 NEW_LINE def sieve ( ) : NEW_LINE INDENT for i in range ( 2 , 100005 ) : NEW_LINE INDENT prime [ i ] = True NEW_LINE DEDENT i = 2 NEW_LINE while i * i < 100005 : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , 100005 , i ) : NEW_LINE INDENT prime [ j ] = False NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def smallestPrimeFactors ( ) : NEW_LINE INDENT for i in range ( 10005 ) : NEW_LINE INDENT spf [ i ] = - 1 NEW_LINE DEDENT i = 2 NEW_LINE while i * i < 100005 : NEW_LINE INDENT for j in range ( i , 100005 , 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 sumOfPrimeFactors ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( n > 1 ) : NEW_LINE INDENT ans += spf [ n ] NEW_LINE n //= spf [ n ] NEW_LINE DEDENT return ans NEW_LINE DEDENT def findLength ( n ) : NEW_LINE INDENT if ( prime [ n ] ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ n ] ) : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT sum = sumOfPrimeFactors ( n ) NEW_LINE dp [ n ] = 1 + findLength ( sum ) NEW_LINE return dp [ n ] NEW_LINE DEDENT def maxLength ( n , m ) : NEW_LINE INDENT sieve ( ) NEW_LINE smallestPrimeFactors ( ) NEW_LINE ans = - sys . maxsize - 1 NEW_LINE for i in range ( n , m + 1 ) : NEW_LINE INDENT if ( i == 4 ) : NEW_LINE INDENT continue NEW_LINE DEDENT ans = max ( ans , findLength ( i ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 2 NEW_LINE m = 14 NEW_LINE print ( maxLength ( n , m ) ) NEW_LINE |
Longest Subarray consisting of unique elements from an Array | Python3 program to implement the above approach ; Function to find largest subarray with no duplicates ; Stores index of array elements ; Update j based on previous occurrence of a [ i ] ; Update ans to store maximum length of subarray ; Store the index of current occurrence of a [ i ] ; Return final ans ; Driver Code | from collections import defaultdict NEW_LINE def largest_subarray ( a , n ) : NEW_LINE INDENT index = defaultdict ( lambda : 0 ) NEW_LINE ans = 0 NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = max ( index [ a [ i ] ] , j ) NEW_LINE ans = max ( ans , i - j + 1 ) NEW_LINE index [ a [ i ] ] = i + 1 NEW_LINE i += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( largest_subarray ( arr , n ) ) NEW_LINE |
Count of Ways to obtain given Sum from the given Array elements | Function to count the number of ways ; Base Case : Reached the end of the array ; Sum is equal to the required sum ; Recursively check if required sum can be obtained by adding current element or by subtracting the current index element ; Function to call dfs ( ) to calculate the number of ways ; Driver Code | def dfs ( nums , S , curr_sum , index ) : NEW_LINE INDENT if ( index == len ( nums ) ) : NEW_LINE INDENT if ( S == curr_sum ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT return ( dfs ( nums , S , curr_sum + nums [ index ] , index + 1 ) + dfs ( nums , S , curr_sum - nums [ index ] , index + 1 ) ) ; NEW_LINE DEDENT def findWays ( nums , S ) : NEW_LINE INDENT return dfs ( nums , S , 0 , 0 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = 3 ; NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE answer = findWays ( arr , S ) ; NEW_LINE print ( answer ) ; NEW_LINE DEDENT |
Check if all the Nodes in a Binary Tree having common values are at least D distance apart | Function to create a new node ; Function to count the frequency of node value present in the tree ; Function that returns the max distance between the nodes that have the same key ; If right and left subtree did not have node whose key is value ; Check if the current node is equal to value ; If the left subtree has no node whose key is equal to value ; If the right subtree has no node whose key is equal to value ; Function that finds if the distance between any same nodes is at most K ; Create the mp to look for same value of nodes ; Counting the frequency of nodes ; If the returned value of distance is exceeds dist ; Print the result ; Driver Code | mp = { } NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def frequencyCounts ( root ) : NEW_LINE INDENT global mp NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT mp [ root . key ] = mp . get ( root . key , 0 ) + 1 NEW_LINE frequencyCounts ( root . left ) NEW_LINE frequencyCounts ( root . right ) NEW_LINE DEDENT def computeDistance ( root , value ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT left = computeDistance ( root . left , value ) NEW_LINE right = computeDistance ( root . right , value ) NEW_LINE if ( left == - 1 and right == - 1 ) : NEW_LINE INDENT if ( root . key == value ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if ( left == - 1 ) : NEW_LINE INDENT return right + 1 NEW_LINE DEDENT if ( right == - 1 ) : NEW_LINE INDENT return left + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 + max ( left , right ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def solve ( root , dist ) : NEW_LINE INDENT global mp NEW_LINE frequencyCounts ( root ) NEW_LINE flag = 0 NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT if ( value > 1 ) : NEW_LINE INDENT result = computeDistance ( root , key ) NEW_LINE if ( result > dist or result == - 1 ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if flag == 0 : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 3 ) NEW_LINE root . right . right = newNode ( 4 ) NEW_LINE root . right . left = newNode ( 4 ) NEW_LINE dist = 7 NEW_LINE solve ( root , dist ) NEW_LINE DEDENT |
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 ; Iterate over the array ; Initialize the min value ; Iterate from i + k to N ; Find the minimum ; Update the minimum sum ; Prthe answer ; Driver Code | import sys NEW_LINE def findMinSum ( A , K ) : NEW_LINE INDENT n = len ( A ) ; NEW_LINE minimum_sum = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT minimum = sys . maxsize ; NEW_LINE for j in range ( i + K , n , 1 ) : NEW_LINE INDENT minimum = min ( minimum , A [ j ] ) ; NEW_LINE DEDENT if ( minimum == sys . maxsize ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT minimum_sum = min ( minimum_sum , A [ i ] + minimum ) ; NEW_LINE DEDENT print ( minimum_sum ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 4 , 2 , 5 , 4 , 3 , 2 , 5 ] ; NEW_LINE K = 3 ; NEW_LINE findMinSum ( A , K ) ; NEW_LINE DEDENT |
Absolute distinct count in a Linked List | Node of the singly linked list ; Function to insert a node at the beginning of the singly Linked List ; Allocate node ; Insert data ; Point to the head ; Make the new Node the new head ; Function to return the count of distinct absolute values in the linked list ; Create the Head ; Insert nodes | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = next NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( 0 ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT def distinctCount ( head_ref1 ) : NEW_LINE INDENT s = set ( ) NEW_LINE ptr1 = head_ref1 NEW_LINE while ( ptr1 != None ) : NEW_LINE INDENT s . add ( abs ( ptr1 . data ) ) NEW_LINE ptr1 = ptr1 . next NEW_LINE DEDENT return len ( s ) NEW_LINE DEDENT head1 = None NEW_LINE head1 = push ( head1 , - 1 ) NEW_LINE head1 = push ( head1 , - 2 ) NEW_LINE head1 = push ( head1 , 0 ) NEW_LINE head1 = push ( head1 , 4 ) NEW_LINE head1 = push ( head1 , 5 ) NEW_LINE head1 = push ( head1 , 8 ) NEW_LINE ans = distinctCount ( head1 ) NEW_LINE print ( ans ) NEW_LINE |
Minimum Cost Maximum Flow from a Graph using Bellman Ford Algorithm | Python3 program to implement the above approach ; Stores the found edges ; Stores the number of nodes ; Stores the capacity of each edge ; Stores the cost per unit flow of each edge ; Stores the distance from each node and picked edges for each node ; Function to check if it is possible to have a flow from the src to sink ; Initialise found [ ] to false ; Initialise the dist [ ] to INF ; Distance from the source node ; Iterate untill src reaches N ; If already found ; Evaluate while flow is still in supply ; Obtain the total value ; If dist [ k ] is > minimum value ; Update ; If dist [ k ] is > minimum value ; Update ; Update src to best for next iteration ; Return the value obtained at sink ; Function to obtain the maximum Flow ; If a path exist from src to sink ; Set the default amount ; Return pair total cost and sink ; Driver Code ; Creating an object flow | from sys import maxsize NEW_LINE from typing import List NEW_LINE found = [ ] NEW_LINE N = 0 NEW_LINE cap = [ ] NEW_LINE flow = [ ] NEW_LINE cost = [ ] NEW_LINE dad = [ ] NEW_LINE dist = [ ] NEW_LINE pi = [ ] NEW_LINE INF = maxsize // 2 - 1 NEW_LINE def search ( src : int , sink : int ) -> bool : NEW_LINE INDENT found = [ False for _ in range ( N ) ] NEW_LINE dist = [ INF for _ in range ( N + 1 ) ] NEW_LINE dist [ src ] = 0 NEW_LINE while ( src != N ) : NEW_LINE INDENT best = N NEW_LINE found [ src ] = True NEW_LINE for k in range ( N ) : NEW_LINE INDENT if ( found [ k ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( flow [ k ] [ src ] != 0 ) : NEW_LINE INDENT val = ( dist [ src ] + pi [ src ] - pi [ k ] - cost [ k ] [ src ] ) NEW_LINE if ( dist [ k ] > val ) : NEW_LINE INDENT dist [ k ] = val NEW_LINE dad [ k ] = src NEW_LINE DEDENT DEDENT if ( flow [ src ] [ k ] < cap [ src ] [ k ] ) : NEW_LINE INDENT val = ( dist [ src ] + pi [ src ] - pi [ k ] + cost [ src ] [ k ] ) NEW_LINE if ( dist [ k ] > val ) : NEW_LINE INDENT dist [ k ] = val NEW_LINE dad [ k ] = src NEW_LINE DEDENT DEDENT if ( dist [ k ] < dist [ best ] ) : NEW_LINE INDENT best = k NEW_LINE DEDENT DEDENT src = best NEW_LINE DEDENT for k in range ( N ) : NEW_LINE INDENT pi [ k ] = min ( pi [ k ] + dist [ k ] , INF ) NEW_LINE DEDENT return found [ sink ] NEW_LINE DEDENT def getMaxFlow ( capi : List [ List [ int ] ] , costi : List [ List [ int ] ] , src : int , sink : int ) -> List [ int ] : NEW_LINE INDENT global cap , cost , found , dist , pi , N , flow , dad NEW_LINE cap = capi NEW_LINE cost = costi NEW_LINE N = len ( capi ) NEW_LINE found = [ False for _ in range ( N ) ] NEW_LINE flow = [ [ 0 for _ in range ( N ) ] for _ in range ( N ) ] NEW_LINE dist = [ INF for _ in range ( N + 1 ) ] NEW_LINE dad = [ 0 for _ in range ( N ) ] NEW_LINE pi = [ 0 for _ in range ( N ) ] NEW_LINE totflow = 0 NEW_LINE totcost = 0 NEW_LINE while ( search ( src , sink ) ) : NEW_LINE INDENT amt = INF NEW_LINE x = sink NEW_LINE while x != src : NEW_LINE INDENT amt = min ( amt , flow [ x ] [ dad [ x ] ] if ( flow [ x ] [ dad [ x ] ] != 0 ) else cap [ dad [ x ] ] [ x ] - flow [ dad [ x ] ] [ x ] ) NEW_LINE x = dad [ x ] NEW_LINE DEDENT x = sink NEW_LINE while x != src : NEW_LINE INDENT if ( flow [ x ] [ dad [ x ] ] != 0 ) : NEW_LINE INDENT flow [ x ] [ dad [ x ] ] -= amt NEW_LINE totcost -= amt * cost [ x ] [ dad [ x ] ] NEW_LINE DEDENT else : NEW_LINE INDENT flow [ dad [ x ] ] [ x ] += amt NEW_LINE totcost += amt * cost [ dad [ x ] ] [ x ] NEW_LINE DEDENT x = dad [ x ] NEW_LINE DEDENT totflow += amt NEW_LINE DEDENT return [ totflow , totcost ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = 0 NEW_LINE t = 4 NEW_LINE cap = [ [ 0 , 3 , 1 , 0 , 3 ] , [ 0 , 0 , 2 , 0 , 0 ] , [ 0 , 0 , 0 , 1 , 6 ] , [ 0 , 0 , 0 , 0 , 2 ] , [ 0 , 0 , 0 , 0 , 0 ] ] NEW_LINE cost = [ [ 0 , 1 , 0 , 0 , 2 ] , [ 0 , 0 , 0 , 3 , 0 ] , [ 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 1 ] , [ 0 , 0 , 0 , 0 , 0 ] ] NEW_LINE ret = getMaxFlow ( cap , cost , s , t ) NEW_LINE print ( " { } β { } " . format ( ret [ 0 ] , ret [ 1 ] ) ) NEW_LINE DEDENT |
Count of all possible pairs having sum of LCM and GCD equal to N | Recursive function to return gcd of a and b ; Function to calculate and return LCM of two numbers ; Function to count pairs whose sum of GCD and LCM is equal to N ; 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 lcm ( a , b ) : NEW_LINE INDENT return ( a * b ) // __gcd ( a , b ) NEW_LINE DEDENT def countPair ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( __gcd ( i , j ) + lcm ( i , j ) == N ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 14 NEW_LINE print ( countPair ( N ) ) NEW_LINE DEDENT |
Minimize cost to color all the vertices of an Undirected Graph using given operation | Python3 program to find the minimum cost to color all vertices of an Undirected Graph ; Function to add edge in the given graph ; Function to perform DFS traversal and find the node with minimum cost ; Update the minimum cost ; Recur for all connected nodes ; Function to calculate and return the minimum cost of coloring all vertices of the Undirected Graph ; Marks if a vertex is visited or not ; Perform DFS traversal ; If vertex is not visited ; Update minimum cost ; Return the final cost ; Driver Code | import sys NEW_LINE MAX = 10 NEW_LINE adj = [ [ ] for i in range ( MAX ) ] NEW_LINE def addEdge ( u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def dfs ( v , cost , vis , min_cost_node ) : NEW_LINE INDENT vis [ v ] = True NEW_LINE min_cost_node = min ( min_cost_node , cost [ v - 1 ] ) NEW_LINE for i in range ( len ( adj [ v ] ) ) : NEW_LINE INDENT if ( vis [ adj [ v ] [ i ] ] == False ) : NEW_LINE INDENT min_cost_node = dfs ( adj [ v ] [ i ] , cost , vis , min_cost_node ) NEW_LINE DEDENT DEDENT return min_cost_node NEW_LINE DEDENT def minimumCost ( V , cost ) : NEW_LINE INDENT vis = [ False for i in range ( V + 1 ) ] NEW_LINE min_cost = 0 NEW_LINE for i in range ( 1 , V + 1 ) : NEW_LINE INDENT if ( not vis [ i ] ) : NEW_LINE INDENT min_cost_node = sys . maxsize NEW_LINE min_cost_node = dfs ( i , cost , vis , min_cost_node ) NEW_LINE min_cost += min_cost_node NEW_LINE DEDENT DEDENT return min_cost NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT V = 6 NEW_LINE E = 5 NEW_LINE cost = [ 12 , 25 , 8 , 11 , 10 , 7 ] NEW_LINE addEdge ( 1 , 2 ) NEW_LINE addEdge ( 1 , 3 ) NEW_LINE addEdge ( 3 , 2 ) NEW_LINE addEdge ( 2 , 5 ) NEW_LINE addEdge ( 4 , 6 ) NEW_LINE min_cost = minimumCost ( V , cost ) NEW_LINE print ( min_cost ) NEW_LINE DEDENT |
Maximize count of set bits in a root to leaf path in a binary tree | Python3 program to implement the above approach ; Node class ; Initialise constructor ; Function to count the number of 1 in number ; Function to find the maximum count of setbits in a root to leaf ; Check if root is null ; Update the maximum count of setbits ; Traverse left of binary tree ; Traverse right of the binary tree ; Driver code | maxm = 0 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . val = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def count_1 ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def maxm_setbits ( root , ans ) : NEW_LINE INDENT global maxm NEW_LINE if not root : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT ans += count_1 ( root . val ) NEW_LINE maxm = max ( ans , maxm ) NEW_LINE return NEW_LINE DEDENT maxm_setbits ( root . left , ans + count_1 ( root . val ) ) NEW_LINE maxm_setbits ( root . right , ans + count_1 ( root . val ) ) NEW_LINE DEDENT root = Node ( 15 ) NEW_LINE root . left = Node ( 3 ) NEW_LINE root . right = Node ( 7 ) NEW_LINE root . left . left = Node ( 5 ) NEW_LINE root . left . right = Node ( 1 ) NEW_LINE root . right . left = Node ( 31 ) NEW_LINE root . right . right = Node ( 9 ) NEW_LINE maxm_setbits ( root , 0 ) NEW_LINE print ( maxm ) NEW_LINE |
Minimize count of divisions by D to obtain at least K equal array elements | Function to return minimum number of moves required ; Stores the number of moves required to obtain respective values from the given array ; Traverse the array ; Insert 0 into V [ a [ i ] ] as it is the initial state ; Insert the moves required to obtain current a [ i ] ; Traverse v [ ] to obtain minimum count of moves ; Check if there are at least K equal elements for v [ i ] ; Add the sum of minimum K moves ; Update answer ; Return the final answer ; Driver Code | def getMinimumMoves ( n , k , d , a ) : NEW_LINE INDENT MAX = 100000 NEW_LINE v = [ ] NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT v . append ( [ ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE v [ a [ i ] ] += [ 0 ] NEW_LINE while ( a [ i ] > 0 ) : NEW_LINE INDENT a [ i ] //= d NEW_LINE cnt += 1 NEW_LINE v [ a [ i ] ] += [ cnt ] NEW_LINE DEDENT DEDENT ans = float ( ' inf ' ) NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( len ( v [ i ] ) >= k ) : NEW_LINE INDENT move = 0 NEW_LINE v [ i ] . sort ( ) NEW_LINE for j in range ( k ) : NEW_LINE INDENT move += v [ i ] [ j ] NEW_LINE DEDENT ans = min ( ans , move ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 3 NEW_LINE D = 2 NEW_LINE A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE print ( getMinimumMoves ( N , K , D , A ) ) NEW_LINE DEDENT |
Longest subarray with odd product | Function to return length of longest subarray with odd product ; If even element is encountered ; Update maximum ; Driver code | def Maxlen ( a , n ) : NEW_LINE INDENT ans = 0 NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] % 2 == 0 : NEW_LINE INDENT count = 0 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT ans = max ( ans , count ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 7 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( Maxlen ( arr , n ) ) NEW_LINE |
Min difference between maximum and minimum element in all Y size subarrays | Function to get the maximum of all the subarrays of size Y ; ith index of maxarr array will be the index upto which Arr [ i ] is maximum ; Stack is used to find the next larger element and keeps track of index of current iteration ; Loop for remaining indexes ; j < i used to keep track whether jth element is inside or outside the window ; Return submax ; Function to get the minimum for all subarrays of size Y ; ith index of minarr array will be the index upto which Arr [ i ] is minimum ; Stack is used to find the next smaller element and keeping track of index of current iteration ; Loop for remaining indexes ; j < i used to keep track whether jth element is inside or outside the window ; Return submin ; Function to get minimum difference ; Create submin and submax arrays ; Store initial difference ; Calculate temporary difference ; Final minimum difference ; Given array arr [ ] ; Given subarray size ; Function call | def get_submaxarr ( arr , n , y ) : NEW_LINE INDENT j = 0 NEW_LINE stk = [ ] NEW_LINE maxarr = [ 0 ] * n NEW_LINE stk . append ( 0 ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT while ( len ( stk ) > 0 and arr [ i ] > arr [ stk [ - 1 ] ] ) : NEW_LINE INDENT maxarr [ stk [ - 1 ] ] = i - 1 NEW_LINE stk . pop ( ) NEW_LINE DEDENT stk . append ( i ) NEW_LINE DEDENT while ( stk ) : NEW_LINE INDENT maxarr [ stk [ - 1 ] ] = n - 1 NEW_LINE stk . pop ( ) NEW_LINE DEDENT submax = [ ] NEW_LINE for i in range ( n - y + 1 ) : NEW_LINE INDENT while ( maxarr [ j ] < i + y - 1 or j < i ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT submax . append ( arr [ j ] ) NEW_LINE DEDENT return submax NEW_LINE DEDENT def get_subminarr ( arr , n , y ) : NEW_LINE INDENT j = 0 NEW_LINE stk = [ ] NEW_LINE minarr = [ 0 ] * n NEW_LINE stk . append ( 0 ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT while ( stk and arr [ i ] < arr [ stk [ - 1 ] ] ) : NEW_LINE INDENT minarr [ stk [ - 1 ] ] = i NEW_LINE stk . pop ( ) NEW_LINE DEDENT stk . append ( i ) NEW_LINE DEDENT while ( stk ) : NEW_LINE INDENT minarr [ stk [ - 1 ] ] = n NEW_LINE stk . pop ( ) NEW_LINE DEDENT submin = [ ] NEW_LINE for i in range ( n - y + 1 ) : NEW_LINE INDENT while ( minarr [ j ] <= i + y - 1 or j < i ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT submin . append ( arr [ j ] ) NEW_LINE DEDENT return submin NEW_LINE DEDENT def getMinDifference ( Arr , N , Y ) : NEW_LINE INDENT submin = get_subminarr ( Arr , N , Y ) NEW_LINE submax = get_submaxarr ( Arr , N , Y ) NEW_LINE minn = submax [ 0 ] - submin [ 0 ] NEW_LINE b = len ( submax ) NEW_LINE for i in range ( 1 , b ) : NEW_LINE INDENT diff = submax [ i ] - submin [ i ] NEW_LINE minn = min ( minn , diff ) NEW_LINE DEDENT print ( minn ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 3 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE Y = 4 NEW_LINE getMinDifference ( arr , N , Y ) NEW_LINE |
Least root of given quadratic equation for value greater than equal to K | Python3 program for the above approach ; Function to calculate value of quadratic equation for some x ; Function to calculate the minimum value of x such that F ( x ) >= K using binary search ; Start and end value for binary search ; Binary Search ; Computing F ( mid ) and F ( mid - 1 ) ; If F ( mid ) >= K and F ( mid - 1 ) < K return mid ; If F ( mid ) < K go to mid + 1 to end ; If F ( mid ) > K go to start to mid - 1 ; If no such value exist ; Given coefficients of Equations ; Find minimum value of x | import math NEW_LINE def func ( A , B , C , x ) : NEW_LINE INDENT return ( A * x * x + B * x + C ) NEW_LINE DEDENT def findMinx ( A , B , C , K ) : NEW_LINE INDENT start = 1 NEW_LINE end = math . ceil ( math . sqrt ( K ) ) NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = start + ( end - start ) // 2 NEW_LINE x = func ( A , B , C , mid ) NEW_LINE Y = func ( A , B , C , mid - 1 ) NEW_LINE if ( x >= K and Y < K ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( x < K ) : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT A = 3 NEW_LINE B = 4 NEW_LINE C = 5 NEW_LINE K = 6 NEW_LINE print ( findMinx ( A , B , C , K ) ) NEW_LINE |
Find the node at the center of an N | To create tree ; Function to store the path from given vertex to the target vertex in a vector path ; If the target node is found , push it into path vector ; To prevent visiting a node already visited ; Recursive call to the neighbours of current node inorder to get the path ; Function to obtain and return the farthest node from a given vertex ; If the current height is maximum so far , then save the current node ; Iterate over all the neighbours of current node ; This is to prevent visiting a already visited node ; Next call will be at 1 height higher than our current height ; Function to add edges ; Reset to - 1 ; Reset to - 1 ; Stores one end of the diameter ; Reset the maxHeight ; Stores the second end of the diameter ; Store the diameter into the vector path ; Diameter is equal to the path between the two farthest nodes leaf1 and leaf2 ; Driver code | tree = { } NEW_LINE path = [ ] NEW_LINE maxHeight , maxHeightNode = - 1 , - 1 NEW_LINE def getDiameterPath ( vertex , targetVertex , parent , path ) : NEW_LINE INDENT if ( vertex == targetVertex ) : NEW_LINE INDENT path . append ( vertex ) NEW_LINE return True NEW_LINE DEDENT for i in range ( len ( tree [ vertex ] ) ) : NEW_LINE INDENT if ( tree [ vertex ] [ i ] == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( getDiameterPath ( tree [ vertex ] [ i ] , targetVertex , vertex , path ) ) : NEW_LINE INDENT path . append ( vertex ) NEW_LINE return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def farthestNode ( vertex , parent , height ) : NEW_LINE INDENT global maxHeight , maxHeightNode NEW_LINE if ( height > maxHeight ) : NEW_LINE INDENT maxHeight = height NEW_LINE maxHeightNode = vertex NEW_LINE DEDENT if ( vertex in tree ) : NEW_LINE INDENT for i in range ( len ( tree [ vertex ] ) ) : NEW_LINE INDENT if ( tree [ vertex ] [ i ] == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT farthestNode ( tree [ vertex ] [ i ] , vertex , height + 1 ) NEW_LINE DEDENT DEDENT DEDENT def addedge ( a , b ) : NEW_LINE INDENT if ( a not in tree ) : NEW_LINE INDENT tree [ a ] = [ ] NEW_LINE DEDENT tree [ a ] . append ( b ) NEW_LINE if ( b not in tree ) : NEW_LINE INDENT tree [ b ] = [ ] NEW_LINE DEDENT tree [ b ] . append ( a ) NEW_LINE DEDENT def FindCenter ( n ) : NEW_LINE INDENT maxHeight = - 1 NEW_LINE maxHeightNode = - 1 NEW_LINE farthestNode ( 0 , - 1 , 0 ) NEW_LINE leaf1 = maxHeightNode NEW_LINE maxHeight = - 1 NEW_LINE farthestNode ( maxHeightNode , - 1 , 0 ) NEW_LINE leaf2 = maxHeightNode NEW_LINE path = [ ] NEW_LINE getDiameterPath ( leaf1 , leaf2 , - 1 , path ) NEW_LINE pathSize = len ( path ) NEW_LINE if ( pathSize % 2 == 1 ) : NEW_LINE INDENT print ( path [ int ( pathSize / 2 ) ] * - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( path [ int ( pathSize / 2 ) ] , " , β " , path [ int ( ( pathSize - 1 ) / 2 ) ] , sep = " " , end = " " ) NEW_LINE DEDENT DEDENT N = 4 NEW_LINE tree = { } NEW_LINE addedge ( 1 , 0 ) NEW_LINE addedge ( 1 , 2 ) NEW_LINE addedge ( 1 , 3 ) NEW_LINE FindCenter ( N ) NEW_LINE |
K | Python3 program to find k - th term of N merged Arithmetic Progressions ; Function to count and return the number of values less than equal to N present in the set ; Check whether j - th bit is set bit or not ; Function to implement Binary Search to find K - th element ; Find middle index of the array ; Search in the left half ; Search in the right half ; If exactly K elements are present ; Driver Code | maxm = 1000000000 NEW_LINE def count ( v , n ) : NEW_LINE INDENT odd , even = 0 , 0 NEW_LINE t = 1 << len ( v ) NEW_LINE size = len ( v ) NEW_LINE for i in range ( 1 , t ) : NEW_LINE INDENT d , count = 1 , 0 NEW_LINE for j in range ( 0 , size ) : NEW_LINE INDENT if ( i & ( 1 << j ) ) : NEW_LINE INDENT d *= v [ j ] NEW_LINE count += 1 NEW_LINE DEDENT DEDENT if ( count & 1 ) : NEW_LINE INDENT odd += n // d NEW_LINE DEDENT else : NEW_LINE INDENT even += n // d NEW_LINE DEDENT DEDENT return ( odd - even ) NEW_LINE DEDENT def BinarySearch ( l , r , v , key ) : NEW_LINE INDENT while ( r - l > 1 ) : NEW_LINE INDENT mid = ( l + r ) // 2 NEW_LINE if ( key <= count ( v , mid ) ) : NEW_LINE INDENT r = mid NEW_LINE DEDENT else : NEW_LINE INDENT l = mid NEW_LINE DEDENT DEDENT if ( key == count ( v , l ) ) : NEW_LINE INDENT return l NEW_LINE DEDENT else : NEW_LINE INDENT return r NEW_LINE DEDENT DEDENT N , K = 2 , 10 NEW_LINE v = [ 2 , 3 ] NEW_LINE print ( BinarySearch ( 1 , maxm , v , K ) ) NEW_LINE |
Find integral points with minimum distance from given set of integers using BFS | Function to find points at minimum distance ; Hash to store points that are encountered ; Queue to store initial set of points ; Vector to store integral points ; Using bfs to visit nearest points from already visited points ; Get first element from queue ; Check if ( x - 1 ) is not encountered so far ; Update hash with this new element ; Insert ( x - 1 ) into queue ; Push ( x - 1 ) as new element ; Decrement counter by 1 ; Check if ( x + 1 ) is not encountered so far ; Update hash with this new element ; Insert ( x + 1 ) into queue ; Push ( x + 1 ) as new element ; Decrement counter by 1 ; Print result array ; Driver code | def minDistancePoints ( A , K , n ) : NEW_LINE INDENT m = { } NEW_LINE q = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ A [ i ] ] = 1 NEW_LINE q . append ( A [ i ] ) NEW_LINE DEDENT ans = [ ] NEW_LINE while ( K > 0 ) : NEW_LINE INDENT x = q [ 0 ] NEW_LINE q = q [ 1 : : ] NEW_LINE if ( ( x - 1 ) not in m and K > 0 ) : NEW_LINE INDENT m [ x - 1 ] = m . get ( x - 1 , 0 ) + 1 NEW_LINE q . append ( x - 1 ) NEW_LINE ans . append ( x - 1 ) NEW_LINE K -= 1 NEW_LINE DEDENT if ( ( x + 1 ) not in m and K > 0 ) : NEW_LINE INDENT m [ x + 1 ] = m . get ( x + 1 , 0 ) + 1 NEW_LINE q . append ( x + 1 ) NEW_LINE ans . append ( x + 1 ) NEW_LINE K -= 1 NEW_LINE DEDENT DEDENT for i in ans : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ - 1 , 4 , 6 ] NEW_LINE K = 3 NEW_LINE n = len ( A ) NEW_LINE minDistancePoints ( A , K , n ) NEW_LINE DEDENT |
Leftmost Column with atleast one 1 in a row | Python3 implementation to find the Leftmost Column with atleast a 1 in a sorted binary matrix ; Function to search for the leftmost column of the matrix with atleast a 1 in sorted binary matrix ; Loop to iterate over all the rows of the matrix ; Binary Search to find the leftmost occurence of the 1 ; Condition if the column contains the 1 at this position of matrix ; If there is a better solution then update the answer ; Condition if the solution doesn 't exist in the matrix ; Driver Code | import sys NEW_LINE N = 3 NEW_LINE def search ( mat , n , m ) : NEW_LINE INDENT a = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT low = 0 NEW_LINE high = m - 1 NEW_LINE ans = sys . maxsize NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( mat [ i ] [ mid ] == 1 ) : NEW_LINE INDENT if ( mid == 0 ) : NEW_LINE INDENT ans = 0 NEW_LINE break NEW_LINE DEDENT elif ( mat [ i ] [ mid - 1 ] == 0 ) : NEW_LINE INDENT ans = mid NEW_LINE break NEW_LINE DEDENT DEDENT if ( mat [ i ] [ mid ] == 1 ) : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT if ( ans < a ) : NEW_LINE INDENT a = ans NEW_LINE DEDENT DEDENT if ( a == sys . maxsize ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return a + 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 0 , 0 , 0 ] , [ 0 , 0 , 1 ] , [ 0 , 1 , 1 ] ] NEW_LINE print ( search ( mat , 3 , 3 ) ) NEW_LINE DEDENT |
Largest index for each distinct character in given string with frequency K | Python3 implementation of the approach Function to find largest index for each distinct character occuring exactly K times . ; Function to find largest index for each distinct character occuring exactly K times ; Finding all characters present in S ; Finding all distinct characters in S ; To store result for each character ; Loop through each lower case English character ; If current character is absent in s ; Getting current character ; Finding count of character ch in S ; To store max Index encountred so far ; Printing required result ; If no such character exists , print - 1 ; Driver code | def maxSubstring ( S , K , N ) : NEW_LINE INDENT def maxSubstring ( S , K , N ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ ord ( S [ i ] ) - 97 ] = 1 NEW_LINE DEDENT answer = [ ] NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT ch = chr ( i + 97 ) NEW_LINE count = 0 NEW_LINE index = - 1 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( S [ j ] == ch ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( count == K ) : NEW_LINE INDENT index = j NEW_LINE DEDENT DEDENT answer . append ( [ ch , index ] ) NEW_LINE DEDENT flag = 0 NEW_LINE for i in range ( len ( answer ) ) : NEW_LINE INDENT if ( answer [ i ] [ 1 ] > - 1 ) : NEW_LINE INDENT flag = 1 NEW_LINE print ( answer [ i ] [ 0 ] , answer [ i ] [ 1 ] ) NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " cbaabaacbcd " NEW_LINE K = 2 NEW_LINE N = len ( S ) NEW_LINE maxSubstring ( S , K , N ) NEW_LINE DEDENT |
Smallest number greater than n that can be represented as a sum of distinct power of k | Function to find the smallest number greater than or equal to n represented as the sum of distinct powers of k ; Vector P to store the base k representation of the number ; If the representation is >= 2 , then this power of k has to be added once again and then increase the next power of k and make the current power 0 ; Reduce all the lower power of k to 0 ; Check if the most significant bit also satisfy the above conditions ; Converting back from the k - nary representation to decimal form . ; Driver code | def greaterK ( n , k ) : NEW_LINE INDENT index = 0 NEW_LINE p = [ 0 for i in range ( n + 2 ) ] NEW_LINE x = n NEW_LINE while ( x > 0 ) : NEW_LINE INDENT p [ index ] = x % k NEW_LINE x //= k NEW_LINE index += 1 NEW_LINE DEDENT idx = 0 NEW_LINE for i in range ( 0 , len ( p ) - 1 , 1 ) : NEW_LINE INDENT if ( p [ i ] >= 2 ) : NEW_LINE INDENT p [ i ] = 0 NEW_LINE p [ i + 1 ] += 1 NEW_LINE for j in range ( idx , i , 1 ) : NEW_LINE INDENT p [ j ] = 0 NEW_LINE DEDENT idx = i + 1 NEW_LINE DEDENT if ( p [ i ] == k ) : NEW_LINE INDENT p [ i ] = 0 NEW_LINE p [ i + 1 ] += 1 NEW_LINE DEDENT DEDENT j = len ( p ) - 1 NEW_LINE if ( p [ j ] >= 2 ) : NEW_LINE INDENT p [ index ] = 1 NEW_LINE index += 1 NEW_LINE DEDENT ans = 0 NEW_LINE i = len ( p ) - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT ans = ans * k + p [ i ] NEW_LINE i -= 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 29 NEW_LINE k = 7 NEW_LINE greaterK ( n , k ) NEW_LINE DEDENT |
Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Set 2 | Function that returns true if the can be balanced ; Count to check the difference between the frequencies of ' ( ' and ' ) ' and count_1 is to find the minimum value of freq ( ' ( ' ) - freq ( ' ) ' ) ; Traverse the given string ; Increase the count ; Decrease the count ; Find the minimum value of freq ( ' ( ' ) - freq ( ' ) ' ) ; If the minimum difference is greater than or equal to - 1 and the overall difference is zero ; Driver code | def canBeBalanced ( s , n ) : NEW_LINE INDENT count = 0 NEW_LINE count_1 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT count_1 = min ( count_1 , count ) NEW_LINE DEDENT if ( count_1 >= - 1 and count == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT s = " ( ) ) ( ) ( " NEW_LINE n = len ( s ) NEW_LINE if ( canBeBalanced ( s , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Absolute difference between the XOR of Non | Function to find the absolute difference between the XOR of non - primes and the XOR of primes in the given array ; Find maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store the XOR of primes in X1 and the XOR of non primes in X2 ; The number is prime ; The number is non - prime ; Return the absolute difference ; Driver code ; Find the absolute difference | def calculateDifference ( arr , n ) : NEW_LINE INDENT max_val = max ( arr ) NEW_LINE prime = [ True for i in range ( max_val + 1 ) ] NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , max_val + 1 ) : NEW_LINE INDENT if p * p > max_val + 1 : NEW_LINE INDENT break NEW_LINE DEDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( 2 * p , max_val + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT X1 = 1 NEW_LINE X2 = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( prime [ arr [ i ] ] ) : NEW_LINE INDENT X1 ^= arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] != 1 ) : NEW_LINE INDENT X2 ^= arr [ i ] NEW_LINE DEDENT DEDENT return abs ( X1 - X2 ) NEW_LINE DEDENT arr = [ 1 , 3 , 5 , 10 , 15 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( calculateDifference ( arr , n ) ) NEW_LINE |
Search in a trie Recursively | Python3 program to traverse in bottom up manner ; Trie node ; endOfWord is true if the node represents end of a word ; Function will return the new node ( initialized to NULLs ) ; Function will insert the string in a trie recursively ; Insert a new node ; Recursive call for insertion of string ; Make the endOfWord true which represents the end of string ; Function call to insert a string ; Function call with necessary arguments ; Function to search the string in a trie recursively ; When a string or any character of a string is not found ; Condition of finding string successfully ; Return true when endOfWord of last node containes true ; Recursive call and return value of function call stack ; Function call to search the string ; If string found ; Driver code ; Function call to insert the string ; Function call to search the string | CHILDREN = 26 NEW_LINE MAX = 100 NEW_LINE class trie : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . child = [ None for i in range ( CHILDREN ) ] NEW_LINE self . endOfWord = False NEW_LINE DEDENT DEDENT def createNode ( ) : NEW_LINE INDENT temp = trie ( ) NEW_LINE return temp NEW_LINE DEDENT def insertRecursively ( itr , str , i ) : NEW_LINE INDENT if ( i < len ( str ) ) : NEW_LINE INDENT index = ord ( str [ i ] ) - ord ( ' a ' ) NEW_LINE if ( itr . child [ index ] == None ) : NEW_LINE INDENT itr . child [ index ] = createNode ( ) ; NEW_LINE DEDENT insertRecursively ( itr . child [ index ] , str , i + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT itr . endOfWord = True ; NEW_LINE DEDENT DEDENT def insert ( itr , str ) : NEW_LINE INDENT insertRecursively ( itr , str , 0 ) ; NEW_LINE DEDENT def searchRecursively ( itr , str , i , len ) : NEW_LINE INDENT if ( itr == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( itr . endOfWord == True and i == len - 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT index = ord ( str [ i ] ) - ord ( ' a ' ) NEW_LINE return searchRecursively ( itr . child [ index ] , str , i + 1 , len ) NEW_LINE DEDENT def search ( root , str ) : NEW_LINE INDENT arr = [ ' ' for i in range ( len ( str ) + 1 ) ] NEW_LINE arr = str NEW_LINE if ( searchRecursively ( root , arr , 0 , len ( str ) + 1 ) ) : NEW_LINE INDENT print ( " found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " not β found " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = createNode ( ) ; NEW_LINE insert ( root , " thier " ) ; NEW_LINE insert ( root , " there " ) ; NEW_LINE insert ( root , " answer " ) ; NEW_LINE insert ( root , " any " ) ; NEW_LINE search ( root , " anywhere " ) NEW_LINE search ( root , " answer " ) NEW_LINE DEDENT |
Count duplicates in a given linked list | Python3 implementation of the approach ; Representation of node ; Function to push a node at the beginning ; Function to count the number of duplicate nodes in the linked list ; print ( 1 ) Starting from the next node ; print ( 2 ) If some duplicate node is found ; Return the count of duplicate nodes ; Driver code | import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head , item ) : NEW_LINE INDENT temp = Node ( item ) ; NEW_LINE temp . data = item ; NEW_LINE temp . next = head ; NEW_LINE head = temp ; NEW_LINE return head ; NEW_LINE DEDENT def countNode ( head ) : NEW_LINE INDENT count = 0 NEW_LINE while ( head . next != None ) : NEW_LINE INDENT ptr = head . next NEW_LINE while ( ptr != None ) : NEW_LINE INDENT if ( head . data == ptr . data ) : NEW_LINE INDENT count = count + 1 NEW_LINE break NEW_LINE DEDENT ptr = ptr . next NEW_LINE DEDENT head = head . next NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None ; NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 7 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 1 ) NEW_LINE head = push ( head , 7 ) NEW_LINE print ( countNode ( head ) ) NEW_LINE DEDENT |
Check if it is possible to form string B from A under the given constraints | Function that returns true if it is possible to form B from A satisfying the given conditions ; List to store the frequency of characters in A ; Vector to store the count of characters used from a particular group of characters ; Store the frequency of the characters ; If a character in B is not present in A ; If count of characters used from a particular group of characters exceeds m ; Update low to the starting index of the next group ; If count of characters used from a particular group of characters has not exceeded m ; | def isPossible ( A , B , b , m ) : NEW_LINE INDENT S = [ ] NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT S . append ( [ ] ) NEW_LINE DEDENT box = [ 0 ] * len ( A ) NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT S [ ord ( A [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE DEDENT low = 0 NEW_LINE for i in range ( len ( B ) ) : NEW_LINE INDENT indexes = S [ ord ( B [ i ] ) - ord ( ' a ' ) ] NEW_LINE it = lower_bound ( indexes , low ) NEW_LINE if ( it == len ( indexes ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT count = indexes [ it ] // b NEW_LINE box [ count ] = box [ count ] + 1 NEW_LINE if ( box [ count ] >= m ) : NEW_LINE INDENT count += 1 NEW_LINE low = ( count ) * b NEW_LINE DEDENT else : NEW_LINE INDENT low = indexes [ it ] + 1 NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def lower_bound ( indexes , k ) : NEW_LINE INDENT low , high = 0 , len ( indexes ) - 1 NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( indexes [ mid ] < k ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid NEW_LINE DEDENT DEDENT if indexes [ low ] < k : NEW_LINE INDENT return ( low + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return low NEW_LINE DEDENT DEDENT / * Driver code * / NEW_LINE A = " abcbbcdefxyz " NEW_LINE B = " acdxyz " NEW_LINE b = 5 NEW_LINE m = 2 NEW_LINE if ( isPossible ( A , B , b , m ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Remove all occurrences of any element for maximum array sum | Python3 program to convert fractional decimal to binary number ; Find total sum and frequencies of elements ; Find minimum value to be subtracted . ; Find maximum sum after removal ; Driver Code | from sys import maxsize NEW_LINE def maxSumArray ( arr , n ) : NEW_LINE INDENT sum1 = 0 NEW_LINE mp = { i : 0 for i in range ( 4 ) } NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum1 += arr [ i ] NEW_LINE mp [ arr [ i ] ] += 1 NEW_LINE DEDENT minimum = maxsize NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT if ( key == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT minimum = min ( minimum , value * key ) NEW_LINE DEDENT return ( sum1 - minimum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 3 , 3 , 2 , 2 , 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSumArray ( arr , n ) ) NEW_LINE DEDENT |
Given an array and two integers l and r , find the kth largest element in the range [ l , r ] | Python3 implementation of the approach ; Function to calculate the prefix ; Creating one based indexing ; Initializing and creating prefix array ; Creating a prefix array for every possible value in a given range ; Function to return the kth largest element in the index range [ l , r ] ; Binary searching through the 2d array and only checking the range in which the sub array is a part ; Driver code ; Creating the prefix array for the given array ; Queries ; Perform queries | MAX = 1001 NEW_LINE prefix = [ [ 0 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE ar = [ 0 for i in range ( MAX ) ] NEW_LINE def cal_prefix ( n , arr ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT ar [ i + 1 ] = arr [ i ] NEW_LINE DEDENT for i in range ( 1 , 1001 , 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT prefix [ i ] [ j ] = 0 NEW_LINE DEDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ar [ j ] <= i : NEW_LINE INDENT k = 1 NEW_LINE DEDENT else : NEW_LINE INDENT k = 0 NEW_LINE DEDENT prefix [ i ] [ j ] = prefix [ i ] [ j - 1 ] + k NEW_LINE DEDENT DEDENT DEDENT def ksub ( l , r , n , k ) : NEW_LINE INDENT lo = 1 NEW_LINE hi = 1000 NEW_LINE while ( lo + 1 < hi ) : NEW_LINE INDENT mid = int ( ( lo + hi ) / 2 ) NEW_LINE if ( prefix [ mid ] [ r ] - prefix [ mid ] [ l - 1 ] >= k ) : NEW_LINE INDENT hi = mid NEW_LINE DEDENT else : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT DEDENT if ( prefix [ lo ] [ r ] - prefix [ lo ] [ l - 1 ] >= k ) : NEW_LINE INDENT hi = lo NEW_LINE DEDENT return hi NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 2 , 3 , 5 , 7 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE k = 4 NEW_LINE cal_prefix ( n , arr ) NEW_LINE queries = [ [ 1 , n , 1 ] , [ 2 , n - 2 , 2 ] , [ 3 , n - 1 , 3 ] ] NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( ksub ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , n , queries [ i ] [ 2 ] ) ) NEW_LINE DEDENT DEDENT |
Find the number of Islands | Set 2 ( Using Disjoint Set ) | Class to represent Disjoint Set Data structure ; Initially , all elements are in their own set . ; Finds the representative of the set that x is an element of ; if x is not the parent of itself , then x is not the representative of its set . so we recursively call Find on its parent and move i 's node directly under the representative of this set ; Unites the set that includes x and the set that includes y ; Find the representatives ( or the root nodes ) for x an y ; Elements are in the same set , no need to unite anything . ; If x ' s β rank β is β less β than β y ' s rank Then move x under y so that depth of tree remains less ; Else if y ' s β rank β is β less β than β x ' s rank Then move y under x so that depth of tree remains less ; Else if their ranks are the same ; Then move y under x ( doesn 't matter which one goes where) ; And increment the result tree 's rank by 1 ; Returns number of islands in a [ ] [ ] ; The following loop checks for its neighbours and unites the indexes if both are 1. ; If cell is 0 , nothing to do ; Check all 8 neighbours and do a Union with neighbour 's set if neighbour is also 1 ; Array to note down frequency of each set ; If frequency of set is 0 , increment numberOfIslands ; Driver Code | class DisjointUnionSets : NEW_LINE INDENT def __init__ ( self , n ) : NEW_LINE INDENT self . rank = [ 0 ] * n NEW_LINE self . parent = [ 0 ] * n NEW_LINE self . n = n NEW_LINE self . makeSet ( ) NEW_LINE DEDENT def makeSet ( self ) : NEW_LINE INDENT for i in range ( self . n ) : NEW_LINE INDENT self . parent [ i ] = i NEW_LINE DEDENT DEDENT def find ( self , x ) : NEW_LINE INDENT if ( self . parent [ x ] != x ) : NEW_LINE INDENT return self . find ( self . parent [ x ] ) NEW_LINE DEDENT return x NEW_LINE DEDENT def Union ( self , x , y ) : NEW_LINE INDENT xRoot = self . find ( x ) NEW_LINE yRoot = self . find ( y ) NEW_LINE if xRoot == yRoot : NEW_LINE INDENT return NEW_LINE DEDENT if self . rank [ xRoot ] < self . rank [ yRoot ] : NEW_LINE INDENT parent [ xRoot ] = yRoot NEW_LINE DEDENT elif self . rank [ yRoot ] < self . rank [ xRoot ] : NEW_LINE INDENT self . parent [ yRoot ] = xRoot NEW_LINE DEDENT else : NEW_LINE INDENT self . parent [ yRoot ] = xRoot NEW_LINE self . rank [ xRoot ] = self . rank [ xRoot ] + 1 NEW_LINE DEDENT DEDENT DEDENT def countIslands ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( a [ 0 ] ) NEW_LINE dus = DisjointUnionSets ( n * m ) NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT for k in range ( 0 , m ) : NEW_LINE INDENT if a [ j ] [ k ] == 0 : NEW_LINE INDENT continue NEW_LINE DEDENT if j + 1 < n and a [ j + 1 ] [ k ] == 1 : NEW_LINE INDENT dus . Union ( j * ( m ) + k , ( j + 1 ) * ( m ) + k ) NEW_LINE DEDENT if j - 1 >= 0 and a [ j - 1 ] [ k ] == 1 : NEW_LINE INDENT dus . Union ( j * ( m ) + k , ( j - 1 ) * ( m ) + k ) NEW_LINE DEDENT if k + 1 < m and a [ j ] [ k + 1 ] == 1 : NEW_LINE INDENT dus . Union ( j * ( m ) + k , ( j ) * ( m ) + k + 1 ) NEW_LINE DEDENT if k - 1 >= 0 and a [ j ] [ k - 1 ] == 1 : NEW_LINE INDENT dus . Union ( j * ( m ) + k , ( j ) * ( m ) + k - 1 ) NEW_LINE DEDENT if ( j + 1 < n and k + 1 < m and a [ j + 1 ] [ k + 1 ] == 1 ) : NEW_LINE INDENT dus . Union ( j * ( m ) + k , ( j + 1 ) * ( m ) + k + 1 ) NEW_LINE DEDENT if ( j + 1 < n and k - 1 >= 0 and a [ j + 1 ] [ k - 1 ] == 1 ) : NEW_LINE INDENT dus . Union ( j * m + k , ( j + 1 ) * ( m ) + k - 1 ) NEW_LINE DEDENT if ( j - 1 >= 0 and k + 1 < m and a [ j - 1 ] [ k + 1 ] == 1 ) : NEW_LINE INDENT dus . Union ( j * m + k , ( j - 1 ) * m + k + 1 ) NEW_LINE DEDENT if ( j - 1 >= 0 and k - 1 >= 0 and a [ j - 1 ] [ k - 1 ] == 1 ) : NEW_LINE INDENT dus . Union ( j * m + k , ( j - 1 ) * m + k - 1 ) NEW_LINE DEDENT DEDENT DEDENT c = [ 0 ] * ( n * m ) NEW_LINE numberOfIslands = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT for k in range ( n ) : NEW_LINE INDENT if a [ j ] [ k ] == 1 : NEW_LINE INDENT x = dus . find ( j * m + k ) NEW_LINE if c [ x ] == 0 : NEW_LINE INDENT numberOfIslands += 1 NEW_LINE c [ x ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT c [ x ] += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return numberOfIslands NEW_LINE DEDENT a = [ [ 1 , 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 0 , 1 ] , [ 1 , 0 , 0 , 1 , 1 ] , [ 0 , 0 , 0 , 0 , 0 ] , [ 1 , 0 , 1 , 0 , 1 ] ] NEW_LINE print ( " Number β of β Islands β is : " , countIslands ( a ) ) NEW_LINE |
Find maximum N such that the sum of square of first N natural numbers is not more than X | Python implementation of the approach ; Function to return the sum of the squares of first N natural numbers ; Function to return the maximum N such that the sum of the squares of first N natural numbers is not more than X ; Iterate till maxvalue of N ; If the condition fails then return the i - 1 i . e sum of squares till i - 1 ; Driver code | import math NEW_LINE def squareSum ( N ) : NEW_LINE INDENT sum = ( N * ( N + 1 ) * ( 2 * N + 1 ) ) // 6 NEW_LINE return sum NEW_LINE DEDENT def findMaxN ( X ) : NEW_LINE INDENT N = ( int ) ( math . sqrt ( X ) ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( squareSum ( i ) > X ) : NEW_LINE INDENT return i - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT X = 25 NEW_LINE print ( findMaxN ( X ) ) NEW_LINE |
Remove exactly one element from the array such that max | Python3 implementation of the above approach ; function to calculate max - min ; There should be at - least two elements ; To store first and second minimums ; To store first and second maximums ; Driver code | import sys NEW_LINE def max_min ( a , n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT f_min = a [ 0 ] NEW_LINE s_min = sys . maxsize NEW_LINE f_max = a [ 0 ] NEW_LINE s_max = - ( sys . maxsize - 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] <= f_min ) : NEW_LINE INDENT s_min = f_min NEW_LINE f_min = a [ i ] NEW_LINE DEDENT elif ( a [ i ] < s_min ) : NEW_LINE INDENT s_min = a [ i ] NEW_LINE DEDENT if ( a [ i ] >= f_max ) : NEW_LINE INDENT s_max = f_max NEW_LINE f_max = a [ i ] NEW_LINE DEDENT elif ( a [ i ] > s_max ) : NEW_LINE INDENT s_max = a [ i ] NEW_LINE DEDENT DEDENT return min ( ( f_max - s_min ) , ( s_max - f_min ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 3 , 3 , 7 ] NEW_LINE n = len ( a ) NEW_LINE print ( max_min ( a , n ) ) NEW_LINE DEDENT |
Minimum in an array which is first decreasing then increasing | function to find the smallest number 's index ; Do a binary search ; find the mid element ; Check for break point ; Return the index ; Driver code ; print the smallest number | def minimal ( a , n ) : NEW_LINE INDENT lo , hi = 0 , n - 1 NEW_LINE while lo < hi : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE if a [ mid ] < a [ mid + 1 ] : NEW_LINE INDENT hi = mid NEW_LINE DEDENT else : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT return lo NEW_LINE return lo NEW_LINE DEDENT DEDENT a = [ 8 , 5 , 4 , 3 , 4 , 10 ] NEW_LINE n = len ( a ) NEW_LINE ind = minimal ( a , n ) NEW_LINE print ( a [ ind ] ) NEW_LINE |
Leftmost and rightmost indices of the maximum and the minimum element of an array | Python3 implementation of the approach ; If found new minimum ; If arr [ i ] = min then rightmost index for min will change ; If found new maximum ; If arr [ i ] = max then rightmost index for max will change ; Driver code | def findIndices ( arr , n ) : NEW_LINE INDENT leftMin , rightMin = 0 , 0 NEW_LINE leftMax , rightMax = 0 , 0 NEW_LINE min_element = arr [ 0 ] NEW_LINE max_element = arr [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < min_element ) : NEW_LINE INDENT leftMin = rightMin = i NEW_LINE min_element = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] == min_element ) : NEW_LINE INDENT rightMin = i NEW_LINE DEDENT if ( arr [ i ] > max_element ) : NEW_LINE INDENT leftMax = rightMax = i NEW_LINE max_element = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] == max_element ) : NEW_LINE INDENT rightMax = i NEW_LINE DEDENT DEDENT print ( " Minimum β left β : β " , leftMin ) NEW_LINE print ( " Minimum β right β : β " , rightMin ) NEW_LINE print ( " Maximum β left β : β " , leftMax ) NEW_LINE print ( " Maximum β right β : β " , rightMax ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 1 , 1 , 2 , 1 , 5 , 6 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE findIndices ( arr , n ) NEW_LINE DEDENT |
Find smallest and largest element from square matrix diagonals | Function to find smallest and largest element from principal and secondary diagonal ; take length of matrix ; declare and initialize variables with appropriate value ; Condition for principal diagonal ; take new smallest value ; take new largest value ; Condition for secondary diagonal ; take new smallest value ; take new largest value ; Declare and initialize 5 X5 matrix | def diagonalsMinMax ( mat ) : NEW_LINE INDENT n = len ( mat ) NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT principalMin = mat [ 0 ] [ 0 ] NEW_LINE principalMax = mat [ 0 ] [ 0 ] NEW_LINE secondaryMin = mat [ 0 ] [ n - 1 ] NEW_LINE secondaryMax = mat [ 0 ] [ n - 1 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT if ( mat [ i ] [ j ] < principalMin ) : NEW_LINE INDENT principalMin = mat [ i ] [ j ] NEW_LINE DEDENT if ( mat [ i ] [ j ] > principalMax ) : NEW_LINE INDENT principalMax = mat [ i ] [ j ] NEW_LINE DEDENT DEDENT if ( ( i + j ) == ( n - 1 ) ) : NEW_LINE INDENT if ( mat [ i ] [ j ] < secondaryMin ) : NEW_LINE INDENT secondaryMin = mat [ i ] [ j ] NEW_LINE DEDENT if ( mat [ i ] [ j ] > secondaryMax ) : NEW_LINE INDENT secondaryMax = mat [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( " Principal β Diagonal β Smallest β Element : β " , principalMin ) NEW_LINE print ( " Principal β Diagonal β Greatest β Element β : β " , principalMax ) NEW_LINE print ( " Secondary β Diagonal β Smallest β Element : β " , secondaryMin ) NEW_LINE print ( " Secondary β Diagonal β Greatest β Element : β " , secondaryMax ) NEW_LINE DEDENT matrix = [ [ 1 , 2 , 3 , 4 , - 10 ] , [ 5 , 6 , 7 , 8 , 6 ] , [ 1 , 2 , 11 , 3 , 4 ] , [ 5 , 6 , 70 , 5 , 8 ] , [ 4 , 9 , 7 , 1 , - 5 ] ] NEW_LINE diagonalsMinMax ( matrix ) NEW_LINE |
Indexed Sequential Search | Python program for Indexed Sequential Search ; Storing element ; Storing the index ; Driver code ; Element to search ; Function call | def indexedSequentialSearch ( arr , n , k ) : NEW_LINE INDENT elements = [ 0 ] * 20 NEW_LINE indices = [ 0 ] * 20 NEW_LINE j , ind , start , end = 0 , 0 , 0 , 0 NEW_LINE set_flag = 0 NEW_LINE for i in range ( 0 , n , 3 ) : NEW_LINE INDENT elements [ ind ] = arr [ i ] NEW_LINE indices [ ind ] = i NEW_LINE ind += 1 NEW_LINE DEDENT if k < elements [ 0 ] : NEW_LINE INDENT print ( " Not β found " ) NEW_LINE exit ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 1 , ind + 1 ) : NEW_LINE INDENT if k <= elements [ i ] : NEW_LINE INDENT start = indices [ i - 1 ] NEW_LINE end = indices [ i ] NEW_LINE set_flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if set_flag == 0 : NEW_LINE INDENT start = indices [ i - 1 ] NEW_LINE end = n NEW_LINE DEDENT for i in range ( start , end + 1 ) : NEW_LINE INDENT if k == arr [ i ] : NEW_LINE INDENT j = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if j == 1 : NEW_LINE INDENT print ( " Found β at β index " , i ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β found " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 7 , 8 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE k = 8 NEW_LINE indexedSequentialSearch ( arr , n , k ) NEW_LINE DEDENT |
Count elements such that there are exactly X elements with values greater than or equal to X | Python3 implementation of the approach ; Sorting the vector ; Count of numbers which are greater than v [ i ] ; Driver codemain ( ) | from bisect import bisect as upper_bound NEW_LINE def getCount ( v , n ) : NEW_LINE INDENT v = sorted ( v ) NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT tmp = n - 1 - upper_bound ( v , v [ i ] - 1 ) NEW_LINE if ( tmp == v [ i ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT n = 4 NEW_LINE v = [ ] NEW_LINE v . append ( 1 ) NEW_LINE v . append ( 2 ) NEW_LINE v . append ( 3 ) NEW_LINE v . append ( 4 ) NEW_LINE print ( getCount ( v , n ) ) NEW_LINE |
Number of segments where all elements are greater than X | Function to count number of segments ; Iterate in the array ; check if array element greater then X or not ; if flag is true ; After iteration complete check for the last segment ; Driver Code | def countSegments ( a , n , x ) : NEW_LINE INDENT flag = False NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > x ) : NEW_LINE INDENT flag = True NEW_LINE DEDENT else : NEW_LINE INDENT if ( flag ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT flag = False NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 8 , 25 , 10 , 19 , 19 , 18 , 20 , 11 , 18 ] NEW_LINE n = len ( a ) NEW_LINE x = 13 NEW_LINE print ( countSegments ( a , n , x ) ) NEW_LINE DEDENT |
Find array elements with frequencies in range [ l , r ] | Python 3 program to find the elements whose frequency lies in the range [ l , r ] ; Hash map which will store the frequency of the elements of the array . ; Increment the frequency of the element by 1. ; Print the element whose frequency lies in the range [ l , r ] ; Driver Code | def findElements ( arr , n , l , r ) : NEW_LINE INDENT mp = { i : 0 for i in range ( len ( arr ) ) } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( l <= mp [ arr [ i ] ] and mp [ arr [ i ] <= r ] ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 3 , 2 , 2 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE l = 2 NEW_LINE r = 3 NEW_LINE findElements ( arr , n , l , r ) NEW_LINE DEDENT |
Count triplets ( a , b , c ) such that a + b , b + c and a + c are all divisible by K | ''Function returns the count of the triplets ; Iterate for all triples pairs ( i , j , l ) ; If the condition is satisfied ; Driver code | def count_triples ( n , k ) : NEW_LINE INDENT count , i , j , l = 0 , 0 , 0 , 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT for l in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( ( i + j ) % k == 0 and ( i + l ) % k == 0 and ( j + l ) % k == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 3 , 2 NEW_LINE ans = count_triples ( n , k ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
kth smallest / largest in a small range unsorted array | Python 3 program of kth smallest / largest in a small range unsorted array ; Storing counts of elements ; Traverse hash array build above until we reach k - th smallest element . ; Driver Code | def kthSmallestLargest ( arr , n , k ) : NEW_LINE INDENT max_val = arr [ 0 ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] > max_val ) : NEW_LINE INDENT max_val = arr [ i ] NEW_LINE DEDENT DEDENT hash = [ 0 for i in range ( max_val + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash [ arr [ i ] ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( max_val + 1 ) : NEW_LINE INDENT while ( hash [ i ] > 0 ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT return i NEW_LINE DEDENT hash [ i ] -= 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 11 , 6 , 2 , 9 , 4 , 3 , 16 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( " kth β smallest β number β is : " , kthSmallestLargest ( arr , n , k ) ) NEW_LINE DEDENT |
Meta Binary Search | One | Function to show the working of Meta binary search ; Set number of bits to represent ; largest array index while ( ( 1 << lg ) < n - 1 ) : lg += 1 ; Incrementally construct the index of the target value ; find the element in one direction and update position ; if element found return pos otherwise - 1 ; Driver code | import math NEW_LINE def bsearch ( A , key_to_search ) : NEW_LINE INDENT n = len ( A ) NEW_LINE lg = int ( math . log2 ( n - 1 ) ) + 1 ; NEW_LINE pos = 0 NEW_LINE for i in range ( lg - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( A [ pos ] == key_to_search ) : NEW_LINE INDENT return pos NEW_LINE DEDENT new_pos = pos | ( 1 << i ) NEW_LINE if ( ( new_pos < n ) and ( A [ new_pos ] <= key_to_search ) ) : NEW_LINE INDENT pos = new_pos NEW_LINE DEDENT DEDENT return ( pos if ( A [ pos ] == key_to_search ) else - 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ - 2 , 10 , 100 , 250 , 32315 ] NEW_LINE print ( bsearch ( A , 10 ) ) NEW_LINE DEDENT |
Queries to check if a number lies in N ranges of L | Python program to check if the number lies in given range ; Function that answers every query ; container to store all range ; hash the L and R ; Push the element to container and hash the L and R ; sort the elements in container ; each query ; get the number same or greater than integer ; if it lies ; check if greater is hashed as 2 ; check if greater is hashed as 1 ; Driver Code ; function call to answer queries | from bisect import bisect_left as lower_bound NEW_LINE def answerQueries ( a : list , n , queries : list , q ) : NEW_LINE INDENT v = list ( ) NEW_LINE mpp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT v . append ( a [ i ] [ 0 ] ) NEW_LINE mpp [ a [ i ] [ 0 ] ] = 1 NEW_LINE v . append ( a [ i ] [ 1 ] ) NEW_LINE mpp [ a [ i ] [ 1 ] ] = 2 NEW_LINE DEDENT v . sort ( ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT num = queries [ i ] NEW_LINE ind = lower_bound ( v , num ) NEW_LINE if v [ ind ] == num : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT if mpp [ v [ ind ] ] == 2 : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ [ 5 , 6 ] , [ 1 , 3 ] , [ 8 , 10 ] ] NEW_LINE n = 3 NEW_LINE queries = [ 2 , 3 , 4 , 7 ] NEW_LINE q = len ( queries ) NEW_LINE answerQueries ( a , n , queries , q ) NEW_LINE DEDENT |
Median of two sorted arrays of different sizes | Set 1 ( Linear ) | This function returns median of a [ ] and b [ ] . Assumptions in this function : Both a [ ] and b [ ] are sorted arrays ; Current index of i / p array a [ ] ; Current index of i / p array b [ ] ; Below is to handle the case where all elements of a [ ] are smaller than smallest ( or first ) element of b [ ] or a [ ] is empty ; Below is to handle case where all elements of b [ ] are smaller than smallest ( or first ) element of a [ ] or b [ ] is empty ; Below is to handle the case where sum of number of elements of the arrays is even ; Below is to handle the case where sum of number of elements of the arrays is odd ; Driver Code | def findmedian ( a , n1 , b , n2 ) : NEW_LINE INDENT j = 0 NEW_LINE m1 = - 1 NEW_LINE m2 = - 1 NEW_LINE for k in range ( ( ( n1 + n2 ) // 2 ) + 1 ) : NEW_LINE INDENT if ( i < n1 and j < n2 ) : NEW_LINE INDENT if ( a [ i ] < b [ j ] ) : NEW_LINE INDENT m2 = m1 NEW_LINE m1 = a [ i ] NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m2 = m1 NEW_LINE m1 = b [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT elif ( i == n1 ) : NEW_LINE INDENT m2 = m1 NEW_LINE m1 = b [ j ] NEW_LINE j += 1 NEW_LINE DEDENT elif ( j == n2 ) : NEW_LINE INDENT m2 = m1 NEW_LINE m1 = a [ i ] NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if ( ( n1 + n2 ) % 2 == 0 ) : NEW_LINE INDENT return ( m1 + m2 ) * 1.0 / 2 NEW_LINE DEDENT return m1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 12 , 15 , 26 , 38 ] NEW_LINE b = [ 2 , 13 , 24 ] NEW_LINE n1 = len ( a ) NEW_LINE n2 = len ( b ) NEW_LINE print ( findmedian ( a , n1 , b , n2 ) ) NEW_LINE DEDENT |
Next Smaller Element | prints element and NSE pair for all elements of list ; Driver program to test above function | def printNSE ( arr ) : NEW_LINE INDENT for i in range ( 0 , len ( arr ) , 1 ) : NEW_LINE INDENT next = - 1 NEW_LINE for j in range ( i + 1 , len ( arr ) , 1 ) : NEW_LINE INDENT if arr [ i ] > arr [ j ] : NEW_LINE INDENT next = arr [ j ] NEW_LINE break NEW_LINE DEDENT DEDENT print ( str ( arr [ i ] ) + " β - - β " + str ( next ) ) NEW_LINE DEDENT DEDENT arr = [ 11 , 13 , 21 , 3 ] NEW_LINE printNSE ( arr ) NEW_LINE |
Longest subarray such that the difference of max and min is at | Python 3 code to find longest subarray with difference between max and min as at - most 1. ; longest constant range length ; first number ; If we see same number ; If we see different number , but same as previous . ; If number is neither same as previous nor as current . ; Driver Code | def longestSubarray ( input , length ) : NEW_LINE INDENT prev = - 1 NEW_LINE prevCount = 0 NEW_LINE currentCount = 1 NEW_LINE longest = 1 NEW_LINE current = input [ 0 ] NEW_LINE for i in range ( 1 , length ) : NEW_LINE INDENT next = input [ i ] NEW_LINE if next == current : NEW_LINE INDENT currentCount += 1 NEW_LINE DEDENT elif next == prev : NEW_LINE INDENT prevCount += currentCount NEW_LINE prev = current NEW_LINE current = next NEW_LINE currentCount = 1 NEW_LINE DEDENT else : NEW_LINE INDENT longest = max ( longest , currentCount + prevCount ) NEW_LINE prev = current NEW_LINE prevCount = currentCount NEW_LINE current = next NEW_LINE currentCount = 1 NEW_LINE DEDENT DEDENT return max ( longest , currentCount + prevCount ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input = [ 5 , 5 , 6 , 7 , 6 ] NEW_LINE n = len ( input ) NEW_LINE print ( longestSubarray ( input , n ) ) NEW_LINE DEDENT |
Reverse tree path | A Binary Tree Node ; ' data ' is input . We need to reverse path from root to data . level ' β is β current β level . β β temp ' that stores path nodes . nextpos ' used to pick next item for reversing. ; return None if root None ; Final condition if the node is found then ; store the value in it 's level ; change the root value with the current next element of the map ; increment in k for the next element ; store the data in perticular level ; We go to right only when left does not contain given data . This way we make sure that correct path node is stored in temp [ ] ; If current node is part of the path , then do reversing . ; return None if not element found ; Reverse Tree path ; store per level data ; it is for replacing the data ; reverse tree path ; INORDER ; Utility function to create a new tree node ; Driver code ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1 ; Reverse Tree Path ; Traverse inorder | 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 reverseTreePathUtil ( root , data , temp , level , nextpos ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None , temp , nextpos ; NEW_LINE DEDENT if ( data == root . data ) : NEW_LINE INDENT temp [ level ] = root . data ; NEW_LINE root . data = temp [ nextpos ] ; NEW_LINE nextpos += 1 NEW_LINE return root , temp , nextpos ; NEW_LINE DEDENT temp [ level ] = root . data ; NEW_LINE right = None NEW_LINE left , temp , nextpos = reverseTreePathUtil ( root . left , data , temp , level + 1 , nextpos ) ; NEW_LINE if ( left == None ) : NEW_LINE INDENT right , temp , nextpos = reverseTreePathUtil ( root . right , data , temp , level + 1 , nextpos ) ; NEW_LINE DEDENT if ( left or right ) : NEW_LINE INDENT root . data = temp [ nextpos ] ; NEW_LINE nextpos += 1 NEW_LINE return ( left if left != None else right ) , temp , nextpos ; NEW_LINE DEDENT return None , temp , nextpos ; NEW_LINE DEDENT def reverseTreePath ( root , data ) : NEW_LINE INDENT temp = dict ( ) NEW_LINE nextpos = 0 ; NEW_LINE reverseTreePathUtil ( root , data , temp , 0 , nextpos ) ; NEW_LINE DEDENT def inorder ( root ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT inorder ( root . left ) ; NEW_LINE print ( root . data , end = ' β ' ) NEW_LINE inorder ( root . right ) ; NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE return temp ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 7 ) ; NEW_LINE root . left = newNode ( 6 ) ; NEW_LINE root . right = newNode ( 5 ) ; NEW_LINE root . left . left = newNode ( 4 ) ; NEW_LINE root . left . right = newNode ( 3 ) ; NEW_LINE root . right . left = newNode ( 2 ) ; NEW_LINE root . right . right = newNode ( 1 ) ; NEW_LINE data = 4 ; NEW_LINE reverseTreePath ( root , data ) ; NEW_LINE inorder ( root ) ; NEW_LINE DEDENT |
Longest Subarray with first element greater than or equal to Last element | Search function for searching the first element of the subarray which is greater or equal to the last element ( num ) ; Returns length of the longest array with first element smaller than the last element . ; Search space for the potential first elements . ; It will store the Indexes of the elements of search space in the original array . ; Initially the search space is empty . ; We will add an ith element in the search space if the search space is empty or if the ith element is greater than the last element of the search space . ; we will search for the index first element in the search space and we will use it find the index of it in the original array . ; Update the answer if the length of the subarray is greater than the previously calculated lengths . ; Driver Code | def binarySearch ( searchSpace , s , e , num ) : NEW_LINE INDENT while ( s <= e ) : NEW_LINE INDENT mid = ( s + e ) // 2 NEW_LINE if searchSpace [ mid ] >= num : NEW_LINE INDENT ans = mid NEW_LINE e = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT s = mid + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def longestSubArr ( arr , n ) : NEW_LINE INDENT searchSpace = [ None ] * n NEW_LINE index = [ None ] * n NEW_LINE j = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( j == 0 or searchSpace [ j - 1 ] < arr [ i ] ) : NEW_LINE INDENT searchSpace [ j ] = arr [ i ] NEW_LINE index [ j ] = i NEW_LINE j += 1 NEW_LINE DEDENT idx = binarySearch ( searchSpace , 0 , j - 1 , arr [ i ] ) NEW_LINE ans = max ( ans , i - index [ idx ] + 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 5 , - 1 , 7 , 5 , 1 , - 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestSubArr ( arr , n ) ) NEW_LINE DEDENT |
Print all pairs with given sum | Python3 program for the above approach ; Driver code | def pairedElements ( arr , sum ) : NEW_LINE INDENT low = 0 ; NEW_LINE high = len ( arr ) - 1 ; NEW_LINE while ( low < high ) : NEW_LINE INDENT if ( arr [ low ] + arr [ high ] == sum ) : NEW_LINE INDENT print ( " The β pair β is β : β ( " , arr [ low ] , " , β " , arr [ high ] , " ) " ) ; NEW_LINE DEDENT if ( arr [ low ] + arr [ high ] > sum ) : NEW_LINE INDENT high -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT low += 1 ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , - 2 , 6 , 8 , 9 , 11 ] ; NEW_LINE arr . sort ( ) ; NEW_LINE pairedElements ( arr , 6 ) ; NEW_LINE DEDENT |
Check if a string is suffix of another | Python 3 program to find if a string is suffix of another ; Driver Code ; Test case - sensitive implementation of endsWith function | def isSuffix ( s1 , s2 ) : NEW_LINE INDENT n1 = len ( s1 ) NEW_LINE n2 = len ( s2 ) NEW_LINE if ( n1 > n2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( n1 ) : NEW_LINE INDENT if ( s1 [ n1 - i - 1 ] != s2 [ n2 - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s1 = " geeks " NEW_LINE s2 = " geeksforgeeks " NEW_LINE result = isSuffix ( s1 , s2 ) NEW_LINE if ( result ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Check if all occurrences of a character appear together | function to find if all occurrences of a character appear together in a string . ; To indicate if one or more occurrences of ' c ' are seen or not . ; Traverse given string ; If current character is same as c , we first check if c is already seen . ; If this is very first appearance of c , we traverse all consecutive occurrences . ; To indicate that character is seen once . ; Driver Code | def checkIfAllTogether ( s , c ) : NEW_LINE INDENT oneSeen = False NEW_LINE i = 0 NEW_LINE n = len ( s ) NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( s [ i ] == c ) : NEW_LINE INDENT if ( oneSeen == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT while ( i < n and s [ i ] == c ) : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT oneSeen = True NEW_LINE DEDENT else : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT s = "110029" ; NEW_LINE if ( checkIfAllTogether ( s , '1' ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Front and Back Search in unsorted array | Python program to implement front and back search ; Start searching from both ends ; Keep searching while two indexes do not cross . ; Driver code | def search ( arr , n , x ) : NEW_LINE INDENT front = 0 ; back = n - 1 NEW_LINE while ( front <= back ) : NEW_LINE INDENT if ( arr [ front ] == x or arr [ back ] == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT front += 1 NEW_LINE back -= 1 NEW_LINE DEDENT return False NEW_LINE DEDENT arr = [ 10 , 20 , 80 , 30 , 60 , 50 , 110 , 100 , 130 , 170 ] NEW_LINE x = 130 NEW_LINE n = len ( arr ) NEW_LINE if ( search ( arr , n , x ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Even | Python3 code to find max ( X , Y ) / min ( X , Y ) after P turns ; 1 st test case ; 2 nd test case | def findValue ( X , Y , P ) : NEW_LINE INDENT if P % 2 == 0 : NEW_LINE INDENT return int ( max ( X , Y ) / min ( X , Y ) ) NEW_LINE DEDENT else : NEW_LINE INDENT return int ( max ( 2 * X , Y ) / min ( 2 * X , Y ) ) NEW_LINE DEDENT DEDENT X = 1 NEW_LINE Y = 2 NEW_LINE P = 1 NEW_LINE print ( findValue ( X , Y , P ) ) NEW_LINE X = 3 NEW_LINE Y = 7 NEW_LINE P = 2 NEW_LINE print ( ( findValue ( X , Y , P ) ) ) NEW_LINE |
The painter 's partition problem | function to calculate sum between two indices in list ; bottom up tabular dp ; initialize table ; base cases k = 1 ; n = 1 ; 2 to k partitions for i in range ( 2 , k + 1 ) : 2 to n boards ; track minimum ; i - 1 th separator before position arr [ p = 1. . j ] ; required ; Driver Code ; Calculate size of array . | def sum ( arr , start , to ) : NEW_LINE INDENT total = 0 NEW_LINE for i in range ( start , to + 1 ) : NEW_LINE INDENT total += arr [ i ] NEW_LINE DEDENT return total NEW_LINE DEDENT def findMax ( arr , n , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( k + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = sum ( arr , 0 , i - 1 ) NEW_LINE DEDENT for i in range ( 1 , k + 1 ) : NEW_LINE INDENT dp [ i ] [ 1 ] = arr [ 0 ] NEW_LINE for j in range ( 2 , n + 1 ) : NEW_LINE INDENT best = 100000000 NEW_LINE for p in range ( 1 , j + 1 ) : NEW_LINE INDENT best = min ( best , max ( dp [ i - 1 ] [ p ] , sum ( arr , p , j - 1 ) ) ) NEW_LINE DEDENT dp [ i ] [ j ] = best NEW_LINE DEDENT DEDENT return dp [ k ] [ n ] NEW_LINE DEDENT arr = [ 10 , 20 , 60 , 50 , 30 , 40 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( findMax ( arr , n , k ) ) NEW_LINE INDENT n = len ( arr ) NEW_LINE DEDENT k = 3 NEW_LINE print ( findMax ( arr , n , k ) ) NEW_LINE |
Counting cross lines in an array | Function return count of cross line in an array ; Move elements of arr [ 0. . i - 1 ] , that are greater than key , to one position ahead of their current position ; increment cross line by one ; Driver Code | def countCrossLine ( arr , n ) : NEW_LINE INDENT count_crossline = 0 ; NEW_LINE i , key , j = 0 , 0 , 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT key = arr [ i ] ; NEW_LINE j = i - 1 ; NEW_LINE while ( j >= 0 and arr [ j ] > key ) : NEW_LINE INDENT arr [ j + 1 ] = arr [ j ] ; NEW_LINE j = j - 1 ; NEW_LINE count_crossline += 1 ; NEW_LINE DEDENT arr [ j + 1 ] = key ; NEW_LINE DEDENT return count_crossline ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 3 , 1 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countCrossLine ( arr , n ) ) ; NEW_LINE DEDENT |
Recursive Programs to find Minimum and Maximum elements of array | function to return maximum element using recursion ; if n = 0 means whole array has been traversed ; Driver Code ; Function calling | def findMaxRec ( A , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return A [ 0 ] NEW_LINE DEDENT return max ( A [ n - 1 ] , findMaxRec ( A , n - 1 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 4 , 45 , 6 , - 50 , 10 , 2 ] NEW_LINE n = len ( A ) NEW_LINE print ( findMaxRec ( A , n ) ) NEW_LINE DEDENT |
Program to remove vowels from a String | Python program to remove vowels from a string Function to remove vowels ; Driver program | import re NEW_LINE def rem_vowel ( string ) : NEW_LINE INDENT return ( re . sub ( " [ aeiouAEIOU ] " , " " , string ) ) NEW_LINE DEDENT string = " GeeksforGeeks β - β A β Computer β Science β Portal β for β Geeks " NEW_LINE print rem_vowel ( string ) NEW_LINE |
Minimum number of swaps required to minimize sum of absolute differences between adjacent array elements | Function to find the minimum number of swaps required to sort the array in increasing order ; Stores the array elements with its index ; Sort the array in the increasing order ; Keeps the track of visited elements ; Stores the count of swaps required ; Traverse array elements ; If the element is already swapped or at correct position ; Find out the number of nodes in this cycle ; Update the value of j ; Move to the next element ; Increment cycle_size ; Update the ans by adding current cycle ; Function to find the minimum number of swaps required to sort the array in decreasing order ; Stores the array elements with its index ; Sort the array in the descending order ; Keeps track of visited elements ; Stores the count of resultant swap required ; Traverse array elements ; If the element is already swapped or at correct position ; Find out the number of node in this cycle ; Update the value of j ; Move to the next element ; Increment the cycle_size ; Update the ans by adding current cycle size ; Function to find minimum number of swaps required to minimize the sum of absolute difference of adjacent elements ; Sort in ascending order ; Sort in descending order ; Return the minimum value ; Drive Code | def minSwapsAsc ( arr , n ) : NEW_LINE INDENT arrPos = [ [ arr [ i ] , i ] for i in range ( n ) ] NEW_LINE arrPos = sorted ( arrPos ) NEW_LINE vis = [ False ] * ( n ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( vis [ i ] or arrPos [ i ] [ 1 ] == i ) : NEW_LINE INDENT continue NEW_LINE DEDENT cycle_size = 0 NEW_LINE j = i NEW_LINE while ( not vis [ j ] ) : NEW_LINE INDENT vis [ j ] = 1 NEW_LINE j = arrPos [ j ] [ 1 ] NEW_LINE cycle_size += 1 NEW_LINE DEDENT if ( cycle_size > 0 ) : NEW_LINE INDENT ans += ( cycle_size - 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def minSwapsDes ( arr , n ) : NEW_LINE INDENT arrPos = [ [ 0 , 0 ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arrPos [ i ] [ 0 ] = arr [ i ] NEW_LINE arrPos [ i ] [ 1 ] = i NEW_LINE DEDENT arrPos = sorted ( arrPos ) [ : : - 1 ] NEW_LINE vis = [ False ] * n NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( vis [ i ] or arrPos [ i ] [ 1 ] == i ) : NEW_LINE INDENT continue NEW_LINE DEDENT cycle_size = 0 NEW_LINE j = i NEW_LINE while ( not vis [ j ] ) : NEW_LINE INDENT vis [ j ] = 1 NEW_LINE j = arrPos [ j ] [ 1 ] NEW_LINE cycle_size += 1 NEW_LINE DEDENT if ( cycle_size > 0 ) : NEW_LINE INDENT ans += ( cycle_size - 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def minimumSwaps ( arr ) : NEW_LINE INDENT S1 = minSwapsAsc ( arr , len ( arr ) ) NEW_LINE S2 = minSwapsDes ( arr , len ( arr ) ) NEW_LINE return min ( S1 , S2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 2 , 5 , 1 ] NEW_LINE print ( minimumSwaps ( arr ) ) NEW_LINE DEDENT |
Sort an array of 0 s , 1 s , 2 s and 3 s | Function to sort the array having array element only 0 , 1 , 2 , and 3 ; Iterate until mid <= j ; If arr [ mid ] is 0 ; Swap integers at indices i and mid ; Increment i ; Increment mid ; Otherwise if the value of arr [ mid ] is 3 ; Swap arr [ mid ] and arr [ j ] ; Decrement j ; Otherwise if the value of arr [ mid ] is either 1 or 2 ; Increment the value of mid ; Iterate until i <= j ; If arr [ i ] the value of is 2 ; Swap arr [ i ] and arr [ j ] ; Decrement j ; Otherwise , increment i ; Print the sorted array arr [ ] ; Driver Code | def sortArray ( arr , N ) : NEW_LINE INDENT i = 0 NEW_LINE j = N - 1 NEW_LINE mid = 0 NEW_LINE while ( mid <= j ) : NEW_LINE INDENT if ( arr [ mid ] == 0 ) : NEW_LINE INDENT arr [ i ] , arr [ mid ] = arr [ mid ] , arr [ i ] NEW_LINE i += 1 NEW_LINE mid += 1 NEW_LINE DEDENT elif ( arr [ mid ] == 3 ) : NEW_LINE INDENT arr [ mid ] , arr [ j ] = arr [ j ] , arr [ mid ] NEW_LINE j -= 1 NEW_LINE DEDENT elif ( arr [ mid ] == 1 or arr [ mid ] == 2 ) : NEW_LINE INDENT mid += 1 NEW_LINE DEDENT DEDENT while ( i <= j ) : NEW_LINE INDENT if ( arr [ i ] == 2 ) : NEW_LINE INDENT arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 0 , 2 , 3 , 1 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE sortArray ( arr , N ) NEW_LINE DEDENT |
Check whether an array can be made strictly increasing by removing at most one element | Function to find if is it possible to make the array strictly increasing by removing at most one element ; Stores the count of numbers that are needed to be removed ; Store the index of the element that needs to be removed ; Traverse the range [ 1 , N - 1 ] ; If arr [ i - 1 ] is greater than or equal to arr [ i ] ; Increment the count by 1 ; Update index ; If count is greater than one ; If no element is removed ; If only the last or the first element is removed ; If a [ index ] is removed ; If a [ index - 1 ] is removed ; Driver Code | def check ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE index = - 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i - 1 ] >= arr [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE index = i NEW_LINE DEDENT DEDENT if ( count > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( count == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( index == n - 1 or index == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( arr [ index - 1 ] < arr [ index + 1 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( arr [ index - 2 ] < arr [ index ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE if ( check ( arr , N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Modify string by rearranging vowels in alphabetical order at their respective indices | Function to arrange the vowels in sorted order in the string at their respective places ; Store the size of the string ; Stores vowels of string S ; Traverse the string , S and push all the vowels to string vow ; If vow is empty , then print S and return ; Sort vow in alphabetical order ; Traverse the string , S ; Replace S [ i ] with vow [ j ] iif S [ i ] is a vowel , and increment j by 1 ; Print the string ; Driver Code | def sortVowels ( S ) : NEW_LINE INDENT n = len ( S ) ; NEW_LINE vow = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( S [ i ] == ' a ' or S [ i ] == ' e ' or S [ i ] == ' i ' or S [ i ] == ' o ' or S [ i ] == ' u ' ) : NEW_LINE INDENT vow += S [ i ] ; NEW_LINE DEDENT DEDENT if len ( vow ) == 0 : NEW_LINE INDENT print ( S , end = " " ) ; NEW_LINE return ; NEW_LINE DEDENT vow = list ( vow ) ; NEW_LINE vow . sort ( ) ; NEW_LINE j = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( S [ i ] == ' a ' or S [ i ] == ' e ' or S [ i ] == ' i ' or S [ i ] == ' o ' or S [ i ] == ' u ' ) : NEW_LINE INDENT S [ i ] = vow [ j ] ; NEW_LINE j += 1 ; NEW_LINE DEDENT DEDENT print ( " " . join ( S ) , end = " " ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geeksforgeeks " ; NEW_LINE sortVowels ( list ( S ) ) ; NEW_LINE DEDENT |
Maximum number of buckets that can be filled | Function to find the maximum number of buckets that can be filled with the amount of water available ; Find the total available water ; Sort the array in ascending order ; Check if bucket can be filled with available water ; Print count of buckets ; Driver code | def getBuckets ( arr , N ) : NEW_LINE INDENT availableWater = N * ( N - 1 ) // 2 NEW_LINE arr . sort ( ) NEW_LINE i , Sum = 0 , 0 NEW_LINE while ( Sum <= availableWater ) : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT print ( i - 1 , end = " " ) NEW_LINE DEDENT arr = [ 1 , 5 , 3 , 4 , 7 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE getBuckets ( arr , N ) ; NEW_LINE |
Minimize the number of strictly increasing subsequences in an array | Set 2 | Function to find the number of strictly increasing subsequences in an array ; Sort the array ; Stores final count of subsequences ; Traverse the array ; Stores current element ; Stores frequency of the current element ; Count frequency of the current element ; If current element frequency is greater than count ; Print the final count ; ; Given array ; Size of the array ; Function call to find the number of strictly increasing subsequences | def minimumIncreasingSubsequences ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE count = 0 NEW_LINE i = 0 NEW_LINE while ( i < N ) : NEW_LINE INDENT x = arr [ i ] NEW_LINE freqX = 0 NEW_LINE while ( i < N and arr [ i ] == x ) : NEW_LINE INDENT freqX += 1 NEW_LINE i += 1 NEW_LINE DEDENT count = max ( count , freqX ) NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT / * Driver Code * / NEW_LINE arr = [ 2 , 1 , 2 , 1 , 4 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE minimumIncreasingSubsequences ( arr , N ) NEW_LINE |
Count triplets from an array which can form quadratic equations with real roots | Function to count the number of triplets ( a , b , c ) Such that the equations ax ^ 2 + bx + c = 0 has real roots ; sort he array in ascending order ; store count of triplets ( a , b , c ) such that ax ^ 2 + bx + c = 0 has real roots ; base case ; Traverse the given array ; if value of a and c are equal to b ; increment a ; Decrement c ; condition for having real roots for a quadratic equation ; if b lies in between a and c ; update count ; update count ; increment a ; Decrement c ; for each pair two values are possible of a and c ; Driver code ; | def getcount ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE count = 0 NEW_LINE if ( N < 3 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for b in range ( 0 , N ) : NEW_LINE INDENT a = 0 NEW_LINE c = N - 1 NEW_LINE d = arr [ b ] * arr [ b ] // 4 NEW_LINE while ( a < c ) : NEW_LINE INDENT if ( a == b ) : NEW_LINE INDENT a += 1 NEW_LINE continue NEW_LINE DEDENT if ( c == b ) : NEW_LINE INDENT c -= 1 NEW_LINE continue NEW_LINE DEDENT if ( arr [ a ] * arr ) <= d : NEW_LINE INDENT if ( a < b and b < c ) : NEW_LINE INDENT count += c - a - 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += c - a NEW_LINE DEDENT a += 1 NEW_LINE DEDENT else : NEW_LINE INDENT c -= 1 NEW_LINE DEDENT DEDENT DEDENT return count * 2 NEW_LINE DEDENT arr = [ 3 , 6 , 10 , 13 , 21 ] NEW_LINE N = len ( arr ) NEW_LINE / * Function Call * / NEW_LINE print ( getcount ( arr , N ) ) NEW_LINE |
Maximize difference between the sum of absolute differences of each element with the remaining array | Function to maximize difference of the sum of absolute difference of an element with the rest of the elements in the array ; Sort the array in ascending order ; Stores prefix sum at any instant ; Store the total array sum ; Initialize minimum and maximum absolute difference ; Traverse the array to find the total array sum ; Traverse the array arr [ ] ; Store the number of elements to its left ; Store the number of elements to its right ; Update the sum of elements on its left ; Store the absolute difference sum ; Update the Minimum ; Update the Maximum ; Update sum of elements on its left ; Prthe result ; Driven Code | def findMaxDifference ( arr , n ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE Leftsum = 0 NEW_LINE Totalsum = 0 NEW_LINE Min , Max = 10 ** 8 , - 10 ** 8 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Totalsum += arr [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT leftNumbers = i NEW_LINE rightNumbers = n - i - 1 NEW_LINE Totalsum = Totalsum - arr [ i ] NEW_LINE sum = ( leftNumbers * arr [ i ] ) - Leftsum + Totalsum - ( rightNumbers * arr [ i ] ) NEW_LINE Min = min ( Min , sum ) NEW_LINE Max = max ( Max , sum ) NEW_LINE Leftsum += arr [ i ] NEW_LINE DEDENT print ( Max - Min ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE findMaxDifference ( arr , N ) NEW_LINE DEDENT |
Minimum pairs required to be removed such that the array does not contain any pair with sum K | Function to find the maximum count of pairs required to be removed such that no pairs exist whose sum equal to K ; Stores maximum count of pairs required to be removed such that no pairs exist whose sum equal to K ; Base Case ; Sort the array ; Stores index of left pointer ; Stores index of right pointer ; Stores sum of left and right pointer ; If s equal to k ; Update cntPairs ; Update left ; Update right ; If s > k ; Update right ; Update left ; Return the cntPairs ; Driver Code ; Function call | def maxcntPairsSumKRemoved ( arr , k ) : NEW_LINE INDENT cntPairs = 0 NEW_LINE if not arr or len ( arr ) == 1 : NEW_LINE INDENT return cntPairs NEW_LINE DEDENT arr . sort ( ) NEW_LINE left = 0 NEW_LINE right = len ( arr ) - 1 NEW_LINE while left < right : NEW_LINE INDENT s = arr [ left ] + arr [ right ] NEW_LINE if s == k : NEW_LINE INDENT cntPairs += 1 NEW_LINE left += 1 NEW_LINE right -= 1 NEW_LINE DEDENT elif s > k : NEW_LINE INDENT right -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT left += 1 NEW_LINE DEDENT DEDENT return cntPairs NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE K = 5 NEW_LINE print ( maxcntPairsSumKRemoved ( arr , K ) ) NEW_LINE DEDENT |
Minimize cost to split an array into K subsets such that the cost of each element is its product with its position in the subset | Function to find the minimum cost to split array into K subsets ; Sort the array in descending order ; Stores minimum cost to split the array into K subsets ; Stores position of elements of a subset ; Iterate over the range [ 1 , N ] ; Calculate the cost to select X - th element of every subset ; Update min_cost ; Update X ; Driver code ; Function call | def getMinCost ( arr , n , k ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE min_cost = 0 ; NEW_LINE X = 0 ; NEW_LINE for i in range ( 0 , n , k ) : NEW_LINE INDENT for j in range ( i , n , 1 ) : NEW_LINE INDENT if ( j < i + k ) : NEW_LINE INDENT min_cost += arr [ j ] * ( X + 1 ) ; NEW_LINE DEDENT DEDENT X += 1 ; NEW_LINE DEDENT return min_cost ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 20 , 7 , 8 ] ; NEW_LINE K = 2 ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( getMinCost ( arr , N , K ) ) ; NEW_LINE DEDENT |
Minimize difference between the largest and smallest array elements by K replacements | Function to find minimum difference between largest and smallest element after K replacements ; Sort array in ascending order ; Length of array ; Minimum difference ; Check for all K + 1 possibilities ; Return answer ; Driver Code ; Given array ; Prints the minimum possible difference | def minDiff ( A , K ) : NEW_LINE INDENT A . sort ( ) ; NEW_LINE n = len ( A ) ; NEW_LINE if ( n <= K ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT mindiff = A [ n - 1 ] - A [ 0 ] ; NEW_LINE if ( K == 0 ) : NEW_LINE INDENT return mindiff ; NEW_LINE DEDENT i = 0 ; NEW_LINE for j in range ( n - 1 - K , n ) : NEW_LINE INDENT mindiff = min ( mindiff , A [ j ] - A [ i ] ) ; NEW_LINE i += 1 ; NEW_LINE j += 1 ; NEW_LINE DEDENT return mindiff ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ - 1 , 3 , - 1 , 8 , 5 , 4 ] ; NEW_LINE K = 3 ; NEW_LINE print ( minDiff ( A , K ) ) ; NEW_LINE DEDENT |
Minimize difference between the largest and smallest array elements by K replacements | Python3 program for above approach ; Function to find minimum difference between the largest and smallest element after K replacements ; Create a MaxHeap ; Create a MinHeap ; Update maxHeap and MinHeap with highest and smallest K elements respectively ; Insert current element into the MaxHeap ; If maxHeap size exceeds K + 1 ; Remove top element ; Insert current element into the MaxHeap ; If maxHeap size exceeds K + 1 ; Remove top element ; Store all max element from maxHeap ; Store all min element from minHeap ; Generating all K + 1 possibilities ; Return answer ; Given array ; Function call | import sys NEW_LINE def minDiff ( A , K ) : NEW_LINE INDENT if ( len ( A ) <= K + 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT maxHeap = [ ] NEW_LINE minHeap = [ ] NEW_LINE for n in A : NEW_LINE INDENT maxHeap . append ( n ) NEW_LINE maxHeap . sort ( ) NEW_LINE if ( len ( maxHeap ) > K + 1 ) : NEW_LINE INDENT del maxHeap [ 0 ] NEW_LINE DEDENT minHeap . append ( n ) NEW_LINE minHeap . sort ( ) NEW_LINE minHeap . reverse ( ) NEW_LINE if ( len ( minHeap ) > K + 1 ) : NEW_LINE INDENT del minHeap [ 0 ] NEW_LINE DEDENT DEDENT maxList = [ ] NEW_LINE while ( len ( maxHeap ) > 0 ) : NEW_LINE INDENT maxList . append ( maxHeap [ 0 ] ) NEW_LINE del maxHeap [ 0 ] NEW_LINE DEDENT minList = [ ] NEW_LINE while ( len ( minHeap ) > 0 ) : NEW_LINE INDENT minList . append ( minHeap [ 0 ] ) NEW_LINE del minHeap [ 0 ] NEW_LINE DEDENT mindiff = sys . maxsize NEW_LINE for i in range ( K ) : NEW_LINE INDENT mindiff = min ( mindiff , maxList [ i ] - minList [ K - i ] ) NEW_LINE DEDENT return mindiff NEW_LINE DEDENT A = [ - 1 , 3 , - 1 , 8 , 5 , 4 ] NEW_LINE K = 3 NEW_LINE print ( minDiff ( A , K ) ) NEW_LINE |
Check if all K | Function to check all subset - sums of K - length subsets in A [ ] is greater that that in the array B [ ] or not ; Sort the array in ascending order ; Sort the array in descending order ; Stores sum of first K elements of A [ ] ; Stores sum of first K elements of B [ ] ; Traverse both the arrays ; Update sum1 ; Update sum2 ; If sum1 exceeds sum2 ; Driver Code | def checkSubsetSum ( A , B , N , K ) : NEW_LINE INDENT A . sort ( ) NEW_LINE B . sort ( reverse = True ) NEW_LINE sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT sum1 += A [ i ] NEW_LINE sum2 += B [ i ] NEW_LINE DEDENT if ( sum1 > sum2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT A = [ 12 , 11 , 10 , 13 ] NEW_LINE B = [ 7 , 10 , 6 , 2 ] NEW_LINE N = len ( A ) NEW_LINE K = 3 NEW_LINE if ( checkSubsetSum ( A , B , N , K ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Sort given array to descending | Function to sort first K array elements in descending and last N - K in ascending order ; Sort the array in descending order ; Sort last ( N - K ) array elements in ascending order ; Driver Code | def sortArrayInDescAsc ( arr , N , K ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE arr = arr [ : : - 1 ] NEW_LINE for i in arr [ : K ] : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT for i in reversed ( arr [ K : ] ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 6 , 8 , 9 , 0 , 1 , 2 , 2 , 1 , 8 , 9 , 6 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE K = 6 NEW_LINE sortArrayInDescAsc ( arr , N , K ) NEW_LINE DEDENT |
Median of all non | Function to calculate the median of all possible subsets by given operations ; Stores sum of elements of arr [ ] ; Traverse the array arr [ ] ; Update sum ; Sort the array ; DP [ i ] [ j ] : Stores total number of ways to form the sum j by either selecting ith element or not selecting ith item . ; Base case ; Fill dp [ i ] [ 0 ] ; Base case ; Fill all the DP states based on the mentioned DP relation ; If j is greater than or equal to arr [ i ] ; Update dp [ i ] [ j ] ; Update dp [ i ] [ j ] ; Stores all possible subset sum ; Traverse all possible subset sum ; Stores count of subsets whose sum is j ; Itearate over the range [ 1 , M ] ; Insert j into sumSub ; Stores middle element of sumSub ; Driver Code | def findMedianOfsubSum ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT arr . sort ( reverse = False ) NEW_LINE dp = [ [ 0 for i in range ( sum + 1 ) ] for j in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 1 NEW_LINE DEDENT dp [ 0 ] [ arr [ 0 ] ] = 1 NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT for j in range ( 1 , sum + 1 , 1 ) : NEW_LINE INDENT if ( j >= arr [ i ] ) : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j - arr [ i ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT sumSub = [ ] NEW_LINE for j in range ( 1 , sum + 1 , 1 ) : NEW_LINE INDENT M = dp [ N - 1 ] [ j ] NEW_LINE for i in range ( 1 , M + 1 , 1 ) : NEW_LINE INDENT sumSub . append ( j ) NEW_LINE DEDENT DEDENT mid = sumSub [ len ( sumSub ) // 2 ] NEW_LINE return mid NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findMedianOfsubSum ( arr , N ) ) NEW_LINE DEDENT |
Reduce array to a single element by repeatedly replacing adjacent unequal pairs with their maximum | Function to prthe index from where the operation can be started ; Initialize B ; Initialize save ; Make B equals to arr ; Sort the array B ; Traverse from N - 1 to 1 ; If B [ i ] & B [ i - 1 ] are unequal ; If all elements are same ; If arr [ 1 ] is maximum element ; If arr [ N - 1 ] is maximum element ; Find the maximum element ; Driver Code ; Given array arr ; Length of array ; Function Call | def printIndex ( arr , N ) : NEW_LINE INDENT B = [ 0 ] * ( N ) NEW_LINE save = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT B [ i ] = arr [ i ] NEW_LINE DEDENT B = sorted ( B ) NEW_LINE for i in range ( N - 1 , 1 , - 1 ) : NEW_LINE INDENT if ( B [ i ] != B [ i - 1 ] ) : NEW_LINE INDENT save = B [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT if ( save == - 1 ) : NEW_LINE INDENT print ( - 1 + " " ) NEW_LINE return NEW_LINE DEDENT if ( save == arr [ 0 ] and save != arr [ 1 ] ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT elif ( save == arr [ N - 1 ] and save != arr [ N - 2 ] ) : NEW_LINE INDENT print ( N ) NEW_LINE DEDENT for i in range ( 1 , N - 1 ) : NEW_LINE INDENT if ( save == arr [ i ] and ( save != arr [ i - 1 ] or save != arr [ i + 1 ] ) ) : NEW_LINE INDENT print ( i + 1 ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 3 , 4 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE printIndex ( arr , N ) NEW_LINE DEDENT |
Lexicographically smallest subsequence possible by removing a character from given string | Function to find the lexicographically smallest subsequence of length N - 1 ; Generate all subsequence of length N - 1 ; Store main value of string str ; Erasing element at position i ; Sort the vector ; Print first element of vector ; Driver Code ; Given string S ; Function Call | def firstSubsequence ( s ) : NEW_LINE INDENT allsubseq = [ ] NEW_LINE k = [ ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT k = [ i for i in s ] NEW_LINE del k [ i ] NEW_LINE allsubseq . append ( " " . join ( k ) ) NEW_LINE DEDENT allsubseq = sorted ( allsubseq ) NEW_LINE print ( allsubseq [ 0 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " geeksforgeeks " NEW_LINE firstSubsequence ( S ) NEW_LINE DEDENT |
Maximum even sum subsequence of length K | Function to find the maximum even sum of any subsequence of length K ; If count of elements is less than K ; Stores maximum even subsequence sum ; Stores Even numbers ; Stores Odd numbers ; Traverse the array ; If current element is an odd number ; Insert odd number ; Insert even numbers ; Sort Odd [ ] array ; Sort Even [ ] array ; Stores current index Of Even [ ] array ; Stores current index Of Odd [ ] array ; If K is odd ; If count of elements in Even [ ] >= 1 ; Update maxSum ; Update i ; If count of elements in Even [ ] array is 0. ; Update K ; If count of elements in Even [ ] and odd [ ] >= 2 ; Update maxSum ; Update j . ; Update maxSum ; Update i ; Update K ; If count of elements in Even [ ] array >= 2. ; Update maxSum ; Update i . ; Update K . ; If count of elements in Odd [ ] array >= 2 ; Update maxSum ; Update i . ; Update K . ; Driver Code | def evenSumK ( arr , N , K ) : NEW_LINE INDENT if ( K > N ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT maxSum = 0 NEW_LINE Even = [ ] NEW_LINE Odd = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 ) : NEW_LINE INDENT Odd . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT Even . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT Odd . sort ( reverse = False ) NEW_LINE Even . sort ( reverse = False ) NEW_LINE i = len ( Even ) - 1 NEW_LINE j = len ( Odd ) - 1 NEW_LINE while ( K > 0 ) : NEW_LINE INDENT if ( K % 2 == 1 ) : NEW_LINE INDENT if ( i >= 0 ) : NEW_LINE INDENT maxSum += Even [ i ] NEW_LINE i -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT K -= 1 NEW_LINE DEDENT elif ( i >= 1 and j >= 1 ) : NEW_LINE INDENT if ( Even [ i ] + Even [ i - 1 ] <= Odd [ j ] + Odd [ j - 1 ] ) : NEW_LINE INDENT maxSum += Odd [ j ] + Odd [ j - 1 ] NEW_LINE j -= 2 NEW_LINE DEDENT else : NEW_LINE INDENT maxSum += Even [ i ] + Even [ i - 1 ] NEW_LINE i -= 2 NEW_LINE DEDENT K -= 2 NEW_LINE DEDENT elif ( i >= 1 ) : NEW_LINE INDENT maxSum += Even [ i ] + Even [ i - 1 ] NEW_LINE i -= 2 NEW_LINE K -= 2 NEW_LINE DEDENT elif ( j >= 1 ) : NEW_LINE INDENT maxSum += Odd [ j ] + Odd [ j - 1 ] NEW_LINE j -= 2 NEW_LINE K -= 2 NEW_LINE DEDENT DEDENT return maxSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 10 , 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( evenSumK ( arr , N , K ) ) NEW_LINE DEDENT |
Program to find weighted median of a given array | Function to calculate weighted median ; Store pairs of arr [ i ] and W [ i ] ; Sort the list of pairs w . r . t . to their arr [ ] values ; If N is odd ; Traverse the set pairs from left to right ; Update sums ; If sum becomes > 0.5 ; If N is even ; For lower median traverse the set pairs from left ; Update sums ; When sum >= 0.5 ; For upper median traverse the set pairs from right ; Update sums ; When sum >= 0.5 ; Driver Code ; Given array arr [ ] ; Given weights W [ ] ; Function Call | def weightedMedian ( arr , W ) : NEW_LINE INDENT pairs = [ ] NEW_LINE for index in range ( len ( arr ) ) : NEW_LINE INDENT pairs . append ( [ arr [ index ] , W [ index ] ] ) NEW_LINE DEDENT pairs . sort ( key = lambda p : p [ 0 ] ) NEW_LINE if len ( arr ) % 2 != 0 : NEW_LINE INDENT sums = 0 NEW_LINE for element , weight in pairs : NEW_LINE INDENT sums += weight NEW_LINE if sums > 0.5 : NEW_LINE INDENT print ( " The β Weighted β Median " , end = ' β ' ) NEW_LINE print ( " is β element β { } " . format ( element ) ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT sums = 0 NEW_LINE for element , weight in pairs : NEW_LINE INDENT sums += weight NEW_LINE if sums >= 0.5 : NEW_LINE INDENT print ( " Lower β Weighted β Median " , end = ' β ' ) NEW_LINE print ( " is β element β { } " . format ( element ) ) NEW_LINE break NEW_LINE DEDENT DEDENT sums = 0 NEW_LINE for index in range ( len ( pairs ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT element = pairs [ index ] [ 0 ] NEW_LINE weight = pairs [ index ] [ 1 ] NEW_LINE sums += weight NEW_LINE if sums >= 0.5 : NEW_LINE INDENT print ( " Upper β Weighted β Median " , end = ' β ' ) NEW_LINE print ( " is β element β { } " . format ( element ) ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 1 , 3 , 2 ] NEW_LINE W = [ 0.25 , 0.49 , 0.25 , 0.01 ] NEW_LINE weightedMedian ( arr , W ) NEW_LINE DEDENT |
Kth smallest element from an array of intervals | Function to get the Kth smallest element from an array of intervals ; Store all the intervals so that it returns the minimum element in O ( 1 ) ; Insert all Intervals into the MinHeap ; Stores the count of popped elements ; Iterate over MinHeap ; Stores minimum element from all remaining intervals ; Remove minimum element ; Check if the minimum of the current interval is less than the maximum of the current interval ; Insert new interval ; Driver Code ; Intervals given ; Size of the arr | def KthSmallestNum ( arr , n , k ) : NEW_LINE INDENT pq = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT pq . append ( [ arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ] ) NEW_LINE DEDENT cnt = 1 NEW_LINE while ( cnt < k ) : NEW_LINE INDENT pq . sort ( reverse = True ) NEW_LINE interval = pq [ 0 ] NEW_LINE pq . remove ( pq [ 0 ] ) NEW_LINE if ( interval [ 0 ] < interval [ 1 ] ) : NEW_LINE INDENT pq . append ( [ interval [ 0 ] + 1 , interval [ 1 ] ] ) NEW_LINE DEDENT cnt += 1 NEW_LINE DEDENT pq . sort ( reverse = True ) NEW_LINE return pq [ 0 ] [ 0 ] + 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 5 , 11 ] , [ 10 , 15 ] , [ 12 , 20 ] ] NEW_LINE n = len ( arr ) NEW_LINE k = 12 NEW_LINE print ( KthSmallestNum ( arr , n , k ) ) NEW_LINE DEDENT |
Maximum Manhattan distance between a distinct pair from N coordinates | Python3 program for the above approach ; Function to calculate the maximum Manhattan distance ; Stores the maximum distance ; Find Manhattan distance using the formula | x1 - x2 | + | y1 - y2 | ; Updating the maximum ; Driver code ; Given co - ordinates ; Function call | import sys NEW_LINE def MaxDist ( A , N ) : NEW_LINE INDENT maximum = - sys . maxsize NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( i + 1 , N ) : NEW_LINE INDENT Sum = ( abs ( A [ i ] [ 0 ] - A [ j ] [ 0 ] ) + abs ( A [ i ] [ 1 ] - A [ j ] [ 1 ] ) ) NEW_LINE maximum = max ( maximum , Sum ) NEW_LINE DEDENT DEDENT print ( maximum ) NEW_LINE DEDENT N = 3 NEW_LINE A = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 4 ] ] NEW_LINE MaxDist ( A , N ) NEW_LINE |
Longest increasing subsequence which forms a subarray in the sorted representation of the array | Function to find the length of the longest increasing sorted sequence ; Stores the count of all elements ; Store the original array ; Sort the array ; If adjacent element are not same ; Increment count ; Store frequency of each element ; Initialize a DP array ; Iterate over the array ar [ ] ; Length of the longest increasing sorted sequence ; Iterate over the array ; Current element ; If the element has been encountered the first time ; If all the x - 1 previous elements have already appeared ; Otherwise ; If all x - 1 elements have already been encountered ; Increment the count of the current element ; Update maximum subsequence size ; Return the maximum subsequence size ; Driver Code ; Function call | def LongestSequence ( a , n ) : NEW_LINE INDENT m = { i : 0 for i in range ( 100 ) } NEW_LINE ar = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ar [ i ] = a [ i - 1 ] NEW_LINE DEDENT a . sort ( reverse = False ) NEW_LINE c = 1 NEW_LINE m [ a [ 0 ] ] = c NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] != a [ i - 1 ] ) : NEW_LINE c += 1 NEW_LINE m [ a [ i ] ] = c NEW_LINE DEDENT cnt = { i : 0 for i in range ( 100 ) } NEW_LINE dp = [ [ 0 for i in range ( 3 ) ] for j in range ( n + 1 ) ] NEW_LINE cnt [ 0 ] = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ar [ i ] = m [ ar [ i ] ] NEW_LINE cnt [ ar [ i ] ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT x = ar [ i ] NEW_LINE if ( dp [ x ] [ 0 ] == 0 ) : NEW_LINE if ( dp [ x - 1 ] [ 0 ] == cnt [ x - 1 ] ) : NEW_LINE INDENT dp [ x ] [ 1 ] = dp [ x - 1 ] [ 1 ] NEW_LINE dp [ x ] [ 2 ] = dp [ x - 1 ] [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ x ] [ 1 ] = dp [ x - 1 ] [ 0 ] NEW_LINE DEDENT dp [ x ] [ 2 ] = max ( dp [ x - 1 ] [ 0 ] , dp [ x ] [ 2 ] ) NEW_LINE if ( dp [ x - 1 ] [ 0 ] == cnt [ x - 1 ] ) : NEW_LINE INDENT dp [ x ] [ 2 ] = max ( dp [ x ] [ 2 ] , dp [ x - 1 ] [ 1 ] ) NEW_LINE DEDENT for j in range ( 3 ) : NEW_LINE INDENT dp [ x ] [ j ] += 1 NEW_LINE ans = max ( ans , dp [ x ] [ j ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 6 , 4 , 8 , 2 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE print ( LongestSequence ( arr , N ) ) NEW_LINE DEDENT |
Maximize the sum of Kth column of a Matrix | Function to maximize the Kth column sum ; Store all the elements of the resultant matrix of size N * N ; Store value of each elements of the matrix ; Fill all the columns < K ; Fill all the columns >= K ; Function to print the matrix ; Driver Code | def findMatrix ( N , K ) : NEW_LINE INDENT mat = [ [ 0 for i in range ( N ) ] for j in range ( N ) ] ; NEW_LINE element = 0 ; NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , K - 1 ) : NEW_LINE INDENT element += 1 ; NEW_LINE mat [ i ] [ j ] = element ; NEW_LINE DEDENT DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( K - 1 , N ) : NEW_LINE INDENT element += 1 ; NEW_LINE mat [ i ] [ j ] = element ; NEW_LINE DEDENT DEDENT return mat ; NEW_LINE DEDENT def printMatrix ( mat , N ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " β " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 ; K = 2 ; NEW_LINE mat = findMatrix ( N , K ) ; NEW_LINE printMatrix ( mat , N ) ; NEW_LINE DEDENT |
Range sum queries based on given conditions | Function to calculate the sum between the given range as per value of m ; Stores the sum ; Condition for a to print the sum between ranges [ a , b ] ; Return sum ; Function to precalculate the sum of both the vectors ; Make Prefix sum array ; Function to compute the result for each query ; Take a dummy vector and copy the element of arr in brr ; Sort the dummy vector ; Compute prefix sum of both vectors ; Performs operations ; Function Call to find sum ; Function Call to find sum ; Driver Code ; Given arr [ ] ; Number of queries ; Given queries ; Function Call | def range_sum ( arr , a , b ) : NEW_LINE INDENT sum = 0 NEW_LINE if ( a - 2 < 0 ) : NEW_LINE INDENT sum = arr [ b - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT sum = ( arr [ b - 1 ] - arr [ a - 2 ] ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def precompute_sum ( arr , brr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT arr [ i ] = arr [ i ] + arr [ i - 1 ] NEW_LINE brr [ i ] = brr [ i ] + brr [ i - 1 ] NEW_LINE DEDENT DEDENT def find_sum ( arr , q , Queries ) : NEW_LINE INDENT brr = arr . copy ( ) NEW_LINE N = len ( arr ) NEW_LINE brr . sort ( ) NEW_LINE precompute_sum ( arr , brr ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT m = Queries [ i ] [ 0 ] NEW_LINE a = Queries [ i ] [ 1 ] NEW_LINE b = Queries [ i ] [ 2 ] NEW_LINE if ( m == 1 ) : NEW_LINE INDENT print ( range_sum ( arr , a , b ) , end = ' β ' ) NEW_LINE DEDENT elif ( m == 2 ) : NEW_LINE INDENT print ( range_sum ( brr , a , b ) , end = ' β ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 6 , 4 , 2 , 7 , 2 , 7 ] NEW_LINE Q = 1 NEW_LINE Queries = [ [ 2 , 3 , 6 ] ] NEW_LINE find_sum ( arr , Q , Queries ) NEW_LINE DEDENT |
XOR of all possible pairwise sum from two given Arrays | Python3 program to implement the above approach ; Function to calculate the XOR of the sum of every pair ; Stores the maximum bit ; Look for all the k - th bit ; Stores the modulo of elements B [ ] with ( 2 ^ ( k + 1 ) ) ; Calculate modulo of array B [ ] with ( 2 ^ ( k + 1 ) ) ; Sort the array C [ ] ; Stores the total number whose k - th bit is set ; Calculate and store the modulo of array A [ ] with ( 2 ^ ( k + 1 ) ) ; Lower bound to count the number of elements having k - th bit in the range ( 2 ^ k - x , 2 * 2 ^ ( k ) - x ) ; Add total number i . e ( r - l ) whose k - th bit is one ; Lower bound to count the number of elements having k - th bit in range ( 3 * 2 ^ k - x , 4 * 2 ^ ( k ) - x ) ; If count is even , Xor of k - th bit becomes zero , no need to add to the answer . If count is odd , only then , add to the final answer ; Return answer ; Driver code ; Function call | from bisect import bisect , bisect_left , bisect_right NEW_LINE def XorSum ( A , B , N ) : NEW_LINE INDENT maxBit = 29 NEW_LINE ans = 0 NEW_LINE for k in range ( maxBit ) : NEW_LINE INDENT C = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT C [ i ] = B [ i ] % ( 1 << ( k + 1 ) ) NEW_LINE DEDENT C = sorted ( C ) NEW_LINE count = 0 NEW_LINE l , r = 0 , 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = A [ i ] % ( 1 << ( k + 1 ) ) NEW_LINE l = bisect_left ( C , ( 1 << k ) - x ) NEW_LINE r = bisect_left ( C , ( 1 << k ) * 2 - x ) NEW_LINE count += ( r - l ) NEW_LINE l = bisect_left ( C , ( 1 << k ) * 3 - x ) NEW_LINE r = bisect_left ( C , ( 1 << k ) * 4 - x ) NEW_LINE count += ( r - l ) NEW_LINE DEDENT if ( count & 1 ) : NEW_LINE INDENT ans += ( 1 << k ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 4 , 6 , 0 , 0 , 3 , 3 ] NEW_LINE B = [ 0 , 5 , 6 , 5 , 0 , 3 ] NEW_LINE N = len ( A ) NEW_LINE print ( XorSum ( A , B , N ) ) NEW_LINE DEDENT |
Minimize count of Subsets with difference between maximum and minimum element not exceeding K | Function to find the minimum count of subsets of required type ; Stores the result ; Store the maximum and minimum element of the current subset ; Update current maximum ; If difference exceeds K ; Update count ; Update maximum and minimum to the current subset ; Driver Code | def findCount ( arr , N , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE result = 1 NEW_LINE cur_max = arr [ 0 ] NEW_LINE cur_min = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT cur_max = arr [ i ] NEW_LINE if ( cur_max - cur_min > K ) : NEW_LINE INDENT result += 1 NEW_LINE cur_max = arr [ i ] NEW_LINE cur_min = arr [ i ] NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 1 , 10 , 8 , 3 , 9 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( findCount ( arr , N , K ) ) NEW_LINE |
Minimize the Sum of all the subarrays made up of the products of same | Python3 Program to implement the above approach ; Function to rearrange the second array such that the sum of its product of same indexed elements from both the arrays is minimized ; Stores ( i - 1 ) * ( n - i ) * a [ i ] for every i - th element ; Updating the value of pro according to the function ; Sort the array in reverse order ; Sort the products ; Updating the ans ; Return the ans ; Driver code ; Function call | mod = 1e9 + 7 NEW_LINE def findMinValue ( a , b ) : NEW_LINE INDENT n = len ( a ) NEW_LINE pro = [ 0 ] * ( n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT pro [ i ] = ( ( i + 1 ) * ( n - i ) ) NEW_LINE pro [ i ] *= ( a [ i ] ) NEW_LINE DEDENT b . sort ( reverse = True ) NEW_LINE pro . sort ( ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += ( pro [ i ] % mod * b [ i ] ) % mod NEW_LINE ans %= mod NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 3 ] NEW_LINE b = [ 2 , 3 , 2 ] NEW_LINE print ( int ( findMinValue ( a , b ) ) ) NEW_LINE DEDENT |
Sort Array such that smallest is at 0 th index and next smallest it at last index and so on | Python3 program for the above approach Function to perform the rearrangement ; Initialize variables ; Loop until i crosses j ; This check is to find the minimum values in the ascending order ; Condition to alternatively iterate variable i and j ; Perform swap operation ; Increment i ; Assign the value of min ; Perform swap ; Decrement i ; Assign the value of min ; Print the array ; Driver Code ; Given Array arr [ ] ; Function call | def rearrange ( a , N ) : NEW_LINE INDENT i = 0 NEW_LINE j = N - 1 NEW_LINE min = 0 NEW_LINE x = 0 NEW_LINE while ( i < j ) : NEW_LINE INDENT for k in range ( i , j + 1 ) : NEW_LINE INDENT if ( a [ k ] < a [ min ] ) : NEW_LINE INDENT min = k NEW_LINE DEDENT DEDENT if ( x % 2 == 0 ) : NEW_LINE INDENT temp = a [ i ] NEW_LINE a [ i ] = a [ min ] NEW_LINE a [ min ] = temp NEW_LINE i += 1 NEW_LINE min = i NEW_LINE DEDENT else : NEW_LINE INDENT temp = a [ j ] NEW_LINE a [ j ] = a [ min ] NEW_LINE a [ min ] = temp NEW_LINE j -= 1 NEW_LINE min = j NEW_LINE DEDENT x += 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE rearrange ( arr , N ) NEW_LINE DEDENT |
Maximum number of elements greater than X after equally distributing subset of array | Function to find the maximum number of elements greater than X by equally distributing ; Sorting the array ; Loop to iterate over the elements of the array ; If no more elements can become larger than x ; Driver Code | def redistribute ( arr , n , x ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE if ( sum / ( i + 1 ) < x ) : NEW_LINE INDENT print ( i ) NEW_LINE break NEW_LINE DEDENT DEDENT if ( i == n ) : NEW_LINE INDENT print ( n ) NEW_LINE DEDENT DEDENT arr = [ 5 , 1 , 2 , 1 ] NEW_LINE x = 3 NEW_LINE redistribute ( arr , 4 , x ) NEW_LINE |
Last element remaining by deleting two largest elements and replacing by their absolute difference if they are unequal | Python3 program for the above approach ; Function to print the remaining element ; Priority queue can be used to construct max - heap ; Insert all element of arr [ ] into priority queue . Default priority queue in Python is min - heap so use - 1 * arr [ i ] ; Perform operation until heap size becomes 0 or 1 ; Remove largest element ; Remove 2 nd largest element ; If extracted elements are not equal ; Find X - Y and push it to heap ; If heap size is 1 , then print the remaining element ; Else print " - 1" ; Driver Code ; Given array arr [ ] ; Size of array arr [ ] ; Function call | from queue import PriorityQueue NEW_LINE def final_element ( arr , n ) : NEW_LINE INDENT heap = PriorityQueue ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT heap . put ( - 1 * arr [ i ] ) NEW_LINE DEDENT while ( heap . qsize ( ) > 1 ) : NEW_LINE INDENT X = - 1 * heap . get ( ) NEW_LINE Y = - 1 * heap . get ( ) NEW_LINE if ( X != Y ) : NEW_LINE INDENT diff = abs ( X - Y ) NEW_LINE heap . put ( - 1 * diff ) NEW_LINE DEDENT DEDENT if ( heap . qsize ( ) == 1 ) : NEW_LINE INDENT print ( - 1 * heap . get ( ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 5 , 2 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE final_element ( arr , n ) NEW_LINE DEDENT |
Sort a string according to the frequency of characters | Returns count of character in the string ; Check for vowel ; Function to sort the string according to the frequency ; Vector to store the frequency of characters with respective character ; Inserting frequency with respective character in the vector pair ; Sort the vector , this will sort the pair according to the number of characters ; Print the sorted vector content ; Driver code | def countFrequency ( string , ch ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ i ] == ch ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT def sortArr ( string ) : NEW_LINE INDENT n = len ( string ) ; NEW_LINE vp = [ ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT vp . append ( ( countFrequency ( string , string [ i ] ) , string [ i ] ) ) ; NEW_LINE DEDENT vp . sort ( ) ; NEW_LINE for i in range ( len ( vp ) ) : NEW_LINE INDENT print ( vp [ i ] [ 1 ] , end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " geeksforgeeks " ; NEW_LINE sortArr ( string ) ; NEW_LINE DEDENT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.