Banana-Leopard/TASTY huggingface dataset:
# An efficient Python3 program to find
# maximum of all minimums of windows of
# different sizes
 
 
def printMaxOfMin(arr, n):
 
    s = []  # Used to find previous
    # and next smaller
 
    # Arrays to store previous and next
    # smaller. Initialize elements of
    # left[] and right[]
    left = [-1] * (n + 1)
    right = [n] * (n + 1)
 
    # Fill elements of left[] using logic discussed on
    # https:#www.geeksforgeeks.org/next-greater-element
    for i in range(n):
        while (len(s) != 0 and
               arr[s[-1]] >= arr[i]):
            s.pop()
 
        if (len(s) != 0):
            left[i] = s[-1]
 
        s.append(i)
 
    # Empty the stack as stack is going
    # to be used for right[]
    while (len(s) != 0):
        s.pop()
 
    # Fill elements of right[] using same logic
    for i in range(n - 1, -1, -1):
        while (len(s) != 0 and arr[s[-1]] >= arr[i]):
            s.pop()
 
        if(len(s) != 0):
            right[i] = s[-1]
 
        s.append(i)
 
    # Create and initialize answer array
    ans = [0] * (n + 1)
    for i in range(n + 1):
        ans[i] = 0
 
    # Fill answer array by comparing minimums
    # of all. Lengths computed using left[]
    # and right[]
    for i in range(n):
 
        # Length of the interval
        Len = right[i] - left[i] - 1
 
        # arr[i] is a possible answer for this
        #  Length 'Len' interval, check if arr[i]
        # is more than max for 'Len'
        ans[Len] = max(ans[Len], arr[i])
 
    # Some entries in ans[] may not be filled
    # yet. Fill them by taking values from
    # right side of ans[]
    for i in range(n - 1, 0, -1):
        ans[i] = max(ans[i], ans[i + 1])
 
    # Print the result
    for i in range(1, n + 1):
        print(ans[i], end=" ")
 
 
# Driver Code
if __name__ == '__main__':
 
    arr = [10, 20, 30, 50, 10, 70, 30]
    n = len(arr)
    printMaxOfMin(arr, n)
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: linear
# Python3 Program to check whether valid
# expression is redundant or not
 
# Function to check redundant brackets
# in a balanced expression
def checkRedundancy(Str):
     
    # create a stack of characters
    st = []
 
    # Iterate through the given expression
    for ch in Str:
 
        # if current character is close
        # parenthesis ')'
        if (ch == ')'):
            top = st[-1]
            st.pop()
 
            # If immediate pop have open parenthesis
            # '(' duplicate brackets found
            flag = True
 
            while (top != '('):
 
                # Check for operators in expression
                if (top == '+' or top == '-' or
                    top == '*' or top == '/'):
                    flag = False
 
                # Fetch top element of stack
                top = st[-1]
                st.pop()
 
            # If operators not found
            if (flag == True):
                return True
 
        else:
            st.append(ch) # append open parenthesis '(',
                          # operators and operands to stack
    return False
 
# Function to check redundant brackets
def findRedundant(Str):
    ans = checkRedundancy(Str)
    if (ans == True):
        print("Yes")
    else:
        print("No")
 
# Driver code
if __name__ == '__main__':
    Str = "((a+b))"
    findRedundant(Str)
 
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: linear
# Python3 program to
# mark balanced and
# unbalanced parenthesis.
def identifyParenthesis(a):
    st = []
 
    # run the loop upto
    # end of the string
    for i in range (len(a)):
 
        # if a[i] is opening
        # bracket then push
        # into stack
        if (a[i] == '('):
            st.append(a[i])
         
        # if a[i] is closing bracket ')'
        elif (a[i] == ')'):
 
            # If this closing bracket
            # is unmatched
            if (len(st) == 0):
                a = a.replace(a[i], "-1", 1)
             
            else:
 
                # replace all opening brackets with 0
                # and closing brackets with 1
                a = a.replace(a[i], "1", 1)
                a = a.replace(st[-1], "0", 1)
                st.pop()
           
    # if stack is not empty
    # then pop out all
    # elements from it and
    # replace -1 at that
    # index of the string
    while (len(st) != 0):
        a = a.replace(st[-1], 1, "-1");
        st.pop()
 
    # print final string
    print(a)
 
# Driver code
if __name__ == "__main__":
 
    st = "(a))"
    identifyParenthesis(st)
     
# This code is contributed by Chitranayal

Time complexity: linear
Space complexity: linear
# Python3 program to check if two expressions
# evaluate to same.
MAX_CHAR = 26;
 
# Return local sign of the operand. For example,
# in the expr a-b-(c), local signs of the operands
# are +a, -b, +c
def adjSign(s, i):
  if (i == 0):
    return True;
  if (s[i - 1] == '-'):
    return False;
  return True;
 
# Evaluate expressions into the count vector of
# the 26 alphabets.If add is True, then add count
# to the count vector of the alphabets, else remove
# count from the count vector.
def eval(s, v, add):
   
  # stack stores the global sign
  # for operands.
  stk = []
  stk.append(True);
   
  # + means True
  # global sign is positive initially
  i = 0;
 
  while (i < len(s)):
 
    if (s[i] == '+' or s[i] == '-'):
      i += 1
      continue;
     
    if (s[i] == '('):
       
      # global sign for the bracket is
      # pushed to the stack
      if (adjSign(s, i)):
        stk.append(stk[-1]);
      else:
        stk.append(not stk[-1]);
     
    # global sign is popped out which
    # was pushed in for the last bracket
    elif (s[i] == ')'):
      stk.pop();
    else:
       
      # global sign is positive (we use different
      # values in two calls of functions so that
      # we finally check if all vector elements
      # are 0.
      if (stk[-1]):
        v[ord(s[i]) - ord('a')] += (1 if add else -1) if adjSign(s, i) else (-1 if add else 1)
       
      # global sign is negative here
      else:
        v[ord(s[i]) - ord('a')] += (-1 if add else 1) if adjSign(s, i) else (1 if add else -1)
     
    i += 1
   
# Returns True if expr1 and expr2 represent
# same expressions
def areSame(expr1, expr2):
   
  # Create a vector for all operands and
  # initialize the vector as 0.
  v = [0 for i in range(MAX_CHAR)];
   
  # Put signs of all operands in expr1
  eval(expr1, v, True);
   
  # Subtract signs of operands in expr2
  eval(expr2, v, False);
   
  # If expressions are same, vector must
  # be 0.
  for i in range(MAX_CHAR):
    if (v[i] != 0):
      return False;
  return True;
 
# Driver Code
if __name__=='__main__':
  expr1 = "-(a+b+c)"
  expr2 = "-a-b-c";
  if (areSame(expr1, expr2)):
    print("Yes");
  else:
    print("No");
 
    # This code is contributed by rutvik_56.

Time complexity: linear
Space complexity: linear
# Python program to find index of closing
# bracket for a given opening bracket.
from collections import deque
  
def getIndex(s, i):
  
    # If input is invalid.
    if s[i] != '[':
        return -1
  
    # Create a deque to use it as a stack.
    d = deque()
  
    # Traverse through all elements
    # starting from i.
    for k in range(i, len(s)):
  
        # Pop a starting bracket
        # for every closing bracket
        if s[k] == ']':
            d.popleft()
  
        # Push all starting brackets
        elif s[k] == '[':
            d.append(s[i])
  
        # If deque becomes empty
        if not d:
            return k
  
    return -1
  
# Driver code to test above method.
def test(s, i):
    matching_index = getIndex(s, i)
    print(s + ", " + str(i) + ": " + str(matching_index))
  
def main():
    test("[ABC[23]][89]", 0) # should be 8
    test("[ABC[23]][89]", 4) # should be 7
    test("[ABC[23]][89]", 9) # should be 12
    test("[ABC[23]][89]", 1) # No matching bracket
  
if __name__ == "__main__":
    main()

Time complexity: linear
Space complexity: linear
# Python3 program to determine whether
# given expression is balanced/ parenthesis
# expression or not.
 
# Function to check if two brackets are
# matching or not.
def isMatching(a, b):
     
    if ((a == '{' and b == '}') or
        (a == '[' and b == ']') or
        (a == '(' and b == ')') or
         a == 'X'):
        return 1
         
    return 0
 
# Recursive function to check if given
# expression is balanced or not.
def isBalanced(s, ele, ind):
     
    # Base case.
    # If the string is balanced then all the
    # opening brackets had been popped and
    # stack should be empty after string is
    # traversed completely.
    if (ind == len(s)):
        if len(ele) == 0:
            return True
        else:
            return False
 
    # Variable to store element at the top
    # of the stack.
    # char topEle;
 
    # Variable to store result of
    # recursive call.
    # int res;
 
    # Case 1: When current element is an
    # opening bracket then push that
    # element in the stack.
    if (s[ind] == '{' or s[ind] == '(' or
        s[ind] == '['):
        ele.append(s[ind])
        return isBalanced(s, ele, ind + 1)
 
    # Case 2: When current element is a closing
    # bracket then check for matching bracket
    # at the top of the stack.
    elif (s[ind] == '}' or s[ind] == ')' or
          s[ind] == ']'):
 
        # If stack is empty then there is no matching
        # opening bracket for current closing bracket
        # and the expression is not balanced.
        if (len(ele) == 0):
            return 0
 
        topEle = ele[-1]
        ele.pop()
 
        # Check bracket is matching or not.
        if (isMatching(topEle, s[ind]) == 0):
            return 0
         
        return isBalanced(s, ele, ind + 1)
 
    # Case 3: If current element is 'X' then check
    # for both the cases when 'X' could be opening
    # or closing bracket.
    elif (s[ind] == 'X'):
        tmp = ele
        tmp.append(s[ind])
        res = isBalanced(s, tmp, ind + 1)
         
        if (res):
            return 1
        if (len(ele) == 0):
            return 0
             
        ele.pop()
         
        return isBalanced(s, ele, ind + 1)
         
# Driver Code
s = "{(X}[]"
ele = []
 
# Check if the length of the given string is even
if(len(s)%2==0):
    if (isBalanced(s, ele, 0)): print("Balanced")
    else: print("Not Balanced")
     
# If the length is not even, then the string is not balanced
else: print("Not Balanced")
 
# This code is contributed by divyeshrabadiya07

Time complexity: np
Space complexity: linear
# Python program to find the difference b/w left and
# right smaller element of every element in the array
 
# Function to fill left smaller element for every
# element of arr[0..n-1]. These values are filled
# in SE[0..n-1]
def leftsmaller(arr, n, SE):
 
    # create an empty stack
    sta = []
    # Traverse all array elements
    # compute nearest smaller elements of every element
    for i in range(n):
         
        # Keep removing top element from S while the top
        # element is greater than or equal to arr[i]
        while(sta != [] and sta[len(sta)-1] >= arr[i]):
            sta.pop()
 
        # Store the smaller element of current element
        if(sta != []):
            SE[i]=sta[len(sta)-1]
        # If all elements in S were greater than arr[i]
        else:
            SE[i]=0
 
        # push this element
        sta.append(arr[i])
 
# Function returns maximum difference b/w  Left  &
# right smaller element
def findMaxDiff(arr, n):
    ls=[0]*n # to store left smaller elements
    rs=[0]*n # to store right smaller elements
 
    # find left smaller elements of every element
    leftsmaller(arr, n, ls)
     
    # find right smaller element of every element
    # by sending reverse of array
    leftsmaller(arr[::-1], n, rs)
 
    # find maximum absolute difference b/w LS  & RRS
    # In the reversed array right smaller for arr[i] is
    # stored at RRS[n-i-1]
    res = -1
    for i in range(n):
        res = max(res, abs(ls[i] - rs[n-1-i]))
    # return maximum difference b/w LS  & RRS
    return res
 
     
# Driver Program
if __name__=='__main__':
    arr = [2, 4, 8, 7, 7, 9, 3]
    print "Maximum Diff :", findMaxDiff(arr, len(arr))
     
#Contributed By: Harshit Sidhwa

Time complexity: linear
Space complexity: linear
# Python 3 Program to find Right smaller element of next
# greater element
  
# function find Next greater element
def nextGreater(arr, n, next, order):
 
    S = []
  
    # Traverse all array elements in reverse order
    # order == 'G' we compute next greater elements of
    #              every element
    # order == 'S' we compute right smaller element of
    #              every element
    for i in range(n-1,-1,-1):
 
        # Keep removing top element from S while the top
        # element is smaller than or equal to arr[i] (if Key is G)
        # element is greater than or equal to arr[i] (if order is S)
        while (S!=[] and (arr[S[len(S)-1]] <= arr[i]
        if (order=='G') else  arr[S[len(S)-1]] >= arr[i] )):
                
            S.pop()
  
        # store the next greater element of current element
        if (S!=[]):
            next[i] = S[len(S)-1]
  
        # If all elements in S were smaller than arr[i]
        else:
            next[i] = -1
  
        # Push this element
        S.append(i)
  
# Function to find Right smaller element of next greater
# element
def nextSmallerOfNextGreater(arr, n):
    NG = [None]*n  #  stores indexes of next greater elements
    RS = [None]*n  # stores indexes of right smaller elements
  
    # Find next greater element
    # Here G indicate next greater element
    nextGreater(arr, n, NG, 'G')
  
    # Find right smaller element
    # using same function nextGreater()
    # Here S indicate right smaller elements
    nextGreater(arr, n, RS, 'S')
  
    # If NG[i] == -1 then there is no smaller element
    # on right side. We can find Right smaller of next
    # greater by arr[RS[NG[i]]]
    for i in range(n):
        if (NG[i] != -1 and RS[NG[i]] != -1):
            print(arr[RS[NG[i]]],end=" ")
        else:
            print("-1",end=" ")
  
# Driver program
if __name__=="__main__":
    arr = [5, 1, 9, 2, 5, 1, 7]
    n = len(arr)
    nextSmallerOfNextGreater(arr, n)
 
# this code is contributed by ChitraNayal

Time complexity: linear
Space complexity: linear
# Python program to calculate maximum sum with equal
# stack sum.
# Returns maximum possible equal sum of three stacks
# with removal of top elements allowed
def maxSum(stack1, stack2, stack3, n1, n2, n3):
    sum1, sum2, sum3 = 0, 0, 0
   
  # Finding the initial sum of stack1.
    for i in range(n1):
        sum1 += stack1[i]
  
  # Finding the initial sum of stack2.
    for i in range(n2):
        sum2 += stack2[i]
  
  # Finding the initial sum of stack3.
    for i in range(n3):
        sum3 += stack3[i]
  
  # As given in question, first element is top
  # of stack..
    top1, top2, top3 = 0, 0, 0
    ans = 0
    while (1):
      # If any stack is empty
        if (top1 == n1 or top2 == n2 or top3 == n3):
            return 0
  
      # If sum of all three stack are equal.
        if (sum1 == sum2 and sum2 == sum3):
            return sum1
      
      # Finding the stack with maximum sum and
      # removing its top element.
        if (sum1 >= sum2 and sum1 >= sum3):
            sum1 -= stack1[top1]
            top1=top1+1
        else if (sum2 >= sum1 and sum2 >= sum3):
            sum2 -= stack2[top2]
            top2=top2+1
        else if (sum3 >= sum2 and sum3 >= sum1):
            sum3 -= stack3[top3]
            top3=top3+1
  
# Driven Program
stack1 = [ 3, 2, 1, 1, 1 ]
stack2 = [ 4, 3, 2 ]
stack3 = [ 1, 1, 4, 1 ]
  
n1 = len(stack1)
n2 = len(stack2)
n3 = len(stack3)
  
print (maxSum(stack1, stack2, stack3, n1, n2, n3))
 
#This code is contributed by Afzal Ansari

Time complexity: linear
Space complexity: constant
# Python3 program to count the number less
# than N, whose all permutation is greater
# than or equal to the number.
 
# Return the count of the number having
# all permutation greater than or equal
# to the number.
 
 
def countNumber(n):
    result = 0
 
    # Pushing 1 to 9 because all number
    # from 1 to 9 have this property.
    s = []
    for i in range(1, 10):
         
        if (i <= n):
            s.append(i)
            result += 1
 
        # take a number from stack and add
        # a digit smaller than or equal to last digit
        # of it.
        while len(s) != 0:
            tp = s[-1]
            s.pop()
            for j in range(tp % 10, 10):
                x = tp * 10 + j
                if (x <= n):
                    s.append(x)
                    result += 1
 
    return result
 
 
# Driver Code
if __name__ == '__main__':
 
    n = 15
    print(countNumber(n))
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: linear
# Python program to decode a string recursively
# encoded as count followed substring
 
# Returns decoded string for 'str'
def decode(Str):
    integerstack = []
    stringstack = []
    temp = ""
    result = ""
    i = 0
    # Traversing the string
    while i < len(Str):
        count = 0
 
        # If number, convert it into number
        # and push it into integerstack.
        if (Str[i] >= '0' and Str[i] <='9'):
            while (Str[i] >= '0' and Str[i] <= '9'):
                count = count * 10 + ord(Str[i]) - ord('0')
                i += 1
            i -= 1
            integerstack.append(count)
 
        # If closing bracket ']', pop element until
        # '[' opening bracket is not found in the
        # character stack.
        elif (Str[i] == ']'):
            temp = ""
            count = 0
 
            if (len(integerstack) != 0):
                count = integerstack[-1]
                integerstack.pop()
 
            while (len(stringstack) != 0 and stringstack[-1] !='[' ):
                temp = stringstack[-1] + temp
                stringstack.pop()
 
            if (len(stringstack) != 0 and stringstack[-1] == '['):
                stringstack.pop()
 
            # Repeating the popped string 'temo' count
            # number of times.
            for j in range(count):
                result = result + temp
 
            # Push it in the character stack.
            for j in range(len(result)):
                stringstack.append(result[j])
 
            result = ""
 
        # If '[' opening bracket, push it into character stack.
        elif (Str[i] == '['):
            if (Str[i-1] >= '0' and Str[i-1] <= '9'):
                stringstack.append(Str[i])
 
            else:
                stringstack.append(Str[i])
                integerstack.append(1)
 
        else:
            stringstack.append(Str[i])
         
        i += 1
 
    # Pop all the element, make a string and return.
    while len(stringstack) != 0:
        result = stringstack[-1] + result
        stringstack.pop()
 
    return result
 
# Driven code
if __name__ == '__main__':
    Str = "3[b2[ca]]"
    print(decode(Str))
     
# This code is contributed by PranchalK.

Time complexity: linear
Space complexity: linear
def decodeString(s):
    st = []
    for i in range(len(s)):
       
        # When ']' is encountered, we need to start decoding
        if s[i] == ']':
            temp = ""
            while len(st) > 0 and st[-1] != '[':
               
                # st.top() + temp makes sure that the
                # string won't be in reverse order eg, if
                # the stack contains 12[abc temp = c + "" =>
                # temp = b + "c" => temp = a + "bc"
                temp = st[-1] + temp
                st.pop()
              
            # remove the '[' from the stack
            st.pop()
            num = ""
              
            # remove the digits from the stack
            while len(st) > 0 and ord(st[-1]) >= 48 and ord(st[-1]) <= 57:
                num = st[-1] + num
                st.pop()
            number = int(num)
            repeat = ""
            for j in range(number):
                repeat += temp
            for c in range(len(repeat)):
                if len(st) > 0:
                    if repeat == st[-1]:
                        break #otherwise this thingy starts appending the same decoded words
                st.append(repeat)
           
        else:
            st.append(s[i])        
         
    return st[0]
  
 
Str = "3[b2[ca]]"
print(decodeString(Str))
 
# This code is contributed by mukesh07.
# And debugged by ivannakreshchenetska

Time complexity: linear
Space complexity: linear
# Python3 program for bubble sort
# using stack
 
# Function for bubble sort using Stack
def bubbleSortStack(a, n):
    s1 = []
     
    # Push all elements of array in 1st stack
    for i in range(n):
        s1.append(a[i]);
    s2 = []
    for i in range(n):
        if (i % 2 == 0):
            while (len(s1) != 0):
                t = s1[-1]
                s1.pop();
                if(len(s2) == 0):
                    s2.append(t);                  
                else:
                 
                    # Swapping
                    if (s2[-1] > t):
                        temp = s2[-1]
                        s2.pop();
                        s2.append(t);
                        s2.append(temp);
                     
                    else:
                        s2.append(t);
                     
            # Tricky step
            a[n - 1 - i] = s2[-1]
            s2.pop();          
        else:
         
            while(len(s2) != 0):
                t = s2[-1]
                s2.pop();
 
                if(len(s1) == 0):
                    s1.append(t);
                else:
                    if (s1[-1] > t):
                        temp = s1[-1]
                        s1.pop();
 
                        s1.append(t);
                        s1.append(temp);
                    else:
                        s1.append(t);
                     
            # Tricky step
            a[n - 1 - i] = s1[-1]
            s1.pop();
    print("[", end = '')
    for i in range(n):
        print(a[i], end = ', ')
    print(']', end = '')
 
# Driver code
if __name__=='__main__':
     
    a = [ 15, 12, 44, 2, 5, 10 ]
    n = len(a)
 
    bubbleSortStack(a, n);
     
    # This code is contributed by rutvik_56.

Time complexity: quadratic
Space complexity: linear