Banana-Leopard/TASTY huggingface dataset:
# Python implementation to
# count sub-matrices having
# sum divisible by the
# value 'k'
 
# function to count all
# sub-arrays divisible by k
def subCount(arr, n, k) :
 
    # create auxiliary hash
    # array to count frequency
    # of remainders
    mod = [0] * k;
 
    # 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
    cumSum = 0;
    for i in range(0, n) :
     
        cumSum = cumSum + arr[i];
         
        # as the sum can be
        # negative, taking
        # modulo twice
        mod[((cumSum % k) + k) % k] = mod[
                   ((cumSum % k) + k) % k] + 1;
 
    result = 0; # Initialize result
 
    # Traverse mod
    for i in range(0, k) :
 
        # If there are more than
        # one prefix subarrays
        # with a particular mod value.
        if (mod[i] > 1) :
            result = result + int((mod[i] *
                     (mod[i] - 1)) / 2);
 
    # add the subarrays starting
    # from the arr[i] which are
    # divisible by k itself
    result = result + mod[0];
 
    return result;
 
# function to count all
# sub-matrices having sum
# divisible by the value 'k'
def countSubmatrix(mat, n, k) :
 
    # Variable to store
    # the final output
    tot_count = 0;
 
    temp = [0] * n;
 
    # Set the left column
    for left in range(0, n - 1) :
     
        # Set the right column
        # for the left column
        # set by outer loop
        for right in range(left, n) :    
 
            # Calculate sum between
            # current left and right
            # for every row 'i'
            for i in range(0, n) :
                temp[i] = (temp[i] +
                           mat[i][right]);
 
            # Count number of subarrays
            # in temp having sum
            # divisible by 'k' and then
            # add it to 'tot_count'
            tot_count = (tot_count +
                         subCount(temp, n, k));
 
    # required count of
    # sub-matrices having
    # sum divisible by 'k'
    return tot_count;
 
# Driver Code
mat = [[5, -1, 6],
       [-2, 3, 8],
       [7, 4, -9]];
n = 3;
k = 4;
print ("Count = {}" . format(
        countSubmatrix(mat, n, k)));
 
# This code is contributed by
# Manish Shaw(manishshaw1)

Time complexity: cubic
Space complexity: linear
# Python Program to check
# whether given matrix is
# Diagonally Dominant Matrix.
 
# check the given 
# matrix is Diagonally
# Dominant Matrix or not.
def isDDM(m, n) :
 
    # for each row
    for i in range(0, n) :        
     
        # for each column, finding
        # sum of each row.
        sum = 0
        for j in range(0, n) :
            sum = sum + abs(m[i][j])    
 
        # removing the
        # diagonal element.
        sum = sum - abs(m[i][i])
 
        # checking if diagonal
        # element is less than
        # sum of non-diagonal
        # element.
        if (abs(m[i][i]) < sum) :
            return False
 
    return True
 
# Driver Code
n = 3
m = [[ 3, -2, 1 ],
    [ 1, -3, 2 ],
    [ -1, 2, 4 ]]
 
if((isDDM(m, n))) :
    print ("YES")
else :
    print ("NO")
 
# This code is contributed by
# Manish Shaw(manishshaw1)

Time complexity: quadratic
Space complexity: constant
# Python 3 Program to Find minimum
# number of operation required such
# that sum of elements on each row
# and column becomes same
 
# Function to find minimum operation
# required to make sum of each row
# and column equals
 
 
def findMinOpeartion(matrix, n):
 
    # Initialize the sumRow[] and sumCol[]
    # array to 0
    sumRow = [0] * n
    sumCol = [0] * n
 
    # Calculate sumRow[] and sumCol[] array
    for i in range(n):
        for j in range(n):
            sumRow[i] += matrix[i][j]
            sumCol[j] += matrix[i][j]
 
    # Find maximum sum value in
    # either row or in column
    maxSum = 0
    for i in range(n):
        maxSum = max(maxSum, sumRow[i])
        maxSum = max(maxSum, sumCol[i])
 
    count = 0
    i = 0
    j = 0
    while i < n and j < n:
 
        # Find minimum increment required
        # in either row or column
        diff = min(maxSum - sumRow[i],
                   maxSum - sumCol[j])
 
        # Add difference in corresponding
        # cell, sumRow[] and sumCol[] array
        matrix[i][j] += diff
        sumRow[i] += diff
        sumCol[j] += diff
 
        # Update the count variable
        count += diff
 
        # If ith row satisfied, increment
        # ith value for next iteration
        if (sumRow[i] == maxSum):
            i += 1
 
        # If jth column satisfied, increment
        # jth value for next iteration
        if (sumCol[j] == maxSum):
            j += 1
 
    return count
 
# Utility function to print matrix
 
 
def printMatrix(matrix, n):
    for i in range(n):
        for j in range(n):
            print(matrix[i][j], end=" ")
        print()
 
 
# Driver code
if __name__ == "__main__":
    matrix = [[1, 2],
              [3, 4]]
    print(findMinOpeartion(matrix, 2))
    printMatrix(matrix, 2)
 
# This code is contributed
# by ChitraNayal

Time complexity: quadratic
Space complexity: linear
# Python program to find
# the frequency of k
# in matrix where
# m(i, j)=i+j
 
import math
 
def find( n,  k):
 
    if (n + 1 >= k):
        return (k - 1)
    else:
        return (2 * n + 1 - k)
 
  
# Driver Code
n = 4
k = 7
 
freq = find(n, k)
 
if (freq < 0):
    print ( " element not exist")
else:
    print(" Frequency of " , k ," is " , freq )
 
# This code is contributed
# by Gitanjali.

Time complexity: constant
Space complexity: constant
# Python3 program to print given number of 1's,
# 2's, 3's ....k's in zig-zag way.
 
# function that prints given number of 1's,
# 2's, 3's ....k's in zig-zag way.
def ZigZag(rows, columns, numbers):
    k = 0
     
    # two-dimensional array to store numbers.
    arr = [[0 for i in range(columns)] for j in range(rows)]
    for i in range(rows):
         
        # for even row.
        if (i % 2 == 0):
             
            # for each column.
            j = 0
            while j < columns and numbers[k] > 0:
                 
                # storing element.
                arr[i][j] = k + 1
                 
                # decrement element at
                # kth index.
                numbers[k] -= 1   
                 
                # if array contains zero
                # then increment index to
                # make this next index
                if numbers[k] == 0:
                    k += 1
                j += 1
        # for odd row.
        else:
             
            # for each column.
            j = columns-1
            while j>=0 and numbers[k]>0:
                 
                # storing element.
                arr[i][j] = k+1
                 
                # decrement element
                # at kth index.
                numbers[k] -= 1
                 
                # if array contains zero then
                # increment index to make this
                # next index.
                if numbers[k] == 0:
                    k += 1
                j -= 1
     
    # printing the stored elements.
    for i in arr:
        for j in i:
            print(j, end =" ")
        print()
 
# Driver code
rows = 4;
columns = 5;
Numbers = [3, 4, 2, 2, 3, 1, 5]
ZigZag(rows, columns, Numbers)
 
# This code is contributed by
# Rajnis09

Time complexity: quadratic
Space complexity: quadratic
# Python3 program to find out the maximum
# product in the matrix which four elements
# are adjacent to each other in one direction
n = 5
 
# function to find max product
def FindMaxProduct(arr, n):
 
    max = 0
 
    # iterate the rows.
    for i in range(n):
 
        # iterate the columns.
        for j in range( n):
 
            # check the maximum product
            # in horizontal row.
            if ((j - 3) >= 0):
                result = (arr[i][j] * arr[i][j - 1] *
                          arr[i][j - 2] * arr[i][j - 3])
                 
                if (max < result):
                    max = result
 
            # check the maximum product
            # in vertical row.
            if ((i - 3) >= 0) :
                result = (arr[i][j] * arr[i - 1][j] *
                          arr[i - 2][j] * arr[i - 3][j])
                 
                if (max < result):
                    max = result
 
            # check the maximum product in
            # diagonal going through down - right
            if ((i - 3) >= 0 and (j - 3) >= 0):
                result = (arr[i][j] * arr[i - 1][j - 1] *
                          arr[i - 2][j - 2] * arr[i - 3][j - 3])
                 
                if (max < result):
                    max = result
 
            # check the maximum product in
            # diagonal going through up - right
            if ((i - 3) >= 0 and (j - 3) <= 0):
                result = (arr[i][j] * arr[i - 1][j + 1] *
                          arr[i - 2][j + 2] * arr[i - 3][j + 3])
 
                if (max < result):
                    max = result
 
    return max
 
# Driver code
if __name__ == "__main__":
     
 
    # int arr[][4] = {{6, 2, 3, 4},
    #                  {5, 4, 3, 1},
    #                  {7, 4, 5, 6},
    #                  {8, 3, 1, 0}};
    # int arr[][5] = {{1, 2, 1, 3, 4},
    #                  {5, 6, 3, 9, 2},
    #                  {7, 8, 8, 1, 2},
    #                  {1, 0, 7, 9, 3},
    #                  {3, 0, 8, 4, 9}};
                         
    arr = [[1, 2, 3, 4, 5],
           [6, 7, 8, 9, 1],
           [2, 3, 4, 5, 6],
           [7, 8, 9, 1, 0],
            [9, 6, 4, 2, 3]]
 
    print(FindMaxProduct(arr, n))
 
# This code is contributed by ita_c

Time complexity: quadratic
Space complexity: constant
# Python implementation of the above approach
def maxPro(a,n,m,k):
    maxi = 1
    mp = 1 
    for i in range(n):
         
        # Window Product for each row.
        wp = 1
         
        for l in range(k):
            wp *= a[i][l]
             
        # Maximum window product for each row
        mp = wp
         
        for j in range(k,m):
            wp = wp * a[i][j] / a[i][j - k]
             
            # Global maximum
            # window product
            maxi = max(
                    maxi,
                    max(mp, wp))
     
    return maxi
 
# Driver Code
n = 6
m = 5
k = 4
a=[[1, 2, 3, 4, 5 ], [ 6, 7, 8, 9, 1 ],
            [ 2, 3, 4, 5, 6 ], [ 7, 8, 9, 1, 0 ],
            [ 9, 6, 4, 2, 3 ], [ 1, 1, 2, 1, 1 ]]
 
# Function call
maxpro = maxPro(a, n, m, k)
print(maxpro)
 
# This code is contributed by ab2127

Time complexity: quadratic
Space complexity: constant
# Python3 Program to check
# lower triangular matrix.
 
# Function to check matrix
# is in lower triangular
def islowertriangular(M):
    for i in range(0, len(M)):
        for j in range(i + 1, len(M)):
            if(M[i][j] != 0):
                    return False
    return True
     
# Driver function.
M = [[1,0,0,0],
     [1,4,0,0],
     [4,6,2,0],
     [0,4,7,6]]
 
if islowertriangular(M):
    print ("Yes")
else:
    print ("No")
     
# This code is contributed by Anurag Rawat

Time complexity: quadratic
Space complexity: constant
# Python3 Program to check upper
# triangular matrix.
 
# Function to check matrix
# is in upper triangular
def isuppertriangular(M):
    for i in range(1, len(M)):
        for j in range(0, i):
            if(M[i][j] != 0):
                    return False
    return True
     
# Driver function.
M = [[1,3,5,3],
    [0,4,6,2],
    [0,0,2,5],
    [0,0,0,6]]
 
if isuppertriangular(M):
    print ("Yes")
else:
    print ("No")
 
# This code is contributed by Anurag Rawat

Time complexity: quadratic
Space complexity: constant
# Python Program to Find the frequency
# of even and odd numbers in a matrix
 
MAX=100
  
# Function for calculating frequency
def freq(ar, m, n):
    even = 0
    odd = 0
      
    for i in range(m):
        for j in range(n):
         
            # modulo by 2 to check
            # even and odd
            if ((ar[i][j] % 2) == 0):
                even += 1
            else:
                odd += 1
      
    # print Frequency of numbers
    print(" Frequency of odd number =", odd)
    print(" Frequency of even number =", even)
 
  
# Driver code
m = 3
n = 3   
      
array = [ [ 1, 2, 3 ],
        [ 4, 5, 6 ],
        [ 7, 8, 9 ] ]
  
freq(array, m, n)
 
# This code is contributed
# by Anant Agarwal.

Time complexity: quadratic
Space complexity: constant
# Python 3 Program to check if the center
# element is equal to the individual
# sum of all the half diagonals
  
MAX = 100
  
# Function to Check center element
# is equal to the individual
# sum of all the half diagonals
def HalfDiagonalSums( mat,  n):
 
    # Find sums of half diagonals
    diag1_left = 0
    diag1_right = 0
    diag2_left = 0
    diag2_right = 0 
    i = 0
    j = n - 1
    while i < n:
          
        if (i < n//2) :
            diag1_left += mat[i][i]
            diag2_left += mat[j][i]          
         
        elif (i > n//2) :
            diag1_right += mat[i][i]
            diag2_right += mat[j][i]          
        i += 1
        j -= 1
      
    return (diag1_left == diag2_right and
            diag2_right == diag2_left and
            diag1_right == diag2_left and
            diag2_right == mat[n//2][n//2])
  
# Driver code
if __name__ == "__main__":
     
    a = [[2, 9, 1, 4, -2],
         [6, 7, 2, 11, 4],
         [ 4, 2, 9, 2, 4],
         [1, 9, 2, 4, 4 ],
         [ 0, 2, 4, 2, 5]]
     
    print("Yes") if (HalfDiagonalSums(a, 5)) else print("No" )

Time complexity: linear
Space complexity: constant
# Python code to print identity matrix
 
# Function to print identity matrix
def Identity(size):
    for row in range(0, size):
        for col in range(0, size):
 
            # Here end is used to stay in same line
            if (row == col):
                print("1 ", end=" ")
            else:
                print("0 ", end=" ")
        print()
 
# Driver Code       
size = 5
Identity(size)

Time complexity: quadratic
Space complexity: constant
# Python3 program to check
# if a given matrix is identity
MAX = 100;
def isIdentity(mat, N):
    for row in range(N):
        for col in range(N):
            if (row == col and
                mat[row][col] != 1):
                return False;
            elif (row != col and
                  mat[row][col] != 0):
                return False;
    return True;
 
# Driver Code
N = 4;
mat = [[1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1]];
if (isIdentity(mat, N)):
    print("Yes ");
else:
    print("No ");
 
# This code is contributed
# by mits

Time complexity: quadratic
Space complexity: constant
# Python Program to implement matrix
# for swapping the upper diagonal
# elements with lower diagonal
# elements of matrix.
 
# Function to swap the diagonal
# elements in a matrix.
def swapUpperToLower(arr):
    n = 4;
     
    # Loop for swap the elements
    # of matrix.
    for i in range(0, n):
        for j in range(i + 1, n):
            temp = arr[i][j];
            arr[i][j] = arr[j][i];
            arr[j][i] = temp;
         
    # Loop for print the matrix elements.
    for i in range(0, n):
        for j in range(0, n):
            print(arr[i][j], end = " ");
        print(" ");
     
# Driver Code
 
arr = [[2, 3, 5, 6 ],[ 4, 5, 7, 9 ],
       [8, 6, 4, 9 ],[ 1, 3, 5, 6 ]];
 
# Function call
swapUpperToLower(arr);
 
# This code is contributed
# by Shivi_Aggarwal

Time complexity: quadratic
Space complexity: constant
# Simple Python3 program to find mirror of
# matrix across diagonal.
MAX = 100
 
def imageSwap(mat, n):
     
    # for diagonal which start from at
    # first row of matrix
    row = 0
     
    # traverse all top right diagonal
    for j in range(n):
         
        # here we use stack for reversing
        # the element of diagonal
        s = []
        i = row
        k = j
        while (i < n and k >= 0):
            s.append(mat[i][k])
            i += 1
            k -= 1
             
        # push all element back to matrix
        # in reverse order
        i = row
        k = j
        while (i < n and k >= 0):
            mat[i][k] = s[-1]
            k -= 1
            i += 1
            s.pop()
             
    # do the same process for all the
    # diagonal which start from last
    # column
    column = n - 1
    for j in range(1, n):
         
        # here we use stack for reversing
        # the elements of diagonal
        s = []
        i = j
        k = column
        while (i < n and k >= 0):
            s.append(mat[i][k])
            i += 1
            k -= 1
             
        # push all element back to matrix
        # in reverse order
        i = j
        k = column
        while (i < n and k >= 0):
            mat[i][k] = s[-1]
            i += 1
            k -= 1
            s.pop()
 
# Utility function to print a matrix
def printMatrix(mat, n):
    for i in range(n):
        for j in range(n):
            print(mat[i][j], end=" ")
        print()
         
# Driver code
mat = [[1, 2, 3, 4],[5, 6, 7, 8],
        [9, 10, 11, 12],[13, 14, 15, 16]]
n = 4
imageSwap(mat, n)
printMatrix(mat, n)
 
# This code is contributed by shubhamsingh10

Time complexity: quadratic
Space complexity: linear
# Efficient Python3 program to find mirror of
# matrix across diagonal.
from builtins import range
MAX = 100;
 
def imageSwap(mat, n):
 
    # traverse a matrix and swap
    # mat[i][j] with mat[j][i]
    for i in range(n):
        for j in range(i + 1):
            t = mat[i][j];
            mat[i][j] = mat[j][i]
            mat[j][i] = t
 
# Utility function to print a matrix
def printMatrix(mat, n):
    for i in range(n):
        for j in range(n):
            print(mat[i][j], end=" ");
        print();
 
# Driver code
if __name__ == '__main__':
    mat = [1, 2, 3, 4], \
        [5, 6, 7, 8], \
        [9, 10, 11, 12], \
        [13, 14, 15, 16];
    n = 4;
    imageSwap(mat, n);
    printMatrix(mat, n);
 
# This code is contributed by Rajput-Ji

Time complexity: quadratic
Space complexity: constant
# Python program to find all
# rectangles filled with 0
 
def findend(i,j,a,output,index):
    x = len(a)
    y = len(a[0])
 
    # flag to check column edge case,
    # initializing with 0
    flagc = 0
 
    # flag to check row edge case,
    # initializing with 0
    flagr = 0
 
    for m in range(i,x):
 
        # loop breaks where first 1 encounters
        if a[m][j] == 1:
            flagr = 1 # set the flag
            break
 
        # pass because already processed
        if a[m][j] == 5:
            pass
 
        for n in range(j, y):
 
            # loop breaks where first 1 encounters
            if a[m][n] == 1:
                flagc = 1 # set the flag
                break
 
            # fill rectangle elements with any
            # number so that we can exclude
            # next time
            a[m][n] = 5
 
    if flagr == 1:
        output[index].append( m-1)
    else:
        # when end point touch the boundary
        output[index].append(m)
 
    if flagc == 1:
        output[index].append(n-1)
    else:
        # when end point touch the boundary
        output[index].append(n)
 
 
def get_rectangle_coordinates(a):
 
    # retrieving the column size of array
    size_of_array = len(a)
 
    # output array where we are going
    # to store our output
    output = []
 
    # It will be used for storing start
    # and end location in the same index
    index = -1
 
    for i in range(0,size_of_array):
        for j in range(0, len(a[0])):
            if a[i][j] == 0:
 
                # storing initial position
                # of rectangle
                output.append([i, j])
 
                # will be used for the
                # last position
                index = index + 1       
                findend(i, j, a, output, index)
 
 
    print (output)
 
# driver code
tests = [
 
            [1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 0, 0, 0, 1],
            [1, 0, 1, 0, 0, 0, 1],
            [1, 0, 1, 1, 1, 1, 1],
            [1, 0, 1, 0, 0, 0, 0],
            [1, 1, 1, 0, 0, 0, 1],
            [1, 1, 1, 1, 1, 1, 1]
 
        ]
 
 
get_rectangle_coordinates(tests)

Time complexity: quadratic
Space complexity: quadratic
# Python3 Code implementation for above problem
 
# QItem for current location and distance
# from source location
class QItem:
    def __init__(self, row, col, dist):
        self.row = row
        self.col = col
        self.dist = dist
 
    def __repr__(self):
        return f"QItem({self.row}, {self.col}, {self.dist})"
 
def minDistance(grid):
    source = QItem(0, 0, 0)
 
    # Finding the source to start from
    for row in range(len(grid)):
        for col in range(len(grid[row])):
            if grid[row][col] == 's':
                source.row = row
                source.col = col
                break
 
    # To maintain location visit status
    visited = [[False for _ in range(len(grid[0]))]
               for _ in range(len(grid))]
     
    # applying BFS on matrix cells starting from source
    queue = []
    queue.append(source)
    visited[source.row][source.col] = True
    while len(queue) != 0:
        source = queue.pop(0)
 
        # Destination found;
        if (grid[source.row][source.col] == 'd'):
            return source.dist
 
        # moving up
        if isValid(source.row - 1, source.col, grid, visited):
            queue.append(QItem(source.row - 1, source.col, source.dist + 1))
            visited[source.row - 1][source.col] = True
 
        # moving down
        if isValid(source.row + 1, source.col, grid, visited):
            queue.append(QItem(source.row + 1, source.col, source.dist + 1))
            visited[source.row + 1][source.col] = True
 
        # moving left
        if isValid(source.row, source.col - 1, grid, visited):
            queue.append(QItem(source.row, source.col - 1, source.dist + 1))
            visited[source.row][source.col - 1] = True
 
        # moving right
        if isValid(source.row, source.col + 1, grid, visited):
            queue.append(QItem(source.row, source.col + 1, source.dist + 1))
            visited[source.row][source.col + 1] = True
 
    return -1
 
 
# checking where move is valid or not
def isValid(x, y, grid, visited):
    if ((x >= 0 and y >= 0) and
        (x < len(grid) and y < len(grid[0])) and
            (grid[x][y] != '0') and (visited[x][y] == False)):
        return True
    return False
 
# Driver code
if __name__ == '__main__':
    grid = [['0', '*', '0', 's'],
            ['*', '0', '*', '*'],
            ['0', '*', '*', '*'],
            ['d', '*', '*', '*']]
 
    print(minDistance(grid))
 
    # This code is contributed by sajalmittaldei.

Time complexity: quadratic
Space complexity: quadratic
# Python3 program to compute number of sets
# in a binary matrix.
m = 3 # no of columns
n = 2 # no of rows
 
# function to calculate the number of
# non empty sets of cell
def countSets(a):
     
    # stores the final answer
    res = 0
     
    # traverses row-wise
    for i in range(n):
        u = 0
        v = 0
        for j in range(m):
            if a[i][j]:
                u += 1
            else:
                v += 1
        res += pow(2, u) - 1 + pow(2, v) - 1
     
    # traverses column wise
    for i in range(m):
         
        u = 0
        v = 0
        for j in range(n):
            if a[j][i]:
                u += 1
            else:
                v += 1
        res += pow(2, u) - 1 + pow(2, v) - 1
     
    # at the end subtract n*m as no of
    # single sets have been added twice.
    return res - (n*m)
 
# Driver program to test the above function.
a = [[1, 0, 1],[0, 1, 0]]
 
print(countSets(a))
 
# This code is contributed by shubhamsingh10

Time complexity: quadratic
Space complexity: constant