Banana-Leopard/TASTY huggingface dataset:
# Python code for the above approach
 
 
# Function to find if there is a celebrity in the party
# or not.
def celebrity(M, n):
    # r=row number
    r = 0
    for i in range(1, n):
        # checking if r th person knows i th person
        if(M[r][i] == 1):
            M[r][r] = 1
            r = i
        else:
            M[i][i] = 1
 
    for i in range(n):
        # checking if i th person can be a celebrity or
        # not
        if(M[i][i] == 0):
            flag = 0
            # iterating in the i th column to check
            # whether everyone knows i th person or not
            for j in range(n):
                # checking if M[j][i] is not a diagonal
                # element and if j th person knows i th
                      # person
                if(j != i and M[j][i] == 0):
                    flag = 1
                    break
            if(flag == 0):
                return i
 
    return -1
 
 
M = [[0, 0, 1, 0],
     [0, 0, 1, 0],
     [0, 0, 0, 0],
     [0, 0, 1, 0]]
a = celebrity(M, 4)
if(a is -1):
    print("No Celebrity")
else:
    print("Celebrity ID", a)
 
# This code is contributed by lokeshmvs21.

Time complexity: linear
Space complexity: constant
# Python3 code
class Solution:
 
    # Function to find if there is a celebrity in the party or not.
    # return index if celebrity else return -1
    def celebrity(self, M, n):
        # code here
        i = 0
        j = n-1
        candidate = -1
        while(i < j):
            if M[j][i] == 1:
                j -= 1
            else:
                i += 1
 
        candidate = i
        for k in range(n):
            if candidate != k:
                if M[candidate][k] == 1 or M[k][candidate] == 0:
                    return -1
 
        return candidate
 
 
n = 4
m = [[0, 0, 1, 0],
     [0, 0, 1, 0],
     [0, 0, 0, 0],
     [0, 0, 1, 0]]
ob = Solution()
a = ob.celebrity(m, n)
if a == -1:
    print("No Celebrity")
else:
    print("Celebrity ID", a)

Time complexity: linear
Space complexity: constant
# Python program to evaluate value of a postfix expression
 
# Class to convert the expression
class Evaluate:
     
    # Constructor to initialize the class variables
    def __init__(self, capacity):
        self.top = -1
        self.capacity = capacity
        # This array is used a stack
        self.array = []
     
    # check if the stack is empty
    def isEmpty(self):
        return True if self.top == -1 else False
     
    # Return the value of the top of the stack
    def peek(self):
        return self.array[-1]
     
    # Pop the element from the stack
    def pop(self):
        if not self.isEmpty():
            self.top -= 1
            return self.array.pop()
        else:
            return "$"
     
    # Push the element to the stack
    def push(self, op):
        self.top += 1
        self.array.append(op)
 
 
    # The main function that converts given infix expression
    # to postfix expression
    def evaluatePostfix(self, exp):
         
        # Iterate over the expression for conversion
        for i in exp:
             
            # If the scanned character is an operand
            # (number here) push it to the stack
            if i.isdigit():
                self.push(i)
 
            # If the scanned character is an operator,
            # pop two elements from stack and apply it.
            else:
                val1 = self.pop()
                val2 = self.pop()
                self.push(str(eval(val2 + i + val1)))
 
        return int(self.pop())
                 
 
             
# Driver program to test above function
exp = "231*+9-"
obj = Evaluate(len(exp))
print ("postfix evaluation: %d"%(obj.evaluatePostfix(exp)))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Time complexity: linear
Space complexity: linear
# Python program to evaluate value of a postfix
# expression with integers containing multiple digits
 
class evalpostfix:
    def __init__(self):
        self.stack =[]
        self.top =-1
    def pop(self):
        if self.top ==-1:
            return
        else:
            self.top-= 1
            return self.stack.pop()
    def push(self, i):
        self.top+= 1
        self.stack.append(i)
 
    def centralfunc(self, ab):
        for i in ab:
 
            # if the component of the list is an integer
            try:
                self.push(int(i))
            # if the component of the list is not an integer,
            # it must be an operator. Using ValueError, we can
            # evaluate components of the list other than type int
            except ValueError:
                val1 = self.pop()
                val2 = self.pop()
                if i == '/':
                  self.push(val2 / val1)
                else:       
                # switch statement to perform operation
                  switcher ={'+':val2 + val1, '-':val2-val1, '*':val2 * val1, '^':val2**val1}
                  self.push(switcher.get(i))
        return int(self.pop())
 
str ='100 200 + 2 / 5 * 7 +'
 
# splitting the given string to obtain
# integers and operators into a list
strconv = str.split(' ')
obj = evalpostfix()
print(obj.centralfunc(strconv))
 
# This code is contributed by Amarnath Reddy

Time complexity: linear
Space complexity: linear
# Python program to reverse a
# stack using recursion
 
# Below is a recursive function
# that inserts an element
# at the bottom of a stack.
 
 
def insertAtBottom(stack, item):
    if isEmpty(stack):
        push(stack, item)
    else:
        temp = pop(stack)
        insertAtBottom(stack, item)
        push(stack, temp)
 
# Below is the function that
# reverses the given stack
# using insertAtBottom()
 
 
def reverse(stack):
    if not isEmpty(stack):
        temp = pop(stack)
        reverse(stack)
        insertAtBottom(stack, temp)
 
# Below is a complete running
# program for testing above
# functions.
 
# Function to create a stack.
# It initializes size of stack
# as 0
 
 
def createStack():
    stack = []
    return stack
 
# Function to check if
# the stack is empty
 
 
def isEmpty(stack):
    return len(stack) == 0
 
# Function to push an
# item to stack
 
 
def push(stack, item):
    stack.append(item)
 
# Function to pop an
# item from stack
 
 
def pop(stack):
 
    # If stack is empty
    # then error
    if(isEmpty(stack)):
        print("Stack Underflow ")
        exit(1)
 
    return stack.pop()
 
# Function to print the stack
 
 
def prints(stack):
    for i in range(len(stack)-1, -1, -1):
        print(stack[i], end=' ')
    print()
 
# Driver Code
 
 
stack = createStack()
push(stack, str(4))
push(stack, str(3))
push(stack, str(2))
push(stack, str(1))
print("Original Stack ")
prints(stack)
 
reverse(stack)
 
print("Reversed Stack ")
prints(stack)
 
# This code is contributed by Sunny Karira

Time complexity: quadratic
Space complexity: linear
# Python program to sort a stack using recursion
 
# Recursive method to insert element in sorted way
 
 
def sortedInsert(s, element):
 
    # Base case: Either stack is empty or newly inserted
    # item is greater than top (more than all existing)
    if len(s) == 0 or element > s[-1]:
        s.append(element)
        return
    else:
 
        # Remove the top item and recur
        temp = s.pop()
        sortedInsert(s, element)
 
        # Put back the top item removed earlier
        s.append(temp)
 
# Method to sort stack
 
 
def sortStack(s):
 
    # If stack is not empty
    if len(s) != 0:
 
        # Remove the top item
        temp = s.pop()
 
        # Sort remaining stack
        sortStack(s)
 
        # Push the top item back in sorted stack
        sortedInsert(s, temp)
 
# Printing contents of stack
 
 
def printStack(s):
    for i in s[::-1]:
        print(i, end=" ")
    print()
 
 
# Driver Code
if __name__ == '__main__':
    s = []
    s.append(30)
    s.append(-5)
    s.append(18)
    s.append(14)
    s.append(-3)
 
    print("Stack elements before sorting: ")
    printStack(s)
 
    sortStack(s)
 
    print("\nStack elements after sorting: ")
    printStack(s)
 
# This code is contributed by Muskan Kalra.

Time complexity: quadratic
Space complexity: linear
# Python program to sort a
# stack using auxiliary stack.
 
# This function return the sorted stack
def sortStack ( stack ):
    tmpStack = createStack()
    while(isEmpty(stack) == False):
         
        # pop out the first element
        tmp = top(stack)
        pop(stack)
 
        # while temporary stack is not
        # empty and top of stack is
        # greater than temp
        while(isEmpty(tmpStack) == False and
             int(top(tmpStack)) > int(tmp)):
             
            # pop from temporary stack and
            # push it to the input stack
            push(stack,top(tmpStack))
            pop(tmpStack)
 
        # push temp in temporary of stack
        push(tmpStack,tmp)
     
    return tmpStack
 
# Below is a complete running
# program for testing above
# function.
 
# Function to create a stack.
# It initializes size of stack
# as 0
def createStack():
    stack = []
    return stack
 
# Function to check if
# the stack is empty
def isEmpty( stack ):
    return len(stack) == 0
 
# Function to push an
# item to stack
def push( stack, item ):
    stack.append( item )
 
# Function to get top
# item of stack
def top( stack ):
    p = len(stack)
    return stack[p-1]
 
# Function to pop an
# item from stack
def pop( stack ):
 
    # If stack is empty
    # then error
    if(isEmpty( stack )):
        print("Stack Underflow ")
        exit(1)
 
    return stack.pop()
 
# Function to print the stack
def prints(stack):
    for i in range(len(stack)-1, -1, -1):
        print(stack[i], end = ' ')
    print()
 
# Driver Code
stack = createStack()
push( stack, str(34) )
push( stack, str(3) )
push( stack, str(31) )
push( stack, str(98) )
push( stack, str(92) )
push( stack, str(23) )
 
print("Sorted numbers are: ")
sortedst = sortStack ( stack )
prints(sortedst)
 
# This code is contributed by
# Prasad Kshirsagar

Time complexity: quadratic
Space complexity: linear
# Python3 code to delete middle of a stack
# without using additional data structure.
  
# Deletes middle of stack of size
# n. Curr is current item number
class Stack:
    def __init__(self):
        self.items = []
      
    def isEmpty(self):
        return self.items == []
      
    def push(self, item):
        self.items.append(item)
      
    def pop(self):
        return self.items.pop()
      
    def peek(self):
        return self.items[len(self.items)-1]
      
    def size(self):
        return len(self.items)
          
def deleteMid(st, n, curr) :
 
    # If stack is empty or all items
    # are traversed
    if (st.isEmpty() or curr == n) :
        return
      
    # Remove current item
    x = st.peek()
    st.pop()
      
    # Remove other items
    deleteMid(st, n, curr+1)
      
    # Put all items back except middle
    if (curr != int(n/2)) :
        st.push(x)
  
# Driver function to test above functions
st = Stack()
  
# push elements into the stack
st.push('1')
st.push('2')
st.push('3')
st.push('4')
st.push('5')
st.push('6')
st.push('7')
  
deleteMid(st, st.size(), 0)
  
# Printing stack after deletion
# of middle.
while (st.isEmpty() == False) :
    p = st.peek()
    st.pop()
    print (str(p) + " ", end="")
 
# This code is contributed by
# Manish Shaw (manishshaw1)

Time complexity: linear
Space complexity: linear
# Python code to delete middle of a stack with iterative method
 
# Deletes middle of stack of size n. Curr is current item number
def deleteMid(st):
    n = len(st)
    tempSt = []
    count = 0
 
    # Put first n/2 element of st in tempSt
    while (count < (n / 2)-1):
        c = st[0]
        st.pop(0)
        tempSt.insert(0, c)
        count = count+1
 
    # Delete middle element
    st.pop(0)
 
    # Put all (n/2) element of tempSt in st
    while (len(tempSt) != 0):
        st.insert(0, tempSt[0])
        tempSt.pop(0)
 
 
# Driver Code
st = []
 
# insert elements into the stack
st.insert(0, 1)
st.insert(0, 2)
st.insert(0, 3)
st.insert(0, 4)
st.insert(0, 5)
st.insert(0, 6)
st.insert(0, 7)
deleteMid(st)
 
# Printing stack after deletion of middle.
while (len(st) != 0):
    p = st[0]
    st.pop(0)
    print(p, " ")
 
# This code is added by adityamaharshi21

Time complexity: linear
Space complexity: linear
# Python3 program to sort an array using stack
 
# This function return the sorted stack
def sortStack(input):
    tmpStack = []
    while (len(input) > 0):
     
        # pop out the first element
        tmp = input[-1]
        input.pop()
 
        # while temporary stack is not empty
        # and top of stack is smaller than temp
        while (len(tmpStack) > 0 and tmpStack[-1] < tmp):
         
            # pop from temporary stack and
            # append it to the input stack
            input.append(tmpStack[-1])
            tmpStack.pop()
         
        # append temp in temporary of stack
        tmpStack.append(tmp)
     
    return tmpStack
 
def sortArrayUsingStacks(arr, n):
 
    # append array elements to stack
    input = []
    i = 0
    while ( i < n ):
        input.append(arr[i])
        i = i + 1
         
    # Sort the temporary stack
    tmpStack = sortStack(input)
    i = 0
     
    # Put stack elements in arrp[]
    while (i < n):
        arr[i] = tmpStack[-1]
        tmpStack.pop()
        i = i + 1
         
    return arr
 
# Driver code
arr = [10, 5, 15, 45]
n = len(arr)
 
arr = sortArrayUsingStacks(arr, n)
i = 0
 
while (i < n):
    print(arr[i] ,end= " ")
    i = i + 1
 
# This code is contributed by Arnab Kundu

Time complexity: quadratic
Space complexity: linear
# Function to delete elements
def deleteElements(arr, n, k):
     
    # create an empty stack st
    st = []
    st.append(arr[0])
     
    # index to maintain the top
    # of the stack
    top = 0
    count = 0
 
    for i in range(1, n):
         
        # pop till the present element
        # is greater than stack's top
        # element
        while(len(st) != 0 and count < k
                   and st[top] < arr[i]):
            st.pop()
            count += 1
            top -= 1
 
        st.append(arr[i])
        top += 1
 
    # print the remaining elements
    for i in range(0, len(st)):
        print(st[i], " ", end="")
 
# Driver code
k = 2
arr = [20, 10, 25, 30, 40]
deleteElements(arr, len(arr), k)
 
# This code is contributed by himan085.

Time complexity: quadratic
Space complexity: linear
# Python3 program to count number of distinct
# instance where second highest number lie
# before highest number in all subarrays.
from typing import List
 
MAXN = 100005
 
# Finding the next greater element
# of the array.
def makeNext(arr: List[int], n: int,
         nextBig: List[int]) -> None:
 
    # Stack
    s = []
 
    for i in range(n - 1, -1, -1):
        nextBig[i] = i
         
        while len(s) and s[-1][0] < arr[i]:
            s.pop()
 
        if len(s):
            nextBig[i] = s[-1][1]
 
        s.append((arr[i], i))
 
# Finding the previous greater
# element of the array.
def makePrev(arr: List[int], n: int,
         prevBig: List[int]) -> None:
 
    # Stack
    s = []
    for i in range(n):
        prevBig[i] = -1
         
        while (len(s) and s[-1][0] < arr[i]):
            s.pop()
 
        if (len(s)):
            prevBig[i] = s[-1][1]
 
        s.append((arr[i], i))
 
# Wrapper Function
def wrapper(arr: List[int], n: int) -> int:
 
    nextBig = [0] * MAXN
    prevBig = [0] * MAXN
    maxi = [0] * MAXN
    ans = 0
 
    # Finding previous largest element
    makePrev(arr, n, prevBig)
 
    # Finding next largest element
    makeNext(arr, n, nextBig)
 
    for i in range(n):
        if (nextBig[i] != i):
            maxi[nextBig[i] - i] = max(
                maxi[nextBig[i] - i],
                    i - prevBig[i])
 
    for i in range(n):
        ans += maxi[i]
 
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 1, 3, 2, 4 ]
    n = len(arr)
     
    print(wrapper(arr, n))
 
# This code is contributed by sanjeev2552

Time complexity: linear
Space complexity: linear
# Python3 program to find maximum
# rectangular area in linear time
  
  
def max_area_histogram(histogram):
  
    # This function calculates maximum
    # rectangular area under given
    # histogram with n bars
  
    # Create an empty stack. The stack
    # holds indexes of histogram[] list.
    # The bars stored in the stack are
    # always in increasing order of
    # their heights.
    stack = list()
  
    max_area = 0  # Initialize max area
  
    # Run through all bars of
    # given histogram
    index = 0
    while index < len(histogram):
  
        # If this bar is higher
        # than the bar on top
        # stack, push it to stack
  
        if (not stack) or (histogram[stack[-1]] <= histogram[index]):
            stack.append(index)
            index += 1
  
        # If this bar is lower than top of stack,
        # then calculate area of rectangle with
        # stack top as the smallest (or minimum
        # height) bar.'i' is 'right index' for
        # the top and element before top in stack
        # is 'left index'
        else:
            # pop the top
            top_of_stack = stack.pop()
  
            # Calculate the area with
            # histogram[top_of_stack] stack
            # as smallest bar
            area = (histogram[top_of_stack] *
                    ((index - stack[-1] - 1)
                     if stack else index))
  
            # update max area, if needed
            max_area = max(max_area, area)
  
    # Now pop the remaining bars from
    # stack and calculate area with
    # every popped bar as the smallest bar
    while stack:
  
        # pop the top
        top_of_stack = stack.pop()
  
        # Calculate the area with
        # histogram[top_of_stack]
        # stack as smallest bar
        area = (histogram[top_of_stack] *
                ((index - stack[-1] - 1)
                 if stack else index))
  
        # update max area, if needed
        max_area = max(max_area, area)
  
    # Return maximum area under
    # the given histogram
    return max_area
  
  
# Driver Code
if __name__ == '__main__':
    hist = [6, 2, 5, 4, 5, 1, 6]
  
    # Function call
    print("Maximum area is",
          max_area_histogram(hist))
  
# This code is contributed
# by Jinay Shah

Time complexity: linear
Space complexity: linear
# Python3 code for the above approach
  
  
def getMaxArea(arr):
    s = [-1]
    n = len(arr)
    area = 0
    i = 0
    left_smaller = [-1]*n
    right_smaller = [n]*n
    while i < n:
        while s and (s[-1] != -1) and (arr[s[-1]] > arr[i]):
            right_smaller[s[-1]] = i
            s.pop()
        if((i > 0) and (arr[i] == arr[i-1])):
            left_smaller[i] = left_smaller[i-1]
        else:
            left_smaller[i] = s[-1]
        s.append(i)
        i += 1
    for j in range(0, n):
        area = max(area, arr[j]*(right_smaller[j]-left_smaller[j]-1))
    return area
  
  
# Driver code
if __name__ == '__main__':
    hist = [6, 2, 5, 4, 5, 1, 6]
  
    # Function call
    print("maxArea = ", getMaxArea(hist))
  
# This code is contributed by Arunit Kumar

Time complexity: linear
Space complexity: linear
# Python program to reverse a string using stack
 
# Function to create an empty stack.
# It initializes size of stack as 0
 
 
def createStack():
    stack = []
    return stack
 
# Function to determine the size of the stack
 
 
def size(stack):
    return len(stack)
 
# Stack is empty if the size is 0
 
 
def isEmpty(stack):
    if size(stack) == 0:
        return true
 
# Function to add an item to stack .
# It increases size by 1
 
 
def push(stack, item):
    stack.append(item)
 
# Function to remove an item from stack.
# It decreases size by 1
 
 
def pop(stack):
    if isEmpty(stack):
        return
    return stack.pop()
 
# A stack based function to reverse a string
 
 
def reverse(string):
    n = len(string)
 
    # Create a empty stack
    stack = createStack()
 
    # Push all characters of string to stack
    for i in range(0, n, 1):
        push(stack, string[i])
 
    # Making the string empty since all
    # characters are saved in stack
    string = ""
 
    # Pop all characters of string and
    # put them back to string
    for i in range(0, n, 1):
        string += pop(stack)
 
    return string
 
 
# Driver program to test above functions
string = "GeeksQuiz"
string = reverse(string)
print("Reversed string is " + string)
 
# This code is contributed by Sunny Karira

Time complexity: linear
Space complexity: linear
# Recursive Python function to solve tower of hanoi
 
 
def TowerOfHanoi(n, from_rod, to_rod, aux_rod):
    if n == 0:
        return
    TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
    print("Move disk", n, "from rod", from_rod, "to rod", to_rod)
    TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)
 
 
# Driver code
N = 3
 
# A, C, B are the name of rods
TowerOfHanoi(N, 'A', 'C', 'B')
 
# Contributed By Harshit Agrawal

Time complexity: linear
Space complexity: linear
# Python code to implement the approach
 
 
def maxDepth(s):
 
    count = 0
    st = []
 
    for i in range(len(s)):
        if (s[i] == '('):
            st.append(i) # pushing the bracket in the stack
        elif (s[i] == ')'):
            if (count < len(st)):
                count = len(st)
            # keeping track of the parenthesis and storing
            # it before removing it when it gets balanced
            st.pop()
         
    return count
 
# Driver program
 
s = "( ((X)) (((Y))) )"
print(maxDepth(s))
 
 
# This code is contributed by shinjanpatra

Time complexity: linear
Space complexity: constant
# A Python program to find the maximum depth of nested
# parenthesis in a given expression
 
# function takes a string and returns the
# maximum depth nested parenthesis
def maxDepth(S):
    current_max = 0
    max = 0
    n = len(S)
 
    # Traverse the input string
    for i in range(n):
        if S[i] == '(':
            current_max += 1
 
            if current_max > max:
                max = current_max
        else if S[i] == ')':
            if current_max > 0:
                current_max -= 1
            else:
                return -1
 
    # finally check for unbalanced string
    if current_max != 0:
        return -1
 
    return max
 
# Driver program
s = "( ((X)) (((Y))) )"
print (maxDepth(s))
 
# This code is contributed by BHAVYA JAIN

Time complexity: linear
Space complexity: constant
# A naive method to find maximum of
# minimum of all windows of different sizes
INT_MIN = -1000000
 
 
def printMaxOfMin(arr, n):
 
    # Consider all windows of different
    # sizes starting from size 1
    for k in range(1, n + 1):
 
        # Initialize max of min for
        # current window size k
        maxOfMin = INT_MIN
 
        # Traverse through all windows
        # of current size k
        for i in range(n - k + 1):
 
            # Find minimum of current window
            min = arr[i]
            for j in range(k):
                if (arr[i + j] < min):
                    min = arr[i + j]
 
            # Update maxOfMin if required
            if (min > maxOfMin):
                maxOfMin = min
 
        # Print max of min for current window size
        print(maxOfMin, end=" ")
 
 
# Driver Code
arr = [10, 20, 30, 50, 10, 70, 30]
n = len(arr)
printMaxOfMin(arr, n)
 
# This code is contributed by sahilshelangia

Time complexity: cubic
Space complexity: constant