Banana-Leopard/TASTY huggingface dataset:
# Optimized Python3 program
# to check if two strings
# are k anagram or not.
MAX_CHAR = 26;
 
# Function to check if str1
# and str2 are k-anagram or not
def areKAnagrams(str1, str2, k):
    # If both strings are
    # not of equal length
    # then return false
 
    n = len(str1);
    if (len(str2) != n):
        return False;
 
    hash_str1 = [0]*(MAX_CHAR);
 
    # Store the occurrence of
    # all characters in a hash_array
    for i in range(n):
        hash_str1[ord(str1[i]) - ord('a')]+=1;
 
    # Store the occurrence of all
    # characters in a hash_array
    count = 0;
    for i in range(n):
        if (hash_str1[ord(str2[i]) - ord('a')] > 0):
            hash_str1[ord(str2[i]) - ord('a')]-=1;
        else:
            count+=1;
 
        if (count > k):
            return False;
 
    # Return true if count is
    # less than or equal to k
    return True;
 
# Driver code
str1 = "fodr";
str2 = "gork";
k = 2;
if (areKAnagrams(str1, str2, k) == True):
    print("Yes");
else:
    print("No");
         
# This code is contributed by mits

Time complexity: linear
Space complexity: constant
# Python 3 program for the above approach
import sys
 
# Function to check k
# anagram of two strings
 
 
def kAnagrams(str1, str2, k):
 
    flag = 0
 
    list1 = []
 
    # First Condition: If both the
    # strings have different length ,
    # then they cannot form anagram
    if (len(str1) != len(str2)):
        sys.exit()
 
    # Converting str1 to Character Array arr1
    arr1 = list(str1)
 
    # Converting str2 to Character Array arr2
    arr2 = list(str2)
 
    # Sort arr1 in increasing order
    arr1.sort()
 
    # Sort arr2 in increasing order
    arr2.sort()
 
    # Iterate till str1.length()
    for i in range(len(str1)):
 
        # Condition if arr1[i] is
        # not equal to arr2[i]
        # then add it to list
        if (arr1[i] != arr2[i]):
            list1.append(arr2[i])
 
    # Condition to check if
    # strings for K-anagram or not
    if (len(list1) <= k):
        flag = 1
 
    if (flag == 1):
        return True
    else:
        return False
 
 
# Driver Code
if __name__ == "__main__":
 
    str1 = "fodr"
    str2 = "gork"
    k = 2
 
    # Function Call
    kAnagrams(str1, str2, k)
    if (kAnagrams(str1, str2, k) == True):
        print("Yes")
    else:
        print("No")

Time complexity: linear
Space complexity: constant
# A simple Python program to check if binary
# representations of two numbers are anagram.
SIZE = 8
def bit_anagram_check(a, b):
 
    # Find reverse binary representation of a
    # and store it in binary_a[]
    global size
 
    i = 0
    binary_a = [0] * SIZE
    while (a > 0):
        binary_a[i] = a % 2
        a //= 2
        i += 1
 
    # Find reverse binary representation of b
    # and store it in binary_a[]
    j = 0
    binary_b = [0] * SIZE
    while (b > 0):
        binary_b[j] = b % 2
        b //= 2
        j += 1
 
    # Sort two binary representations
    binary_a.sort()
    binary_b.sort()
 
    # Compare two sorted binary representations
    for i in range(SIZE):
        if (binary_a[i] != binary_b[i]):
            return 0
    return 1
 
# Driver code
if __name__ == "__main__":
 
    a = 8
    b = 4
    print(bit_anagram_check(a, b))
 
    # This code is contributed by ukasp.

Time complexity: constant
Space complexity: constant
# Python3 program to check if binary
# representations of two numbers are anagrams.
   
# Check each bit in a number is set or not
# and return the total count of the set bits.
def countSetBits(n) :
     
    count = 0
    while n>0 :
        count += n & 1
        n >>= 1
    return count
 
def areAnagrams(A, B) :
    return countSetBits(A) == countSetBits(B)
     
# Driver code
if __name__ == "__main__" :
     
    a,b = 8,4
    if areAnagrams(a, b) :
        print("1")
    else :
        print("0")
 
# this code is contributed by aditya942003patil

Time complexity: constant
Space complexity: constant
# Python3 program for finding all anagram
# pairs in the given array
from collections import defaultdict
 
# Utility function for
# printing anagram list
def printAnagram(store: dict) -> None:
     
    for (k, v) in store.items():
        temp_vec = v
        size = len(temp_vec)
         
        if (size > 1):
            for i in range(size):
                print(temp_vec[i], end = " ")
                 
            print()
 
# Utility function for storing
# the vector of strings into HashMap
def storeInMap(vec: list) -> None:
 
    store = defaultdict(lambda: list)
     
    for i in range(len(vec)):
        tempString = vec[i]
        tempString = ''.join(sorted(tempString))
 
        # Check for sorted string
        # if it already exists
        if (tempString not in store):
            temp_vec = []
            temp_vec.append(vec[i])
            store[tempString] = temp_vec
 
        else:
             
            # Push new string to
            # already existing key
            temp_vec = store[tempString]
            temp_vec.append(vec[i])
            store[tempString] = temp_vec
 
    # Print utility function for
    # printing all the anagrams
    printAnagram(store)
 
# Driver code
if __name__ == "__main__":
 
    # Initialize vector of strings
    arr = []
    arr.append("geeksquiz")
    arr.append("geeksforgeeks")
    arr.append("abcd")
    arr.append("forgeeksgeeks")
    arr.append("zuiqkeegs")
    arr.append("cat")
    arr.append("act")
    arr.append("tca")
 
    # Utility function for storing
    # strings into hashmap
    storeInMap(arr)
 
# This code is contributed by sanjeev2552

Time complexity: quadratic
Space complexity: linear
# Python3 program to count total anagram
# substring of a string
def countOfAnagramSubstring(s):
     
    # Returns total number of anagram
    # substrings in s
    n = len(s)
    mp = dict()
     
    # loop for length of substring
    for i in range(n):
        sb = ''
        for j in range(i, n):
            sb = ''.join(sorted(sb + s[j]))
            mp[sb] = mp.get(sb, 0)
             
            # increase count corresponding
            # to this dict array
            mp[sb] += 1
 
    anas = 0
     
    # loop over all different dictionary
    # items and aggregate substring count
    for k, v in mp.items():
        anas += (v*(v-1))//2
    return anas
 
# Driver Code
s = "xyyx"
print(countOfAnagramSubstring(s))
 
# This code is contributed by fgaim

Time complexity: quadratic
Space complexity: linear
# Python3 Program to find minimum number
# of manipulations required to make
# two strings identical
 
# Counts the no of manipulations
# required
def countManipulations(s1, s2):
     
    count = 0
 
    # store the count of character
    char_count = [0] * 26
     
    for i in range(26):
        char_count[i] = 0
 
    # iterate though the first String
    # and update count
    for i in range(len( s1)):
        char_count[ord(s1[i]) -
                   ord('a')] += 1
 
    # iterate through the second string
    # update char_count.
    # if character is not found in
    # char_count then increase count
    for i in range(len(s2)):
        char_count[ord(s2[i]) - ord('a')] -= 1
         
    for i in range(26):
        if char_count[i] != 0:
            count += abs(char_count[i])
         
 
    return count / 2
 
# Driver code
if __name__ == "__main__":
 
    s1 = "ddcf"
    s2 = "cedk"
     
    print(countManipulations(s1, s2))
 
# This code is contributed by ita_c

Time complexity: linear
Space complexity: constant
# Python program to check if a given string is a rotation
# of a palindrome
 
# A utility function to check if a string str is palindrome
def isPalindrome(string):
 
    # Start from leftmost and rightmost corners of str
    l = 0
    h = len(string) - 1
 
    # Keep comparing characters while they are same
    while h > l:
        l+= 1
        h-= 1
        if string[l-1] != string[h + 1]:
            return False
 
    # If we reach here, then all characters were matching   
    return True
 
# Function to check if a given string is a rotation of a
# palindrome.
def isRotationOfPalindrome(string):
 
    # If string itself is palindrome
    if isPalindrome(string):
        return True
 
    # Now try all rotations one by one
    n = len(string)
    for i in range(n-1):
        string1 = string[i + 1:n]
        string2 = string[0:i + 1]
 
        # Check if this rotation is palindrome
        string1+=(string2)
        if isPalindrome(string1):
            return True
 
    return False
 
# Driver program
print ("1" if isRotationOfPalindrome("aab") == True else "0")
print ("1" if isRotationOfPalindrome("abcde") == True else "0")
print ("1" if isRotationOfPalindrome("aaaad") == True else "0")
 
# This code is contributed by BHAVYA JAIN

Time complexity: quadratic
Space complexity: linear
# Python3 implementation of above idea
  
# A function to check if n is palindrome
def isPalindrome(n: int) -> bool:
  
    # Find reverse of n
    rev = 0
    i = n
    while i > 0:
        rev = rev * 10 + i % 10
        i //= 10
  
    # If n and rev are same, 
    # then n is palindrome
    return (n == rev)
  
# prints palindrome between min and max
def countPal(minn: int, maxx: int) -> None:
    for i in range(minn, maxx + 1):
        if isPalindrome(i):
            print(i, end = " ")
  
# Driver Code
if __name__ == "__main__":
    countPal(100, 2000)
  
# This code is contributed by
# sanjeev2552

Time complexity: logn
Space complexity: constant
# Python 3 implementation of O(n^2)
# time and O(1) space method
# to find the longest palindromic substring
class LongestPalinSubstring :
    maxLength = 0
      
    # variables to store and
    res = None
      
    # update  maxLength and res
    # A utility function to get the longest palindrome
    # starting and expanding out from given center indices
    @staticmethod
    def cSubUtil( s,  l,  r) :
        
        # check if the indices lie in the range of string
        # and also if it is palindrome
        while (l >= 0 and r < len(s) and s[l] == s[r]) :
            
            # expand the boundary
            l -= 1
            r += 1
              
        # if it's length is greater than maxLength update
        # maxLength and res
        if (r - l - 1 >= LongestPalinSubstring.maxLength) :
            LongestPalinSubstring.res = s[l + 1:r]
            LongestPalinSubstring.maxLength = r - l - 1
        return
        
    # A function which takes a string prints the LPS and
    # returns the length of LPS
    @staticmethod
    def  longestPalSubstr( str) :
        LongestPalinSubstring.res = ""
        LongestPalinSubstring.maxLength = 1
          
        # for every index in the string check palindromes
        # starting from that index
        i = 0
        while (i < len(str)) :
            
            # check for odd length palindromes
            LongestPalinSubstring.cSubUtil(str, i, i)
              
            # check for even length palindromes
            LongestPalinSubstring.cSubUtil(str, i, i + 1)
            i += 1
        print("Longest palindrome substring is: ", end ="")
        print(LongestPalinSubstring.res)
        return LongestPalinSubstring.maxLength
        
    # Driver program to test above function
    @staticmethod
    def main( args) :
        str1 = "forgeeksskeegfor"
        print("Length is: " + str(LongestPalinSubstring.longestPalSubstr(str1)))
      
if __name__=="__main__":
    LongestPalinSubstring.main([])
      
    # This code is contributed by phasing17.

Time complexity: quadratic
Space complexity: constant
# Python3 program to Count number of ways we
# can get palindrome string from a given
# string
 
# function to find the substring of the
# string
def substring(s, a, b):
    s1 = ""
 
    # extract the specified position of
    # the string
    for i in range(a, b, 1):
        s1 += s[i]
 
    return s1
 
# can get palindrome string from a
# given string
def allPalindromeSubstring(s):
    v = []
 
    # moving the pivot from starting till
    # end of the string
    pivot = 0.0
    while pivot < len(s):
 
        # set radius to the first nearest
        # element on left and right
        palindromeRadius = pivot - int(pivot)
 
        # if the position needs to be
        # compared has an element and the
        # characters at left and right
        # matches
        while ((pivot + palindromeRadius) < len(s) and
                   (pivot - palindromeRadius) >= 0 and
                  (s[int(pivot - palindromeRadius)] ==
                   s[int(pivot + palindromeRadius)])):
             v.append(s[int(pivot - palindromeRadius):
                        int(pivot + palindromeRadius + 1)])
 
             # increasing the radius by 1 to point
             # to the next elements in left and right
             palindromeRadius += 1
 
        pivot += 0.5
    return v
 
# Driver Code
if __name__ == "__main__":
    v = allPalindromeSubstring("hellolle")
    print(len(v))
    print(v)
 
    v = allPalindromeSubstring("geeksforgeeks")
    print(len(v))
    print(v)
 
# This code is contributed by
# sanjeev2552

Time complexity: cubic
Space complexity: linear
# Python program Online algorithm for checking palindrome
# in a stream
 
# d is the number of characters in input alphabet
d = 256
 
# q is a prime number used for evaluating Rabin Karp's
# Rolling hash
q = 103
 
def checkPalindromes(string):
 
    # Length of input string
    N = len(string)
 
    # A single character is always a palindrome
    print string[0] + " Yes"
 
    # Return if string has only one character
    if N == 1:
        return
 
    # Initialize first half reverse and second half for
    # as firstr and second characters
    firstr = ord(string[0]) % q
    second = ord(string[1]) % q
 
    h = 1
    i = 0
    j = 0
 
    # Now check for palindromes from second character
    # onward
    for i in xrange(1,N):
 
        # If the hash values of 'firstr' and 'second'
        # match, then only check individual characters
        if firstr == second:
 
            # Check if str[0..i] is palindrome using
            # simple character by character match
            for j in xrange(0,i/2):
                if string[j] != string[i-j]:
                    break
            j += 1
            if j == i/2:
                print string[i] + " Yes"
            else:
                print string[i] + " No"
        else:
            print string[i] + " No"
 
        # Calculate hash values for next iteration.
        # Don't calculate hash for next characters if
        # this is the last character of string
        if i != N-1:
 
            # If i is even (next i is odd)
            if i % 2 == 0:
 
                # Add next character after first half at
                # beginning of 'firstr'
                h = (h*d) % q
                firstr = (firstr + h*ord(string[i/2]))%q
 
                # Add next character after second half at
                # the end of second half.
                second = (second*d + ord(string[i+1]))%q
            else:
                # If next i is odd (next i is even) then we
                # need not to change firstr, we need to remove
                # first character of second and append a
                # character to it.
                second = (d*(second + q - ord(string[(i+1)/2])*h)%q
                            + ord(string[i+1]))%q
 
# Driver program
txt = "aabaacaabaa"
checkPalindromes(txt)
# This code is contributed by Bhavya Jain

Time complexity: quadratic
Space complexity: constant
# Python3 program to print all palindromic
# partitions of a given string.
def checkPalindrome(string):
     
    # Returns true if str is palindrome,
    # else false
    length = len(string)
    length -= 1
    for i in range(length):
        if string[i] != string[length]:
            return False
        length -= 1
    return True
 
def printSolution(partitions):
    for i in range(len(partitions)):
        for j in range(len(partitions[i])):
            print(partitions[i][j], end = " ")
        print()
 
def addStrings(v, s, temp, index):
     
    # Goes through all indexes and
    # recursively add remaining partitions
    # if current string is palindrome.
    length = len(s)
    string = ""
 
    current = temp[:]
 
    if index == 0:
        temp = []
    for i in range(index, length):
        string += s[i]
        if checkPalindrome(string):
            temp.append(string)
            if i + 1 < length:
                addStrings(v, s, temp[:], i + 1)
            else:
                v.append(temp)
            temp = current
 
def partition(s, v):
     
    # Generates all palindromic partitions
    # of 's' and stores the result in 'v'.
    temp = []
    addStrings(v, s, temp[:], 0)
    printSolution(v)
 
# Driver Code
if __name__ == "__main__":
    s = "geeks"
    partitions = []
    partition(s, partitions)
 
# This code is contributed by
# vibhu4agarwal

Time complexity: quadratic
Space complexity: linear
# Python3 code to Count Palindromic
# Subsequence in a given String
 
# Function return the total
# palindromic subsequence
 
 
def countPS(str):
 
    N = len(str)
 
    # Create a 2D array to store the count
    # of palindromic subsequence
    cps = [[0 for i in range(N + 2)]for j in range(N + 2)]
 
    # palindromic subsequence of length 1
    for i in range(N):
        cps[i][i] = 1
 
    # check subsequence of length L
    # is palindrome or not
    for L in range(2, N + 1):
 
        for i in range(N):
            k = L + i - 1
            if (k < N):
                if (str[i] == str[k]):
                    cps[i][k] = (cps[i][k - 1] +
                                 cps[i + 1][k] + 1)
                else:
                    cps[i][k] = (cps[i][k - 1] +
                                 cps[i + 1][k] -
                                 cps[i + 1][k - 1])
 
    # return total palindromic subsequence
    return cps[0][N - 1]
 
 
# Driver program
str = "abcb"
print("Total palindromic subsequence are : ", countPS(str))
 
 
# This code is contributed by Anant Agarwal.

Time complexity: quadratic
Space complexity: quadratic
# Python 3 program to counts Palindromic
# Subsequence in a given String using recursion
 
str = "abcb"
 
# Function return the total
# palindromic subsequence
 
 
def countPS(i, j):
 
    if(i > j):
        return 0
 
    if(dp[i][j] != -1):
        return dp[i][j]
 
    if(i == j):
        dp[i][j] = 1
        return dp[i][j]
 
    else if (str[i] == str[j]):
        dp[i][j] = (countPS(i + 1, j) +
                    countPS(i, j - 1) + 1)
        return dp[i][j]
    else:
        dp[i][j] = (countPS(i + 1, j) +
                    countPS(i, j - 1) -
                    countPS(i + 1, j - 1))
        return dp[i][j]
 
 
# Driver code
if __name__ == "__main__":
 
    dp = [[-1 for x in range(1000)]
          for y in range(1000)]
 
    n = len(str)
    print("Total palindromic subsequence are :",
          countPS(0, n - 1))
 
# This code is contributed by ita_c

Time complexity: quadratic
Space complexity: quadratic
# Python 3 program for getting minimum character
# to be added at front to make string palindrome
 
# function for checking string is
# palindrome or not
def ispalindrome(s):
 
    l = len(s)
     
    i = 0
    j = l - 1
    while i <= j:
     
        if(s[i] != s[j]):
            return False
        i += 1
        j -= 1
     
    return True
 
# Driver code
if __name__ == "__main__":
     
    s = "BABABAA"
    cnt = 0
    flag = 0
     
    while(len(s) > 0):
     
        # if string becomes palindrome then break
        if(ispalindrome(s)):
            flag = 1
            break
         
        else:
            cnt += 1
         
            # erase the last element of the string
            s = s[:-1]
     
    # print the number of insertion at front
    if(flag):
        print(cnt)
 
# This code is contributed by ita_c

Time complexity: quadratic
Space complexity: constant
# Python3 program for getting minimum
# character to be added at the front
# to make string palindrome
 
# Returns vector lps for given string str
def computeLPSArray(string):
 
    M = len(string)
    lps = [None] * M
 
    length = 0
    lps[0] = 0 # lps[0] is always 0
 
    # the loop calculates lps[i]
    # for i = 1 to M-1
    i = 1
    while i < M:
     
        if string[i] == string[length]:
         
            length += 1
            lps[i] = length
            i += 1
         
        else: # (str[i] != str[len])
         
            # This is tricky. Consider the example.
            # AAACAAAA and i = 7. The idea is
            # similar to search step.
            if length != 0:
             
                length = lps[length - 1]
 
                # Also, note that we do not
                # increment i here
             
            else: # if (len == 0)
             
                lps[i] = 0
                i += 1
 
    return lps
 
# Method returns minimum character
# to be added at front to make
# string palindrome
def getMinCharToAddedToMakeStringPalin(string):
 
    revStr = string[::-1]
 
    # Get concatenation of string,
    # special character and reverse string
    concat = string + "$" + revStr
 
    # Get LPS array of this
    # concatenated string
    lps = computeLPSArray(concat)
 
    # By subtracting last entry of lps
    # vector from string length, we
    # will get our result
    return len(string) - lps[-1]
 
# Driver Code
if __name__ == "__main__":
 
    string = "AACECAAAA"
    print(getMinCharToAddedToMakeStringPalin(string))
     
# This code is contributed by Rituraj Jain

Time complexity: linear
Space complexity: linear
# Python3 program to get largest palindrome changing
# atmost K digits
 
# Returns maximum possible
# palindrome using k changes
def maximumPalinUsingKChanges(strr, k):
    palin = strr[::]
 
    # Initialize l and r by leftmost and
    # rightmost ends
    l = 0
    r = len(strr) - 1
 
    # first try to make palindrome
    while (l <= r):
 
        # Replace left and right character by
        # maximum of both
        if (strr[l] != strr[r]):
            palin[l] = palin[r] =
                   max(strr[l], strr[r])
 
            # print(strr[l],strr[r])
            k -= 1
        l += 1
        r -= 1
 
    # If k is negative then we can't make
    # palindrome
    if (k < 0):
        return "Not possible"
 
    l = 0
    r = len(strr) - 1
 
    while (l <= r):
 
        # At mid character, if K>0 then change
        # it to 9
        if (l == r):
            if (k > 0):
                palin[l] = '9'
 
        # If character at lth (same as rth) is
        # less than 9
        if (palin[l] < '9'):
 
            # If none of them is changed in the
            # previous loop then subtract 2 from K
            # and convert both to 9
            if (k >= 2 and palin[l] == strr[l] and
                           palin[r] == strr[r]):
                k -= 2
                palin[l] = palin[r] = '9'
 
            # If one of them is changed in the previous
            # loop then subtract 1 from K (1 more is
            # subtracted already) and make them 9
            elif (k >= 1 and (palin[l] != strr[l] or
                              palin[r] != strr[r])):
                k -= 1
                palin[l] = palin[r] = '9'
 
        l += 1
        r -= 1
 
    return palin
 
 
# Driver code
st = "43435"
strr = [i for i in st]
k = 3
a = maximumPalinUsingKChanges(strr, k)
print("".join(a))
 
# This code is contributed by mohit kumar 29

Time complexity: linear
Space complexity: linear