Banana-Leopard/TASTY huggingface dataset:
# Python3 program to replace all of the O's in the matrix
# with their shortest distance from a guard
from collections import deque as queue
 
# store dimensions of the matrix
M = 5
N = 5
 
 
# These arrays are used to get row and column
# numbers of 4 neighbors of a given cell
row = [-1, 0, 1, 0]
col = [0, 1, 0, -1]
 
# return true if row number and column number
# is in range
def isValid(i, j):
    if ((i < 0 or i > M - 1) or (j < 0 or j > N - 1)):
        return False
 
    return True
 
# return true if current cell is an open area and its
# distance from guard is not calculated yet
def isSafe(i, j,matrix, output):
 
    if (matrix[i][j] != 'O' or output[i][j] != -1):
        return False
 
    return True
 
# Function to replace all of the O's in the matrix
# with their shortest distance from a guard
def findDistance(matrix):
    output = [[ -1 for i in range(N)]for i in range(M)]
    q = queue()
 
    # finding Guards location and adding into queue
    for i in range(M):
        for j in range(N):
             
            # initialize each cell as -1
            output[i][j] = -1
            if (matrix[i][j] == 'G'):
                pos = [i, j, 0]
                q.appendleft(pos)
                 
                # guard has 0 distance
                output[i][j] = 0
 
 
 
    # do till queue is empty
    while (len(q) > 0):
         
        # get the front cell in the queue and update
        # its adjacent cells
        curr = q.pop()
        x, y, dist = curr[0], curr[1], curr[2]
 
        # do for each adjacent cell
        for i in range(4):
             
            # if adjacent cell is valid, has path and
            # not visited yet, en-queue it.
 
            if isValid(x + row[i], y + col[i]) and isSafe(x + row[i], y + col[i], matrix, output) :
                output[x + row[i]][y + col[i]] = dist + 1
 
                pos = [x + row[i], y + col[i], dist + 1]
                q.appendleft(pos)
 
    # print output matrix
 
    for i in range(M):
        for j in range(N):
            if output[i][j] > 0:
                print(output[i][j], end=" ")
            else:
                print(output[i][j],end=" ")
        print()
 
 
# Driver code
 
matrix = [['O', 'O', 'O', 'O', 'G'],
    ['O', 'W', 'W', 'O', 'O'],
    ['O', 'O', 'O', 'W', 'O'],
    ['G', 'W', 'W', 'W', 'O'],
    ['O', 'O', 'O', 'O', 'G']]
 
findDistance(matrix)
 
# This code is contributed by mohit kumar 29

Time complexity: quadratic
Space complexity: quadratic
# Program to count islands in boolean 2D matrix
class Graph:
 
    def __init__(self, row, col, g):
        self.ROW = row
        self.COL = col
        self.graph = g
 
    # A function to check if a given cell
    # (row, col) can be included in DFS
    def isSafe(self, i, j, visited):
        # row number is in range, column number
        # is in range and value is 1
        # and not yet visited
        return (i >= 0 and i < self.ROW and
                j >= 0 and j < self.COL and
                not visited[i][j] and self.graph[i][j])
 
    # A utility function to do DFS for a 2D
    # boolean matrix. It only considers
    # the 8 neighbours as adjacent vertices
 
    def DFS(self, i, j, visited):
 
        # These arrays are used to get row and
        # column numbers of 8 neighbours
        # of a given cell
        rowNbr = [-1, -1, -1,  0, 0,  1, 1, 1]
        colNbr = [-1,  0,  1, -1, 1, -1, 0, 1]
 
        # Mark this cell as visited
        visited[i][j] = True
 
        # Recur for all connected neighbours
        for k in range(8):
            if self.isSafe(i + rowNbr[k], j + colNbr[k], visited):
                self.DFS(i + rowNbr[k], j + colNbr[k], visited)
 
    # The main function that returns
    # count of islands in a given boolean
    # 2D matrix
 
    def countIslands(self):
        # Make a bool array to mark visited cells.
        # Initially all cells are unvisited
        visited = [[False for j in range(self.COL)]for i in range(self.ROW)]
 
        # Initialize count as 0 and traverse
        # through the all cells of
        # given matrix
        count = 0
        for i in range(self.ROW):
            for j in range(self.COL):
                # If a cell with value 1 is not visited yet,
                # then new island found
                if visited[i][j] == False and self.graph[i][j] == 1:
                    # Visit all cells in this island
                    # and increment island count
                    self.DFS(i, j, visited)
                    count += 1
 
        return count
 
 
graph = [[1, 1, 0, 0, 0],
         [0, 1, 0, 0, 1],
         [1, 0, 0, 1, 1],
         [0, 0, 0, 0, 0],
         [1, 0, 1, 0, 1]]
 
 
row = len(graph)
col = len(graph[0])
 
g = Graph(row, col, graph)
 
print("Number of islands is:")
print(g.countIslands())
 
# This code is contributed by Neelam Yadav

Time complexity: quadratic
Space complexity: quadratic
# Program to count islands in boolean 2D matrix
class Graph:
 
    def __init__(self, row, col, graph):
        self.ROW = row
        self.COL = col
        self.graph = graph
 
    # A utility function to do DFS for a 2D
    # boolean matrix. It only considers
    # the 8 neighbours as adjacent vertices
    def DFS(self, i, j):
        if i < 0 or i >= len(self.graph) or j < 0 or j >= len(self.graph[0]) or self.graph[i][j] != 1:
            return
 
        # mark it as visited
        self.graph[i][j] = -1
 
        # Recur for 8 neighbours
        self.DFS(i - 1, j - 1)
        self.DFS(i - 1, j)
        self.DFS(i - 1, j + 1)
        self.DFS(i, j - 1)
        self.DFS(i, j + 1)
        self.DFS(i + 1, j - 1)
        self.DFS(i + 1, j)
        self.DFS(i + 1, j + 1)
 
    # The main function that returns
    # count of islands in a given boolean
    # 2D matrix
    def countIslands(self):
        # Initialize count as 0 and traverse
        # through the all cells of
        # given matrix
        count = 0
        for i in range(self.ROW):
            for j in range(self.COL):
                # If a cell with value 1 is not visited yet,
                # then new island found
                if self.graph[i][j] == 1:
                    # Visit all cells in this island
                    # and increment island count
                    self.DFS(i, j)
                    count += 1
 
        return count
 
 
graph = [
    [1, 1, 0, 0, 0],
    [0, 1, 0, 0, 1],
    [1, 0, 0, 1, 1],
    [0, 0, 0, 0, 0],
    [1, 0, 1, 0, 1]
]
 
 
row = len(graph)
col = len(graph[0])
 
g = Graph(row, col, graph)
 
print("Number of islands is:", g.countIslands())
 
# This code is contributed by Shivam Shrey

Time complexity: quadratic
Space complexity: quadratic
# Python3 program to count walks from
# u to v with exactly k edges
 
# Number of vertices in the graph
V = 4
 
# A naive recursive function to count
# walks from u to v with k edges
def countwalks(graph, u, v, k):
 
    # Base cases
    if (k == 0 and u == v):
        return 1
    if (k == 1 and graph[u][v]):
        return 1
    if (k <= 0):
        return 0
     
    # Initialize result
    count = 0
     
    # Go to all adjacents of u and recur
    for i in range(0, V):
         
        # Check if is adjacent of u
        if (graph[u][i] == 1):
            count += countwalks(graph, i, v, k-1)
     
    return count
 
# Driver Code
 
# Let us create the graph shown in above diagram
graph = [[0, 1, 1, 1, ],
         [0, 0, 0, 1, ],
         [0, 0, 0, 1, ],
         [0, 0, 0, 0] ]
 
u = 0; v = 3; k = 2
print(countwalks(graph, u, v, k))
 
# This code is contributed by Smitha Dinesh Semwal.

Time complexity: quadratic
Space complexity: linear
# Python3 program to count walks from
# u to v with exactly k edges
 
# Number of vertices
V = 4
 
# A Dynamic programming based function
# to count walks from u to v with k edges
 
 
def countwalks(graph, u, v, k):
 
    # Table to be filled up using DP.
    # The value count[i][j][e] will/
    # store count of possible walks
    # from i to j with exactly k edges
    count = [[[0 for k in range(k + 1)]
              for i in range(V)]
             for j in range(V)]
 
    # Loop for number of edges from 0 to k
    for e in range(0, k + 1):
        # For Source
        for i in range(V):
            # For Destination
            for j in range(V):
                # Initialize value
                # count[i][j][e] = 0
 
                # From base cases
                if (e == 0 and i == j):
                    count[i][j][e] = 1
                if (e == 1 and graph[i][j] != 0):
                    count[i][j][e] = 1
 
                # Go to adjacent only when number
                # of edges is more than 1
                if (e > 1):
 
                    for a in range(V):
 
                        # Adjacent of i
                        if (graph[i][a] != 0):
                            count[i][j][e] += count[a][j][e - 1]
 
    return count[u][v][k]
 
 
# Driver code
if __name__ == '__main__':
 
    # Let us create the graph shown
    # in above diagram
    graph = [[0, 1, 1, 1],
             [0, 0, 0, 1],
             [0, 0, 0, 1],
             [0, 0, 0, 0]]
 
    u = 0
    v = 3
    k = 2
 
    print(countwalks(graph, u, v, k))
 
# This code is contributed by Rajput-Ji

Time complexity: cubic
Space complexity: np
# Python program to print all paths from a source to destination.
  
from collections import defaultdict
  
# This class represents a directed graph
# using adjacency list representation
class Graph:
  
    def __init__(self, vertices):
        # No. of vertices
        self.V = vertices
         
        # default dictionary to store graph
        self.graph = defaultdict(list)
  
    # function to add an edge to graph
    def addEdge(self, u, v):
        self.graph[u].append(v)
  
    '''A recursive function to print all paths from 'u' to 'd'.
    visited[] keeps track of vertices in current path.
    path[] stores actual vertices and path_index is current
    index in path[]'''
    def printAllPathsUtil(self, u, d, visited, path):
 
        # Mark the current node as visited and store in path
        visited[u]= True
        path.append(u)
 
        # If current vertex is same as destination, then print
        # current path[]
        if u == d:
            print (path)
        else:
            # If current vertex is not destination
            # Recur for all the vertices adjacent to this vertex
            for i in self.graph[u]:
                if visited[i]== False:
                    self.printAllPathsUtil(i, d, visited, path)
                     
        # Remove current vertex from path[] and mark it as unvisited
        path.pop()
        visited[u]= False
  
  
    # Prints all paths from 's' to 'd'
    def printAllPaths(self, s, d):
 
        # Mark all the vertices as not visited
        visited =[False]*(self.V)
 
        # Create an array to store paths
        path = []
 
        # Call the recursive helper function to print all paths
        self.printAllPathsUtil(s, d, visited, path)
  
  
  
# Create a graph given in the above diagram
g = Graph(4)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(0, 3)
g.addEdge(2, 0)
g.addEdge(2, 1)
g.addEdge(1, 3)
  
s = 2 ; d = 3
print ("Following are all different paths from % d to % d :" %(s, d))
g.printAllPaths(s, d)
# This code is contributed by Neelam Yadav

Time complexity: quadratic
Space complexity: np
# Python3 code to check if
# cyclic order is possible
# among strings under given
# constraints
M = 26
 
# Utility method for a depth
# first search among vertices
def dfs(g, u, visit):
    visit[u] = True
 
    for i in range(len(g[u])):
        if(not visit[g[u][i]]):
            dfs(g, g[u][i], visit)
 
# Returns true if all vertices
# are strongly connected i.e.
# can be made as loop
def isConnected(g, mark, s):
 
    # Initialize all vertices
    # as not visited
    visit = [False for i in range(M)]
 
    # Perform a dfs from s
    dfs(g, s, visit)
 
    # Now loop through
    # all characters
    for i in range(M):
 
        # I character is marked
        # (i.e. it was first or last
        # character of some string)
        # then it should be visited
        # in last dfs (as for looping,
        # graph should be strongly
        # connected) */
        if(mark[i] and (not visit[i])):
            return False
           
    # If we reach that means
    # graph is connected
    return True
 
# return true if an order among
# strings is possible
def possibleOrderAmongString(arr, N):
 
    # Create an empty graph
    g = {}
 
    # Initialize all vertices
    # as not marked
    mark = [False for i in range(M)]
 
    # Initialize indegree and
    # outdegree of every
    # vertex as 0.
    In = [0 for i in range(M)]
    out = [0 for i in range(M)]
 
    # Process all strings
    # one by one
    for i in range(N):
 
        # Find first and last
        # characters
        f = (ord(arr[i][0]) -
             ord('a'))
        l = (ord(arr[i][-1]) -
             ord('a'))
 
        # Mark the characters
        mark[f] = True
        mark[l] = True
 
        # Increase indegree
        # and outdegree count
        In[l] += 1
        out[f] += 1
 
        if f not in g:
            g[f] = []
 
        # Add an edge in graph
        g[f].append(l)
 
    # If for any character
    # indegree is not equal to
    # outdegree then ordering
    # is not possible
    for i in range(M):
        if(In[i] != out[i]):
            return False
           
    return isConnected(g, mark,
                       ord(arr[0][0]) -
                       ord('a'))
 
# Driver code
arr = ["ab", "bc",
       "cd", "de",
       "ed", "da"]
N = len(arr)
if(possibleOrderAmongString(arr, N) ==
   False):
    print("Ordering not possible")
else:
    print("Ordering is possible")
 
# This code is contributed by avanitrachhadiya2155

Time complexity: linear
Space complexity: linear
# Python3 program for the above approach
def maxindex(dist, n):
    mi = 0
    for i in range(n):
        if (dist[i] > dist[mi]):
            mi = i
    return mi
 
def selectKcities(n, weights, k):
    dist = [0]*n
    centers = []
 
    for i in range(n):
        dist[i] = 10**9
         
    # index of city having the
    # maximum distance to it's
    # closest center
    max = 0
    for i in range(k):
        centers.append(max)
        for j in range(n):
 
            # updating the distance
            # of the cities to their
            # closest centers
            dist[j] = min(dist[j], weights[max][j])
 
        # updating the index of the
        # city with the maximum
        # distance to it's closest center
        max = maxindex(dist, n)
 
    # Printing the maximum distance
    # of a city to a center
    # that is our answer
    # print()
    print(dist[max])
 
    # Printing the cities that
    # were chosen to be made
    # centers
    for i in centers:
        print(i, end = " ")
 
# Driver Code
if __name__ == '__main__':
    n = 4
    weights = [ [ 0, 4, 8, 5 ],
              [ 4, 0, 10, 7 ],
              [ 8, 10, 0, 9 ],
              [ 5, 7, 9, 0 ] ]
    k = 2
 
    # Function Call
    selectKcities(n, weights, k)
 
# This code is contributed by mohit kumar 29.

Time complexity: quadratic
Space complexity: constant
# Python3 program to find the minimum
# number of operations required to
# make all elements of array equal
from collections import defaultdict
 
# Function for min operation
def minOperation(arr, n):
 
    # Insert all elements in hash.
    Hash = defaultdict(lambda:0)
    for i in range(0, n):
        Hash[arr[i]] += 1
 
    # find the max frequency
    max_count = 0
    for i in Hash:
        if max_count < Hash[i]:
            max_count = Hash[i]
 
    # return result
    return n - max_count
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 5, 2, 1, 3, 2, 1]
    n = len(arr)
    print(minOperation(arr, n))
     
# This code is contributed
# by Rituraj Jain

Time complexity: linear
Space complexity: linear
# Python program to find maximum distance between two
# same occurrences of a number.
 
# Function to find maximum distance between equal elements
def maxDistance(arr, n):
     
    # Used to store element to first index mapping
    mp = {}
 
    # Traverse elements and find maximum distance between
    # same occurrences with the help of map.
    maxDict = 0
    for i in range(n):
 
        # If this is first occurrence of element, insert its
        # index in map
        if arr[i] not in mp.keys():
            mp[arr[i]] = i
 
        # Else update max distance
        else:
            maxDict = max(maxDict, i-mp[arr[i]])
 
    return maxDict
 
# Driver Program
if __name__=='__main__':
    arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2]
    n = len(arr)
    print (maxDistance(arr, n))
         
# Contributed By: Harshit Sidhwa

Time complexity: linear
Space complexity: linear
# python3 program to find maximum number of 2D points that lie on the same line.
 
from collections import defaultdict
from math import gcd
from typing import DefaultDict, List, Tuple
 
IntPair = Tuple[int, int]
 
 
def normalized_slope(a: IntPair, b: IntPair) -> IntPair:
    """
    Returns normalized (rise, run) tuple. We won't return the actual rise/run
    result in order to avoid floating point math, which leads to faulty
    comparisons.
 
    See
    https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems
    """
    run = b[0] - a[0]
 
    # normalize undefined slopes to (1, 0)
    if run == 0:
        return (1, 0)
 
    # normalize to left-to-right
    if run < 0:
        a, b = b, a
        run = b[0] - a[0]
 
    rise = b[1] - a[1]
    # Normalize by greatest common divisor.
    # math.gcd only works on positive numbers.
    gcd_ = gcd(abs(rise), run)
    return (
        rise // gcd_,
        run // gcd_,
    )
 
 
def maximum_points_on_same_line(points: List[List[int]]) -> int:
    # You need at least 3 points to potentially have non-collinear points.
    # For [0, 2] points, all points are on the same line.
    if len(points) < 3:
        return len(points)
 
    # Note that every line we find will have at least 2 points.
    # There will be at least one line because len(points) >= 3.
    # Therefore, it's safe to initialize to 0.
    max_val = 0
 
    for a_index in range(0, len(points) - 1):
        # All lines in this iteration go through point a.
        # Note that lines a-b and a-c cannot be parallel.
        # Therefore, if lines a-b and a-c have the same slope, they're the same
        # line.
        a = tuple(points[a_index])
        # Fresh lines already have a, so default=1
        slope_counts: DefaultDict[IntPair, int] = defaultdict(lambda: 1)
 
        for b_index in range(a_index + 1, len(points)):
            b = tuple(points[b_index])
            slope_counts[normalized_slope(a, b)] += 1
 
        max_val = max(
            max_val,
            max(slope_counts.values()),
        )
 
    return max_val
 
 
print(maximum_points_on_same_line([
    [-1, 1],
    [0, 0],
    [1, 1],
    [2, 2],
    [3, 3],
    [3, 4],
]))
 
# This code is contributed by Jose Alvarado Torre

Time complexity: quadratic
Space complexity: linear
# Python3 implementation of the
# above approach
 
# Function to find the Duplicates,
# if duplicate occurs 2 times or
# more than 2 times in array so,
# it will print duplicate value
# only once at output
def findDuplicates(arr, Len):
     
    # Initialize ifPresent as false
    ifPresent = False
 
    # ArrayList to store the output
    a1 = []
    for i in range(Len - 1):
        for j in range(i + 1, Len):
 
            # Checking if element is
            # present in the ArrayList
            # or not if present then break
            if (arr[i] == arr[j]):
                if arr[i] in a1:
                    break
                 
                # If element is not present in the
                # ArrayList then add it to ArrayList
                # and make ifPresent at true
                else:
                    a1.append(arr[i])
                    ifPresent = True
 
    # If duplicates is present
    # then print ArrayList
    if (ifPresent):
        print(a1, end = " ")
    else:
        print("No duplicates present in arrays")
 
# Driver Code
arr = [ 12, 11, 40, 12, 5, 6, 5, 12, 11 ]
n = len(arr)
 
findDuplicates(arr, n)
 
# This code is contributed by rag2127

Time complexity: quadratic
Space complexity: linear
# Python3 program to find duplicates
# using dictionary approach.
def printDuplicates(arr):
    dict = {}
 
    for ele in arr:
        try:
            dict[ele] += 1
        except:
            dict[ele] = 1
             
    for item in dict:
         
         # if frequency is more than 1
         # print the element
        if(dict[item] > 1):
            print(item, end=" ")
 
    print("\n")
 
# Driver Code
if __name__ == "__main__":
    list = [12, 11, 40, 12,
            5, 6, 5, 12, 11]
    printDuplicates(list)
 
# This code is contributed
# by Sushil Bhile

Time complexity: linear
Space complexity: linear
# Python program to find top k elements in a stream
 
# Function to print top k numbers
def kTop(a, n, k):
 
    # list of size k + 1 to store elements
    top = [0 for i in range(k + 1)]
  
    # dictionary to keep track of frequency
    freq = {i:0 for i in range(k + 1)}
 
    # iterate till the end of stream
    for m in range(n):
 
        # increase the frequency
        if a[m] in freq.keys():
            freq[a[m]] += 1
        else:
            freq[a[m]] = 1
 
        # store that element in top vector
        top[k] = a[m]
  
        i = top.index(a[m])
        i -= 1
         
        while i >= 0:
 
            # compare the frequency and swap if higher
            # frequency element is stored next to it
            if (freq[top[i]] < freq[top[i + 1]]):
                t = top[i]
                top[i] = top[i + 1]
                top[i + 1] = t
             
            # if frequency is same compare the elements
            # and swap if next element is high
            else if ((freq[top[i]] == freq[top[i + 1]]) and (top[i] > top[i + 1])):
                t = top[i]
                top[i] = top[i + 1]
                top[i + 1] = t
            else:
                break
            i -= 1
         
        # print top k elements
        i = 0
        while i < k and top[i] != 0:
            print(top[i],end=" ")
            i += 1
    print()
  
# Driver program to test above function
k = 4
arr = [ 5, 2, 1, 3, 2 ]
n = len(arr)
kTop(arr, n, k)
 
# This code is contributed by Sachin Bisht

Time complexity: quadratic
Space complexity: linear
# Python3 program to find the most
# frequent element in an array.
def mostFrequent(arr, n):
  maxcount = 0;
  element_having_max_freq = 0;
  for i in range(0, n):
    count = 0
    for j in range(0, n):
      if(arr[i] == arr[j]):
        count += 1
    if(count > maxcount):
      maxcount = count
      element_having_max_freq = arr[i]
   
  return element_having_max_freq;
 
# Driver Code
arr = [40,50,30,40,50,30,30]
n = len(arr)
print(mostFrequent(arr, n))
 
# This code is contributed by Arpit Jain

Time complexity: quadratic
Space complexity: constant
# Python3 program to find the most
# frequent element in an array.
 
 
def mostFrequent(arr, n):
 
    # Sort the array
    arr.sort()
 
    # find the max frequency using
    # linear traversal
    max_count = 1
    res = arr[0]
    curr_count = 1
 
    for i in range(1, n):
        if (arr[i] == arr[i - 1]):
            curr_count += 1
        else:
            curr_count = 1
 
         # If last element is most frequent
        if (curr_count > max_count):
            max_count = curr_count
            res = arr[i - 1]
 
    return res
 
 
# Driver Code
arr = [40,50,30,40,50,30,30]
n = len(arr)
print(mostFrequent(arr, n))
 
# This code is contributed by Smitha Dinesh Semwal.

Time complexity: nlogn
Space complexity: constant