Banana-Leopard/TASTY huggingface dataset:
# Python3 program to find the longest path in a matrix
# with given constraints
 
n = 3
# Returns length of the longest path beginning with mat[i][j].
# This function mainly uses lookup table dp[n][n]
 
 
def findLongestFromACell(i, j, mat, dp):
    # Base case
    if (i < 0 or i >= n or j < 0 or j >= n):
        return 0
 
    # If this subproblem is already solved
    if (dp[i][j] != -1):
        return dp[i][j]
 
    # To store the path lengths in all the four directions
    x, y, z, w = -1, -1, -1, -1
 
    # Since all numbers are unique and in range from 1 to n * n,
    # there is atmost one possible direction from any cell
    if (j < n-1 and ((mat[i][j] + 1) == mat[i][j + 1])):
        x = 1 + findLongestFromACell(i, j + 1, mat, dp)
 
    if (j > 0 and (mat[i][j] + 1 == mat[i][j-1])):
        y = 1 + findLongestFromACell(i, j-1, mat, dp)
 
    if (i > 0 and (mat[i][j] + 1 == mat[i-1][j])):
        z = 1 + findLongestFromACell(i-1, j, mat, dp)
 
    if (i < n-1 and (mat[i][j] + 1 == mat[i + 1][j])):
        w = 1 + findLongestFromACell(i + 1, j, mat, dp)
 
    # If none of the adjacent fours is one greater we will take 1
    # otherwise we will pick maximum from all the four directions
    dp[i][j] = max(x, max(y, max(z, max(w, 1))))
    return dp[i][j]
 
 
# Returns length of the longest path beginning with any cell
def finLongestOverAll(mat):
    result = 1  # Initialize result
 
    # Create a lookup table and fill all entries in it as -1
    dp = [[-1 for i in range(n)]for i in range(n)]
 
    # Compute longest path beginning from all cells
    for i in range(n):
        for j in range(n):
            if (dp[i][j] == -1):
                findLongestFromACell(i, j, mat, dp)
            # Update result if needed
            result = max(result, dp[i][j])
    return result
 
 
# Driver program
mat = [[1, 2, 9],
       [5, 3, 8],
       [4, 6, 7]]
print("Length of the longest path is ", finLongestOverAll(mat))
 
# this code is improved by sahilshelangia

Time complexity: quadratic
Space complexity: quadratic
# Python3 program to find minimum initial
# points to reach destination
import math as mt
R = 3
C = 3
 
 
def minInitialPoints(points):
    '''
    dp[i][j] represents the minimum initial
    points player should have so that when
    starts with cell(i, j) successfully
    reaches the destination cell(m-1, n-1)
    '''
    dp = [[0 for x in range(C + 1)]
          for y in range(R + 1)]
    m, n = R, C
 
    if points[m - 1][n - 1] > 0:
        dp[m - 1][n - 1] = 1
    else:
        dp[m - 1][n - 1] = abs(points[m - 1][n - 1]) + 1
    '''
    Fill last row and last column as base
    to fill entire table
    '''
    for i in range(m - 2, -1, -1):
        dp[i][n - 1] = max(dp[i + 1][n - 1] -
                           points[i][n - 1], 1)
    for i in range(n - 2, -1, -1):
        dp[m - 1][i] = max(dp[m - 1][i + 1] -
                           points[m - 1][i], 1)
    '''
    fill the table in bottom-up fashion
    '''
    for i in range(m - 2, -1, -1):
        for j in range(n - 2, -1, -1):
            min_points_on_exit = min(dp[i + 1][j],
                                     dp[i][j + 1])
            dp[i][j] = max(min_points_on_exit -
                           points[i][j], 1)
 
    return dp[0][0]
 
 
# Driver code
points = [[-2, -3, 3],
          [-5, -10, 1],
          [10, 30, -5]]
 
print("Minimum Initial Points Required:",
      minInitialPoints(points))
 
 
# This code is contributed by
# Mohit kumar 29 (IIIT gwalior)

Time complexity: quadratic
Space complexity: quadratic
# Python3 program to find maximum sum
# subarray in a given 2D array
 
# Implementation of Kadane's algorithm
# for 1D array. The function returns the
# maximum sum and stores starting and
# ending indexes of the maximum sum subarray
# at addresses pointed by start and finish
# pointers respectively.
 
 
def kadane(arr, start, finish, n):
 
    # initialize sum, maxSum and
    Sum = 0
    maxSum = -999999999999
    i = None
 
    # Just some initial value to check
    # for all negative values case
    finish[0] = -1
 
    # local variable
    local_start = 0
 
    for i in range(n):
        Sum += arr[i]
        if Sum < 0:
            Sum = 0
            local_start = i + 1
        elif Sum > maxSum:
            maxSum = Sum
            start[0] = local_start
            finish[0] = i
 
    # There is at-least one
    # non-negative number
    if finish[0] != -1:
        return maxSum
 
    # Special Case: When all numbers
    # in arr[] are negative
    maxSum = arr[0]
    start[0] = finish[0] = 0
 
    # Find the maximum element in array
    for i in range(1, n):
        if arr[i] > maxSum:
            maxSum = arr[i]
            start[0] = finish[0] = i
    return maxSum
 
# The main function that finds maximum
# sum rectangle in M[][]
 
 
def findMaxSum(M):
    global ROW, COL
 
    # Variables to store the final output
    maxSum, finalLeft = -999999999999, None
    finalRight, finalTop, finalBottom = None, None, None
    left, right, i = None, None, None
 
    temp = [None] * ROW
    Sum = 0
    start = [0]
    finish = [0]
 
    # Set the left column
    for left in range(COL):
 
        # Initialize all elements of temp as 0
        temp = [0] * ROW
 
        # Set the right column for the left
        # column set by outer loop
        for right in range(left, COL):
 
            # Calculate sum between current left
            # and right for every row 'i'
            for i in range(ROW):
                temp[i] += M[i][right]
 
            # Find the maximum sum subarray in
            # temp[]. The kadane() function also
            # sets values of start and finish.
            # So 'sum' is sum of rectangle between
            # (start, left) and (finish, right) which
            # is the maximum sum with boundary columns
            # strictly as left and right.
            Sum = kadane(temp, start, finish, ROW)
 
            # Compare sum with maximum sum so far.
            # If sum is more, then update maxSum
            # and other output values
            if Sum > maxSum:
                maxSum = Sum
                finalLeft = left
                finalRight = right
                finalTop = start[0]
                finalBottom = finish[0]
 
    # Prfinal values
    print("(Top, Left)", "(", finalTop,
          finalLeft, ")")
    print("(Bottom, Right)", "(", finalBottom,
          finalRight, ")")
    print("Max sum is:", maxSum)
 
 
# Driver Code
ROW = 4
COL = 5
M = [[1, 2, -1, -4, -20],
     [-8, -3, 4, 2, 1],
     [3, 8, 10, 1, 3],
     [-4, -1, 1, 7, -6]]
 
# Function call
findMaxSum(M)
 
# This code is contributed by PranchalK

Time complexity: cubic
Space complexity: linear
# Program to implement a stack using
# two queue
from _collections import deque
 
 
class Stack:
 
    def __init__(self):
 
        # Two inbuilt queues
        self.q1 = deque()
        self.q2 = deque()
 
    def push(self, x):
 
        # Push x first in empty q2
        self.q2.append(x)
 
        # Push all the remaining
        # elements in q1 to q2.
        while (self.q1):
            self.q2.append(self.q1.popleft())
 
        # swap the names of two queues
        self.q1, self.q2 = self.q2, self.q1
 
    def pop(self):
 
        # if no elements are there in q1
        if self.q1:
            self.q1.popleft()
 
    def top(self):
        if (self.q1):
            return self.q1[0]
        return None
 
    def size(self):
        return len(self.q1)
 
 
# Driver Code
if __name__ == '__main__':
    s = Stack()
    s.push(1)
    s.push(2)
    s.push(3)
 
    print("current size: ", s.size())
    print(s.top())
    s.pop()
    print(s.top())
    s.pop()
    print(s.top())
 
    print("current size: ", s.size())
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: linear
# Program to implement a stack using
# two queue
from _collections import deque
 
 
class Stack:
 
    def __init__(self):
 
        # Two inbuilt queues
        self.q1 = deque()
        self.q2 = deque()
 
    def push(self, x):
        self.q1.append(x)
 
    def pop(self):
        # if no elements are there in q1
        if (not self.q1):
            return
        # Leave one element in q1 and push others in q2
        while(len(self.q1) != 1):
            self.q2.append(self.q1.popleft())
 
        # swap the names of two queues
        self.q1, self.q2 = self.q2, self.q1
 
    def top(self):
        # if no elements are there in q1
        if (not self.q1):
            return
        # Leave one element in q1 and push others in q2
        while(len(self.q1) != 1):
            self.q2.append(self.q1.popleft())
 
        # Pop the only left element from q1 to q2
        top = self.q1[0]
        self.q2.append(self.q1.popleft())
 
        # swap the names of two queues
        self.q1, self.q2 = self.q2, self.q1
 
        return top
 
    def size(self):
        return len(self.q1)
 
 
# Driver Code
if __name__ == '__main__':
    s = Stack()
    s.push(1)
    s.push(2)
    s.push(3)
 
    print("current size: ", s.size())
    print(s.top())
    s.pop()
    print(s.top())
    s.pop()
    print(s.top())
 
    print("current size: ", s.size())
 
# This code is contributed by jainlovely450

Time complexity: linear
Space complexity: linear
from _collections import deque
 
# Stack Class that acts as a queue
 
 
class Stack:
    def __init__(self):
        self.q = deque()
 
    # Push operation
    def push(self, data):
        # Get previous size of queue
        s = len(self.q)
 
        # Push the current element
        self.q.append(data)
 
        # Pop all the previous elements and put them after
        # current element
        for i in range(s):
            self.q.append(self.q.popleft())
 
    # Removes the top element
    def pop(self):
        if (not self.q):
            print("No elements")
        else:
            self.q.popleft()
 
    # Returns top of stack
    def top(self):
        if (not self.q):
            return
        return self.q[0]
 
    def size(self):
        return len(self.q)
 
 
if __name__ == '__main__':
    st = Stack()
    st.push(1)
    st.push(2)
    st.push(3)
    print("current size: ", st.size())
    print(st.top())
    st.pop()
    print(st.top())
    st.pop()
    print(st.top())
    print("current size: ", st.size())

Time complexity: linear
Space complexity: linear
# Python3 program to demonstrate linked list
# based implementation of queue
 
# A linked list (LL) node
# to store a queue entry
 
 
class Node:
 
    def __init__(self, data):
        self.data = data
        self.next = None
 
# A class to represent a queue
 
# The queue, front stores the front node
# of LL and rear stores the last node of LL
 
 
class Queue:
 
    def __init__(self):
        self.front = self.rear = None
 
    def isEmpty(self):
        return self.front == None
 
    # Method to add an item to the queue
    def EnQueue(self, item):
        temp = Node(item)
 
        if self.rear == None:
            self.front = self.rear = temp
            return
        self.rear.next = temp
        self.rear = temp
 
    # Method to remove an item from queue
    def DeQueue(self):
 
        if self.isEmpty():
            return
        temp = self.front
        self.front = temp.next
 
        if(self.front == None):
            self.rear = None
 
 
# Driver Code
if __name__ == '__main__':
    q = Queue()
    q.EnQueue(10)
    q.EnQueue(20)
    q.DeQueue()
    q.DeQueue()
    q.EnQueue(30)
    q.EnQueue(40)
    q.EnQueue(50)
    q.DeQueue()
    print("Queue Front : " + str(q.front.data))
    print("Queue Rear : " + str(q.rear.data))

Time complexity: constant
Space complexity: constant
# Python Program to print zigzag traversal
# of binary tree
 
# Binary tree node
class Node:
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
 
# function to print zigzag traversal of
# binary tree
def zizagtraversal(root):
 
    # Base Case
    if root is None:
        return
 
    # Create two stacks to store current
    # and next level
    currentLevel = []
    nextLevel = []
 
    # if ltr is true push nodes from
    # left to right otherwise from
    # right to left
    ltr = True
 
    # append root to currentlevel stack
    currentLevel.append(root)
 
    # Check if stack is empty
    while len(currentLevel) > 0:
        # pop from stack
        temp = currentLevel.pop(-1)
        # print the data
        print(temp.data, " ", end="")
 
        if ltr:
            # if ltr is true push left
            # before right
            if temp.left:
                nextLevel.append(temp.left)
            if temp.right:
                nextLevel.append(temp.right)
        else:
            # else push right before left
            if temp.right:
                nextLevel.append(temp.right)
            if temp.left:
                nextLevel.append(temp.left)
 
        if len(currentLevel) == 0:
            # reverse ltr to push node in
            # opposite order
            ltr = not ltr
            # swapping of stacks
            currentLevel, nextLevel = nextLevel, currentLevel
 
 
# Driver program to check above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
print("Zigzag Order traversal of binary tree is")
zizagtraversal(root)
 
# This code is contributed by Shweta Singh

Time complexity: linear
Space complexity: linear
# Python3 implementation of a O(n) time method for
# Zigzag order traversal
from collections import deque
 
# Binary Tree node
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Function to print the zigzag traversal
def zigZagTraversal(root):
    q = deque([])
    v = []
    q.append(root)
    v.append(root.data)
    
    # set initial level as 1, because root is
    # already been taken care of.
    l = 1
                 
    while len(q) > 0:
        n = len(q)
        for i in range(n):
            # popping mechanism
            if (l % 2 == 0):
                temp = q[-1]
                q.pop()
            else:
                temp = q[0]
                q.popleft()
  
            # pushing mechanism
            if (l % 2 != 0):
                if (temp.right):
                    q.append(temp.right)
                    v.append(temp.right.data)
                if (temp.left):
                    q.append(temp.left)
                    v.append(temp.left.data)
            elif (l % 2 == 0):
                if (temp.left):
                    q.appendleft(temp.left)
                    v.append(temp.left.data)
                if (temp.right):
                    q.appendleft(temp.right)
                    v.append(temp.right.data)
        l+=1 # level plus one
    return v
 
# vector to store the traversal order.
v = []
 
# create tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
print("ZigZag Order traversal of binary tree is")
 
v = zigZagTraversal(root)
 
for i in range(len(v)):
    print(v[i], end = " ")
     
    # This code is contributed by suresh07.

Time complexity: linear
Space complexity: linear
# Python Program to print zigzag traversal
# of binary tree
 
# Binary tree node
class Node:
   
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
 
# function to print zigzag traversal of
# binary tree
def zigzagtraversal(root):
 
    # Base Case
    if root is None:
        return
    ans = []  # store the traversal in the ans array
    queue = [root] # use list as queue
    flag = False
    while len(queue) != 0:
 
        n = len(queue)
        level = []
        for i in range(n):
            node = queue[0]
            queue.pop(0)
            level.append(node.data)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        flag = not flag
        if flag == False:
            level = level[::-1]
        for i in range(n):
 
            ans.append(level[i])
 
    return ans
 
 
# Driver program to check above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
print("Zigzag Order traversal of binary tree is")
 
v = zigzagtraversal(root)
for i in v:
    print(i,end = " ")
#This Code is Contributed By Vivek Maddeshiya

Time complexity: linear
Space complexity: linear
# Python3 program to demonstrate working of LIFO
 
# Pushing element on the top of the stack
def stack_push(stack):
    for i in range(5):
        stack.append(i)
    return stack
  
# Popping element from the top of the stack
def stack_pop(stack):
    print("Pop :")
  
    for i in range(5):
        y = stack[-1]
        stack.pop()
        print(y)
    return stack
  
# Displaying element on the top of the stack
def stack_peek(stack):
    element = stack[-1]
    print("Element on stack top :", element)
  
# Searching element in the stack
def stack_search(stack, element):
    pos = -1
    co = 0
    while(len(stack) > 0):
        co+=1
        if(stack[-1] == element):
            pos = co
            break
        stack.pop()
  
    if (pos == -1):
        print( "Element not found")
    else:
        print("Element is found at position", pos)
 
stack = []
stack_push(stack)
stack_pop(stack)
stack_push(stack)
stack_peek(stack)
stack_search(stack, 2)
stack_search(stack, 6)
 
# This code is contributed by rameshtravel07.

Time complexity: linear
Space complexity: linear
from queue import Queue
 
 
def reverse_queue(queue: Queue):
    # Base case
    if queue.empty():
        return
 
    # Dequeue current item (from front)
    item = queue.queue[0]
    queue.get()
 
    # Reverse remaining queue
    reverse_queue(queue)
 
    # Enqueue current item (to rear)
    queue.put(item)
 
 
def print_queue(queue: Queue):
    while not queue.empty():
        print(queue.queue[0], end=" ")
        queue.get()
    print()
 
 
# Driver Code
if __name__ == "__main__":
    q = Queue()
    q.put(56)
    q.put(27)
    q.put(30)
    q.put(45)
    q.put(85)
    q.put(92)
    q.put(58)
    q.put(80)
    q.put(90)
    q.put(100)
 
    reverse_queue(q)
    print_queue(q)

Time complexity: linear
Space complexity: linear
# Python3 program to reverse first k
# elements of a queue.
from queue import Queue
 
# Function to reverse the first K
# elements of the Queue
 
 
def reverseQueueFirstKElements(k, Queue):
    if (Queue.empty() == True or
            k > Queue.qsize()):
        return
    if (k <= 0):
        return
 
    Stack = []
 
    # put the first K elements
    # into a Stack
    for i in range(k):
        Stack.append(Queue.queue[0])
        Queue.get()
 
    # Enqueue the contents of stack
    # at the back of the queue
    while (len(Stack) != 0):
        Queue.put(Stack[-1])
        Stack.pop()
 
    # Remove the remaining elements and
    # enqueue them at the end of the Queue
    for i in range(Queue.qsize() - k):
        Queue.put(Queue.queue[0])
        Queue.get()
 
# Utility Function to print the Queue
 
 
def Print(Queue):
    while (not Queue.empty()):
        print(Queue.queue[0], end=" ")
        Queue.get()
 
 
# Driver code
if __name__ == '__main__':
    Queue = Queue()
    Queue.put(10)
    Queue.put(20)
    Queue.put(30)
    Queue.put(40)
    Queue.put(50)
    Queue.put(60)
    Queue.put(70)
    Queue.put(80)
    Queue.put(90)
    Queue.put(100)
 
    k = 5
    reverseQueueFirstKElements(k, Queue)
    Print(Queue)
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: linear
# Python3 program for the above approach
 
# Method to find the maximum for each
# and every contiguous subarray
# of size K
 
def printMax(arr, N, K):
    max = 0
 
    for i in range(N - K + 1):
        max = arr[i]
        for j in range(1, K):
            if arr[i + j] > max:
                max = arr[i + j]
        print(str(max) + " ", end="")
 
 
# Driver's code
if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    N = len(arr)
    K = 3
     
    # Function call
    printMax(arr, N, K)
 
# This code is contributed by Shiv Shankar

Time complexity: quadratic
Space complexity: constant
# Python3 program to find the maximum for
# each and every contiguous subarray of
# size K
 
from collections import deque
 
# A Deque (Double ended queue) based
# method for printing maximum element
# of all subarrays of size K
 
 
def printMax(arr, N, K):
    """ Create a Double Ended Queue, Qi that
    will store indexes of array elements.
    The queue will store indexes of useful
    elements in every window and it will
    maintain decreasing order of values from
    front to rear in Qi, i.e., arr[Qi.front[]]
    to arr[Qi.rear()] are sorted in decreasing
    order"""
    Qi = deque()
 
    # Process first k (or first window)
    # elements of array
    for i in range(K):
 
        # For every element, the previous
        # smaller elements are useless
        # so remove them from Qi
        while Qi and arr[i] >= arr[Qi[-1]]:
            Qi.pop()
 
        # Add new element at rear of queue
        Qi.append(i)
 
    # Process rest of the elements, i.e.
    # from arr[k] to arr[n-1]
    for i in range(K, N):
 
        # The element at the front of the
        # queue is the largest element of
        # previous window, so print it
        print(str(arr[Qi[0]]) + " ", end="")
 
        # Remove the elements which are
        # out of this window
        while Qi and Qi[0] <= i-K:
 
            # remove from front of deque
            Qi.popleft()
 
        # Remove all elements smaller than
        # the currently being added element
        # (Remove useless elements)
        while Qi and arr[i] >= arr[Qi[-1]]:
            Qi.pop()
 
        # Add current element at the rear of Qi
        Qi.append(i)
 
    # Print the maximum element of last window
    print(str(arr[Qi[0]]))
 
 
# Driver's code
if __name__ == "__main__":
    arr = [12, 1, 78, 90, 57, 89, 56]
    K = 3
     
    # Function call
    printMax(arr, len(arr), K)
 
# This code is contributed by Shiv Shankar

Time complexity: linear
Space complexity: constant