Banana-Leopard/TASTY huggingface dataset:
# Python3 code to find the first repeating character in a
# string
INT_MAX = 2147483647
 
# Function to find left most repeating character.
def firstRep(s):
    map = dict()
    c = '#'
    index = INT_MAX
     
    # single traversal of string.
    i = 0
    while (i < len(s)):
        p = s[i]
        if (not (p in map.keys())):
            map[p] = i
        else:
            if (map.get(p) < index):
                index = map.get(p)
                c = p
        i += 1
    return c
 
if __name__ == "__main__":
   
    # Input string.
    s = "abccdbd"
    print(firstRep(s), end="")
    print("\n", end="")
 
# This code is contributed by Aarti_Rathi

Time complexity: linear
Space complexity: constant
# Python program to find the first
# repeated character in a string
def firstRepeatedChar(str):
 
    h = {} # Create empty hash
 
    # Traverse each characters in string
    # in lower case order
    for ch in str:
 
        # If character is already present
        # in hash, return char
        if ch in h:
            return ch;
 
        # Add ch to hash
        else:
            h[ch] = 0
 
    return ''
 
 
# Driver code
print(firstRepeatedChar("geeksforgeeks"))

Time complexity: linear
Space complexity: linear
# Efficiently check First repeated character
# in Python
 
# Returns -1 if all characters of str are
# unique.
# Assumptions : (1) str contains only characters
#                 from 'a' to 'z'
##             (2) integers are stored using 32
##                 bits
def FirstRepeated(string):
     
    # An integer to store presence/absence
    # of 26 characters using its 32 bits.
    checker = 0
  
    pos = 0
    for i in string:
        val = ord(i) - ord('a');
  
        # If bit corresponding to current
        # character is already set
        if ((checker & (1 << val)) > 0):
            return pos
  
        # set bit in checker
        checker |= (1 << val)
        pos += 1
  
    return -1
  
# Driver code
string = "abcfdeacf"
i = FirstRepeated(string)
if i != -1:
    print ("Char = ", string[i], " and Index = ", i)
else:
    print ("No repeated Char")
 
# This code is contributed by Sachin Bisht

Time complexity: linear
Space complexity: constant
# Queries for same characters in a repeated
# string
 
# Print whether index i and j have same
# element or not.
def query(s, i, j):
    n = len(s)
 
    # Finding relative position of index i,j.
    i %= n
    j %= n
 
    # Checking is element are same at index i, j.
    print("Yes") if s[i] == s[j] else print("No")
 
# Driver code
if __name__ == "__main__":
    X = "geeksforgeeks"
    query(X, 0, 8)
    query(X, 8, 13)
    query(X, 6, 15)
 
# This code is contributed by
# sanjeev2552

Time complexity: constant
Space complexity: constant
# Python3 program to print all occurrences
# of every character together.
 
# Since only lower case characters are there
MAX_CHAR = 26
 
# Function to print the string
def printGrouped(string):
    n = len(string)
 
    # Initialize counts of all characters as 0
    count = [0] * MAX_CHAR
 
    # Count occurrences of all characters in string
    for i in range(n):
        count[ord(string[i]) - ord("a")] += 1
 
    # Starts traversing the string
    for i in range(n):
 
        # Print the character till its count in
        # hash array
        while count[ord(string[i]) - ord("a")]:
            print(string[i], end = "")
            count[ord(string[i]) - ord("a")] -= 1
 
        # Make this character's count value as 0.
        count[ord(string[i]) - ord("a")] = 0
 
# Driver code
if __name__ == "__main__":
    string = "geeksforgeeks"
    printGrouped(string)
 
# This code is contributed by
# sanjeev2552

Time complexity: linear
Space complexity: constant
# Python3 program to print the string
# in given pattern
 
# Function to print the string
def printStringAlternate(string):
 
    occ = {}
 
    # Start traversing the string
    for i in range(0, len(string)):
 
        # Convert uppercase to lowercase
        temp = string[i].lower()
 
        # Increment occurrence count
        occ[temp] = occ.get(temp, 0) + 1
 
        # If count is odd then print the character
        if occ[temp] & 1:
            print(string[i], end = "")
 
    print()
 
# Driver code
if __name__ == "__main__":
 
    string = "Geeks for geeks"
    string2 = "It is a long day Dear"
 
    printStringAlternate(string)
    printStringAlternate(string2)
 
# This code is contributed by Rituraj Jain

Time complexity: linear
Space complexity: linear
# Python3 program for above implementation
 
# Function to print the string
def printString(str, ch, count):
    occ, i = 0, 0
 
    # If given count is 0
    # print the given string and return
    if (count == 0):
        print(str)
 
    # Start traversing the string
    for i in range(len(str)):
 
        # Increment occ if current char
        # is equal to given character
        if (str[i] == ch):
            occ += 1
 
        # Break the loop if given character has
        # been occurred given no. of times
        if (occ == count):
            break
 
    # Print the string after the occurrence
    # of given character given no. of times
    if (i < len(str)- 1):
        print(str[i + 1: len(str) - i + 2])
 
    # Otherwise string is empty
    else:
        print("Empty string")
 
# Driver code
if __name__ == '__main__':
    str = "geeks for geeks"
    printString(str, 'e', 2)
 
# This code is contributed
# by 29AjayKumar

Time complexity: linear
Space complexity: constant
# Python3 Program to find all occurrences of the word in
# a matrix
ROW = 3
COL = 5
 
# check whether given cell (row, col) is a valid
# cell or not.
def isvalid(row, col, prevRow, prevCol):
     
    # return true if row number and column number
    # is in range
    return (row >= 0) and (row < ROW) and (col >= 0) and \
           (col < COL) and not (row== prevRow and col == prevCol)
 
# These arrays are used to get row and column
# numbers of 8 neighboursof a given cell
rowNum = [-1, -1, -1, 0, 0, 1, 1, 1]
colNum = [-1, 0, 1, -1, 1, -1, 0, 1]
 
# A utility function to do DFS for a 2D boolean
# matrix. It only considers the 8 neighbours as
# adjacent vertices
def DFS(mat, row, col,prevRow, prevCol, word,path, index, n):
     
    # return if current character doesn't match with
    # the next character in the word
    if (index > n or mat[row][col] != word[index]):
        return
     
    # append current character position to path
    path += word[index] + "(" + str(row)+ ", " + str(col) + ") "
     
    # current character matches with the last character\
    # in the word
    if (index == n):
        print(path)
        return
     
    # Recur for all connected neighbours
    for k in range(8):
        if (isvalid(row + rowNum[k], col + colNum[k],prevRow, prevCol)):
            DFS(mat, row + rowNum[k], col + colNum[k],row, col, word, path, index + 1, n)
 
# The main function to find all occurrences of the
# word in a matrix
def findWords(mat,word, n):
     
    # traverse through the all cells of given matrix
    for i in range(ROW):
        for j in range(COL):
             
            # occurrence of first character in matrix
            if (mat[i][j] == word[0]):
                # check and print if path exists
                DFS(mat, i, j, -1, -1, word, "", 0, n)
 
# Driver code
mat = [['B', 'N', 'E', 'Y', 'S'],
        ['H', 'E', 'D', 'E', 'S'],
        ['S', 'G', 'N', 'D', 'E']]
word = list("DES")
findWords(mat, word, len(word) - 1)
     
# This code is contributed by SHUBHAMSINGH10

Time complexity: quadratic
Space complexity: quadratic
# Python3 program to arrange given string
 
# Function which arrange the given string
def arrangeString(str1,x,y):
    count_0=0
    count_1 =0
    n = len(str1)
 
    # Counting number of 0's and 1's in the
    # given string.
    for i in range(n):
        if str1[i] == '0':
            count_0 +=1
        else:
            count_1 +=1
 
    # Printing first all 0's x-times
    # and decrement count of 0's x-times
    # and do the similar task with '1'
    while count_0>0 or count_1>0:
        for i in range(0,x):
            if count_0>0:
                print("0",end="")
                count_0 -=1
        for j in range(0,y):
            if count_1>0:
                print("1",end="")
                count_1 -=1
 
# Driver code
if __name__=='__main__':
    str1 = "01101101101101101000000"
    x = 1
    y = 2
    arrangeString(str1, x, y)
 
# This code is contributed by
# Shrikant13

Time complexity: quadratic
Space complexity: constant
# Finds maximum occurring digit
# without using any array/string
 
# Simple function to count
# occurrences of digit d in x
def countOccurrences(x, d):
    count = 0; # Initialize count
               # of digit d
    while (x):
         
        # Increment count if current
        # digit is same as d
        if (x % 10 == d):
            count += 1;
        x = int(x / 10);
 
    return count;
 
# Returns the max occurring
# digit in x
def maxOccurring(x):
     
    # Handle negative number
    if (x < 0):
        x = -x;
     
    result = 0; # Initialize result
                # which is a digit
    max_count = 1; # Initialize count
                   # of result
     
    # Traverse through all digits
    for d in range(10):
         
        # Count occurrences of current digit
        count = countOccurrences(x, d);
         
        # Update max_count and
        # result if needed
        if (count >= max_count):
            max_count = count;
            result = d;
         
    return result;
 
# Driver Code
x = 1223355;
print("Max occurring digit is",
              maxOccurring(x));
 
# This code is contributed by mits.

Time complexity: constant
Space complexity: constant
# Python3 program to bring all spaces
# in front of string using swapping technique
 
# Function to find spaces and move to beginning
def moveSpaceInFront(s):
 
    # Traverse from end and swap spaces
    i = len(s) - 1;
    for j in range(i, -1, -1):
        if (s[j] != ' '):
            s = swap(s, i, j);
            i -= 1;
    return s;
     
def swap(c, i, j):
    c = list(c)
    c[i], c[j] = c[j], c[i]
    return ''.join(c)
     
# Driver code
s = "Hey there, it's GeeksforGeeks";
s = moveSpaceInFront(s);
print(s);
 
# This code is contributed
# by Princi Singh

Time complexity: linear
Space complexity: constant
# Python3 program to bring all spaces
# in front of string using swapping technique
 
# Function to find spaces and
# move to beginning
def moveSpaceInFront(s):
 
    # Keep copying non-space characters
    i = len(s) - 1;
     
    for j in range(i, -1, -1):
        if (s[j] != ' '):
            s = s[:i] + s[j] + s[i + 1:]
            i -= 1;
 
    # Move spaces to be beginning
    while (i >= 0):
        s = s[:i] + ' ' + s[i + 1:]
        i -= 1
    return s;
 
# Driver code
s = "Hey there, it's GeeksforGeeks";
s = moveSpaceInFront(s);
print(s);
 
# This code is contributed
# by Princi Singh

Time complexity: linear
Space complexity: constant
# Python3 program to put spaces between words
# starting with capital letters.
 
# Function to amend the sentence
def amendSentence(string):
    string = list(string)
 
    # Traverse the string
    for i in range(len(string)):
 
        # Convert to lowercase if its
        # an uppercase character
        if string[i] >= 'A' and string[i] <= 'Z':
            string[i] = chr(ord(string[i]) + 32)
 
            # Print space before it
            # if its an uppercase character
            if i != 0:
                print(" ", end = "")
 
            # Print the character
            print(string[i], end = "")
 
        # if lowercase character
        # then just print
        else:
            print(string[i], end = "")
 
# Driver Code
if __name__ == "__main__":
    string = "BruceWayneIsBatman"
    amendSentence(string)
 
# This code is contributed by
# sanjeev2552

Time complexity: linear
Space complexity: constant
# Python program to Remove
# extra spaces from a string
input_string = \
    '   Hello Geeks  .  Welcome ,    Do you love Geeks , Geeks  ? '
output_string = []
space_flag = False # Flag to check if spaces have occurred
 
for index in range(len(input_string)):
 
    if input_string[index] != ' ':
        if space_flag == True:
            if (input_string[index] == '.'
                    or input_string[index] == '?'
                    or input_string[index] == ','):
                pass
            else:
                output_string.append(' ')
            space_flag = False
        output_string.append(input_string[index])
    elif input_string[index - 1] != ' ':
        space_flag = True
 
print (''.join(output_string))

Time complexity: linear
Space complexity: constant
# Python 3 program to find the string which
# contain the first character of each word
# of another string.
 
# Function to find string which has first
# character of each word.
def firstLetterWord(str):
 
    result = ""
 
    # Traverse the string.
    v = True
    for i in range(len(str)):
         
        # If it is space, set v as true.
        if (str[i] == ' '):
            v = True
 
        # Else check if v is true or not.
        # If true, copy character in output
        # string and set v as false.
        elif (str[i] != ' ' and v == True):
            result += (str[i])
            v = False
 
    return result
 
# Driver Code
if __name__ == "__main__":
     
    str = "geeks for geeks"
    print(firstLetterWord(str))
 
# This code is contributed by ita_c

Time complexity: linear
Space complexity: linear
# An efficient Python3 implementation
# of above approach
charBuffer = []
def processWords(input):
 
    """ we are splitting the input based on
    spaces (s)+ : this regular expression
    will handle scenarios where we have words
    separated by multiple spaces """
    s = input.split(" ")
 
    for values in s:
        """ charAt(0) will pick only the first
        character from the string and append
        to buffer """
        charBuffer.append(values[0])
    return charBuffer
 
# Driver Code
if __name__ == '__main__':
    input = "geeks for geeks"
    print(*processWords(input), sep = "")
 
# This code is contributed
# by SHUBHAMSINGH10

Time complexity: quadratic
Space complexity: linear
# Python 3 program to print all strings
# that can be made by placing spaces
from math import pow
 
def printSubsequences(str):
    n = len(str)
    opsize = int(pow(2, n - 1))
 
    for counter in range(opsize):
        for j in range(n):
            print(str[j], end = "")
            if (counter & (1 << j)):
                print(" ", end = "")
 
        print("\n", end = "")
 
# Driver code
if __name__ == '__main__':
    str = "ABC"
    printSubsequences(str)
 
# This code is contributed by
# Sanjit_Prasad

Time complexity: quadratic
Space complexity: constant
class Solution:
 
    # Function is to check whether two strings are anagram of each other or not.
    def isAnagram(self, a, b):
 
        if sorted(a) == sorted(b):
            return True
        else:
            return False
 
# {
#  Driver Code Starts
 
if __name__ == '__main__':
    a = "gram"
    b = "arm"
    if(Solution().isAnagram(a, b)):
      print("The two strings are anagram of each other")
    else:
      print("The two strings are not anagram of each other")
# } Driver Code Ends

Time complexity: nlogn
Space complexity: constant
# Python program to check if two strings are anagrams of
# each other
NO_OF_CHARS = 256
 
# Function to check whether two strings are anagram of
# each other
 
 
def areAnagram(str1, str2):
 
    # Create two count arrays and initialize all values as 0
    count1 = [0] * NO_OF_CHARS
    count2 = [0] * NO_OF_CHARS
 
    # For each character in input strings, increment count
    # in the corresponding count array
    for i in str1:
        count1[ord(i)] += 1
 
    for i in str2:
        count2[ord(i)] += 1
 
    # If both strings are of different length. Removing this
    # condition will make the program fail for strings like
    # "aaca" and "aca"
    if len(str1) != len(str2):
        return 0
 
    # Compare count arrays
    for i in xrange(NO_OF_CHARS):
        if count1[i] != count2[i]:
            return 0
 
    return 1
 
 
# Driver code
str1 = "gram"
str2 = "arm"
 
# Function call
if areAnagram(str1, str2):
    print "The two strings are anagram of each other"
else:
    print "The two strings are not anagram of each other"
 
# This code is contributed by Bhavya Jain

Time complexity: linear
Space complexity: constant
# Python program to check if two strings
# are anagrams of each other
 
NO_OF_CHARS = 256
 
# function to check if two strings
# are anagrams of each other
def areAnagram(str1,str2):
     
    # If both strings are of different
    # length. Removing this condition
    # will make the program fail for
    # strings like "aaca" and "aca"   
    if(len(str1) != len(str2)):
        return False;
       
    # Create a count array and initialize
    # all values as 0
    count=[0 for i in range(NO_OF_CHARS)]
    i=0
     
    # For each character in input strings,
    # increment count in the corresponding
    # count array
    for i in range(len(str1)):
        count[ord(str1[i]) - ord('a')] += 1;
        count[ord(str2[i]) - ord('a')] -= 1;
         
    # See if there is any non-zero
    # value in count array
    for i in range(NO_OF_CHARS):
        if (count[i] != 0):
            return False
         
     
    return True
 
# Driver code
str1="gram"
str2="arm"
 
# Function call
if (areAnagram(str1, str2)):
    print("The two strings are anagram of each other")
else:
    print("The two strings are not anagram of each other")
     
     
# This code is contributed by patel2127

Time complexity: linear
Space complexity: constant
# Python3 implementation of the approach
# Function that returns True if a and b
# are anagarams of each other
 
 
def isAnagram(a, b):
 
    # Check if length of both strings is same or not
    if (len(a) != len(b)):
        return False
 
    # Create a HashMap containing Character as Key and
    # Integer as Value. We will be storing character as
    # Key and count of character as Value.
    map = {}
    # Loop over all character of String a and put in
    # HashMap.
    for i in range(len(a)):
        # Check if HashMap already contain current
        # character or not
        if (a[i] in map):
            # If contains increase count by 1 for that
            # character
            map[a[i]] += 1
 
        else:
            # else set that character in map and set
            # count to 1 as character is encountered
            # first time
            map[a[i]] = 1
 
    # Now loop over String b
    for i in range(len(b)):
        # Check if current character already exists in
        # HashMap/map
        if (b[i] in map):
            # If contains reduce count of that
            # character by 1 to indicate that current
            # character has been already counted as
            # idea here is to check if in last count of
            # all characters in last is zero which
            # means all characters in String a are
            # present in String b.
            map[b[i]] -= 1
        else:
            return False
 
    # Extract all keys of HashMap/map
    keys = map.keys()
    # Loop over all keys and check if all keys are 0.
    # If so it means it is anagram.
    for key in keys:
        if (map[key] != 0):
            return False
 
    # Returning True as all keys are zero
    return True
 
 
# Driver code
str1 = "gram"
str2 = "arm"
 
# Function call
if (isAnagram(str1, str2)):
    print("The two strings are anagram of each other")
else:
    print("The two strings are not anagram of each other")
 
 
# This code is contributed by shinjanpatra

Time complexity: linear
Space complexity: constant
# Python program to search all
# anagrams of a pattern in a text
 
MAX=256
 
# This function returns true
# if contents of arr1[] and arr2[]
# are same, otherwise false.
def compare(arr1, arr2):
    for i in range(MAX):
        if arr1[i] != arr2[i]:
            return False
    return True
     
# This function search for all
# permutations of pat[] in txt[] 
def search(pat, txt):
 
    M = len(pat)
    N = len(txt)
 
    # countP[]:  Store count of
    # all characters of pattern
    # countTW[]: Store count of
    # current window of text
    countP = [0]*MAX
 
    countTW = [0]*MAX
 
    for i in range(M):
        (countP[ord(pat[i]) ]) += 1
        (countTW[ord(txt[i]) ]) += 1
 
    # Traverse through remaining
    # characters of pattern
    for i in range(M,N):
 
        # Compare counts of current
        # window of text with
        # counts of pattern[]
        if compare(countP, countTW):
            print("Found at Index", (i-M))
 
        # Add current character to current window
        (countTW[ ord(txt[i]) ]) += 1
 
        # Remove the first character of previous window
        (countTW[ ord(txt[i-M]) ]) -= 1
     
    # Check for the last window in text   
    if compare(countP, countTW):
        print("Found at Index", N-M)
         
# Driver program to test above function      
txt = "BACDGABCDA"
pat = "ABCD"      
search(pat, txt)  
 
# This code is contributed
# by Upendra Singh Bartwal

Time complexity: linear
Space complexity: linear
# Python 3 program to find minimum
# number of characters
# to be removed to make two
# strings anagram.
 
CHARS = 26
 
# function to calculate minimum
# numbers of characters
# to be removed to make two
# strings anagram
def remAnagram(str1, str2):
 
    # make hash array for both string
    # and calculate
    # frequency of each character
    count1 = [0]*CHARS
    count2 = [0]*CHARS
 
    # count frequency of each character
    # in first string
    i = 0
    while i < len(str1):
        count1[ord(str1[i])-ord('a')] += 1
        i += 1
 
    # count frequency of each character
    # in second string
    i =0
    while i < len(str2):
        count2[ord(str2[i])-ord('a')] += 1
        i += 1
 
    # traverse count arrays to find
    # number of characters
    # to be removed
    result = 0
    for i in range(26):
        result += abs(count1[i] - count2[i])
    return result
 
# Driver program to run the case
if __name__ == "__main__":
    str1 = "bcadeh"
    str2 = "hea"
    print(remAnagram(str1, str2))
     
# This code is contributed by
# ChitraNayal

Time complexity: linear
Space complexity: constant
# Python3 program to find minimum
# number of characters to be
# removed to make two strings
# anagram.
 
# function to calculate minimum
# numbers of characters to be
# removed to make two strings anagram
def makeAnagram(a, b):
    buffer = [0] * 26
    for char in a:
        buffer[ord(char) - ord('a')] += 1
    for char in b:
        buffer[ord(char) - ord('a')] -= 1
    return sum(map(abs, buffer))
 
# Driver Code
if __name__ == "__main__" :
 
    str1 = "bcadeh"
    str2 = "hea"
    print(makeAnagram(str1, str2))
     
# This code is contributed
# by Raghib Ahsan

Time complexity: linear
Space complexity: constant
# Python3 program to check if two
# strings are k anagram or not.
MAX_CHAR = 26
 
# Function to check that is
# 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
 
    count1 = [0] * MAX_CHAR
    count2 = [0] * MAX_CHAR
 
    # Store the occurrence of all
    # characters in a hash_array
    for i in range(n):
        count1[ord(str1[i]) -
               ord('a')] += 1
    for i in range(n):
        count2[ord(str2[i]) -
               ord('a')] += 1
         
    count = 0
 
    # Count number of characters that
    # are different in both strings
    for i in range(MAX_CHAR):
        if (count1[i] > count2[i]) :
            count = count + abs(count1[i] -
                                count2[i])
 
    # Return true if count is less
    # than or equal to k
    return (count <= k)
 
# Driver Code
if __name__ == '__main__':
    str1 = "anagram"
    str2 = "grammar"
    k = 2
    if (arekAnagrams(str1, str2, k)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed
# by SHUBHAMSINGH10

Time complexity: linear
Space complexity: constant