Banana-Leopard/TASTY huggingface dataset:
# python program to count substrings
# with odd decimal value
import math
 
# function to count number of substrings
# with odd decimal representation
def countSubstr( s):
 
    n = len(s)
     
    # auxiliary array to store count
    # of 1's before ith index
    auxArr= [0 for i in range(n)]
     
    if (s[0] == '1'):
        auxArr[0] = 1
     
    # store count of 1's before
    # i-th index
    for i in range(0,n):
         
      if (s[i] == '1'):
            auxArr[i] = auxArr[i-1]+1
      else:
            auxArr[i] = auxArr[i-1]
     
     
    # variable to store answer
    count = 0
     
    # traverse the string reversely to
    # calculate number of odd substrings
    # before i-th index
    for i in range(n-1,-1,-1):
        if (s[i] == '1'):
            count += auxArr[i]
     
    return count
# Driver method
s = "1101"
print (countSubstr(s))
 
# This code is contributed by Gitanjali.

Time complexity: linear
Space complexity: linear
# Python3 program to generate n-bit Gray codes
import math as mt
 
# This function generates all n bit Gray
# codes and prints the generated codes
def generateGrayarr(n):
 
    # base case
    if (n <= 0):
        return
 
    # 'arr' will store all generated codes
    arr = list()
 
    # start with one-bit pattern
    arr.append("0")
    arr.append("1")
 
    # Every iteration of this loop generates
    # 2*i codes from previously generated i codes.
    i = 2
    j = 0
    while(True):
 
        if i >= 1 << n:
            break
     
        # Enter the previously generated codes
        # again in arr[] in reverse order.
        # Nor arr[] has double number of codes.
        for j in range(i - 1, -1, -1):
            arr.append(arr[j])
 
        # append 0 to the first half
        for j in range(i):
            arr[j] = "0" + arr[j]
 
        # append 1 to the second half
        for j in range(i, 2 * i):
            arr[j] = "1" + arr[j]
        i = i << 1
 
    # print contents of arr[]
    for i in range(len(arr)):
        print(arr[i])
 
# Driver Code
generateGrayarr(3)
 
# This code is contributed
# by Mohit kumar 29

Time complexity: np
Space complexity: np
# Python3 program to generate
# n-bit Gray codes
 
# This function generates all n
# bit Gray codes and prints the
# generated codes
def generateGray(n):
     
    # Base case
    if (n <= 0):
        return ["0"]
    if (n == 1):
        return [ "0", "1" ]
 
    # Recursive case
    recAns = generateGray(n - 1)
 
    mainAns = []
     
    # Append 0 to the first half
    for i in range(len(recAns)):
        s = recAns[i]
        mainAns.append("0" + s)
 
    # Append 1 to the second half
    for i in range(len(recAns) - 1, -1, -1):
        s = recAns[i]
        mainAns.append("1" + s)
 
    return mainAns
 
# Function to generate the
# Gray code of N bits
def generateGrayarr(n):
     
    arr = generateGray(n)
 
    # Print contents of arr
    print(*arr, sep = "\n")
 
# Driver Code
generateGrayarr(3)
 
# This code is contributed by avanitrachhadiya2155

Time complexity: np
Space complexity: np
# Python3 implementation of the above approach
def GreyCode(n):
 
    # power of 2
    for i in range(1 << n):
       
        # Generating the decimal
        # values of gray code then using
        # bitset to convert them to binary form
        val = (i ^ (i >> 1))
         
        # Converting to binary string
        s = bin(val)[2::]
        print(s.zfill(n), end = " ")
 
# Driver Code
n = 4
   
# Function call
GreyCode(n)
 
# This code is contributed by phasing17

Time complexity: np
Space complexity: linear
# Python 3 program to print all N-bit binary
 
# function to generate n digit numbers
 
 
def printRec(number, extraOnes, remainingPlaces):
 
    # if number generated
    if (0 == remainingPlaces):
        print(number, end=" ")
        return
 
    # Append 1 at the current number and
    # reduce the remaining places by one
    printRec(number + "1", extraOnes + 1,
             remainingPlaces - 1)
 
    # If more ones than zeros, append 0 to
    # the current number and reduce the
    # remaining places by one
    if (0 < extraOnes):
        printRec(number + "0", extraOnes - 1,
                 remainingPlaces - 1)
 
 
def printNums(n):
    str = ""
    printRec(str, 0, n)
 
 
# Driver Code
if __name__ == '__main__':
    n = 4
      
    # Function call
    printNums(n)
 
# This code is contributed by
# Surendra_Gangwar

Time complexity: linear
Space complexity: linear
# Python3 program to print
# all N-bit binary
 
# Function to get the binary
# representation of the number N
def getBinaryRep(N, num_of_bits):
 
    r = "";
    num_of_bits -= 1
   
    # loop for each bit
    while (num_of_bits >= 0):   
        if (N & (1 << num_of_bits)):
            r += ("1");
        else:
            r += ("0");
        num_of_bits -= 1
     
    return r;
 
def NBitBinary(N):
 
    r = []
    first = 1 << (N - 1);
    last = first * 2;
     
    # generate numbers in the range
    # of (2^N)-1 to 2^(N-1) inclusive
    for i in range (last - 1,
                    first - 1, -1):   
        zero_cnt = 0;
        one_cnt = 0;
        t = i;
        num_of_bits = 0;
         
        # longest prefix check
        while (t):       
            if (t & 1):
                one_cnt += 1
            else:
                zero_cnt += 1
            num_of_bits += 1
            t = t >> 1;       
       
        # if counts of 1 is greater
        # than counts of zero
        if (one_cnt >= zero_cnt):
         
            # do sub-prefixes check
            all_prefix_match = True;
            msk = (1 << num_of_bits) - 2;
            prefix_shift = 1;
             
            while (msk):           
                prefix = ((msk & i) >>
                           prefix_shift);
                prefix_one_cnt = 0;
                prefix_zero_cnt = 0;
                 
                while (prefix):               
                    if (prefix & 1):
                        prefix_one_cnt += 1
                    else:
                        prefix_zero_cnt += 1
                    prefix = prefix >> 1;
                 
                if (prefix_zero_cnt >
                    prefix_one_cnt):               
                    all_prefix_match = False;
                    break;
                 
                prefix_shift += 1
                msk = msk & (msk << 1);
             
            if (all_prefix_match):           
                r.append(getBinaryRep(i,
                                      num_of_bits));         
    return r
 
# Driver code
if __name__ == "__main__":
  
    n = 4;
   
    # Function call
    results = NBitBinary(n);
    for i in range (len(results)):
        print (results[i],
               end = " ")
    print ()
     
# This code is contributed by Chitranayal

Time complexity: quadratic
Space complexity: linear
# Python3 program to add n binary strings
 
# This function adds two binary strings and
# return result as a third string
def addBinaryUtil(a, b):
     
    result = ""; # Initialize result
    s = 0;       # Initialize digit sum
 
    # Traverse both strings
    # starting from last characters
    i = len(a) - 1;
    j = len(b) - 1;
    while (i >= 0 or j >= 0 or s == 1):
 
        # Compute sum of last digits and carry
        s += (ord(a[i]) - ord('0')) if(i >= 0) else 0;
        s += (ord(b[j]) - ord('0')) if(j >= 0) else 0;
 
        # If current digit sum is 1 or 3,
        # add 1 to result
        result = chr(s % 2 + ord('0')) + result;
 
        # Compute carry
        s //= 2;
 
        # Move to next digits
        i -= 1;
        j -= 1;
 
    return result;
 
# function to add n binary strings
def addBinary(arr, n):
    result = "";
    for i in range(n):
        result = addBinaryUtil(result, arr[i]);
    return result;
 
# Driver code
arr = ["1", "10", "11"];
n = len(arr);
print(addBinary(arr, n));
     
# This code is contributed by mits

Time complexity: linear
Space complexity: linear
# Python3 program to generate power
# set in lexicographic order.
 
# str : Stores input string
# n : Length of str.
# curr : Stores current permutation
# index : Index in current permutation, curr
def permuteRec(string, n, index = -1, curr = ""):
 
    # base case
    if index == n:
        return
 
    if len(curr) > 0:
        print(curr)
 
    for i in range(index + 1, n):
        curr += string[i]
        permuteRec(string, n, i, curr)
 
        # backtracking
        curr = curr[:len(curr) - 1]
 
# Generates power set in lexicographic order
def powerSet(string):
    string = ''.join(sorted(string))
    permuteRec(string, len(string))
 
# Driver Code
if __name__ == "__main__":
    string = "cab"
    powerSet(string)
 
# This code is contributed by vibhu4agarwal

Time complexity: quadratic
Space complexity: constant
# Python3 program to print nth permutation
# with using next_permute()
 
# next_permutation method implementation
def next_permutation(L):
    n = len(L)
    i = n - 2
    while i >= 0 and L[i] >= L[i + 1]:
        i -= 1
 
    if i == -1:
        return False
 
    j = i + 1
    while j < n and L[j] > L[i]:
        j += 1
    j -= 1
 
    L[i], L[j] = L[j], L[i]
 
    left = i + 1
    right = n - 1
 
    while left < right:
        L[left], L[right] = L[right], L[left]
        left += 1
        right -= 1
 
    return True
 
# Function to print nth permutation
# using next_permute()
def nPermute(string, n):
    string = list(string)
    new_string = []
 
    # Sort the string in lexicographically
    # ascending order
    string.sort()
    j = 2
 
    # Keep iterating until
    # we reach nth position
    while next_permutation(string):
        new_string = string
 
        # check for nth iteration
        if j == n:
            break
        j += 1
 
    # print string after nth iteration
    print(''.join(new_string))
 
# Driver Code
if __name__ == "__main__":
    string = "GEEKSFORGEEKS"
    n = 100
    nPermute(string, n)
 
# This code is contributed by
# sanjeev2552

Time complexity: nlogn
Space complexity: constant
# A simple Python3 program to find lexicographically
# minimum rotation of a given string
 
# This function return lexicographically minimum
# rotation of str
def minLexRotation(str_) :
 
    # Find length of given string
    n = len(str_)
 
    # Create an array of strings to store all rotations
    arr = [0] * n
 
    # Create a concatenation of string with itself
    concat = str_ + str_
 
    # One by one store all rotations of str in array.
    # A rotation is obtained by getting a substring of concat
    for i in range(n) :
        arr[i] = concat[i : n + i]
 
    # Sort all rotations
    arr.sort()
 
    # Return the first rotation from the sorted array
    return arr[0]
 
# Driver Code
print(minLexRotation("GEEKSFORGEEKS"))
print(minLexRotation("GEEKSQUIZ"))
print(minLexRotation("BCABDADAB"))
 
# This code is contributed by divyamohan123

Time complexity: quadratic
Space complexity: linear
# Python program to print all distinct
# subsequences of a string.
 
# Finds and stores result in st for a given
# string s.
def generate(st, s):
    if len(s) == 0:
        return
 
    # If current string is not already present.
    if s not in st:
        st.add(s)
 
        # Traverse current string, one by one
        # remove every character and recur.
        for i in range(len(s)):
            t = list(s).copy()
            t.remove(s[i])
            t = ''.join(t)
            generate(st, t)
 
    return
 
 
# Driver Code
if __name__ == "__main__":
    s = "xyz"
    st = set()
    generate(st, s)
    for i in st:
        print(i)
 
# This code is contributed by
# sanjeev2552

Time complexity: quadratic
Space complexity: linear
# Python 3 code to find the lexicographically
# smallest string
def lexSmallest(a, n):
  # Sort strings using above compare()
  for i in range(0,n):
    for j in range(i+1,n):
      if(a[i]+a[j]>a[j]+a[i]):
        s=a[i]
        a[i]=a[j]
        a[j]=s
 
  # Concatenating sorted strings
  answer = ""
  for i in range( n):
    answer += a[i]
  return answer
 
# Driver code
if __name__ == "__main__":
     
    a = [ "c", "cb", "cba" ]
    n = len(a)
    print(lexSmallest(a, n))
 
# This code is contributed by vibhu karnwal
 
 
   

Time complexity: quadratic
Space complexity: linear
# Python Program to create concatenation of all
# substrings in lexicographic order.
 
def lexicographicSubConcat(s):
    n = len(s);
 
    # Creating an array to store substrings
    sub_count = (n * (n + 1))//2;
    arr = [0]*sub_count;    
 
    # finding all substrings of string
    index = 0;
    for i in range(n):
        for j in range(1,n - i + 1):
            arr[index] = s[i:i + j];
            index += 1;
     
    # Sort all substrings in lexicographic
    # order
    arr.sort();
 
    # Concatenating all substrings
    res = "";
    for i in range(sub_count):
        res += arr[i];    
         
    return res;
 
s = "abc";
print(lexicographicSubConcat(s));
 
# This code is contributed by Princi Singh

Time complexity: cubic
Space complexity: linear
# Python3 for constructing smallest palindrome
 
# function for printing palindrome
def constructPalin(string, l):
    string = list(string)
    i = -1
    j = l
     
    # iterate till i<j
    while i < j:
        i += 1
        j -= 1
 
        # continue if str[i]==str[j]
        if (string[i] == string[j] and
            string[i] != '*'):
            continue
 
        # update str[i]=str[j]='a' if both are '*'
        elif (string[i] == string[j] and
              string[i] == '*'):
            string[i] = 'a'
            string[j] = 'a'
            continue
 
        # update str[i]=str[j] if only str[i]='*'
        elif string[i] == '*':
            string[i] = string[j]
            continue
 
        # update str[j]=str[i] if only str[j]='*'
        elif string[j] == '*':
            string[j] = string[i]
            continue
 
        # else print not possible and return
        print("Not Possible")
        return ""
    return ''.join(string)
 
# Driver Code
if __name__ == "__main__":
    string = "bca*xc**b"
    l = len(string)
    print(constructPalin(string, l))
 
# This code is contributed by
# sanjeev2552

Time complexity: linear
Space complexity: constant
# Python 3 program to find Lexicographically
# smallest string whose hamming distance
# from the given string is exactly K
 
# function to find Lexicographically
# smallest string with hamming distance k
def findString(str, n, k):
     
    # If k is 0, output input string
    if (k == 0):
        print(str)
        return
     
    # Copying input string into output
    # string
    str2 = str
    p = 0
 
    # Traverse all the character of the
    # string
    for i in range(0, n, 1):
         
        # If current character is not 'a'
        if (str2[i] != 'a'):
             
            # copy character 'a' to
            # output string
            str2 = str2.replace(str2[i], 'a')
            p += 1
 
            # If hamming distance became k,
            # break;
            if (p == k):
                break
     
    # If k is less than p
    if (p < k):
         
        # Traversing string in reverse
        # order
        i = n - 1
        while(i >= 0):
            if (str[i] == 'a'):
                str2 = str2.replace(str2[i], 'b')
                p += 1
 
            if (p == k):
                break
            i -= 1
             
    print(str2)
 
# Driver Code
if __name__ == '__main__':
    str = "pqrs"
    n = len(str)
    k = 2
 
    findString(str, n, k)
 
# This code is contributed by
# Surendra_Gangwar

Time complexity: linear
Space complexity: linear
# Python 3 program to find lexicographically
# next string
 
def nextWord(s):
     
    # If string is empty.
    if (s == " "):
        return "a"
 
    # Find first character from right
    # which is not z.
    i = len(s) - 1
    while (s[i] == 'z' and i >= 0):
        i -= 1
 
    # If all characters are 'z', append
    # an 'a' at the end.
    if (i == -1):
        s = s + 'a'
 
    # If there are some non-z characters
    else:
        s = s.replace(s[i], chr(ord(s[i]) + 1), 1)
 
    return s
 
# Driver code
if __name__ == '__main__':
    str = "samez"
    print(nextWord(str))
     
# This code is contributed by
# Sanjit_Prasad

Time complexity: linear
Space complexity: constant
# Python3 program to find lexicographically largest
# subsequence where every character appears at
# least k times.
 
# Find lexicographically largest subsequence of
# s[0..n-1] such that every character appears
# at least k times. The result is filled in t[]
def subsequence(s, t, n, k):
    last = 0
    cnt = 0
    new_last = 0
    size = 0
 
    string = 'zyxwvutsrqponmlkjihgfedcba'
 
    # Starting from largest character 'z' to 'a'
    for ch in string:
        cnt = 0
        for i in range(last, n):
            if s[i] == ch:
                cnt += 1
 
        # If frequency is greater than k
        if cnt >= k:
 
            # From the last point we leave
            for i in range(last, n):
 
                # check if string contain ch
                if s[i] == ch:
 
                    # If yes, append to output string
                    t[size] = ch
                    new_last = i
                    size += 1
 
            # Update the last point.
            last = new_last
 
# Driver Code
if __name__ == "__main__":
    s = ['b', 'a', 'n', 'a', 'n', 'a']
    n = len(s)
    k = 2
    t = [''] * n
    subsequence(s, t, n - 1, k)
    t = ''.join(t)
    print(t)
 
# This code is contributed by
# sanjeev2552

Time complexity: linear
Space complexity: linear
# Python3 implementation of lexicographically first
# alternate vowel and consonant string
SIZE = 26
 
# 'ch' is vowel or not
def isVowel(ch):
    if (ch == 'a' or ch == 'e' or
        ch == 'i' or ch == 'o' or
        ch == 'u'):
        return True
    return False
 
# create alternate vowel and consonant string
# str1[0...l1-1] and str2[start...l2-1]
def createAltStr(str1, str2, start, l):
    finalStr = ""
    i = 0
    j = start
 
    # first adding character of vowel/consonant
    # then adding character of consonant/vowel
    while j < l:
        finalStr += str1[i] + str2[j]
        i += 1
        j += 1
    return finalStr
 
# function to find the required lexicographically
# first alternate vowel and consonant string
def findAltStr(string):
 
    # hash table to store frequencies
    # of each character in 'str'
    char_freq = [0] * SIZE # initialize all elements
                           # of char_freq[] to 0
    nv = 0
    nc = 0
    vstr = ""
    cstr = ""
    l = len(string)
 
    for i in range(l):
        ch = string[i]
 
        # count vowels
        if isVowel(ch):
            nv += 1
 
        # count consonants
        else:
            nc += 1
 
        # update frequency of 'ch' in
        # char_freq[]
        char_freq[ord(ch) - 97] += 1
 
    # no such string can be formed
    if abs(nv - nc) >= 2:
        return "no such string"
 
    # form the vowel string 'vstr' and
    # consonant string 'cstr' which contains
    # characters in lexicographical order
    for i in range(SIZE):
        ch = chr(i + 97)
        for j in range(1, char_freq[i] + 1):
            if isVowel(ch):
                vstr += ch
            else:
                cstr += ch
 
    # remove first character of vowel string
    # then create alternate string with
    # cstr[0...nc-1] and vstr[1...nv-1]
    if nv > nc:
        return vstr[0] + createAltStr(cstr,
                                      vstr, 1, nv)
 
    # remove first character of consonant string
    # then create alternate string with
    # vstr[0...nv-1] and cstr[1...nc-1]
    if nc > nv:
        return cstr[0] + createAltStr(vstr,
                                      cstr, 1, nc)
 
    # if both vowel and consonant
    # strings are of equal length
    # start creating string with consonant
    if cstr[0] < vstr[0]:
        return createAltStr(cstr, vstr, 0, nv)
 
    # start creating string with vowel
    return createAltStr(vstr, cstr, 0, nc)
 
# Driver Code
if __name__ == "__main__":
    string = "aeroplane"
    print(findAltStr(string))
 
# This code is contributed by
# sanjeev2552

Time complexity: linear
Space complexity: constant
# Python3 program to find the string
# in lexicographic order which is
# in between given two strings
 
# Function to find the lexicographically
# next string
def lexNext(s, n):
 
    # Iterate from last character
    for i in range(n - 1, -1, -1):
 
        # If not 'z', increase by one
        if s[i] != 'z':
            k = ord(s[i])
            s[i] = chr(k + 1)
            return ''.join(s)
 
        # if 'z', change it to 'a'
        s[i] = 'a'
 
# Driver Code
if __name__ == "__main__":
    S = "abcdeg"
    T = "abcfgh"
    n = len(S)
 
    S = list(S)
    res = lexNext(S, n)
 
    # If not equal, print the
    # resultant string
    if res != T:
        print(res)
    else:
        print(-1)
 
# This code is contributed by
# sanjeev2552

Time complexity: linear
Space complexity: constant
# Python3 program to print n-th permutation
 
MAX_CHAR = 26
MAX_FACT = 20
fact = [None] * (MAX_FACT)
 
# Utility for calculating factorials
def precomputeFactorials():
 
    fact[0] = 1
    for i in range(1, MAX_FACT):
        fact[i] = fact[i - 1] * i
 
# Function for nth permutation
def nPermute(string, n):
 
    precomputeFactorials()
 
    # length of given string
    length = len(string)
 
    # Count frequencies of all
    # characters
    freq = [0] * (MAX_CHAR)
    for i in range(0, length):
        freq[ord(string[i]) - ord('a')] += 1
 
    # out string for output string
    out = [None] * (MAX_CHAR)
 
    # iterate till sum equals n
    Sum, k = 0, 0
 
    # We update both n and sum in
    # this loop.
    while Sum != n:
 
        Sum = 0
         
        # check for characters present in freq[]
        for i in range(0, MAX_CHAR):
            if freq[i] == 0:
                continue
 
            # Remove character
            freq[i] -= 1
 
            # calculate sum after fixing
            # a particular char
            xsum = fact[length - 1 - k]
            for j in range(0, MAX_CHAR):
                xsum = xsum // fact[freq[j]]
            Sum += xsum
 
            # if sum > n fix that char as
            # present char and update sum
            # and required nth after fixing
            # char at that position
            if Sum >= n:
                out[k] = chr(i + ord('a'))
                n -= Sum - xsum
                k += 1
                break
             
            # if sum < n, add character back
            if Sum < n:
                freq[i] += 1
         
    # if sum == n means this char will provide
    # its greatest permutation as nth permutation
    i = MAX_CHAR-1
    while k < length and i >= 0:
        if freq[i]:
            out[k] = chr(i + ord('a'))
            freq[i] -= 1
            i += 1
            k += 1
         
        i -= 1
 
    # print result
    print(''.join(out[:k]))
 
# Driver Code
if __name__ == "__main__":
 
    n = 2
    string = "geeksquiz"
 
    nPermute(string, n)
     
# This code is contributed by Rituraj Jain

Time complexity: linear
Space complexity: linear
# Python program to find lexicographic
# rank of a string
 
# A utility function to find factorial
# of n
def fact(n):
    f = 1
    while n >= 1:
        f = f * n
        n = n - 1
    return f
 
# A utility function to count smaller
# characters on right of arr[low]
def findSmallerInRight(st, low, high):
    countRight = 0
    i = low + 1
    while i <= high:
        if st[i] < st[low]:
            countRight = countRight + 1
        i = i + 1
 
    return countRight
 
# A function to find rank of a string
# in all permutations of characters
def findRank(st):
    ln = len(st)
    mul = fact(ln)
    rank = 1
    i = 0
 
    while i < ln:
        mul = mul // (ln - i)
 
        # count number of chars smaller
        # than str[i] from str[i + 1] to
        # str[len-1]
        countRight = findSmallerInRight(st, i, ln-1)
 
        rank = rank + countRight * mul
        i = i + 1
 
    return rank
 
 
# Driver code
if __name__ == '__main__':
    st = "string"
     
    # Function call
    print(findRank(st))
 
# This code is contributed by Nikita Tiwari.

Time complexity: quadratic
Space complexity: constant