text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Interchange elements of first and last rows in matrix | Python code to swap the element of first and last row and display the result ; swapping of element between first and last rows ; input in the array ; printing the interchanged matrix | def interchangeFirstLast ( mat , n , m ) : NEW_LINE INDENT rows = n NEW_LINE for i in range ( n ) : NEW_LINE INDENT t = mat [ 0 ] [ i ] NEW_LINE mat [ 0 ] [ i ] = mat [ rows - 1 ] [ i ] NEW_LINE mat [ rows - 1 ] [ i ] = t NEW_LINE DEDENT DEDENT mat = [ [ 8 , 9 , 7 , 6 ] , [ 4 , 7 , 6 , 5 ] , [ 3 , 2 , 1 , 8 ] , [ 9 , 9... |
Construct Binary Tree from given Parent Array representation | A node structure ; Creates a node with key as ' i ' . If i is root , then it changes root . If parent of i is not created , then it creates parent first ; If this node is already created ; Create a new node and set created [ i ] ; If ' i ' is root , change ... | class Node : 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 createNode ( parent , i , created , root ) : NEW_LINE INDENT if created [ i ] is not None : NEW_LINE INDENT return NEW_LINE DEDENT created [ i ]... |
Row wise sorting in 2D array | Python3 code to sort 2D matrix row - wise ; loop for rows of matrix ; loop for column of matrix ; loop for comparison and swapping ; swapping of elements ; printing the sorted matrix ; Driver code | def sortRowWise ( m ) : NEW_LINE INDENT for i in range ( len ( m ) ) : NEW_LINE INDENT for j in range ( len ( m [ i ] ) ) : NEW_LINE INDENT for k in range ( len ( m [ i ] ) - j - 1 ) : NEW_LINE INDENT if ( m [ i ] [ k ] > m [ i ] [ k + 1 ] ) : NEW_LINE INDENT t = m [ i ] [ k ] NEW_LINE m [ i ] [ k ] = m [ i ] [ k + 1 ]... |
Row wise sorting in 2D array | Python3 code to sort 2D matrix row - wise ; One by one sort individual rows . ; printing the sorted matrix ; Driver code | def sortRowWise ( m ) : NEW_LINE INDENT for i in range ( len ( m ) ) : NEW_LINE INDENT m [ i ] . sort ( ) NEW_LINE DEDENT for i in range ( len ( m ) ) : NEW_LINE INDENT for j in range ( len ( m [ i ] ) ) : NEW_LINE INDENT print ( m [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT return 0 NEW_LINE ... |
Program for Markov matrix | Python 3 code to check Markov Matrix ; Outer loop to access rows and inner to access columns ; Find sum of current row ; Matrix to check ; Calls the function check ( ) | def checkMarkov ( m ) : NEW_LINE INDENT for i in range ( 0 , len ( m ) ) : NEW_LINE INDENT sm = 0 NEW_LINE for j in range ( 0 , len ( m [ i ] ) ) : NEW_LINE INDENT sm = sm + m [ i ] [ j ] NEW_LINE DEDENT if ( sm != 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT m = [ [ 0 , 0 , 1 ]... |
Program to check diagonal matrix and scalar matrix | Python3 Program to check if matrix is diagonal matrix or not . ; Function to check matrix is diagonal matrix or not . ; condition to check other elements except main diagonal are zero or not . ; Driver function | N = 4 NEW_LINE def isDiagonalMatrix ( mat ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT if ( ( i != j ) and ( mat [ i ] [ j ] != 0 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT mat = [ [ 4 , 0 , 0 , 0 ] , [ 0 , 7 ... |
Program to check diagonal matrix and scalar matrix | Program to check matrix is scalar matrix or not . ; Function to check matrix is scalar matrix or not . ; Check all elements except main diagonal are zero or not . ; Check all diagonal elements are same or not . ; Driver function ; Function call | N = 4 NEW_LINE def isScalarMatrix ( mat ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT if ( ( i != j ) and ( mat [ i ] [ j ] != 0 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT for i in range ( 0 , N - 1 ) : NEW_LINE INDENT if ( mat [ i ] [ i ... |
Construct a Binary Tree from Postorder and Inorder | Recursive function to construct binary of size n from Inorder traversal in [ ] and Postorder traversal post [ ] . Initial values of inStrt and inEnd should be 0 and n - 1. The function doesn 't do any error checking for cases where inorder and postorder do not form a... | def buildUtil ( In , post , inStrt , inEnd , pIndex ) : NEW_LINE INDENT if ( inStrt > inEnd ) : NEW_LINE INDENT return None NEW_LINE DEDENT node = newNode ( post [ pIndex [ 0 ] ] ) NEW_LINE pIndex [ 0 ] -= 1 NEW_LINE if ( inStrt == inEnd ) : NEW_LINE INDENT return node NEW_LINE DEDENT iIndex = search ( In , inStrt , in... |
Check given matrix is magic square or not | Python3 program to check whether a given matrix is magic matrix or not ; Returns true if mat [ ] [ ] is magic square , else returns false . ; calculate the sum of the prime diagonal ; the secondary diagonal ; For sums of Rows ; check if every row sum is equal to prime diagona... | N = 3 NEW_LINE def isMagicSquare ( mat ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT s = s + mat [ i ] [ i ] NEW_LINE DEDENT s2 = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT s2 = s2 + mat [ i ] [ N - i - 1 ] NEW_LINE DEDENT if ( s != s2 ) : NEW_LINE INDENT return False NEW_LINE... |
Count sub | function to count all sub - arrays divisible by k ; create auxiliary hash array to count frequency of remainders ; Traverse original array and compute cumulative sum take remainder of this current cumulative sum and increase count by 1 for this remainder in mod array ; as the sum can be negative , taking mo... | def subCount ( arr , n , k ) : NEW_LINE INDENT mod = [ 0 ] * k ; NEW_LINE cumSum = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT cumSum = cumSum + arr [ i ] ; NEW_LINE mod [ ( ( cumSum % k ) + k ) % k ] = mod [ ( ( cumSum % k ) + k ) % k ] + 1 ; NEW_LINE DEDENT result = 0 ; NEW_LINE for i in range ( 0 , k ) :... |
Minimum operations required to make each row and column of matrix equals | Function to find minimum operation required to make sum of each row and column equals ; Initialize the sumRow [ ] and sumCol [ ] array to 0 ; Calculate sumRow [ ] and sumCol [ ] array ; Find maximum sum value in either row or in column ; Find mi... | def findMinOpeartion ( matrix , n ) : NEW_LINE INDENT sumRow = [ 0 ] * n NEW_LINE sumCol = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT sumRow [ i ] += matrix [ i ] [ j ] NEW_LINE sumCol [ j ] += matrix [ i ] [ j ] NEW_LINE DEDENT DEDENT maxSum = 0 NEW_LINE for i in r... |
Count frequency of k in a matrix of size n where matrix ( i , j ) = i + j | Python program to find the frequency of k in matrix where m ( i , j ) = i + j ; Driver Code | import math NEW_LINE def find ( n , k ) : NEW_LINE INDENT if ( n + 1 >= k ) : NEW_LINE INDENT return ( k - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( 2 * n + 1 - k ) NEW_LINE DEDENT DEDENT n = 4 NEW_LINE k = 7 NEW_LINE freq = find ( n , k ) NEW_LINE if ( freq < 0 ) : NEW_LINE INDENT print ( " β element β not β... |
Given 1 ' s , β 2' s , 3 ' s β . . . . . . k ' s print them in zig zag way . | function that prints given number of 1 ' s , β 2' s , 3 ' s β . . . . k ' s in zig - zag way . ; two - dimensional array to store numbers . ; for even row . ; for each column . ; storing element . ; decrement element at kth index . ; if arra... | def ZigZag ( rows , columns , numbers ) : NEW_LINE INDENT k = 0 NEW_LINE arr = [ [ 0 for i in range ( columns ) ] for j in range ( rows ) ] NEW_LINE for i in range ( rows ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT j = 0 NEW_LINE while j < columns and numbers [ k ] > 0 : NEW_LINE INDENT arr [ i ] [ j ] = k ... |
Maximum product of 4 adjacent elements in matrix | Python3 program to find out the maximum product in the matrix which four elements are adjacent to each other in one direction ; function to find max product ; iterate the rows . ; iterate the columns . ; check the maximum product in horizontal row . ; check the maximum... | n = 5 NEW_LINE def FindMaxProduct ( arr , n ) : NEW_LINE INDENT max = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ( j - 3 ) >= 0 ) : NEW_LINE INDENT result = ( arr [ i ] [ j ] * arr [ i ] [ j - 1 ] * arr [ i ] [ j - 2 ] * arr [ i ] [ j - 3 ] ) NEW_LINE if ( max < result... |
Construct a Binary Tree from Postorder and Inorder | A binary tree node has data , pointer to left child and a pointer to right child ; Recursive function to construct binary of size n from Inorder traversal in [ ] and Postorder traversal post [ ] . Initial values of inStrt and inEnd should be 0 and n - 1. The function... | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def buildUtil ( inn , post , innStrt , innEnd ) : NEW_LINE INDENT global mp , index NEW_LINE if ( innStrt > innEnd ) : NEW_LINE INDENT return None NEW_... |
Minimum flip required to make Binary Matrix symmetric | Python3 code to find minimum flip required to make Binary Matrix symmetric along main diagonal ; Return the minimum flip required to make Binary Matrix symmetric along main diagonal . ; finding the transpose of the matrix ; Finding the number of position where ele... | N = 3 NEW_LINE def minimumflip ( mat , n ) : NEW_LINE INDENT transpose = [ [ 0 ] * n ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT transpose [ i ] [ j ] = mat [ j ] [ i ] NEW_LINE DEDENT DEDENT flip = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) :... |
Minimum flip required to make Binary Matrix symmetric | Python3 code to find minimum flip required to make Binary Matrix symmetric along main diagonal ; Return the minimum flip required to make Binary Matrix symmetric along main diagonal . ; Comparing elements across diagonal ; Driver Program | N = 3 NEW_LINE def minimumflip ( mat , n ) : NEW_LINE INDENT flip = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if mat [ i ] [ j ] != mat [ j ] [ i ] : NEW_LINE INDENT flip += 1 NEW_LINE DEDENT DEDENT DEDENT return flip NEW_LINE DEDENT n = 3 NEW_LINE mat = [ [ 0 , 0 , 1 ] , ... |
Frequencies of even and odd numbers in a matrix | Python Program to Find the frequency of even and odd numbers in a matrix ; Function for calculating frequency ; modulo by 2 to check even and odd ; print Frequency of numbers ; Driver code | MAX = 100 NEW_LINE def freq ( ar , m , n ) : NEW_LINE INDENT even = 0 NEW_LINE odd = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ( ar [ i ] [ j ] % 2 ) == 0 ) : NEW_LINE INDENT even += 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT DEDENT DEDENT print... |
Center element of matrix equals sums of half diagonals | Python 3 Program to check if the center element is equal to the individual sum of all the half diagonals ; Function to Check center element is equal to the individual sum of all the half diagonals ; Find sums of half diagonals ; Driver code | MAX = 100 NEW_LINE def HalfDiagonalSums ( mat , n ) : NEW_LINE INDENT diag1_left = 0 NEW_LINE diag1_right = 0 NEW_LINE diag2_left = 0 NEW_LINE diag2_right = 0 NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE while i < n : NEW_LINE INDENT if ( i < n // 2 ) : NEW_LINE INDENT diag1_left += mat [ i ] [ i ] NEW_LINE diag2_left +=... |
Program for Identity Matrix | Python code to print identity matrix Function to print identity matrix ; Here end is used to stay in same line ; Driver Code | def Identity ( size ) : NEW_LINE INDENT for row in range ( 0 , size ) : NEW_LINE INDENT for col in range ( 0 , size ) : NEW_LINE INDENT if ( row == col ) : NEW_LINE INDENT print ( "1 β " , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( "0 β " , end = " β " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDEN... |
Program for Identity Matrix | Python3 program to check if a given matrix is identity ; Driver Code | MAX = 100 ; NEW_LINE def isIdentity ( mat , N ) : NEW_LINE INDENT for row in range ( N ) : NEW_LINE INDENT for col in range ( N ) : NEW_LINE INDENT if ( row == col and mat [ row ] [ col ] != 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT elif ( row != col and mat [ row ] [ col ] != 0 ) : NEW_LINE INDENT return Fa... |
Ways of filling matrix such that product of all rows and all columns are equal to unity | Returns a raised power t under modulo mod ; Counting number of ways of filling the matrix ; Function calculating the answer ; if sum of numbers of rows and columns is odd i . e ( n + m ) % 2 == 1 and k = - 1 then there are 0 ways ... | def modPower ( a , t ) : NEW_LINE INDENT now = a ; NEW_LINE ret = 1 ; NEW_LINE mod = 100000007 ; NEW_LINE while ( t ) : NEW_LINE INDENT if ( t & 1 ) : NEW_LINE INDENT ret = now * ( ret % mod ) ; NEW_LINE DEDENT now = now * ( now % mod ) ; NEW_LINE t >>= 1 ; NEW_LINE DEDENT return ret ; NEW_LINE DEDENT def countWays ( n... |
Mirror of matrix across diagonal | Simple Python3 program to find mirror of matrix across diagonal . ; for diagonal which start from at first row of matrix ; traverse all top right diagonal ; here we use stack for reversing the element of diagonal ; push all element back to matrix in reverse order ; do the same process... | MAX = 100 NEW_LINE def imageSwap ( mat , n ) : NEW_LINE INDENT row = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT s = [ ] NEW_LINE i = row NEW_LINE k = j NEW_LINE while ( i < n and k >= 0 ) : NEW_LINE INDENT s . append ( mat [ i ] [ k ] ) NEW_LINE i += 1 NEW_LINE k -= 1 NEW_LINE DEDENT i = row NEW_LINE k = j NEW_L... |
Mirror of matrix across diagonal | Efficient Python3 program to find mirror of matrix across diagonal . ; traverse a matrix and swap mat [ i ] [ j ] with mat [ j ] [ i ] ; Utility function to pra matrix ; Driver code | from builtins import range NEW_LINE MAX = 100 ; NEW_LINE def imageSwap ( mat , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT t = mat [ i ] [ j ] ; NEW_LINE mat [ i ] [ j ] = mat [ j ] [ i ] NEW_LINE mat [ j ] [ i ] = t NEW_LINE DEDENT DEDENT DEDENT def printMatr... |
Find all rectangles filled with 0 | Python program to find all rectangles filled with 0 ; flag to check column edge case , initializing with 0 ; flag to check row edge case , initializing with 0 ; loop breaks where first 1 encounters ; set the flag ; pass because already processed ; loop breaks where first 1 encounters... | def findend ( i , j , a , output , index ) : NEW_LINE INDENT x = len ( a ) NEW_LINE y = len ( a [ 0 ] ) NEW_LINE flagc = 0 NEW_LINE flagr = 0 NEW_LINE for m in range ( i , x ) : NEW_LINE INDENT if a [ m ] [ j ] == 1 : NEW_LINE INDENT flagr = 1 NEW_LINE break NEW_LINE DEDENT if a [ m ] [ j ] == 5 : NEW_LINE INDENT pass ... |
Search in a row wise and column wise sorted matrix | Searches the element x in mat [ ] [ ] . If the element is found , then prints its position and returns true , otherwise prints " not β found " and returns false ; Traverse through the matrix ; If the element is found ; Driver code | def search ( mat , n , x ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == x ) : NEW_LINE INDENT print ( " Element β found β at β ( " , i , " , " , j , " ) " ) NEW_LINE return 1 NEW_LINE DE... |
Search in a row wise and column wise sorted matrix | Searches the element x in mat [ ] [ ] . If the element is found , then prints its position and returns true , otherwise prints " not β found " and returns false ; set indexes for top right element ; if mat [ i ] [ j ] < x ; if ( i == n j == - 1 ) ; Driver Code | def search ( mat , n , x ) : NEW_LINE INDENT i = 0 NEW_LINE j = n - 1 NEW_LINE while ( i < n and j >= 0 ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == x ) : NEW_LINE INDENT print ( " n β Found β at β " , i , " , β " , j ) NEW_LINE return 1 NEW_LINE DEDENT if ( mat [ i ] [ j ] > x ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT... |
Create a matrix with alternating rectangles of O and X | Function to pralternating rectangles of 0 and X ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; Store given number of rows and columns for later use ; A 2D array to store the output to be printed ; In... | def fill0X ( m , n ) : NEW_LINE INDENT i , k , l = 0 , 0 , 0 NEW_LINE r = m NEW_LINE c = n NEW_LINE a = [ [ None ] * n for i in range ( m ) ] NEW_LINE x = ' X ' NEW_LINE while k < m and l < n : NEW_LINE INDENT for i in range ( l , n ) : NEW_LINE INDENT a [ k ] [ i ] = x NEW_LINE DEDENT k += 1 NEW_LINE for i in range ( ... |
Zigzag ( or diagonal ) traversal of Matrix | ; we will use a 2D vector to store the diagonals of our array the 2D vector will have ( n + m - 1 ) rows that is equal to the number of diagnols ; Driver Code ; Function call | R = 5 NEW_LINE C = 5 NEW_LINE def diagonalOrder ( arr , n , m ) : NEW_LINE INDENT ans = [ [ ] for i in range ( n + m - 1 ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT ans [ i + j ] . append ( arr [ j ] [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( ans ) ) : NEW_LINE ... |
Minimum cost to sort a matrix of numbers from 0 to n ^ 2 | implementation to find the total energy required to rearrange the numbers ; function to find the total energy required to rearrange the numbers ; nested loops to access the elements of the given matrix ; store quotient ; final destination location ( i_des , j_d... | n = 4 NEW_LINE def calculateEnergy ( mat , n ) : NEW_LINE INDENT tot_energy = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT q = mat [ i ] [ j ] // n NEW_LINE i_des = q NEW_LINE j_des = mat [ i ] [ j ] - ( n * q ) NEW_LINE tot_energy += ( abs ( i_des - i ) + abs ( j_des - j ) )... |
Unique cells in a binary matrix | Python3 program to count unique cells in a matrix ; Returns true if mat [ i ] [ j ] is unique ; checking in row calculating sumrow will be moving column wise ; checking in column calculating sumcol will be moving row wise ; Driver code | MAX = 100 NEW_LINE def isUnique ( mat , i , j , n , m ) : NEW_LINE INDENT sumrow = 0 NEW_LINE for k in range ( m ) : NEW_LINE INDENT sumrow += mat [ i ] [ k ] NEW_LINE if ( sumrow > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT sumcol = 0 NEW_LINE for k in range ( n ) : NEW_LINE INDENT sumcol += mat [ k ] [... |
Unique cells in a binary matrix | Efficient Python3 program to count unique cells in a binary matrix ; Count number of 1 s in each row and in each column ; Using above count arrays , find cells ; Driver code | MAX = 100 ; NEW_LINE def countUnique ( mat , n , m ) : NEW_LINE INDENT rowsum = [ 0 ] * n ; NEW_LINE colsum = [ 0 ] * m ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != 0 ) : NEW_LINE INDENT rowsum [ i ] += 1 ; NEW_LINE colsum [ j ] += 1 ; NEW_LINE DEDENT ... |
Check if a given matrix is sparse or not | Python 3 code to check if a matrix is sparse . ; Count number of zeros in the matrix ; Driver Function | MAX = 100 NEW_LINE def isSparse ( array , m , n ) : NEW_LINE INDENT counter = 0 NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( array [ i ] [ j ] == 0 ) : NEW_LINE INDENT counter = counter + 1 NEW_LINE DEDENT DEDENT DEDENT return ( counter > ( ( m * n ) // 2 ) ) NEW_L... |
Row | Python3 program to find common elements in two diagonals . ; Returns count of row wise same elements in two diagonals of mat [ n ] [ n ] ; Driver Code | Max = 100 NEW_LINE def countCommon ( mat , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if mat [ i ] [ i ] == mat [ i ] [ n - i - 1 ] : NEW_LINE INDENT res = res + 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE print ... |
Check if sums of i | Python3 program to check the if sum of a row is same as corresponding column ; Function to check the if sum of a row is same as corresponding column ; number of rows ; number of columns | MAX = 100 ; NEW_LINE def areSumSame ( a , n , m ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE for j in range ( 0 , m ) : NEW_LINE INDENT sum1 += a [ i ] [ j ] NEW_LINE sum2 += a [ j ] [ i ] NEW_LINE DEDENT if ( sum1 == sum2 ) : NEW... |
Creating a tree with Left | Creating new Node ; Adds a sibling to a list with starting with n ; Add child Node to a Node ; Check if child list is not empty . ; Traverses tree in depth first order ; Driver code | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . Next = self . child = None NEW_LINE self . data = data NEW_LINE DEDENT DEDENT def addSibling ( n , data ) : NEW_LINE INDENT if ( n == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT while ( n . Next ) : NEW_LINE INDENT n = n . Ne... |
Find row number of a binary matrix having maximum number of 1 s | python program to find row with maximum 1 in row sorted binary matrix ; function for finding row with maximum 1 ; find left most position of 1 in a row find 1 st zero in a row ; driver program | N = 4 NEW_LINE def findMax ( arr ) : NEW_LINE INDENT row = 0 NEW_LINE j = N - 1 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT while ( arr [ i ] [ j ] == 1 and j >= 0 ) : NEW_LINE INDENT row = i NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT print ( " Row β number β = β " , row + 1 , " , β MaxCount β = β " , N - 1 - j ) N... |
Program to Print Matrix in Z form | Python3 program to pra square matrix in Z form ; Driver code | def diag ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT elif ( i == j ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT elif ( i == n - 1 ) : NEW... |
Print all palindromic paths from top left to bottom right in a matrix | Python 3 program to print all palindromic paths from top left to bottom right in a grid . ; i and j are row and column indexes of current cell ( initially these are 0 and 0 ) . ; If we have not reached bottom right corner , keep exlporing ; If we r... | def isPalin ( str ) : NEW_LINE INDENT l = len ( str ) // 2 NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( str [ i ] != str [ len ( str ) - i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def palindromicPath ( str , a , i , j , m , n ) : NEW_LINE INDENT if ( j < m - 1 or... |
Possible moves of knight | Python3 program to find number of possible moves of knight ; To calculate possible moves ; All possible moves of a knight ; Check if each possible move is valid or not ; Position of knight after move ; count valid moves ; Return number of possible moves ; Driver code | n = 4 ; NEW_LINE m = 4 ; NEW_LINE def findPossibleMoves ( mat , p , q ) : NEW_LINE INDENT global n , m ; NEW_LINE X = [ 2 , 1 , - 1 , - 2 , - 2 , - 1 , 1 , 2 ] ; NEW_LINE Y = [ 1 , 2 , 2 , 1 , - 1 , - 2 , - 2 , - 1 ] ; NEW_LINE count = 0 ; NEW_LINE for i in range ( 8 ) : NEW_LINE INDENT x = p + X [ i ] ; NEW_LINE y = q... |
Efficiently compute sums of diagonals of a matrix | A simple Python program to find sum of diagonals ; Condition for principal diagonal ; Condition for secondary diagonal ; Driver code | MAX = 100 NEW_LINE def printDiagonalSums ( mat , n ) : NEW_LINE INDENT principal = 0 NEW_LINE secondary = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT principal += mat [ i ] [ j ] NEW_LINE DEDENT if ( ( i + j ) == ( n - 1 ) ) : NEW_LI... |
Efficiently compute sums of diagonals of a matrix | A simple Python3 program to find sum of diagonals ; Driver code | MAX = 100 NEW_LINE def printDiagonalSums ( mat , n ) : NEW_LINE INDENT principal = 0 NEW_LINE secondary = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT principal += mat [ i ] [ i ] NEW_LINE secondary += mat [ i ] [ n - i - 1 ] NEW_LINE DEDENT print ( " Principal β Diagonal : " , principal ) NEW_LINE print ( " S... |
Creating a tree with Left | Python3 program to create a tree with left child right sibling representation ; Creating new Node ; Adds a sibling to a list with starting with n ; Add child Node to a Node ; Check if child list is not empty ; Traverses tree in level order ; Corner cases ; Create a queue and enque root ; Tak... | from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE self . child = None NEW_LINE DEDENT DEDENT def addSibling ( n , data ) : NEW_LINE INDENT if ( n == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT whi... |
Boundary elements of a Matrix | Python program to print boundary element of the matrix . ; Driver code | MAX = 100 NEW_LINE def printBoundary ( a , m , n ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT print a [ i ] [ j ] , NEW_LINE DEDENT elif ( i == m - 1 ) : NEW_LINE INDENT print a [ i ] [ j ] , NEW_LINE DEDENT elif ( j == 0 ) : NEW_LINE ... |
Boundary elements of a Matrix | Python program to print boundary element of the matrix . ; Driver code | MAX = 100 NEW_LINE def printBoundary ( a , m , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT sum += a [ i ] [ j ] NEW_LINE DEDENT elif ( i == m - 1 ) : NEW_LINE INDENT sum += a [ i ] [ j ] NEW_LINE DEDENT elif ( j == ... |
Print a matrix in a spiral form starting from a point | Python3 program to print a matrix in spiral form . ; Driver code ; Function calling | MAX = 100 NEW_LINE def printSpiral ( mat , r , c ) : NEW_LINE INDENT a = 0 NEW_LINE b = 2 NEW_LINE low_row = 0 if ( 0 > a ) else a NEW_LINE low_column = 0 if ( 0 > b ) else b - 1 NEW_LINE high_row = r - 1 if ( ( a + 1 ) >= r ) else a + 1 NEW_LINE high_column = c - 1 if ( ( b + 1 ) >= c ) else b + 1 NEW_LINE while ( ( l... |
Program to Interchange Diagonals of Matrix | Python program to interchange the diagonals of matrix ; Function to interchange diagonals ; swap elements of diagonal ; Driver Code | N = 3 ; NEW_LINE def interchangeDiagonals ( array ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if ( i != N / 2 ) : NEW_LINE INDENT temp = array [ i ] [ i ] ; NEW_LINE array [ i ] [ i ] = array [ i ] [ N - i - 1 ] ; NEW_LINE array [ i ] [ N - i - 1 ] = temp ; NEW_LINE DEDENT DEDENT for i in range ( N ) : N... |
Find difference between sums of two diagonals | Python3 program to find the difference between the sum of diagonal . ; Initialize sums of diagonals ; finding sum of primary diagonal ; finding sum of secondary diagonal ; Absolute difference of the sums across the diagonals ; Driver Code | def difference ( arr , n ) : NEW_LINE INDENT d1 = 0 NEW_LINE d2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT d1 += arr [ i ] [ j ] NEW_LINE DEDENT if ( i == n - j - 1 ) : NEW_LINE INDENT d2 += arr [ i ] [ j ] NEW_LINE DEDENT DEDENT DE... |
Find difference between sums of two diagonals | Python3 program to find the difference between the sum of diagonal . ; Initialize sums of diagonals ; Absolute difference of the sums across the diagonals ; Driver Code | def difference ( arr , n ) : NEW_LINE INDENT d1 = 0 NEW_LINE d2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT d1 = d1 + arr [ i ] [ i ] NEW_LINE d2 = d2 + arr [ i ] [ n - i - 1 ] NEW_LINE DEDENT return abs ( d1 - d2 ) NEW_LINE DEDENT n = 3 NEW_LINE arr = [ [ 11 , 2 , 4 ] , [ 4 , 5 , 6 ] , [ 10 , 8 , - 12 ] ] ... |
Circular Matrix ( Construct a matrix with numbers 1 to m * n in spiral way ) | Fills a [ m ] [ n ] with values from 1 to m * n in spiral fashion . ; Initialize value to be filled in matrix . ; k - starting row index m - ending row index l - starting column index n - ending column index ; Print the first row from the re... | def spiralFill ( m , n , a ) : NEW_LINE INDENT val = 1 NEW_LINE k , l = 0 , 0 NEW_LINE while ( k < m and l < n ) : NEW_LINE INDENT for i in range ( l , n ) : NEW_LINE INDENT a [ k ] [ i ] = val NEW_LINE val += 1 NEW_LINE DEDENT k += 1 NEW_LINE for i in range ( k , m ) : NEW_LINE INDENT a [ i ] [ n - 1 ] = val NEW_LINE ... |
Prufer Code to Tree Creation | Prints edges of tree represented by give Prufer code ; Initialize the array of vertices ; Number of occurrences of vertex in code ; Find the smallest label not present in prufer . ; If j + 1 is not present in prufer set ; Remove from Prufer set and print pair . ; For the last element ; Dr... | def printTreeEdges ( prufer , m ) : NEW_LINE INDENT vertices = m + 2 NEW_LINE vertex_set = [ 0 ] * vertices NEW_LINE for i in range ( vertices - 2 ) : NEW_LINE INDENT vertex_set [ prufer [ i ] - 1 ] += 1 NEW_LINE DEDENT print ( " The β edge β set β E ( G ) β is β : " ) NEW_LINE j = 0 NEW_LINE for i in range ( vertices ... |
Maximum and Minimum in a square matrix . | Python3 program for finding MAXimum and MINimum in a matrix . ; Finds MAXimum and MINimum in arr [ 0. . n - 1 ] [ 0. . n - 1 ] using pair wise comparisons ; Traverses rows one by one ; Compare elements from beginning and end of current row ; Driver Code | MAX = 100 NEW_LINE def MAXMIN ( arr , n ) : NEW_LINE INDENT MIN = 10 ** 9 NEW_LINE MAX = - 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n // 2 + 1 ) : NEW_LINE INDENT if ( arr [ i ] [ j ] > arr [ i ] [ n - j - 1 ] ) : NEW_LINE INDENT if ( MIN > arr [ i ] [ n - j - 1 ] ) : NEW_LINE INDENT MIN... |
Print matrix in antispiral form | Python 3 program to print matrix in anti - spiral form ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; Print the first row from the remaining rows ; Print the last column from the remaining columns ; Print the last row from... | R = 4 NEW_LINE C = 5 NEW_LINE def antiSpiralTraversal ( m , n , a ) : NEW_LINE INDENT k = 0 NEW_LINE l = 0 NEW_LINE stk = [ ] NEW_LINE while ( k <= m and l <= n ) : NEW_LINE INDENT for i in range ( l , n + 1 ) : NEW_LINE INDENT stk . append ( a [ k ] [ i ] ) NEW_LINE DEDENT k += 1 NEW_LINE for i in range ( k , m + 1 ) ... |
Minimum operations required to set all elements of binary matrix | Return minimum operation required to make all 1 s . ; check if this cell equals 0 ; increase the number of moves ; flip from this cell to the start point ; flip the cell ; Driver Code | def minOperation ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( M - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] [ j ] == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE for k in range ( i + 1 ) : NEW_LINE INDENT for h in range ( j + 1 ) : NEW_LINE INDENT ... |
C Program To Check whether Matrix is Skew Symmetric or not | Python 3 program to check whether given matrix is skew - symmetric or not ; Utility function to create transpose matrix ; Utility function to check skew - symmetric matrix condition ; Utility function to print a matrix ; Driver program to test above functions... | ROW = 3 NEW_LINE COL = 3 NEW_LINE def transpose ( transpose_matrix , matrix ) : NEW_LINE INDENT for i in range ( ROW ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT transpose_matrix [ j ] [ i ] = matrix [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT def check ( transpose_matrix , matrix ) : NEW_LINE INDENT for ... |
Sum of matrix element where each elements is integer division of row and column | Return sum of matrix element where each element is division of its corresponding row and column . ; For each column . ; count the number of elements of each column . Initialize to i - 1 because number of zeroes are i - 1. ; For multiply ;... | def findSum ( n ) : NEW_LINE INDENT ans = 0 ; temp = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if temp < n : NEW_LINE INDENT temp = i - 1 NEW_LINE num = 1 NEW_LINE while temp < n : NEW_LINE INDENT if temp + i <= n : NEW_LINE INDENT ans += i * num NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( n - tem... |
Find number of transformation to make two Matrix Equal | Python3 program to find number of countOpsation to make two matrix equals ; Update matrix A [ ] [ ] so that only A [ ] [ ] has to be countOpsed ; Check necessary condition for condition for existence of full countOpsation ; If countOpsation is possible calculate ... | def countOps ( A , B , m , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT A [ i ] [ j ] -= B [ i ] [ j ] ; NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE INDENT if ( A [ i ] [ j ] - A [ i ] [ 0 ] - A [ 0 ] [ j ] ... |
Construct the full k | Python3 program to build full k - ary tree from its preorder traversal and to print the postorder traversal of the tree . ; Utility function to create a new tree node with k children ; Function to build full k - ary tree ; For None tree ; For adding k children to a node ; Check if ind is in range... | from math import ceil , log NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , value ) : NEW_LINE INDENT self . key = value NEW_LINE self . child = [ ] NEW_LINE DEDENT DEDENT def BuildkaryTree ( A , n , k , h , ind ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return None NEW_LINE DEDENT nNode = newNo... |
Form coils in a matrix | Prcoils in a matrix of size 4 n x 4 n ; Number of elements in each coil ; Let us fill elements in coil 1. ; First element of coil1 4 * n * 2 * n + 2 * n ; Fill remaining m - 1 elements in coil1 [ ] ; Fill elements of current step from down to up ; Next element from current element ; Fill elemen... | def printCoils ( n ) : NEW_LINE INDENT m = 8 * n * n NEW_LINE coil1 = [ 0 ] * m NEW_LINE coil1 [ 0 ] = 8 * n * n + 2 * n NEW_LINE curr = coil1 [ 0 ] NEW_LINE nflg = 1 NEW_LINE step = 2 NEW_LINE index = 1 NEW_LINE while ( index < m ) : NEW_LINE INDENT for i in range ( step ) : NEW_LINE INDENT curr = coil1 [ index ] = ( ... |
Sum of matrix in which each element is absolute difference of its row and column numbers | Return the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; Generate matrix ; Compute sum ; Driver Code | def findSum ( n ) : NEW_LINE INDENT arr = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT arr [ i ] [ j ] = abs ( i - j ) NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_L... |
Sum of matrix in which each element is absolute difference of its row and column numbers | Return the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; Driver code | def findSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += i * ( n - i ) NEW_LINE DEDENT return 2 * sum NEW_LINE DEDENT n = 3 NEW_LINE print ( findSum ( n ) ) NEW_LINE |
Sum of matrix in which each element is absolute difference of its row and column numbers | Return the sum of matrix in which each element is absolute difference of its corresponding row and column number row ; Driver Code | def findSum ( n ) : NEW_LINE INDENT n -= 1 NEW_LINE sum = 0 NEW_LINE sum += ( n * ( n + 1 ) ) / 2 NEW_LINE sum += ( n * ( n + 1 ) * ( 2 * n + 1 ) ) / 6 NEW_LINE return int ( sum ) NEW_LINE DEDENT n = 3 NEW_LINE print ( findSum ( n ) ) NEW_LINE |
Sum of both diagonals of a spiral odd | function returns sum of diagonals ; as order should be only odd we should pass only odd integers ; Driver program | def spiralDiaSum ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( 4 * n * n - 6 * n + 6 + spiralDiaSum ( n - 2 ) ) NEW_LINE DEDENT n = 7 ; NEW_LINE print ( spiralDiaSum ( n ) ) NEW_LINE |
Find perimeter of shapes formed with 1 s in binary matrix | Python3 program to find perimeter of area covered by 1 in 2D matrix consisits of 0 ' s β and β 1' s . ; Find the number of covered side for mat [ i ] [ j ] . ; UP ; LEFT ; DOWN ; RIGHT ; Returns sum of perimeter of shapes formed with 1 s ; Traversing the matri... | R = 3 NEW_LINE C = 5 NEW_LINE def numofneighbour ( mat , i , j ) : NEW_LINE INDENT count = 0 ; NEW_LINE if ( i > 0 and mat [ i - 1 ] [ j ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( j > 0 and mat [ i ] [ j - 1 ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( i < R - 1 and mat [ i + 1 ] [ j ] ) : NEW_L... |
Construct Binary Tree from String with bracket representation | Helper class that allocates a new node ; This funtcion is here just to test ; function to return the index of close parenthesis ; Inbuilt stack ; if open parenthesis , push it ; if close parenthesis ; if stack is empty , this is the required index ; if not... | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def preOrder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( node . data , end = " β " ) NEW_LINE preOrder (... |
Print matrix in diagonal pattern | Python 3 program to print matrix in diagonal order ; Initialize indexes of element to be printed next ; Direction is initially from down to up ; Traverse the matrix till all elements get traversed ; If isUp = True then traverse from downward to upward ; Set i and j according to direct... | MAX = 100 NEW_LINE def printMatrixDiagonal ( mat , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE isUp = True NEW_LINE while k < n * n : NEW_LINE INDENT if isUp : NEW_LINE INDENT while i >= 0 and j < n : NEW_LINE INDENT print ( str ( mat [ i ] [ j ] ) , end = " β " ) NEW_LINE k += 1 NEW_LINE j += 1 ... |
Print matrix in diagonal pattern | Initialize matrix ; n - size mode - switch to derive up / down traversal it - iterator count - increases until it reaches n and then decreases ; 2 n will be the number of iterations | mat = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] ; NEW_LINE n = 4 NEW_LINE mode = 0 NEW_LINE it = 0 NEW_LINE lower = 0 NEW_LINE for t in range ( 2 * n - 1 ) : NEW_LINE INDENT t1 = t NEW_LINE if ( t1 >= n ) : NEW_LINE INDENT mode += 1 NEW_LINE t1 = n - 1 NEW_LINE it -= 1 NEW... |
Maximum difference of sum of elements in two rows in a matrix | Function to find maximum difference of sum of elements of two rows such that second row appears before first row . ; auxiliary array to store sum of all elements of each row ; calculate sum of each row and store it in rowSum array ; calculating maximum dif... | def maxRowDiff ( mat , m , n ) : NEW_LINE INDENT rowSum = [ 0 ] * m NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT sum += mat [ i ] [ j ] NEW_LINE DEDENT rowSum [ i ] = sum NEW_LINE DEDENT max_diff = rowSum [ 1 ] - rowSum [ 0 ] NEW_LINE min_element = rowS... |
Total coverage of all zeros in a binary matrix | Python3 program to get total coverage of all zeros in a binary matrix ; Returns total coverage of all zeros in mat [ ] [ ] ; looping for all rows of matrix ; 1 is not seen yet ; looping in columns from left to right direction to get left ones ; If one is found from left ... | R = 4 NEW_LINE C = 4 NEW_LINE def getTotalCoverageOfMatrix ( mat ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( R ) : NEW_LINE INDENT isOne = False NEW_LINE for j in range ( C ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT isOne = True NEW_LINE DEDENT elif ( isOne ) : NEW_LINE INDENT res += 1 ... |
Count all sorted rows in a matrix | Function to count all sorted rows in a matrix ; Initialize result ; Start from left side of matrix to count increasing order rows ; Check if there is any pair ofs element that are not in increasing order . ; If the loop didn 't break (All elements of current row were in increasing or... | def sortedCount ( mat , r , c ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( r ) : NEW_LINE INDENT j = 0 NEW_LINE for j in range ( c - 1 ) : NEW_LINE INDENT if mat [ i ] [ j + 1 ] <= mat [ i ] [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if j == c - 2 : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDE... |
Maximum XOR value in matrix | Python3 program to Find maximum XOR value in matrix either row / column wise maximum number of row and column ; Function return the maximum xor value that is either row or column wise ; For row xor and column xor ; Traverse matrix ; xor row element ; for each column : j is act as row & i a... | MAX = 1000 NEW_LINE def maxXOR ( mat , N ) : NEW_LINE INDENT max_xor = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT r_xor = 0 NEW_LINE c_xor = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT r_xor = r_xor ^ mat [ i ] [ j ] NEW_LINE c_xor = c_xor ^ mat [ j ] [ i ] NEW_LINE DEDENT if ( max_xor < max ( r_xor , c_xo... |
Direction at last square block | Function which tells the Current direction ; Driver code | def direction ( R , C ) : NEW_LINE INDENT if ( R != C and R % 2 == 0 and C % 2 != 0 and R < C ) : NEW_LINE INDENT print ( " Left " ) NEW_LINE return NEW_LINE DEDENT if ( R != C and R % 2 == 0 and C % 2 == 0 and R > C ) : NEW_LINE INDENT print ( " Up " ) NEW_LINE return NEW_LINE DEDENT if R == C and R % 2 != 0 and C % 2... |
Print K 'th element in spiral form of matrix | ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; check the first row from the remaining rows ; check the last column from the remaining columns ; check the last row from the remaining rows ; check the first col... | R = 3 NEW_LINE C = 6 NEW_LINE def spiralPrint ( m , n , a , c ) : NEW_LINE INDENT k = 0 NEW_LINE l = 0 NEW_LINE count = 0 NEW_LINE while ( k < m and l < n ) : NEW_LINE INDENT for i in range ( l , n ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count == c ) : NEW_LINE INDENT print ( a [ k ] [ i ] , end = " β " ) NEW_LINE... |
Print K 'th element in spiral form of matrix | Python3 program for Kth element in spiral form of matrix ; function for Kth element ; Element is in first row ; Element is in last column ; Element is in last row ; Element is in first column ; Recursion for sub - matrix . & A [ 1 ] [ 1 ] is address to next inside sub matr... | MAX = 100 NEW_LINE def findK ( A , n , m , k ) : NEW_LINE INDENT if ( n < 1 or m < 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( k <= m ) : NEW_LINE INDENT return A [ 0 ] [ k - 1 ] NEW_LINE DEDENT if ( k <= ( m + n - 1 ) ) : NEW_LINE INDENT return A [ ( k - m ) ] [ m - 1 ] NEW_LINE DEDENT if ( k <= ( m + n - 1 ... |
Find if given matrix is Toeplitz or not | Python3 program to check whether given matrix is a Toeplitz matrix or not ; Function to check if all elements present in descending diagonal starting from position ( i , j ) in the matrix are all same or not ; mismatch found ; we only reach here when all elements in given diago... | N = 5 NEW_LINE M = 4 NEW_LINE def checkDiagonal ( mat , i , j ) : NEW_LINE INDENT res = mat [ i ] [ j ] NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE while ( i < N and j < M ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != res ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return True NEW... |
Find if given matrix is Toeplitz or not | Python3 program to check whether given matrix is a Toeplitz matrix or not ; row = number of rows col = number of columns ; dictionary to store key , value pairs ; if key value exists in the map , ; we check whether the current value stored in this key matches to element at curr... | def isToeplitz ( matrix ) : NEW_LINE INDENT row = len ( matrix ) NEW_LINE col = len ( matrix [ 0 ] ) NEW_LINE map = { } NEW_LINE for i in range ( row ) : NEW_LINE INDENT for j in range ( col ) : NEW_LINE INDENT key = i - j NEW_LINE if ( key in map ) : NEW_LINE INDENT if ( map [ key ] != matrix [ i ] [ j ] ) : NEW_LINE ... |
Count zeros in a row wise and column wise sorted matrix | Python program to count number of 0 s in the given row - wise and column - wise sorted binary matrix . ; Function to count number of 0 s in the given row - wise and column - wise sorted binary matrix . ; start from bottom - left corner of the matrix ; stores num... | N = 5 ; NEW_LINE def countZeroes ( mat ) : NEW_LINE INDENT row = N - 1 ; NEW_LINE col = 0 ; NEW_LINE count = 0 ; NEW_LINE while ( col < N ) : NEW_LINE INDENT while ( mat [ row ] [ col ] ) : NEW_LINE INDENT if ( row < 0 ) : NEW_LINE INDENT return count ; NEW_LINE DEDENT row = row - 1 ; NEW_LINE DEDENT count = count + ( ... |
Linked complete binary tree & its creation | For Queue Size ; A tree node ; A queue node ; A utility function to create a new tree node ; A utility function to create a new Queue ; Standard Queue Functions ; A utility function to check if a tree node has both left and right children ; Function to insert a new node in c... | SIZE = 50 NEW_LINE class node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . right = None NEW_LINE self . left = None NEW_LINE DEDENT DEDENT class Queue : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . front = None NEW_LINE self . rear = None NEW_LINE... |
Find size of the largest ' + ' formed by all ones in a binary matrix | size of binary square matrix ; Function to find the size of the largest ' + ' formed by all 1 's in given binary matrix ; left [ j ] [ j ] , right [ i ] [ j ] , top [ i ] [ j ] and bottom [ i ] [ j ] store maximum number of consecutive 1 's present ... | N = 10 NEW_LINE def findLargestPlus ( mat ) : NEW_LINE INDENT left = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE right = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE top = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE bottom = [ [ 0 for x in range ( N ) ] for y in range (... |
Return previous element in an expanding matrix | Returns left of str in an expanding matrix of a , b , c , and d . ; Start from rightmost position ; If the current character is b or d , change to a or c respectively and break the loop ; If the current character is a or c , change it to b or d respectively ; Driver Code | def findLeft ( str ) : NEW_LINE INDENT n = len ( str ) - 1 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( str [ n ] == ' d ' ) : NEW_LINE INDENT str = str [ 0 : n ] + ' c ' + str [ n + 1 : ] ; NEW_LINE break ; NEW_LINE DEDENT if ( str [ n ] == ' b ' ) : NEW_LINE INDENT str = str [ 0 : n ] + ' a ' + str [ n + 1 : ] ;... |
Print n x n spiral matrix using O ( 1 ) extra space | Prints spiral matrix of size n x n containing numbers from 1 to n x n ; Finds minimum of four inputs ; For upper right half ; For lower left half ; Driver code ; print a n x n spiral matrix in O ( 1 ) space | def printSpiral ( n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT x = min ( min ( i , j ) , min ( n - 1 - i , n - 1 - j ) ) NEW_LINE if ( i <= j ) : NEW_LINE INDENT print ( ( n - 2 * x ) * ( n - 2 * x ) - ( i - x ) - ( j - x ) , end = " TABSYMBOL " ) NEW_LINE ... |
Shortest path in a Binary Maze | Python program to find the shortest path between a given source cell to a destination cell . ; To store matrix cell cordinates ; A data structure for queue used in BFS ; The cordinates of the cell ; Cell 's distance from the source ; Check whether given cell ( row , col ) is a valid cel... | from collections import deque NEW_LINE ROW = 9 NEW_LINE COL = 10 NEW_LINE class Point : NEW_LINE INDENT def __init__ ( self , x : int , y : int ) : NEW_LINE INDENT self . x = x NEW_LINE self . y = y NEW_LINE DEDENT DEDENT class queueNode : NEW_LINE INDENT def __init__ ( self , pt : Point , dist : int ) : NEW_LINE INDEN... |
Convert a given Binary Tree to Doubly Linked List | Set 1 | Binary tree Node class has data , left and right child ; This is a utility function to convert the binary tree to doubly linked list . Most of the core task is done by this function . ; Base case ; Convert left subtree and link to root ; Convert the left subtr... | class Node ( object ) : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def BTToDLLUtil ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return root NEW_LINE DEDENT if root . left : NEW_LINE IND... |
A Boolean Matrix Question | Python3 Code For A Boolean Matrix Question ; Initialize all values of row [ ] as 0 ; Initialize all values of col [ ] as 0 ; Store the rows and columns to be marked as 1 in row [ ] and col [ ] arrays respectively ; Modify the input matrix mat [ ] using the above constructed row [ ] and col [... | R = 3 NEW_LINE C = 4 NEW_LINE def modifyMatrix ( mat ) : NEW_LINE INDENT row = [ 0 ] * R NEW_LINE col = [ 0 ] * C NEW_LINE for i in range ( 0 , R ) : NEW_LINE INDENT row [ i ] = 0 NEW_LINE DEDENT for i in range ( 0 , C ) : NEW_LINE INDENT col [ i ] = 0 NEW_LINE DEDENT for i in range ( 0 , R ) : NEW_LINE INDENT for j in... |
A Boolean Matrix Question | Python3 Code For A Boolean Matrix Question ; variables to check if there are any 1 in first row and column ; updating the first row and col if 1 is encountered ; Modify the input matrix mat [ ] using the first row and first column of Matrix mat ; modify first row if there was any 1 ; modify ... | def modifyMatrix ( mat ) : NEW_LINE INDENT row_flag = False NEW_LINE col_flag = False NEW_LINE for i in range ( 0 , len ( mat ) ) : NEW_LINE INDENT for j in range ( 0 , len ( mat ) ) : NEW_LINE INDENT if ( i == 0 and mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT row_flag = True NEW_LINE DEDENT if ( j == 0 and mat [ i ] [ j ... |
Given a Boolean Matrix , find k such that all elements in k ' th β row β are β 0 β and β k ' th column are 1. | Python program to find k such that all elements in k ' th β row β β β are β 0 β and β k ' th column are 1 ; start from top right - most corner ; initialise result ; find the index ( This loop runs at most 2 n... | def find ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE res = - 1 NEW_LINE while i < n and j >= 0 : NEW_LINE INDENT if arr [ i ] [ j ] == 0 : NEW_LINE INDENT while j >= 0 and ( arr [ i ] [ j ] == 0 or i == j ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if j == - 1 : NEW_LINE INDENT r... |
Print unique rows in a given boolean matrix | Given a binary matrix of M X N of integers , you need to return only unique rows of binary array ; The main function that prints all unique rows in a given matrix . ; Traverse through the matrix ; Check if there is similar column is already printed , i . e if i and jth colu... | ROW = 4 NEW_LINE COL = 5 NEW_LINE def findUniqueRows ( M ) : NEW_LINE INDENT for i in range ( ROW ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( i ) : NEW_LINE INDENT flag = 1 NEW_LINE for k in range ( COL ) : NEW_LINE INDENT if ( M [ i ] [ k ] != M [ j ] [ k ] ) : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT DEDEN... |
Print unique rows in a given boolean matrix | Python3 code to print unique row in a given binary matrix ; Driver Code | def printArray ( matrix ) : NEW_LINE INDENT rowCount = len ( matrix ) NEW_LINE if rowCount == 0 : NEW_LINE INDENT return NEW_LINE DEDENT columnCount = len ( matrix [ 0 ] ) NEW_LINE if columnCount == 0 : NEW_LINE INDENT return NEW_LINE DEDENT row_output_format = " β " . join ( [ " % s " ] * columnCount ) NEW_LINE printe... |
Find the largest rectangle of 1 's with swapping of columns allowed | Python 3 program to find the largest rectangle of 1 's with swapping of columns allowed. ; Returns area of the largest rectangle of 1 's ; An auxiliary array to store count of consecutive 1 's in every column. ; Step 1 : Fill the auxiliary array hist... | R = 3 NEW_LINE C = 5 NEW_LINE def maxArea ( mat ) : NEW_LINE INDENT hist = [ [ 0 for i in range ( C + 1 ) ] for i in range ( R + 1 ) ] NEW_LINE for i in range ( 0 , C , 1 ) : NEW_LINE INDENT hist [ 0 ] [ i ] = mat [ 0 ] [ i ] NEW_LINE for j in range ( 1 , R , 1 ) : NEW_LINE INDENT if ( ( mat [ j ] [ i ] == 0 ) ) : NEW_... |
Submatrix Sum Queries | Python 3 program to compute submatrix query sum in O ( 1 ) time ; Function to preprcess input mat [ M ] [ N ] . This function mainly fills aux [ M ] [ N ] such that aux [ i ] [ j ] stores sum of elements from ( 0 , 0 ) to ( i , j ) ; Copy first row of mat [ ] [ ] to aux [ ] [ ] ; Do column wise ... | M = 4 NEW_LINE N = 5 NEW_LINE def preProcess ( mat , aux ) : NEW_LINE INDENT for i in range ( 0 , N , 1 ) : NEW_LINE INDENT aux [ 0 ] [ i ] = mat [ 0 ] [ i ] NEW_LINE DEDENT for i in range ( 1 , M , 1 ) : NEW_LINE INDENT for j in range ( 0 , N , 1 ) : NEW_LINE INDENT aux [ i ] [ j ] = mat [ i ] [ j ] + aux [ i - 1 ] [ ... |
Program for Rank of Matrix | Python 3 program to find rank of a matrix ; Function for exchanging two rows of a matrix ; Find rank of a matrix ; Before we visit current row ' row ' , we make sure that mat [ row ] [ 0 ] , ... . mat [ row ] [ row - 1 ] are 0. Diagonal element is not zero ; This makes all entries of curren... | class rankMatrix ( object ) : NEW_LINE INDENT def __init__ ( self , Matrix ) : NEW_LINE INDENT self . R = len ( Matrix ) NEW_LINE self . C = len ( Matrix [ 0 ] ) NEW_LINE DEDENT def swap ( self , Matrix , row1 , row2 , col ) : NEW_LINE INDENT for i in range ( col ) : NEW_LINE INDENT temp = Matrix [ row1 ] [ i ] NEW_LIN... |
Maximum size rectangle binary sub | Finds the maximum area under the histogram represented by histogram . See below article for details . ; Create an empty stack . The stack holds indexes of hist array / The bars stored in stack are always in increasing order of their heights . ; Top of stack ; Initialize max area in c... | class Solution ( ) : NEW_LINE INDENT def maxHist ( self , row ) : NEW_LINE INDENT result = [ ] NEW_LINE top_val = 0 NEW_LINE max_area = 0 NEW_LINE area = 0 NEW_LINE i = 0 NEW_LINE while ( i < len ( row ) ) : NEW_LINE INDENT if ( len ( result ) == 0 ) or ( row [ result [ - 1 ] ] <= row [ i ] ) : NEW_LINE INDENT result .... |
Find sum of all elements in a matrix except the elements in row and / or column of given cell ? | A structure to represent a cell index ; r is row , varies from 0 to R - 1 ; c is column , varies from 0 to C - 1 ; A simple solution to find sums for a given array of cell indexes ; Iterate through all cell indexes ; Compu... | class Cell : NEW_LINE INDENT def __init__ ( self , r , c ) : NEW_LINE INDENT self . r = r NEW_LINE self . c = c NEW_LINE DEDENT DEDENT def printSums ( mat , arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT Sum = 0 ; r = arr [ i ] . r ; c = arr [ i ] . c NEW_LINE for j in range ( 0 , R ) : NEW_LINE... |
Find sum of all elements in a matrix except the elements in row and / or column of given cell ? | Python3 implementation of the approach A structure to represent a cell index ; r is row , varies from 0 to R - 1 ; c is column , varies from 0 to C - 1 ; Compute sum of all elements , sum of every row and sum every column ... | class Cell : NEW_LINE INDENT def __init__ ( self , r , c ) : NEW_LINE INDENT self . r = r NEW_LINE self . c = c NEW_LINE DEDENT DEDENT def printSums ( mat , arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE row , col = [ 0 ] * R , [ 0 ] * C NEW_LINE for i in range ( 0 , R ) : NEW_LINE INDENT for j in range ( 0 , C ) : NEW_L... |
Count number of islands where every island is row | This function takes a matrix of ' X ' and ' O ' and returns the number of rectangular islands of ' X ' where no two islands are row - wise or column - wise adjacent , the islands may be diagonaly adjacent ; Initialize result ; Traverse the input matrix ; If current ce... | def countIslands ( mat ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( 0 , M ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == ' X ' ) : NEW_LINE INDENT if ( ( i == 0 or mat [ i - 1 ] [ j ] == ' O ' ) and ( j == 0 or mat [ i ] [ j - 1 ] == ' O ' ) ) : NEW_LINE INDENT count... |
Find a common element in all rows of a given row | Specify number of rows and columns ; Returns common element in all rows of mat [ M ] [ N ] . If there is no common element , then - 1 is returned ; An array to store indexes of current last column ; Initialize min_row as first row ; Keep finding min_row in current last... | M = 4 NEW_LINE N = 5 NEW_LINE def findCommon ( mat ) : NEW_LINE INDENT column = [ N - 1 ] * M NEW_LINE min_row = 0 NEW_LINE while ( column [ min_row ] >= 0 ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT if ( mat [ i ] [ column [ i ] ] < mat [ min_row ] [ column [ min_row ] ] ) : NEW_LINE INDENT min_row = i ... |
Find a common element in all rows of a given row | Python3 implementation of the approach ; Specify number of rows and columns ; Returns common element in all rows of mat [ M ] [ N ] . If there is no common element , then - 1 is returned ; A hash map to store count of elements ; Increment the count of first element of ... | from collections import defaultdict NEW_LINE M = 4 NEW_LINE N = 5 NEW_LINE def findCommon ( mat ) : NEW_LINE INDENT global M NEW_LINE global N NEW_LINE cnt = dict ( ) NEW_LINE cnt = defaultdict ( lambda : 0 , cnt ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while ( i < M ) : NEW_LINE INDENT cnt [ mat [ i ] [ 0 ] ] = cnt [ ... |
Given a matrix of β O β and β X β , replace ' O ' with ' X ' if surrounded by ' X ' | Size of given matrix is M x N ; A recursive function to replace previous value ' prevV ' at ' ( x , β y ) ' and all surrounding values of ( x , y ) with new value ' newV ' . ; Base Cases ; Replace the color at ( x , y ) ; Recur for no... | M = 6 NEW_LINE N = 6 NEW_LINE def floodFillUtil ( mat , x , y , prevV , newV ) : NEW_LINE INDENT if ( x < 0 or x >= M or y < 0 or y >= N ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( mat [ x ] [ y ] != prevV ) : NEW_LINE INDENT return NEW_LINE DEDENT mat [ x ] [ y ] = newV NEW_LINE floodFillUtil ( mat , x + 1 , y , p... |
Convert a given Binary Tree to Doubly Linked List | Set 2 | A Binary Tree node ; Standard Inorder traversal of tree ; Changes left pointers to work as previous pointers in converted DLL The function simply does inorder traversal of Binary Tree and updates left pointer using previously visited node ; Changes right point... | 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 inorder ( root ) : NEW_LINE INDENT if root is not None : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print " TABSYMBOL % d " % ( root . ... |
Given a matrix of ' O ' and ' X ' , find the largest subsquare surrounded by ' X ' | Size of given matrix is N X N ; Initialize maxside with 0 ; Fill the dp matrix horizontally . for contiguous ' X ' increment the value of x , otherwise make it 0 ; Fill the dp matrix vertically . For contiguous ' X ' increment the valu... | N = 6 NEW_LINE def maximumSubSquare ( arr ) : NEW_LINE INDENT dp = [ [ [ - 1 , - 1 ] for i in range ( 51 ) ] for j in range ( 51 ) ] NEW_LINE maxside = [ [ 0 for i in range ( 51 ) ] for j in range ( 51 ) ] NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = 0 NEW_LINE for j in range ( N ) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.