text
stringlengths
1
636
code
stringlengths
8
1.89k
Function to find minimum reversals
def minRev ( edges , n ) : NEW_LINE
Add all adjacent nodes to the node in the graph
graph = dict ( ) NEW_LINE graph_rev = dict ( ) NEW_LINE for i in range ( len ( edges ) ) : NEW_LINE INDENT x = edges [ i ] [ 0 ] ; NEW_LINE y = edges [ i ] [ 1 ] ; NEW_LINE DEDENT
Insert edges in the graph
if x not in graph : NEW_LINE INDENT graph [ x ] = [ ] NEW_LINE DEDENT graph [ x ] . append ( y ) ; NEW_LINE
Insert edges in the reversed graph
if y not in graph_rev : NEW_LINE INDENT graph_rev [ y ] = [ ] NEW_LINE DEDENT graph_rev [ y ] . append ( x ) ; NEW_LINE q = [ ] NEW_LINE
Create array visited to mark all the visited nodes
visited = [ 0 for i in range ( n ) ] NEW_LINE q . append ( 0 ) ; NEW_LINE
Stores the number of edges to be reversed
ans = 0 ; NEW_LINE
BFS Traversal
while ( len ( q ) != 0 ) : NEW_LINE
Pop the current node from the queue
curr = q [ 0 ] NEW_LINE
mark the current node visited
visited [ curr ] = 1 ; NEW_LINE
Intitialize count of edges need to be reversed to 0
count = 0 ; NEW_LINE q . pop ( 0 ) ; NEW_LINE
Push adjacent nodes in the reversed graph to the queue , if not visited
if curr in graph_rev : NEW_LINE INDENT for i in range ( len ( graph_rev [ curr ] ) ) : NEW_LINE INDENT if ( not visited [ graph_rev [ curr ] [ i ] ] ) : NEW_LINE INDENT q . append ( graph_rev [ curr ] [ i ] ) ; NEW_LINE DEDENT DEDENT DEDENT
Push adjacent nodes in graph to the queue , if not visited count the number of nodes added to the queue
if curr in graph : NEW_LINE INDENT for i in range ( len ( graph [ curr ] ) ) : NEW_LINE INDENT if ( not visited [ graph [ curr ] [ i ] ] ) : NEW_LINE INDENT q . append ( graph [ curr ] [ i ] ) ; NEW_LINE count += 1 NEW_LINE DEDENT DEDENT DEDENT
Update the reverse edge to the final count
ans += count ; NEW_LINE
Return the result
return ans ; NEW_LINE
Driver Code
if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT edges = [ ] NEW_LINE DEDENT
Given edges to the graph
edges = [ [ 0 , 1 ] , [ 1 , 3 ] , [ 2 , 3 ] , [ 4 , 0 ] , [ 4 , 5 ] ] ; NEW_LINE
Number of nodes
n = 6 ; NEW_LINE
Function Call
print ( minRev ( edges , n ) ) NEW_LINE
Function to split the array
def splitArray ( arr , N ) : NEW_LINE
Sort the array in increasing order
arr = sorted ( arr ) NEW_LINE result = 10 ** 9 NEW_LINE
Calculating the max difference between consecutive elements
for i in range ( 1 , N ) : NEW_LINE INDENT result = min ( result , arr [ i ] - arr [ i - 1 ] ) NEW_LINE DEDENT
Return the final minimum difference
return result NEW_LINE
Driver Code
if __name__ == ' _ _ main _ _ ' : NEW_LINE
Given array arr [ ]
arr = [ 3 , 1 , 2 , 6 , 4 ] NEW_LINE
Size of array
N = len ( arr ) NEW_LINE
Function Call
print ( splitArray ( arr , N ) ) NEW_LINE
Function to find the R ' th ▁ row ▁ and ▁ C ' th column value in the given pattern
def findValue ( R , C ) : NEW_LINE
First element of a given row
k = ( R * ( R - 1 ) ) // 2 + 1 NEW_LINE diff = R + 1 NEW_LINE
Element in the given column
for i in range ( 1 , C ) : NEW_LINE INDENT k = ( k + diff ) NEW_LINE diff += 1 NEW_LINE DEDENT return k NEW_LINE
Driver Code
if __name__ == " _ _ main _ _ " : NEW_LINE INDENT R = 4 NEW_LINE C = 4 NEW_LINE DEDENT
Function call
k = findValue ( R , C ) NEW_LINE print ( k ) NEW_LINE
Function that prints the number of maximum groups
def makeGroups ( a , n ) : NEW_LINE INDENT v = [ 0 ] * ( n + 1 ) NEW_LINE DEDENT
Store the number of occurrence of elements
for i in range ( n ) : NEW_LINE INDENT v [ a [ i ] ] += 1 NEW_LINE DEDENT no_of_groups = 0 NEW_LINE
Make all groups of similar elements and store the left numbers
for i in range ( 1 , n + 1 ) : NEW_LINE INDENT no_of_groups += v [ i ] // i NEW_LINE v [ i ] = v [ i ] % i NEW_LINE DEDENT i = 1 NEW_LINE total = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE
Condition for finding first leftover element
if ( v [ i ] != 0 ) : NEW_LINE INDENT total = v [ i ] NEW_LINE break NEW_LINE DEDENT i += 1 NEW_LINE while ( i <= n ) : NEW_LINE
Condition for current leftover element
if ( v [ i ] != 0 ) : NEW_LINE INDENT total += v [ i ] NEW_LINE DEDENT
Condition if group size is equal to or more than current element
if ( total >= i ) : NEW_LINE INDENT rem = total - i NEW_LINE no_of_groups += 1 NEW_LINE total = rem NEW_LINE DEDENT i += 1 NEW_LINE
Printing maximum number of groups
print ( no_of_groups ) NEW_LINE
Driver Code
if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 1 , 2 , 2 ] NEW_LINE size = len ( arr ) NEW_LINE makeGroups ( arr , size ) NEW_LINE DEDENT
Python3 program to calculate leftmost column having at least a 1
N = 3 NEW_LINE M = 4 NEW_LINE
Function return leftmost column having at least a 1
def findColumn ( mat : list ) -> int : NEW_LINE INDENT row = 0 NEW_LINE col = M - 1 NEW_LINE while row < N and col >= 0 : NEW_LINE DEDENT
If current element is 1 decrement column by 1
if mat [ row ] [ col ] == 1 : NEW_LINE INDENT col -= 1 NEW_LINE flag = 1 NEW_LINE DEDENT
If current element is 0 increment row by 1
else : NEW_LINE INDENT row += 1 NEW_LINE DEDENT col += 1 NEW_LINE if flag : NEW_LINE return col + 1 NEW_LINE else : NEW_LINE return - 1 NEW_LINE
Driver Code
if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 0 , 0 , 0 , 1 ] , [ 0 , 1 , 1 , 1 ] , [ 0 , 0 , 1 , 1 ] ] NEW_LINE print ( findColumn ( mat ) ) NEW_LINE DEDENT
Function to implement the above approach
def findNumbers ( N , M ) : NEW_LINE INDENT m = M NEW_LINE DEDENT
Hashmap to store remainder - length of the number as key - value pairs
remLen = { } NEW_LINE
Iterate till N + 1 length
for len1 in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT remainder = M % N NEW_LINE DEDENT
Search remainder in the map
if ( remLen . get ( remainder ) == None ) : NEW_LINE
If remainder is not already present insert the length for the corresponding remainder
remLen [ remainder ] = len1 NEW_LINE else : NEW_LINE break NEW_LINE
Keep increasing M
M = M * 10 + m NEW_LINE
To keep M in range of integer
M = M % N NEW_LINE
Length of one number is the current Length
LenA = len1 NEW_LINE
Length of the other number is the length paired with current remainder in map
LenB = remLen [ remainder ] NEW_LINE for i in range ( LenB ) : NEW_LINE INDENT print ( m , end = " " ) NEW_LINE DEDENT print ( " ▁ " , end = " " ) NEW_LINE for i in range ( LenA ) : NEW_LINE INDENT print ( m , end = " " ) NEW_LINE DEDENT return NEW_LINE
Driver code
if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE M = 2 NEW_LINE findNumbers ( N , M ) NEW_LINE DEDENT
2D prefix sum for submatrix sum query for matrix
prefix_2D = [ [ 0 for x in range ( 2005 ) ] for y in range ( 2005 ) ] NEW_LINE
Function to find the prefix sum of the matrix from i and j
def subMatrixSum ( i , j , length ) : NEW_LINE INDENT return ( prefix_2D [ i ] [ j ] - prefix_2D [ i ] [ j - length ] - prefix_2D [ i - length ] [ j ] + prefix_2D [ i - length ] [ j - length ] ) NEW_LINE DEDENT
Function to count the number of ways to select equal sized subarrays such that they have atleast K common elements
def numberOfWays ( a , b , n , m , k ) : NEW_LINE
Combining the two arrays
for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( a [ i - 1 ] == b [ j - 1 ] ) : NEW_LINE INDENT prefix_2D [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT prefix_2D [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT
Calculating the 2D prefix sum
for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT prefix_2D [ i ] [ j ] += prefix_2D [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT prefix_2D [ i ] [ j ] += prefix_2D [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT answer = 0 NEW_LINE
iterating through all the elements of matrix and considering them to be the bottom right
for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE DEDENT
applying binary search over side length
low = 1 NEW_LINE high = min ( i , j ) NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = ( low + high ) >> 1 NEW_LINE DEDENT
if sum of this submatrix >= k then new search space will be [ low , mid ]
if ( subMatrixSum ( i , j , mid ) >= k ) : NEW_LINE INDENT high = mid NEW_LINE DEDENT
else new search space will be [ mid + 1 , high ]
else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT
Adding the total submatrices
if ( subMatrixSum ( i , j , low ) >= k ) : NEW_LINE INDENT answer += ( min ( i , j ) - low + 1 ) NEW_LINE DEDENT return answer NEW_LINE
Driver Code
if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE M = 3 NEW_LINE A = [ 1 , 2 ] NEW_LINE B = [ 1 , 2 , 3 ] NEW_LINE K = 1 NEW_LINE print ( numberOfWays ( A , B , N , M , K ) ) NEW_LINE DEDENT
Function to return the lexicographically smallest string that can be formed by swapping at most one character . The characters might not necessarily be adjacent .
def findSmallest ( s ) : NEW_LINE INDENT length = len ( s ) ; NEW_LINE DEDENT
Set - 1 as default for every character .
loccur = [ - 1 ] * 26 ; NEW_LINE for i in range ( length - 1 , - 1 , - 1 ) : NEW_LINE
Character index to fill in the last occurrence array
chI = ord ( s [ i ] ) - ord ( ' a ' ) ; NEW_LINE if ( loccur [ chI ] == - 1 ) : NEW_LINE
If this is true then this character is being visited for the first time from the last Thus last occurrence of this character is stored in this index
loccur [ chI ] = i ; NEW_LINE sorted_s = s ; NEW_LINE sorted_s . sort ( ) ; NEW_LINE for i in range ( length ) : NEW_LINE if ( s [ i ] != sorted_s [ i ] ) : NEW_LINE
Character to replace
chI = ord ( sorted_s [ i ] ) - ord ( ' a ' ) ; NEW_LINE
Find the last occurrence of this character .
last_occ = loccur [ chI ] ; NEW_LINE
Swap this with the last occurrence swap ( s [ i ] , s [ last_occ ] ) ;
s [ i ] , s [ last_occ ] = s [ last_occ ] , s [ i ] NEW_LINE break ; NEW_LINE return " " . join ( s ) ; NEW_LINE
Driver code
if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " geeks " ; NEW_LINE print ( findSmallest ( list ( s ) ) ) ; NEW_LINE DEDENT
Function to preprocess the matrix for computing the sum of every possible matrix of the given size
def preProcess ( mat , aux ) : NEW_LINE
Loop to copy the first row of the matrix into the aux matrix
for i in range ( 5 ) : NEW_LINE INDENT aux [ 0 ] [ i ] = mat [ 0 ] [ i ] NEW_LINE DEDENT
Computing the sum column - wise
for i in range ( 1 , 4 ) : NEW_LINE INDENT for j in range ( 5 ) : NEW_LINE INDENT aux [ i ] [ j ] = ( mat [ i ] [ j ] + aux [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT
Computing row wise sum
for i in range ( 4 ) : NEW_LINE INDENT for j in range ( 1 , 5 ) : NEW_LINE INDENT aux [ i ] [ j ] += aux [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT return aux NEW_LINE
Function to find the sum of a submatrix with the given indices
def sumQuery ( aux , tli , tlj , rbi , rbj ) : NEW_LINE
Overall sum from the top to right corner of matrix
res = aux [ rbi ] [ rbj ] NEW_LINE
Removing the sum from the top corer of the matrix
if ( tli > 0 ) : NEW_LINE INDENT res = res - aux [ tli - 1 ] [ rbj ] NEW_LINE DEDENT
Remove the overlapping sum
if ( tlj > 0 ) : NEW_LINE INDENT res = res - aux [ rbi ] [ tlj - 1 ] NEW_LINE DEDENT
Add the sum of top corner which is subtracted twice
if ( tli > 0 and tlj > 0 ) : NEW_LINE INDENT res = res + aux [ tli - 1 ] [ tlj - 1 ] NEW_LINE DEDENT return res NEW_LINE
Function to check whether square sub matrices of size mid satisfy the condition or not
def check ( mid , aux , K ) : NEW_LINE INDENT satisfies = True NEW_LINE DEDENT
Iterating throught all possible submatrices of given size
for x in range ( 4 ) : NEW_LINE INDENT for y in range ( 5 ) : NEW_LINE INDENT if ( x + mid - 1 <= 4 - 1 and y + mid - 1 <= 5 - 1 ) : NEW_LINE INDENT if ( sumQuery ( aux , x , y , x + mid - 1 , y + mid - 1 ) > K ) : NEW_LINE INDENT satisfies = False NEW_LINE DEDENT DEDENT DEDENT DEDENT return True if satisfies == True else False NEW_LINE
Function to find the maximum square size possible with the such that every submatrix have sum less than the given sum
def maximumSquareSize ( mat , K ) : NEW_LINE INDENT aux = [ [ 0 for i in range ( 5 ) ] for i in range ( 4 ) ] NEW_LINE aux = preProcess ( mat , aux ) NEW_LINE DEDENT
Search space
low , high = 1 , min ( 4 , 5 ) NEW_LINE mid = 0 NEW_LINE
Binary search for size
while ( high - low > 1 ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE DEDENT
Check if the mid satisfies the given condition
if ( check ( mid , aux , K ) ) : NEW_LINE INDENT low = mid NEW_LINE DEDENT else : NEW_LINE INDENT high = mid NEW_LINE DEDENT if ( check ( high , aux , K ) ) : NEW_LINE return high NEW_LINE return low NEW_LINE
Driver Code
if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 30 NEW_LINE mat = [ [ 1 , 2 , 3 , 4 , 6 ] , [ 5 , 3 , 8 , 1 , 2 ] , [ 4 , 6 , 7 , 5 , 5 ] , [ 2 , 4 , 8 , 9 , 4 ] ] NEW_LINE print ( maximumSquareSize ( mat , K ) ) NEW_LINE DEDENT
Initialize array for segment tree
segment_tree = [ 0 ] * ( 4 * 1000000 ) ; NEW_LINE
Function that builds the segment tree to return the max element in a range
def build ( A , start , end , node ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE DEDENT
update the value in segment tree from given array
segment_tree [ node ] = A [ start ] ; NEW_LINE else : NEW_LINE
find the middle index
mid = ( start + end ) // 2 ; NEW_LINE
If there are more than one elements , then recur for left and right subtrees and store the max of values in this node
segment_tree [ node ] = max ( build ( A , start , mid , 2 * node + 1 ) , build ( A , mid + 1 , end , 2 * node + 2 ) ) ; NEW_LINE return segment_tree [ node ] ; NEW_LINE
Function to return the max element in the given range
def query ( start , end , l , r , node ) : NEW_LINE
If the range is out of bounds , return - 1
if ( start > r or end < l ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( start >= l and end <= r ) : NEW_LINE INDENT return segment_tree [ node ] ; NEW_LINE DEDENT mid = ( start + end ) // 2 ; NEW_LINE return max ( query ( start , mid , l , r , 2 * node + 1 ) , query ( mid + 1 , end , l , r , 2 * node + 2 ) ) ; NEW_LINE
Function that returns length of longest subarray with same elements in atmost K increments .
def longestSubArray ( A , N , K ) : NEW_LINE
Initialize the result variable Even though the K is 0 , the required longest subarray , in that case , will also be of length 1
res = 1 ; NEW_LINE
Initialize the prefix sum array
preSum = [ 0 ] * ( N + 1 ) ; NEW_LINE
Build the prefix sum array
preSum [ 0 ] = A [ 0 ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT preSum [ i + 1 ] = preSum [ i ] + A [ i ] ; NEW_LINE DEDENT