Banana-Leopard/TASTY huggingface dataset:
# Python program to print all ancestors of a given key
 
# A class to create a new tree node
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
# Iterative Function to print all ancestors of a
# given key
def printAncestors(root, key):
    if (root == None):
        return
 
    # Create a stack to hold ancestors
    st = []
 
    # Traverse the complete tree in postorder way till
    # we find the key
    while (1):
 
        # Traverse the left side. While traversing, push
        # the nodes into the stack so that their right
        # subtrees can be traversed later
        while (root and root.data != key):
            st.append(root) # push current node
            root = root.left # move to next node
 
        # If the node whose ancestors are to be printed
        # is found, then break the while loop.
        if (root and root.data == key):
            break
 
        # Check if right sub-tree exists for the node at top
        # If not then pop that node because we don't need
        # this node any more.
        if (st[-1].right == None):
            root = st[-1]
            st.pop()
 
            # If the popped node is right child of top,
            # then remove the top as well. Left child of
            # the top must have processed before.
            while (len(st) != 0 and st[-1].right == root):
                root = st[-1]
                st.pop()
 
        # if stack is not empty then simply set the root
        # as right child of top and start traversing right
        # sub-tree.
        root = None if len(st) == 0 else st[-1].right
 
    # If stack is not empty, print contents of stack
    # Here assumption is that the key is there in tree
    while (len(st) != 0):
        print(st[-1].data,end = " ")
        st.pop()
 
# Driver code
if __name__ == '__main__':
 
    # Let us construct a binary tree
    root = newNode(1)
    root.left = newNode(2)
    root.right = newNode(7)
    root.left.left = newNode(3)
    root.left.right = newNode(5)
    root.right.left = newNode(8)
    root.right.right = newNode(9)
    root.left.left.left = newNode(4)
    root.left.right.right = newNode(6)
    root.right.right.left = newNode(10)
 
    key = 6
    printAncestors(root, key)
     
# This code is contributed by PranchalK.

Time complexity: linear
Space complexity: linear
# Python3 program to keep track of
# maximum element in a stack
 
class StackWithMax:
    def __init__(self):
         
        # main stack
        self.mainStack = []
     
        # stack to keep track of
        # max element
        self.trackStack = []
 
    def push(self, x):
        self.mainStack.append(x)
        if (len(self.mainStack) == 1):
            self.trackStack.append(x)
            return
 
        # If current element is greater than
        # the top element of track stack,
        # append the current element to track
        # stack otherwise append the element
        # at top of track stack again into it.
        if (x > self.trackStack[-1]):
            self.trackStack.append(x)
        else:
            self.trackStack.append(self.trackStack[-1])
 
    def getMax(self):
        return self.trackStack[-1]
 
    def pop(self):
        self.mainStack.pop()
        self.trackStack.pop()
 
# Driver Code
if __name__ == '__main__':
 
    s = StackWithMax()
    s.push(20)
    print(s.getMax())
    s.push(10)
    print(s.getMax())
    s.push(50)
    print(s.getMax())
 
# This code is contributed by PranchalK

Time complexity: constant
Space complexity: linear
# Python3 program to reverse the
# number using a stack
 
# Stack to maintain order of digits
st = [];
 
# Function to push digits into stack
def push_digits(number):
 
    while (number != 0):
        st.append(number % 10);
        number = int(number / 10);
 
# Function to reverse the number
def reverse_number(number):
     
    # Function call to push number's
    # digits to stack
    push_digits(number);
     
    reverse = 0;
    i = 1;
     
    # Popping the digits and forming
    # the reversed number
    while (len(st) > 0):
        reverse = reverse + (st[len(st) - 1] * i);
        st.pop();
        i = i * 10;
     
    # Return the reversed number formed
    return reverse;
 
# Driver Code
number = 39997;
 
# Function call to reverse number
print(reverse_number(number));
 
# This code is contributed by mits

Time complexity: logn
Space complexity: logn
# 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: constant
# Python3 program to check if successive
# pair of numbers in the stack are
# consecutive or not
 
# Function to check if elements are
# pairwise consecutive in stack
def pairWiseConsecutive(s):
     
    # Transfer elements of s to aux.
    aux = []
    while (len(s) != 0):
        aux.append(s[-1])
        s.pop()
 
    # Traverse aux and see if elements
    # are pairwise consecutive or not.
    # We also need to make sure that
    # original content is retained.
    result = True
    while (len(aux) > 1):
 
        # Fetch current top two
        # elements of aux and check
        # if they are consecutive.
        x = aux[-1]
        aux.pop()
        y = aux[-1]
        aux.pop()
        if (abs(x - y) != 1):
            result = False
 
        # append the elements to
        # original stack.
        s.append(x)
        s.append(y)
 
    if (len(aux) == 1):
        s.append(aux[-1])
 
    return result
 
# Driver Code
if __name__ == '__main__':
 
    s = []
    s.append(4)
    s.append(5)
    s.append(-2)
    s.append(-3)
    s.append(11)
    s.append(10)
    s.append(5)
    s.append(6)
    s.append(20)
 
    if (pairWiseConsecutive(s)):
        print("Yes")
    else:
        print("No")
 
    print("Stack content (from top)",
               "after function call")
    while (len(s) != 0):
        print(s[-1], end = " ")
        s.pop()
 
# This code is contributed by PranchalK

Time complexity: linear
Space complexity: linear
# Python3 Program to implement growable array based stack
# using tight strategy
 
# constant amount at which stack is increased
BOUND = 4
 
# top of the stack
top = -1
a = []
 
# length of stack
length = 0
 
# function to create new stack
 
 
def create_new():
    global length
 
    # allocate memory for new stack
    new_a = [0 for i in range(length + BOUND)]
 
    # copying the content of old stack
    for i in range(length):
        new_a[i] = a[i]
 
    # re-sizing the length
    length += BOUND
    return new_a
 
# function to push new element
 
 
def push(element):
 
    global top, a
 
    # if stack is full, create new one
    if (top == length - 1):
        a = create_new()
 
    top += 1
 
    # insert element at top of the stack
    a[top] = element
    return a
 
# function to pop an element
 
 
def pop():
    global top
 
    # stack is empty can't pop
    if (top < 0)
    print("Stack is Empty")
    else:
    top -= 1
 
# function to display
 
 
def display():
    global top
 
    # if top is less than 0, that means stack is empty
    if (top < 0)
    print("Stack is Empty")
    else:
        print("Stack: ", end='')
        for i in range(top + 1):
 
            print(a[i], end=' ')
        print()
 
 
# Driver Code
if __name__ == '__main__':
 
    # creating initial stack
    a = create_new()
 
    # pushing element to top of stack
    push(1)
    push(2)
    push(3)
    push(4)
    display()
 
    # pushing more element when stack is full
    push(5)
    push(6)
    display()
 
    push(7)
    push(8)
    display()
 
    # pushing more element so that stack can grow
    push(9)
    display()
 
# This code is contributed by rutvik_56.

Time complexity: linear
Space complexity: linear
# Python3 code to answer the query in constant time
 
'''
BOP[] stands for "Balanced open parentheses"
BCP[] stands for "Balanced close parentheses"
 
'''
# Function for precomputation
def constructBalanceArray(BOP, BCP, str, n):
     
    # Create a stack and push -1
    # as initial index to it.
    stk = []
 
    # Traverse all characters of given String
    for i in range(n):
         
        # If opening bracket, push index of it
        if (str[i] == '('):
            stk.append(i);
             
        # If closing bracket, i.e., str[i] = ')'
        else:
             
            # If closing bracket, i.e., str[i] = ')'
            # && stack is not empty then mark both
            # "open & close" bracket indexes as 1 .
            # Pop the previous opening bracket's index
            if (len(stk) != 0):
                BCP[i] = 1;
                BOP[stk[-1]] = 1;
                stk.pop();
 
            # If stack is empty.
            else:
                BCP[i] = 0;
         
    for i in range(1, n):
 
        BCP[i] += BCP[i - 1];
        BOP[i] += BOP[i - 1];
     
# Function return output of each query in O(1)
def query(BOP, BCP, s, e):
 
    if (BOP[s - 1] == BOP[s]):
        return (BCP[e] - BOP[s]) * 2;
     
    else:
        return (BCP[e] - BOP[s] + 1) * 2;
 
# Driver code
if __name__=='__main__':
 
    string = "())(())(())(";
    n = len(string)
 
    BCP = [0 for i in range(n + 1)];
    BOP = [0 for i in range(n + 1)];
 
    constructBalanceArray(BOP, BCP, string, n);
    startIndex = 5
    endIndex = 11;
    print("Maximum Length Correct " +
                     "Bracket Subsequence between " +
                     str(startIndex) + " and " + str(endIndex) +
                     " = " + str(query(BOP, BCP, startIndex,
                                   endIndex)));
    startIndex = 4;
    endIndex = 5;
    print("Maximum Length Correct " + 
                     "Bracket Subsequence between " +
                     str(startIndex) + " and " + str(endIndex) +
                     " = " + str(query(BOP, BCP, startIndex,
                                   endIndex)))
    startIndex = 1;
    endIndex = 5;
    print("Maximum Length Correct " +
                     "Bracket Subsequence between " +
                     str(startIndex) + " and " + str(endIndex) +
                     " = " + str(query(BOP, BCP, startIndex,
                                   endIndex)));
 
# This code is contributed by rutvik_56.

Time complexity: linear
Space complexity: linear
# Function to find Maximum length of consecutive 1's in a binary string
 
def maxConsecutive1(input):
     # input.split('0') --> splits all sub-strings of consecutive 1's
     # separated by 0's, output will be like ['11','1111','1','1','111']
     # map(len,input.split('0'))  --> map function maps len function on each
     # sub-string of consecutive 1's
     # max() returns maximum element from a list
     print max(map(len,input.split('0')))
 
# Driver program
if __name__ == "__main__":
    input = '11000111101010111'
    maxConsecutive1(input)

Time complexity: linear
Space complexity: constant
# Function to print common characters of two Strings
# in alphabetical order
from collections import Counter
 
def common(str1,str2):
     
    # convert both strings into counter dictionary
    dict1 = Counter(str1)
    dict2 = Counter(str2)
 
    # take intersection of these dictionaries
    commonDict = dict1 & dict2
 
    if len(commonDict) == 0:
        print (-1)
        return
 
    # get a list of common elements
    commonChars = list(commonDict.elements())
 
    # sort list in ascending order to print resultant
    # string on alphabetical order
    commonChars = sorted(commonChars)
 
    # join characters without space to produce
    # resultant string
    print (''.join(commonChars))
 
# Driver program
if __name__ == "__main__":
    str1 = 'geeks'
    str2 = 'forgeeks'
    common(str1, str2)

Time complexity: linear
Space complexity: linear
# Function Generate two output strings depending upon
# occurrence of character in input string
 
from collections import Counter
 
def generateStrings(input):
     
    # convert string into dictionary
    # having characters as keys and frequency as value
    freqDict = Counter(input)
 
    # separate out characters having frequency 1 and more than 1
    freq1 = [ key for (key,count) in freqDict.items() if count==1]
    freqMore1 = [ key for (key,count) in freqDict.items() if count>1]
 
    # sort lists and concatenate characters
    # with out space to print resultant strings
    freq1.sort()
    freqMore1.sort()
 
    # print output strings
    print ('String with characters occurring once:')
    print (''.join(freq1))
    print ('String with characters occurring multiple times:')
    print (''.join(freqMore1))
 
# Driver program
if __name__ == "__main__":
    input = "geeksforgeeks"
    generateStrings(input)

Time complexity: nlogn
Space complexity: linear
# function to mirror characters of a string
 
def mirrorChars(input,k):
 
    # create dictionary
    original = 'abcdefghijklmnopqrstuvwxyz'
    reverse = 'zyxwvutsrqponmlkjihgfedcba'
    dictChars = dict(zip(original,reverse))
 
    # separate out string after length k to change
    # characters in mirror
    prefix = input[0:k-1]
    suffix = input[k-1:]
    mirror = ''
 
    # change into mirror
    for i in range(0,len(suffix)):
         mirror = mirror + dictChars[suffix[i]]
 
    # concat prefix and mirrored part
    print (prefix+mirror)
          
# Driver program
if __name__ == "__main__":
    input = 'paradox'
    k = 3
    mirrorChars(input,k)

Time complexity: linear
Space complexity: linear
# Function to change string to a new character
 
def newString(charSet,input):
 
    # map original character set of english
    # onto new character set given
    origCharSet = 'abcdefghijklmnopqrstuvwxyz'
    mapChars = dict(zip(charSet,origCharSet))
 
    # iterate through original string and get
    #  characters of original character set
    changeChars = [mapChars[chr] for chr in input]
 
    # join characters without space to get new string
    print (''.join(changeChars))
 
# Driver program
if __name__ == "__main__":
    charSet = 'qwertyuiopasdfghjklzxcvbnm'
    input = 'utta'
    newString(charSet,input)

Time complexity: linear
Space complexity: linear
# python program to print initials of a name
def name(s):
 
    # split the string into a list
    l = s.split()
    new = ""
 
    # traverse in the list
    for i in range(len(l)-1):
        s = l[i]
         
        # adds the capital first character
        new += (s[0].upper()+'.')
         
    # l[-1] gives last item of list l. We
    # use title to print first character in
    # capital.
    new += l[-1].title()
     
    return new
     
# Driver code           
s ="mohandas karamchand gandhi"
print(name(s))       

Time complexity: linear
Space complexity: linear
# Python code to find if we can make first string
# from second by deleting some characters from
# second and rearranging remaining characters.
from collections import Counter
 
def makeString(str1,str2):
 
    # convert both strings into dictionaries
    # output will be like str1="aabbcc",
    # dict1={'a':2,'b':2,'c':2}
    # str2 = 'abbbcc', dict2={'a':1,'b':3,'c':2}
    dict1 = Counter(str1)
    dict2 = Counter(str2)
 
    # take intersection of two dictionaries
    # output will be result = {'a':1,'b':2,'c':2}
    result = dict1 & dict2
 
    # compare resultant dictionary with first
    # dictionary comparison first compares keys
    # and then compares their corresponding values
    return result == dict1
 
# Driver program
if __name__ == "__main__":
    str1 = 'ABHISHEKsinGH'
    str2 = 'gfhfBHkooIHnfndSHEKsiAnG'
    if (makeString(str1,str2)==True):
        print("Possible")
    else:
        print("Not Possible")

Time complexity: linear
Space complexity: constant
# import from string all ascii_lowercase and asc_lower
from string import ascii_lowercase as asc_lower
 
# function to check if all elements are present or not
def check(s):
    return set(asc_lower) - set(s.lower()) == set([])
     
# driver code
string ="The quick brown fox jumps over the lazy dog"
if(check(string)== True):
    print("The string is a pangram")
else:
    print("The string isn't a pangram")

Time complexity: linear
Space complexity: constant
# Python program to Count all
# prefixes in given string with
# greatest frequency
 
# Function to print the prefixes
def prefix(string1, alphabet1, alphabet2):
    count = 0
    non_empty_string = ""
     
    string2 = list(string1)
     
    # Loop for iterating the length of
    # the string and print the prefixes
    # and the count of query prefixes.
    for i in range(0, len(string2)):
        non_empty_string = non_empty_string + (string2[i])
         
        if (non_empty_string.count(alphabet1) >
            non_empty_string.count(alphabet2)):
                 
            # prints all required prefixes
            print(non_empty_string)
             
            # increment count
            count += 1
             
    # returns count of the
    # required prefixes
    return(count)
     
# Driver Code
print(prefix("geeksforgeeks", "e", "g"))

Time complexity: linear
Space complexity: linear
# Function to Check if both halves of
# the string have same set of characters
from collections import Counter
 
def checkTwoHalves(input):
     
    length = len(input)
     
    # Break input string in two parts
    if (length % 2 != 0):
        first = input[0:length // 2]
        second = input[(length // 2) + 1:]
    else:
        first = input[0:length // 2]
        second = input[length // 2:]
 
    # Convert both halves into dictionary and compare
    if Counter(first) == Counter(second):
        print ('YES')
    else:
        print ('NO')
 
# Driver program
if __name__ == "__main__":
    input = 'abbaab'
    checkTwoHalves(input)

Time complexity: linear
Space complexity: linear
# Function to concatenated string with uncommon
# characters of two strings
 
def uncommonConcat(str1, str2):
 
    # convert both strings into set
    set1 = set(str1)
    set2 = set(str2)
 
    # take intersection of two sets to get list of
    # common characters
    common = list(set1 & set2)
 
    # separate out characters in each string
    # which are not common in both strings
    result = [ch for ch in str1 if ch not in common] + [ch for ch in str2 if ch not in common]
 
    # join each character without space to get
    # final string
    print( ''.join(result) )
 
# Driver program
if __name__ == "__main__":
    str1 = 'aacdb'
    str2 = 'gafd'
    uncommonConcat(str1,str2)

Time complexity: linear
Space complexity: linear
# Function to concatenated string with uncommon
# characters of two strings
 
def uncommonConcat(str1, str2):
 
    # convert both strings into set
    set1 = set(str1)
    set2 = set(str2)
 
    # Performing symmetric difference operation of set
    # to pull out uncommon characters
    uncommon = list(set1 ^ set2)
 
    # join each character without space to get
    # final string
    print( ''.join(uncommon) )
 
# Driver program
if __name__ == "__main__":
    str1 = 'aacdb'
    str2 = 'gafd'
    uncommonConcat(str1,str2)

Time complexity: linear
Space complexity: linear
# Python code to print Second most repeated
# word in a sequence in Python
from collections import Counter
 
 
def secondFrequent(input):
 
    # Convert given list into dictionary
    # it's output will be like {'ccc':1,'aaa':3,'bbb':2}
    dict = Counter(input)
 
    # Get the list of all values and sort it in ascending order
    value = sorted(dict.values(), reverse=True)
 
    # Pick second largest element
    secondLarge = value[1]
 
    # Traverse dictionary and print key whose
    # value is equal to second large element
    for (key, val) in dict.items():
        if val == secondLarge:
            print(key)
            return
 
 
# Driver program
if __name__ == "__main__":
    input = ['aaa', 'bbb', 'ccc', 'bbb', 'aaa', 'aaa']
    secondFrequent(input)

Time complexity: nlogn
Space complexity: linear
# returns the second most repeated word
from collections import Counter
class Solution:
    def secFrequent(self, arr, n):
        all_freq = dict(Counter(arr))
        store = []
        for w in sorted(all_freq, key=all_freq.get):
            # if add key=all_freq.get will sort according to values
            # without key=all_freq.get will sort according to keys
            if w not in store:
                store.append(w)
             
        return store[-2]
# driver code or main function
if __name__ == '__main__':
    # no. of test cases
    t = 1
    for _ in range(t):
        # no of words
        n = 7
        # String of words
        arr = ["cat","mat","cat","mat","cat",'ball',"tall"]
        ob = Solution()
        ans = ob.secFrequent(arr,n)
        print(ans)

Time complexity: nlogn
Space complexity: linear
import re
   
def putSpace(input):
   
    # regex [A-Z][a-z]* means any string starting 
    # with capital character followed by many 
    # lowercase letters 
    words = re.findall('[A-Z][a-z]*', input)
   
    # Change first letter of each word into lower
    # case
    for i in range(0,len(words)):
      words[i]=words[i][0].lower()+words[i][1:]
    print(' '.join(words))
     
   
# Driver program
if __name__ == "__main__":
    input = 'BruceWayneIsBatman'
    putSpace(input)

Time complexity: linear
Space complexity: linear
def checkEmpty(input, pattern):
     
    # If both are empty
    if len(input)== 0 and len(pattern)== 0:
        return 'true'
 
    # If only pattern is empty
    if len(pattern)== 0:
        return 'true'
 
    while (len(input) != 0):
 
        # find sub-string in main string
        index = input.find(pattern)
 
        # check if sub-string founded or not
        if (index ==(-1)):
            return 'false'
 
        # slice input string in two parts and concatenate
        input = input[0:index] + input[index + len(pattern):]           
    return 'true'
 
# Driver program
if __name__ == "__main__":
    input ='GEEGEEKSKS'
    pattern ='GEEKS'
    print (checkEmpty(input, pattern))

Time complexity: linear
Space complexity: constant
# Python code
# To reverse words in a given string
 
# input string
string = "geeks quiz practice code"
# reversing words in a given string
s = string.split()[::-1]
l = []
for i in s:
    # apending reversed words to l
    l.append(i)
# printing reverse words
print(" ".join(l))

Time complexity: linear
Space complexity: linear
# Function to reverse words of string
 
def rev_sentence(sentence):
 
    # first split the string into words
    words = sentence.split(' ')
 
    # then reverse the split string list and join using space
    reverse_sentence = ' '.join(reversed(words))
 
    # finally return the joined string
    return reverse_sentence
 
if __name__ == "__main__":
    input = 'geeks quiz practice code'
    print (rev_sentence(input))

Time complexity: linear
Space complexity: linear