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 ; Inc... | 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 ... |
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 ; F... | 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_L... |
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 ] , su... |
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 ma... | 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 ] ... |
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 ... | 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... |
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 ; Pus... | 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 ... |
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 ro... | 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_L... |
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 in... | 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 ... |
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 ; Travers... | 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 ( ( t... |
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 ; ... | 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... |
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... | 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 ... |
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 retu... |
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 [ - ... |
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 ; F... | 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_s... |
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 ... | 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... |
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 ... | 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... |
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 cal... | 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_su... |
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 w... | 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 ... |
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 ; Up... | 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 =... |
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 H... | 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 ) = n... |
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 ... | 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 ... |
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 ra... |
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... | 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_nod... |
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... | 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 r... |
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 require... | 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_LIN... |
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... |
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 r... | 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 ( ) N... |
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 Sear... | 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 =... |
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 ; Fun... | 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 ] ) ) ... |
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 t... | 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_... |
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 e... | 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 ... |
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 le... | 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 ) :... |
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... | 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 ) : NE... |
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 t... | 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 ... |
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... | 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 co... |
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 p... | 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 (... |
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 s... | 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 insert... |
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 c... | 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_... |
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 fr... | 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 ra... |
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 IN... |
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 ... | 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... |
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 ... | 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 ... |
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 ; Iter... | 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... |
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_... |
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... |
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 = ar... |
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 ; C... | 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 ) :... |
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_L... |
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 ... |
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... |
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 , ... | 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 ] , e... |
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 ... |
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 ... |
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 othe... | 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 <<... |
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... | 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_... |
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 [ ] ... | 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 :... |
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... |
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... | 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 DE... |
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 ... | 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 , nex... |
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 firs... | 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 longes... |
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 ... |
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 DEDE... |
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 ... | 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... |
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 ... |
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... |
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 ... | 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... |
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 c... |
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 ... |
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... | 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 c... |
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 ... | 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 ar... |
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 ; Traver... | 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... |
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 , t... | 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 IND... |
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_LI... |
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... | 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 , freq... |
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 ; ba... | 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 IN... |
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... | 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 ... |
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 Cas... | 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 =... |
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... | 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 +... |
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 ;... | 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 IND... |
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 el... | 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 max... |
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 ; Upd... | 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 Fa... |
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__ == ' _ _... |
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 . ; B... | 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... |
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 eleme... | 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 br... |
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 v... | 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 DE... |
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 e... | 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 . appen... |
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 tr... | 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 , weigh... |
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 ... | 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... |
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 - ordi... | 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 ,... |
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... | 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 ... |
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 ,... |
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 ... | 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 fo... |
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... | 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... |
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 maxi... | 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 c... |
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 ;... | 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_... |
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 iterat... | 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_... |
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 ... |
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 pri... | 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... |
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 t... | 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 = [ ] ; N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.