Banana-Leopard/TASTY huggingface dataset:
node = {"data":0,"maximum":0}
 
# It is a modification  in the way of implementation of
# queue using two stack
def insert( s2, val):
   
  # inserting the element in s2
  other = node
  other["data"] = val
     
  if (len(s2)==0):
    other["maximum"] = val
  else:
    front = node
    front["data"] = s2[0]["data"]
    front["maximum"] = s2[0]["maximum"]
    # updating maximum in that stack append it
    other["maximum"] = max(val, front["maximum"])
  s2.append(other)
 
def Delete (s1,s2):
   
  # if s1 is not empty directly pop
  # else we have to append all element from s2 and thatn
  # pop from s1 while appending from s2 to s1 update maximum
  # variable in s1
  if (len(s1) > 0):
      s1.pop()
  else:
    while (len(s2) > 0):
      val = node
      val = s2[0]
      insert(s1, val["data"])
      s2.pop()
    s1.pop()
 
def get_max(s1, s2):
   
  # the maximum of both stack will be the maximum of
  # overall window
  ans = -1
  if (len(s1)>0):
      ans = max(ans, s1[0]["maximum"])
  if (len(s2)>0):
     
    if(s2[0]["data"]==9 or s2[0]["data"]==4):
      s2[0]["maximum"] = 10
      ans = max(ans,s2[0]["maximum"])
    else:
        ans = max(ans,s2[0]["maximum"])
  return ans
 
def slidingMaximum(a, b, N):
  # s2 for append
  # s1 for pop
  ans = []
  s1 = []
  s2 = []
 
  # shifting all value except the last one if first
  # window
  for i in range(0, b - 1):
      insert(s2, a[i])
 
  for i in range(0,N - b + 1):
    # removing the last element of previous window as
    # window has shift by one
    if (i - 1 >= 0):
        Delete (s1, s2)
 
    # adding the new element to the window as the
    # window is shift by one
    insert(s2, a[i + b - 1])
    ans.append(get_max(s1, s2))
  return ans
 
# Driver's code
arr = [ 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 ]
N = len(arr)
K = 4
 
# Function call
ans = slidingMaximum(arr, K, N)
print(ans)
 
# This code is contributed by akashish__

Time complexity: linear
Space complexity: constant
# Python program to find circular tour for a truck
# In this approach we will start the tour from the first petrol pump
# then while moving to the next pumps in the loop we will store the cumulative
# information that whether we have a deficit of petrol at the current pump or not
# If there is a deficit then we will add it to the deficit value calculated
# till the previous petrol pump and then update the starting point to the next pump
# and reset the petrol available in the truck as 0
 
# This function return starting point if there is a possible
# solution otherwise returns -1
def printTour(arr,n):
     
    # Consider first petrol pump as starting point
    start = 0
    # These two variable will keep tracking if there is
    # surplus(s) or deficit(d) of petrol in the truck
    s = 0          # petrol available the truck till now
    d = 0        # deficit of petrol till visiting this petrol pump
     
    # Start from the first petrol pump and complete one loop
    # of visiting all the petrol pumps and keep updating s and d at each pump
    for i in range(n):
      s += arr[i][0] - arr[i][1]
      if s < 0:            # the truck has a deficit of petrol
        start = i+1        # change the starting point
        d += s            # storing the deficit of petrol till current petrol pump
        s = 0            # starting again from new station
     
    # when we reach first petrol pump again and sum of the petrol available at the truck
    # and the petrol deficit till now is 0 or more petrol then return the starting point
    # else return -1
    return start if (s+d)>=0 else -1
   
   
# Driver program to test above function
arr = [[6,4], [3,6], [7,3]]
start = printTour(arr,3)
if start == -1:
  print("No Solution Possible !!!")
else:
  print("start = {}".format(start))
 
# This code is contributed by Antara Das(anny)

Time complexity: linear
Space complexity: constant
# Python program to find circular tour for a truck
 
# A petrol pump has petrol and distance to next petrol pump
class petrolPump:
    def __init__(self, petrol, distance):
        self.petrol = petrol
        self.distance = distance
 
# The function returns starting point if there is a
# possible solution, otherwise returns -1
def printTour(arr, n):
    start = 0
 
    for i in range(n):
       
        # Identify the first petrol pump from where we
        # might get a full circular tour
        if arr[i].petrol >= arr[i].distance:
            start = i
            break
             
    # To store the excess petrol
    curr_petrol = 0
    for i in range(start, n):
        curr_petrol += (arr[i].petrol - arr[i].distance)
 
        # If at any point remaining petrol is less than 0,
        # it means that we cannot start our journey from
        # current start
        if(curr_petrol < 0):
 
            # We move to the next petrol pump
            i += 1
 
            # We try to identify the next petrol pump from
            # where we might get a full circular tour
            while(i < n):
                if(arr[i].petrol >= arr[i].distance):
                    start = i
 
                    # Reset rem_petrol
                    curr_petrol = 0
                    break
                i += 1
 
        else:
            # Move to the next petrolpump if curr_petrol is
            # >= 0
            i += 1
 
    ''' If remaining petrol is less than 0 while we reach the
     first petrol pump, it means no circular tour is
     possible '''
    if(curr_petrol < 0):
        return -1
 
    for i in range(start):
        curr_petrol += (arr[i].petrol - arr[i].distance)
 
        ''' If remaining petrol is less than 0 at any point
         before we reach initial start, it means no
         circular tour is possible '''
        if(curr_petrol < 0):
            return -1
 
    ''' If we have successfully reached intial_start, it
     means can get a circular tour from final_start, hence
     return it '''
    return start
 
# Driver code
arr = [petrolPump(6, 4), petrolPump(3, 6), petrolPump(7, 3)]
start = printTour(arr, len(arr))
if start == -1:
    print("No solution")
else:
    print("Start = {}".format(start))
 
# This code is contributed by jainlovely450

Time complexity: linear
Space complexity: constant
# Python program to find circular tour for a truck
 
# A petrol pump has petrol and distance to next petrol pump
class petrolPump:
    def __init__(self,a, b):
        self.petrol = a;
        self.distance = b;
     
# The function returns starting point if there is a
# possible solution, otherwise returns -1
def printTour( p, n):
 
    # deficit is used to store the value of the capacity as
    # soon as the value of capacity becomes negative so as
    # not to traverse the array twice in order to get the
    # solution
    start = 0;
    deficit = 0;
    capacity = 0;
    for i in range(n):
        capacity += p[i].petrol - p[i].distance;
        if (capacity < 0):
            # If this particular step is not done then the
            # between steps would be redundant
            start = i + 1;
            deficit += capacity;
            capacity = 0;
         
    if(capacity + deficit >= 0):
        return start;
    else:
        return -1;
 
# Driver code
if __name__ == '__main__':
    arr = [petrolPump(6, 4),petrolPump(3, 6),petrolPump(7, 3)] ;
 
    n = len(arr);
    start = printTour(arr, n);
 
    if (start == -1):
        print("No solution");
    else:
        print("Start = " , start);
 
 
# This code is contributed by Rajput-Ji

Time complexity: linear
Space complexity: constant
# Python3 program to find smallest multiple of
# a given number made of digits 0 and 9 only
from queue import Queue
 
# Preprocessing function to generate
# all possible numbers formed by 0 and 9
def generateNumbersUtil():
    global vec
     
    # Create an empty queue of strings
    q = Queue()
         
    # enqueue the first number
    q.put("9")
     
    # This loops is like BFS of a tree
    # with 9 as root, 0 as left child
    # and 9 as right child and so on
    for count in range(MAX_COUNT, -1, -1):
        s1 = q.queue[0]
        q.get()
         
        # storing the front of queue
        # in the vector
        vec.append(s1)
         
        s2 = s1
         
        # Append "0" to s1 and enqueue it
        s1 += "0"
        q.put(s1)
         
        # Append "9" to s2 and enqueue it. Note
        # that s2 contains the previous front
        s2 += "9"
        q.put(s2)
 
# function to find smallest number made
# up of only digits 9’s and 0’s, which
# is a multiple of n.
def findSmallestMultiple(n):
    global vec
     
    # traverse the vector to find
    # the smallest multiple of n
    for i in range(len(vec)):
 
        # int is used for string to
        # conversion
        if (int(vec[i]) % n == 0):
            return vec[i]
 
# Driver Code
 
# Maximum number of numbers
# made of 0 and 9
MAX_COUNT = 10000
 
# stack to store all numbers that
# can be formed using digits 0 and
# 9 and are less than 10^5
vec = []
generateNumbersUtil()    
n = 7   
print(findSmallestMultiple(n))
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: np
# Python3 program to generate binary numbers from
# 1 to n
 
# This function uses queue data structure to print binary numbers
 
 
def generatePrintBinary(n):
 
    # Create an empty queue
    from queue import Queue
    q = Queue()
 
    # Enqueue the first binary number
    q.put("1")
 
    # This loop is like BFS of a tree with 1 as root
    # 0 as left child and 1 as right child and so on
    while(n > 0):
        n -= 1
        # Print the front of queue
        s1 = q.get()
        print(s1)
 
        s2 = s1  # Store s1 before changing it
 
        # Append "0" to s1 and enqueue it
        q.put(s1+"0")
 
        # Append "1" to s2 and enqueue it. Note that s2
        # contains the previous front
        q.put(s2+"1")
 
 
# Driver code
if __name__ == "__main__":
    n = 10
 
    # Function call
    generatePrintBinary(n)
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Time complexity: linear
Space complexity: linear
# Python3 program to find Sum of all minimum and maximum
# elements Of Sub-array Size k.
from collections import deque
 
# Returns Sum of min and max element of all subarrays
# of size k
def SumOfKsubArray(arr, n , k):
 
    Sum = 0 # Initialize result
 
    # The queue will store indexes of useful elements
    # in every window
    # In deque 'G' we maintain decreasing order of
    # values from front to rear
    # In deque 'S' we maintain increasing order of
    # values from front to rear
    S = deque()
    G = deque()
 
 
    # Process first window of size K
 
    for i in range(k):
         
        # Remove all previous greater elements
        # that are useless.
        while ( len(S) > 0 and arr[S[-1]] >= arr[i]):
            S.pop() # Remove from rear
 
        # Remove all previous smaller that are elements
        # are useless.
        while ( len(G) > 0 and arr[G[-1]] <= arr[i]):
            G.pop() # Remove from rear
 
        # Add current element at rear of both deque
        G.append(i)
        S.append(i)
 
    # Process rest of the Array elements
    for i in range(k, n):
         
        # Element at the front of the deque 'G' & 'S'
        # is the largest and smallest
        # element of previous window respectively
        Sum += arr[S[0]] + arr[G[0]]
 
        # Remove all elements which are out of this
        # window
        while ( len(S) > 0 and S[0] <= i - k):
            S.popleft()
        while ( len(G) > 0 and G[0] <= i - k):
            G.popleft()
 
        # remove all previous greater element that are
        # useless
        while ( len(S) > 0 and arr[S[-1]] >= arr[i]):
            S.pop() # Remove from rear
 
        # remove all previous smaller that are elements
        # are useless
        while ( len(G) > 0 and arr[G[-1]] <= arr[i]):
            G.pop() # Remove from rear
 
        # Add current element at rear of both deque
        G.append(i)
        S.append(i)
 
    # Sum of minimum and maximum element of last window
    Sum += arr[S[0]] + arr[G[0]]
 
    return Sum
 
# Driver program to test above functions
arr=[2, 5, -1, 7, -3, -1, -2]
n = len(arr)
k = 3
print(SumOfKsubArray(arr, n, k))
 
# This code is contributed by mohit kumar

Time complexity: linear
Space complexity: constant
# Python3 program to find distance of
# nearest cell having 1 in a binary matrix.
 
# Print distance of nearest cell
# having 1 for each cell.
 
 
def printDistance(mat):
    global N, M
    ans = [[None] * M for i in range(N)]
 
    # Initialize the answer matrix
    # with INT_MAX.
    for i in range(N):
        for j in range(M):
            ans[i][j] = 999999999999
 
    # For each cell
    for i in range(N):
        for j in range(M):
 
            # Traversing the whole matrix
            # to find the minimum distance.
            for k in range(N):
                for l in range(M):
 
                    # If cell contain 1, check
                    # for minimum distance.
                    if (mat[k][l] == 1):
                        ans[i][j] = min(ans[i][j],
                                        abs(i - k) + abs(j - l))
 
    # Printing the answer.
    for i in range(N):
        for j in range(M):
            print(ans[i][j], end=" ")
        print()
 
 
# Driver Code
if __name__ == '__main__':
  N = 3
  M = 4
  mat = [[0, 0, 0, 1],
         [0, 0, 1, 1],
         [0, 1, 1, 0]]
 
  # Function call
  printDistance(mat)
 
# This code is contributed by PranchalK

Time complexity: quadratic
Space complexity: quadratic
# Python3 program for the above approach
 
import sys
 
 
class matrix_element:
 
    def __init__(self, row, col):
        self.row = row
        self.col = col
 
 
def printDistance(arr):
    Row_Count = len(arr)
    Col_Count = len(arr[0])
 
    q = []
 
    # Adding all ones in queue
    for i in range(Row_Count):
        for j in range(Col_Count):
            if (arr[i][j] == 1):
                q.append(matrix_element(i, j))
 
    # In order to find min distance we will again
    # traverse all elements in Matrix. If its zero then
    # it will check against all 1's in Queue. Whatever
    # will be dequeued from queued, will be enqueued
    # back again.
 
    Queue_Size = len(q)
    for i in range(Row_Count):
 
        for j in range(Col_Count):
 
            distance = 0
            min_distance = sys.maxsize
 
            if (arr[i][j] == 0):
 
                for k in range(Queue_Size):
 
                    One_Pos = q[0]
                    q = q[1:]
                    One_Row = One_Pos.row
                    One_Col = One_Pos.col
                    distance = abs(One_Row - i) + abs(One_Col - j)
                    min_distance = min(min_distance, distance)
                    if (min_distance == 1):
 
                        arr[i][j] = 1
                        q.append(matrix_element(One_Row, One_Col))
                        break
 
                    q.append(matrix_element(One_Row, One_Col))
 
                    arr[i][j] = min_distance
 
            else:
                arr[i][j] = 0
 
    # print elements
    for i in range(Row_Count):
        for j in range(Col_Count):
            print(arr[i][j], end=" ")
 
        print()
 
 
# Driver code
if __name__ == '__main__':
  arr = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 0]]
 
  # Function call
  printDistance(arr)
 
# This code is contributed by shinjanpatra

Time complexity: quadratic
Space complexity: quadratic
# Python3 program to find distance of nearest
# cell having 1 in a binary matrix.
from collections import deque
 
MAX = 500
N = 3
M = 4
 
# Making a class of graph with bfs function.
g = [[] for i in range(MAX)]
n, m = 0, 0
 
# Function to create graph with N*M nodes
# considering each cell as a node and each
# boundary as an edge.
 
 
def createGraph():
 
    global g, n, m
 
    # A number to be assigned to a cell
    k = 1
 
    for i in range(1, n + 1):
        for j in range(1, m + 1):
 
            # If last row, then add edge on right side.
            if (i == n):
 
                # If not bottom right cell.
                if (j != m):
                    g[k].append(k + 1)
                    g[k + 1].append(k)
 
            # If last column, then add edge toward down.
            elif (j == m):
                g[k].append(k+m)
                g[k + m].append(k)
 
            # Else makes an edge in all four directions.
            else:
                g[k].append(k + 1)
                g[k + 1].append(k)
                g[k].append(k+m)
                g[k + m].append(k)
 
            k += 1
 
# BFS function to find minimum distance
 
 
def bfs(visit, dist, q):
 
    global g
    while (len(q) > 0):
        temp = q.popleft()
 
        for i in g[temp]:
            if (visit[i] != 1):
                dist[i] = min(dist[i], dist[temp] + 1)
                q.append(i)
                visit[i] = 1
 
    return dist
 
# Printing the solution.
 
 
def prt(dist):
 
    c = 1
    for i in range(1, n * m + 1):
        print(dist[i], end=" ")
        if (c % m == 0):
            print()
 
        c += 1
 
# Find minimum distance
 
 
def findMinDistance(mat):
 
    global g, n, m
 
    # Creating a graph with nodes values assigned
    # from 1 to N x M and matrix adjacent.
    n, m = N, M
    createGraph()
 
    # To store minimum distance
    dist = [0] * MAX
 
    # To mark each node as visited or not in BFS
    visit = [0] * MAX
 
    # Initialising the value of distance and visit.
    for i in range(1, M * N + 1):
        dist[i] = 10**9
        visit[i] = 0
 
    # Inserting nodes whose value in matrix
    # is 1 in the queue.
    k = 1
    q = deque()
    for i in range(N):
        for j in range(M):
            if (mat[i][j] == 1):
                dist[k] = 0
                visit[k] = 1
                q.append(k)
 
            k += 1
 
    # Calling for Bfs with given Queue.
    dist = bfs(visit, dist, q)
 
    # Printing the solution.
    prt(dist)
 
 
# Driver code
if __name__ == '__main__':
 
    mat = [[0, 0, 0, 1],
           [0, 0, 1, 1],
           [0, 1, 1, 0]]
 
    # Function call
    findMinDistance(mat)
 
# This code is contributed by mohit kumar 29

Time complexity: quadratic
Space complexity: quadratic
"""
Python program to do level order traversal
line by line using dual queue"""
class GFG:
     
    """Constructor to create a new tree node"""
    def __init__(self,data):
        self.val = data
        self.left = None
        self.right = None
     
    """Prints level order traversal line by
    line using two queues."""
    def levelOrder(self,node):
        q1 = [] # Queue 1
        q2 = [] # Queue 2
        q1.append(node)
         
        """Executing loop till both the
        queues become empty"""
        while(len(q1) > 0 or len(q2) > 0):
         
            """Empty string to concatenate
            the string for q1"""
            concat_str_q1 = ''
            while(len(q1) > 0):
                 
                """Poped node at the first
                pos in queue 1 i.e q1"""
                poped_node = q1.pop(0)
                concat_str_q1 += poped_node.val +' '
                 
                """Pushing left child of current
                node in first queue into second queue"""
                if poped_node.left:
                    q2.append(poped_node.left)
                     
                """Pushing right child of current node
                in first queue into second queue"""
                if poped_node.right:
                    q2.append(poped_node.right)
            print( str(concat_str_q1))
            concat_str_q1 = ''
             
            """Empty string to concatenate the
            string for q1"""
            concat_str_q2 = ''
            while (len(q2) > 0):
             
                """Poped node at the first pos
                in queue 1 i.e q1"""
                poped_node = q2.pop(0)
                concat_str_q2 += poped_node.val + ' '
                 
                """Pushing left child of current node
                in first queue into first queue"""
                if poped_node.left:
                    q1.append(poped_node.left)
                 
                """Pushing right child of current node
                in first queue into first queue"""
                if poped_node.right:
                    q1.append(poped_node.right)
            print(str(concat_str_q2))
            concat_str_q2 = ''
 
""" Driver program to test above functions"""
node = GFG("1")
node.left = GFG("2")
node.right = GFG("3")
node.left.left = GFG("4")
node.left.right = GFG("5")
node.right.right = GFG("6")
node.levelOrder(node)
 
# This code is contributed by Vaibhav Kumar 12

Time complexity: linear
Space complexity: linear
# Python3 program to find min sum of
# squares of characters after k removals
from queue import PriorityQueue
 
MAX_CHAR = 26
 
# Main Function to calculate min sum of
# squares of characters after k removals
def minStringValue(str, k):
    l = len(str) # find length of string
 
    # if K is greater than length of string
    # so reduced string will become 0
    if(k >= l):
        return 0
     
    # Else find Frequency of each
    # character and store in an array
    frequency = [0] * MAX_CHAR
    for i in range(0, l):
        frequency[ord(str[i]) - 97] += 1
 
    # Push each char frequency negative
    # into a priority_queue as the queue
    # by default is minheap
    q = PriorityQueue()
    for i in range(0, MAX_CHAR):
        q.put(-frequency[i])
 
    # Removal of K characters
    while(k > 0):
         
        # Get top element in priority_queue
        # multiply it by -1 as temp is negative
        # remove it. Increment by 1 and again
        # push into priority_queue
        temp = q.get()
        temp = temp + 1
        q.put(temp, temp)
        k = k - 1
 
    # After removal of K characters find
    # sum of squares of string Value    
    result = 0; # initialize result
    while not q.empty():
        temp = q.get()
        temp = temp * (-1)
        result += temp * temp
    return result
 
# Driver Code
if __name__ == "__main__":
    str = "abbccc"
    k = 2
    print(minStringValue(str, k))
 
    str = "aaab"
    k = 2
    print(minStringValue(str, k))
     
# This code is contributed
# by Sairahul Jella

Time complexity: nlogn
Space complexity: constant