Banana-Leopard/TASTY huggingface dataset:
# Python program to find min sum of squares
# of characters after k removals
MAX_CHAR = 26
 
# Main Function to calculate min sum of
# squares of characters after k removals
 
def minStringValue(str, k):
   
    alphabetCount =[]
    for i in range(MAX_CHAR):
      alphabetCount.append(0)
 
    # Here the array stored frequency the number of
    # occurrences in string m[frequency]=number of alphabets
    # with frequency i.e, in our example abbccc m[1]=1(1
    # a's occur),m[2]=1(2 b's occur),m[3]=1(3 c'soccur)
    m = []
    for i in range(len(str)):
        m.append(0)
 
    for i in range(len(str)):
        alphabetCount[ord(str[i]) - ord('a')] += 1
 
    # Store the maximum
    maximum = 0
 
    for i in range(MAX_CHAR):
        m[alphabetCount[i]] += 1
        maximum = max(maximum, alphabetCount[i])
 
    while (k > 0):
        z = m[maximum]
        if z <= k:
            # Remove one occurrence of alphabet from each
            # with frequency as maximum.
            # So we will have k-z more remove operations to
            # perform as z is number of characters and we
            # perform one removal from each of the alphabet
            # with that frequency.
            k = k - z
            # As we removed one occurrence from each the
            # alphabets will no longer have the frequency
            # of maximum their frequency will be decreased
            # by one so add these number of alphabets to
            # group with frequency one less than maximum.
            # Remove them from maximum count.
            m[maximum] = 0
            # Add those to frequency one less.
            m[maximum - 1] += z
            # new maximum will be one less.
            maximum -= 1
 
        else:
            # if all the elements of that frequency cannot
            # be removed we should partially remove them.
            m[maximum] -= k
            maximum -= 1
            m[maximum] += k
            k = 0
 
    ans = 0
    for i in range(len(str)):
        # (square of frequency)*(number of
        # characters corresponding to that frequency)
        ans = ans + (i * i) * m[i]
 
    return ans
 
# Driver Code
str = "abbccc"  # Input 1
k = 2
 
print(minStringValue(str, k))
 
str = "aaab"  # Input 2
k = 2
print(minStringValue(str, k))
 
 
# This code is contributed by Abhijeet Kumar(abhijeet19403)

Time complexity: linear
Space complexity: linear
# Python3 program for a Queue based approach
# to find first non-repeating character
from queue import Queue
 
# function to find first non
# repeating character of sa Stream
def firstnonrepeating(Str):
    global MAX_CHAR
    q = Queue()
    charCount = [0] * MAX_CHAR
     
    # traverse whole Stream
    for i in range(len(Str)):
 
        # push each character in queue
        q.put(Str[i])
 
        # increment the frequency count
        charCount[ord(Str[i]) -
                  ord('a')] += 1
 
        # check for the non repeating
        # character
        while (not q.empty()):
            if (charCount[ord(q.queue[0]) -
                          ord('a')] > 1):
                q.get()
            else:
                print(q.queue[0], end = " ")
                break
 
        if (q.empty()):
            print(-1, end = " ")
    print()
 
# Driver Code
MAX_CHAR = 26
Str = "aabc"
firstnonrepeating(Str)
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: linear
# Given two arrays, check if one array is
# stack permutation of other.
from queue import Queue
 
# function to check if Input queue
# is permutable to output queue
def checkStackPermutation(ip, op, n):
     
    # Input queue
    Input = Queue()
    for i in range(n):
        Input.put(ip[i])
 
    # output queue
    output = Queue()
    for i in range(n):
        output.put(op[i])
 
    # stack to be used for permutation
    tempStack = []
    while (not Input.empty()):
        ele = Input.queue[0]
        Input.get()
        if (ele == output.queue[0]):
            output.get()
            while (len(tempStack) != 0):
                if (tempStack[-1] == output.queue[0]):
                    tempStack.pop()
                    output.get()
                else:
                    break
        else:
            tempStack.append(ele)
 
    # If after processing, both Input
    # queue and stack are empty then 
    # the Input queue is permutable
    # otherwise not.
    return (Input.empty() and
        len(tempStack) == 0)
 
# Driver Code
if __name__ == '__main__':
 
    # Input Queue
    Input = [1, 2, 3]
 
    # Output Queue
    output = [2, 1, 3]
 
    n = 3
 
    if (checkStackPermutation(Input,
                              output, n)):
        print("Yes")
    else:
        print("Not Possible")
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: linear
# Given two arrays, check if one array is
# stack permutation of other.
 
# function to check if input array is
# permutable to output array
def checkStackPermutation(ip, op, n):
 
    # we will be appending elements from input array to stack uptill top of our stack
    # matches with first element of output array
    s = []
     
    # will maintain a variable j to iterate on output array
    j = 0
 
    # will iterate one by one in input array
    for i in range(n):
 
        # appended an element from input array to stack
        s.append(ip[i])
         
        # if our stack isn't empty and top matches with output array
        # then we will keep popping out from stack uptill top matches with
        # output array
        while(len(s) > 0 and s[- 1] == op[j]):
            s.pop()
             
            # increasing j so next time we can compare next element in output array
            j += 1
         
     
    # if output array was a correct permutation of input array then
    # by now our stack should be empty
    if(len(s)  == 0):
        return True
     
    return False
     
# Driver program to test above function
 
# Input Array
input = [4,5,6,7,8]
 
# Output Array
 
output = [8,7,6,5,4]
n = 5
if (checkStackPermutation(input, output, n)):
    print("Yes")
else:
    print("Not Possible")
 
# This code is contributed by shinjanpatra

Time complexity: linear
Space complexity: linear
# Program to demonstrate customized data structure
# which supports functions in O(1)
import sys
 
stack = []
Min = sys.maxsize
 
# Utility function for adding a new element
def addElement(x):
     
    global Min, stack
    if (len(stack) == 0 or x < Min):
        Min = x
    pair = [x, Min]
    stack.append(pair)
    print(x, "inserted successfully")
 
# Utility function for returning last
# element of stack
def getLastElement():
     
    global Min, stack
     
    if (len(stack) == 0):
        print("UnderFlow Error")
        return -1
    else:
        return stack[-1][0]
 
# Utility function for removing last
# element successfully;
def removeLastElement():
     
    global Min, stack
    if (len(stack) == 0):
        print("UnderFlow Error")
    elif (len(stack) > 1):
        Min = stack[-2][1]
    else:
        Min = sys.maxsize
    stack.pop()
     
    print("removed successfully")
 
# Utility function for returning min
# element till now;
def getMin():
     
    global Min, stack
    if (len(stack) == 0):
        print("UnderFlow Error")
        return -1
         
    return stack[-1][1]
 
# Driver code
addElement(5)
addElement(7)
addElement(3)
print("min element ::", getMin())
removeLastElement()
addElement(2)
addElement(9)
print("Last element ::", getLastElement())
addElement(0)
print("min element ::", getMin())
removeLastElement()
addElement(11)
print("min element ::", getMin())
 
# This code is contributed by mukesh07

Time complexity: constant
Space complexity: linear
# Python program to convert infix expression to postfix
  
# Class to convert the expression
  
  
class Conversion:
  
    # Constructor to initialize the class variables
    def __init__(self, capacity):
        self.top = -1
        self.capacity = capacity
        # This array is used a stack
        self.array = []
        # Precedence setting
        self.output = []
        self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
  
    # 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)
  
    # A utility function to check is the given character
    # is operand
    def isOperand(self, ch):
        return ch.isalpha()
  
    # Check if the precedence of operator is strictly
    # less than top of stack or not
    def notGreater(self, i):
        try:
            a = self.precedence[i]
            b = self.precedence[self.peek()]
            return True if a <= b else False
        except KeyError:
            return False
  
    # The main function that
    # converts given infix expression
    # to postfix expression
    def infixToPostfix(self, exp):
  
        # Iterate over the expression for conversion
        for i in exp:
            # If the character is an operand,
            # add it to output
            if self.isOperand(i):
                self.output.append(i)
  
            # If the character is an '(', push it to stack
            elif i == '(':
                self.push(i)
  
            # If the scanned character is an ')', pop and
            # output from the stack until and '(' is found
            elif i == ')':
                while((not self.isEmpty()) and
                      self.peek() != '('):
                    a = self.pop()
                    self.output.append(a)
                if (not self.isEmpty() and self.peek() != '('):
                    return -1
                else:
                    self.pop()
  
            # An operator is encountered
            else:
                while(not self.isEmpty() and self.notGreater(i)):
                    self.output.append(self.pop())
                self.push(i)
  
        # pop all the operator from the stack
        while not self.isEmpty():
            self.output.append(self.pop())
  
        print "".join(self.output)
  
  
# Driver's code
if __name__ == '__main__':
    exp = "a+b*(c^d-e)^(f+g*h)-i"
    obj = Conversion(len(exp))
  
    # Function call
    obj.infixToPostfix(exp)
  
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

Time complexity: linear
Space complexity: linear
# Python Program to convert prefix to Infix
def prefixToInfix(prefix):
    stack = []
     
    # read prefix in reverse order
    i = len(prefix) - 1
    while i >= 0:
        if not isOperator(prefix[i]):
             
            # symbol is operand
            stack.append(prefix[i])
            i -= 1
        else:
           
            # symbol is operator
            str = "(" + stack.pop() + prefix[i] + stack.pop() + ")"
            stack.append(str)
            i -= 1
     
    return stack.pop()
 
def isOperator(c):
    if c == "*" or c == "+" or c == "-" or c == "/" or c == "^" or c == "(" or c == ")":
        return True
    else:
        return False
 
# Driver code
if __name__=="__main__":
    str = "*-A/BC-/AKL"
    print(prefixToInfix(str))
     
# This code is contributed by avishekarora

Time complexity: linear
Space complexity: linear
# Python3 Program to convert postfix to prefix
 
# function to check if
# character is operator or not
 
 
def isOperator(x):
 
    if x == "+":
        return True
 
    if x == "-":
        return True
 
    if x == "/":
        return True
 
    if x == "*":
        return True
 
    return False
 
# Convert postfix to Prefix expression
 
 
def postToPre(post_exp):
 
    s = []
 
    # length of expression
    length = len(post_exp)
 
    # reading from right to left
    for i in range(length):
 
        # check if symbol is operator
        if (isOperator(post_exp[i])):
 
            # pop two operands from stack
            op1 = s[-1]
            s.pop()
            op2 = s[-1]
            s.pop()
 
            # concat the operands and operator
            temp = post_exp[i] + op2 + op1
 
            # Push string temp back to stack
            s.append(temp)
 
        # if symbol is an operand
        else:
 
            # push the operand to the stack
            s.append(post_exp[i])
 
    
    ans = ""
    for i in s:
        ans += i
    return ans
 
 
# Driver Code
if __name__ == "__main__":
 
    post_exp = "AB+CD-"
     
    # Function call
    print("Prefix : ", postToPre(post_exp))
 
# This code is contributed by AnkitRai01

Time complexity: linear
Space complexity: linear
# Python3 program to check for
# balanced brackets.
 
# function to check if
# brackets are balanced
 
 
def areBracketsBalanced(expr):
    stack = []
 
    # Traversing the Expression
    for char in expr:
        if char in ["(", "{", "["]:
 
            # Push the element in the stack
            stack.append(char)
        else:
 
            # IF current character is not opening
            # bracket, then it must be closing.
            # So stack cannot be empty at this point.
            if not stack:
                return False
            current_char = stack.pop()
            if current_char == '(':
                if char != ")":
                    return False
            if current_char == '{':
                if char != "}":
                    return False
            if current_char == '[':
                if char != "]":
                    return False
 
    # Check Empty Stack
    if stack:
        return False
    return True
 
 
# Driver Code
if __name__ == "__main__":
    expr = "{()}[]"
 
    # Function call
    if areBracketsBalanced(expr):
        print("Balanced")
    else:
        print("Not Balanced")
 
# This code is contributed by AnkitRai01 and improved
# by Raju Pitta

Time complexity: linear
Space complexity: linear
'''NFG function to find the next greater frequency
   element for each element in the array'''
 
 
def NFG(a, n):
 
    if (n <= 0):
        print("List empty")
        return []
 
    # stack data structure to store the position
    # of array element
    stack = [0]*n
 
    # freq is a dictionary which maintains the
    # frequency of each element
    freq = {}
    for i in a:
        freq[a[i]] = 0
    for i in a:
        freq[a[i]] += 1
 
    # res to store the value of next greater
    # frequency element for each element
    res = [0]*n
 
    # initialize top of stack to -1
    top = -1
 
    # push the first position of array in the stack
    top += 1
    stack[top] = 0
 
    # now iterate for the rest of elements
    for i in range(1, n):
 
        ''' If the frequency of the element which is
            pointed by the top of stack is greater
            than frequency of the current element
            then push the current position i in stack'''
        if (freq[a[stack[top]]] > freq[a[i]]):
            top += 1
            stack[top] = i
 
        else:
            ''' If the frequency of the element which
            is pointed by the top of stack is less
            than frequency of the current element, then
            pop the stack and continuing popping until
            the above condition is true while the stack
            is not empty'''
 
            while (top > -1 and freq[a[stack[top]]] < freq[a[i]]):
                res[stack[top]] = a[i]
                top -= 1
 
            # now push the current element
            top += 1
            stack[top] = i
 
    '''After iterating over the loop, the remaining
    position of elements in stack do not have the
    next greater element, so print -1 for them'''
    while (top > -1):
        res[stack[top]] = -1
        top -= 1
 
    # return the res list containing next
    # greater frequency element
    return res
 
 
# Driver Code
print(NFG([1, 1, 2, 3, 4, 2, 1], 7))

Time complexity: linear
Space complexity: linear
# Python3 program of Next Greater Frequency Element
 
mystack = []
mymap = {}
  
"""NFG function to find the next greater frequency
element for each element and for placing it in the
resultant array """
def NGF(arr, res):
    n = len(arr)
      
    # Initially store the frequencies of all elements
    # in a hashmap
    for i in range(n):
        if arr[i] in mymap:
            mymap[arr[i]] += 1
        else:
            mymap[arr[i]] = 1
      
    # Get the frequency of the last element
    curr_freq = mymap[arr[n-1]]
     
    # push it to the stack
    mystack.append([arr[n-1],curr_freq])
     
    # place -1 as next greater freq for the last
    # element as it does not have next greater.
    res[n-1] = -1
      
    # iterate through array in reverse order
    for i in range(n - 2, -1, -1):
        curr_freq = mymap[arr[i]]
          
        """ If the frequency of the element which is
        pointed by the top of stack is greater
        than frequency of the current element
        then push the current position i in stack"""
        while len(mystack) > 0  and  curr_freq >= mystack[-1][1]:
            mystack.pop()
          
        # If the stack is empty, place -1. If it is not empty
        # then we will have next higher freq element at the top of the stack.
        if (len(mystack) == 0):
            res[i] = -1
        else:
            res[i] = mystack[-1][0]
          
        # push the element at current position
        mystack.append([arr[i],mymap[arr[i]]])
 
arr = [1, 1, 1, 2, 2, 2, 2, 11, 3, 3]
  
res = [0]*(len(arr))
NGF(arr, res)
print(res)
 
# This code is contributed by rameshtravel07.

Time complexity: linear
Space complexity: linear
class GFG:
    # Function to find number of next greater elements on
    # the right of a given element
    @staticmethod
    def nextGreaterElements(a,  index):
        count = 0
        N = len(a)
        i = index + 1
        while (i < N):
            if (a[i] > a[index]):
                count += 1
            i += 1
        return count
 
    @staticmethod
    def main(args):
        a = [3, 4, 2, 7, 5, 8, 10, 6]
        Q = 2
        queries = [0, 5]
        i = 0
        while (i < Q):
            # Function call
            print(str(GFG.nextGreaterElements(a, queries[i])) + " ", end="")
            i += 1
 
 
if __name__ == "__main__":
    GFG.main([])

Time complexity: linear
Space complexity: constant
# Python3 program to find celebrity
 
# Max # of persons in the party
N = 8
 
# Person with 2 is celebrity
MATRIX = [[0, 0, 1, 0],
          [0, 0, 1, 0],
          [0, 0, 0, 0],
          [0, 0, 1, 0]]
 
 
def knows(a, b):
 
    return MATRIX[a][b]
 
 
def findCelebrity(n):
 
    # The graph needs not be constructed
    # as the edges can be found by
    # using knows function
 
    # degree array;
    indegree = [0 for x in range(n)]
    outdegree = [0 for x in range(n)]
 
    # Query for all edges
    for i in range(n):
        for j in range(n):
            x = knows(i, j)
 
            # Set the degrees
            outdegree[i] += x
            indegree[j] += x
 
    # Find a person with indegree n-1
    # and out degree 0
    for i in range(n):
        if (indegree[i] == n - 1 and
                outdegree[i] == 0):
            return i
 
    return -1
 
 
# Driver code
if __name__ == '__main__':
 
    n = 4
    id_ = findCelebrity(n)
 
    if id_ == -1:
        print("No celebrity")
    else:
        print("Celebrity ID", id_)
 
# This code is contributed by UnworthyProgrammer

Time complexity: quadratic
Space complexity: linear
# Python3 program to find celebrity
 
# Max # of persons in the party
N = 8
 
# Person with 2 is celebrity
MATRIX = [[0, 0, 1, 0],
          [0, 0, 1, 0],
          [0, 0, 0, 0],
          [0, 0, 1, 0]]
 
 
def knows(a, b):
 
    return MATRIX[a][b]
 
# Returns -1 if a potential celebrity
# is not present. If present,
# returns id (value from 0 to n-1).
 
 
def findPotentialCelebrity(n):
 
    # Base case
    if (n == 0):
        return 0
 
    # Find the celebrity with n-1
    # persons
    id_ = findPotentialCelebrity(n - 1)
 
    # If there are no celebrities
    if (id_ == -1):
        return n - 1
    # if the id knows the nth person
    # then the id cannot be a celebrity, but nth person
    # could be on
    elif knows(id_, n - 1):
        return n - 1
    # if the id knows the nth person
    # then the id cannot be a celebrity, but nth person
    # could be one
    elif knows(n - 1, id_):
        return id_
    # If there is no celebrity
    return - 1
 
# Returns -1 if celebrity
# is not present. If present,
# returns id (value from 0 to n-1).
# a wrapper over findCelebrity
 
 
def Celebrity(n):
 
    # Find the celebrity
    id_ = findPotentialCelebrity(n)
 
    # Check if the celebrity found
    # is really the celebrity
    if (id_ == -1):
        return id_
    else:
        c1 = 0
        c2 = 0
 
        # Check the id is really the
        # celebrity
        for i in range(n):
            if (i != id_):
                c1 += knows(id_, i)
                c2 += knows(i, id_)
 
        # If the person is known to
        # everyone.
        if (c1 == 0 and c2 == n - 1):
            return id_
 
        return -1
 
 
# Driver code
if __name__ == '__main__':
 
    n = 4
    id_ = Celebrity(n)
 
    if id_ == -1:
        print("No celebrity")
    else:
        print("Celebrity ID", id_)
 
# This code is contributed by UnworthyProgrammer

Time complexity: linear
Space complexity: constant
# Python3 program to find celebrity
# using stack data structure
 
# Max # of persons in the party
N = 8
 
# Person with 2 is celebrity
MATRIX = [[0, 0, 1, 0],
          [0, 0, 1, 0],
          [0, 0, 0, 0],
          [0, 0, 1, 0]]
 
 
def knows(a, b):
 
    return MATRIX[a][b]
 
# Returns -1 if celebrity
# is not present. If present,
# returns id (value from 0 to n-1).
 
 
def findCelebrity(n):
 
    # Handle trivial
    # case of size = 2
    s = []
 
    # Push everybody to stack
    for i in range(n):
        s.append(i)
 
    # Find a potential celebrity
    while (len(s) > 1):
 
          # Pop out the first two elements from stack
        A = s.pop()
        B = s.pop()
 
        # if A knows B, we find that B might be the celebrity and vice versa
        if (knows(A, B)):
            s.append(B)
        else:
            s.append(A)
 
    # If there are only two people
    # and there is no
    # potential candidate
    if(len(s) == 0):
        return -1
 
    # Potential candidate?
    C = s.pop()
 
    # Last candidate was not
    # examined, it leads one
    # excess comparison (optimize)
    if (knows(C, B)):
        C = B
 
    if (knows(C, A)):
        C = A
 
    # Check if C is actually
    # a celebrity or not
    for i in range(n):
 
        # If any person doesn't
        # know 'a' or 'a' doesn't
        # know any person, return -1
        if ((i != C) and
            (knows(C, i) or
                not(knows(i, C)))):
            return -1
 
    return C
 
 
# Driver code
if __name__ == '__main__':
 
    n = 4
    id_ = findCelebrity(n)
 
    if id_ == -1:
        print("No celebrity")
    else:
        print("Celebrity ID ", id_)
 
# This code is contributed by UnworthyProgrammer

Time complexity: linear
Space complexity: linear