giulio98/xlcost-single-prompt huggingface dataset:
# convert given strings into t by replacing characters in between strings any number of times | function to check if it possible to make all the strings equal to the t ; stores the frequency of all the strings in the array arr [ ] ; stores the frequency of the t ; iterate over the characters of the t ; iterate in the range [ 0 , n - 1 ] ; iterate over the characters of the arr [ i ] ; if freqt [ i ] is 0 and freqs [ i ] is not 0 ; if freqs [ i ] is 0 and freqt [ i ] is not 0 ; if freqs [ i ] is not freqt [ i ] * n ; otherwise , return " yes " ; 
def checkIfPossible(N, arr, T):
    freqS = [0] * 256
    freqT = [0] * 256
    for ch in T:
        freqT[ord(ch) - ord('a')] += 1
    for i in range(N):
        for ch in arr[i]:
            freqS[ord(ch) - ord('a')] += 1
    for i in range(256):
        if (freqT[i] == 0 and freqS[i] != 0):
            return "No"
        elif (freqS[i] == 0 and freqT[i] != 0):
            return "No"
        elif (freqT[i] != 0 and freqS[i] != (freqT[i] * N)):
            return "No"
    return "Yes"


if __name__ == '__main__':
    arr = ["abc", "abb", "acc"]
    T = "abc"
    N = len(arr)
    print(checkIfPossible(N, arr, T))

# Expected output:
Yes
# palindromic strings of length 3 possible by using characters of a given string | function to print all palindromic strings of length 3 that can be formed using characters of string s ; stores the count of character ; traverse the string s ; stores all palindromic strings ; iterate over the charchaters over the range [ ' a ' , ' z ' ] ; if hash [ ch ] is equal to 2 ; iterate over the characters over the range [ ' a ' , ' z ' ] ; stores all the palindromic string ; push the s into the set st ; if hash [ i ] is greater than or equal to 3 ; iterate over charchaters over the range [ ' a ' , ' z ' ] ; stores all the palindromic string ; if hash [ j ] is positive ; push s into the set st ; iterate over the set ; 
def generatePalindrome(S):
    Hash = {}
    for ch in S:
        Hash[ch] = Hash .get(ch, 0) + 1
    st = {}
    for i in range(ord('a'), ord('z') + 1):
        if (chr(i) in Hash and Hash[chr(i)] == 2):
            for j in range(ord('a'), ord('z') + 1):
                s = ""
                if (chr(j) in Hash and i != j):
                    s += chr(i)
                    s += chr(j)
                    s += chr(i)
                    st[s] = 1
        if ((chr(i) in Hash) and Hash[chr(i)] >= 3):
            for j in range(ord('a'), ord('z') + 1):
                s = ""
                if (chr(j) in Hash):
                    s += chr(i)
                    s += chr(j)
                    s += chr(i)
                    st[s] = 1
    for ans in st:
        print(ans)


if __name__ == '__main__':
    S = "ddabdac"
    generatePalindrome(S)

# Expected output:
aba
aca
ada
dad
dbd
dcd
ddd
# count occurrences of substring x before every occurrence of substring y in a given string | function to count occurrences of the string y in the string s for every occurrence of x in s ; stores the count of occurrences of x ; stores the lengths of the three strings ; traverse the string s ; if the current substring is y , then increment the value of count by 1 ; if the current substring is x , then print the count ; 
def countOccurrences(S, X, Y):
    count = 0
    N = len(S)
    A = len(X)
    B = len(Y)
    for i in range(0, N):
        if (S[i:i + B] == Y):
            count += 1
        if (S[i:i + A] == X):
            print(count, end=" ")


S = "abcdefdefabc"
X = "abc"
Y = "def"
countOccurrences(S, X, Y)

# Expected output:
0 2
# program to construct dfa for regular expression c ( a + b ) + | function to find whether the given is accepted by the dfa ; if n <= 1 , then prno ; to count the matched characters ; check if the first character is c ; traverse the rest of string ; if character is a or b , increment count by 1 ; if the first character is not c , pr - 1 ; if all characters matches ; 
def DFA(str, N):
    if (N <= 1):
        print("No")
        return
    count = 0
    if (str[0] == 'C'):
        count += 1
        for i in range(1, N):
            if (str[i] == 'A' or str[i] == 'B'):
                count += 1
            else:
                break
    else:
        print("No")
        return
    if (count == N):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    str = "CAABBAAB"
    N = len(str)
    DFA(str, N)

# Expected output:
Yes
# minimum and maximum number of digits required to be removed to make a given number divisible by 3 | function to find the maximum and minimum number of digits to be removed to make str divisible by 3 ; convert the string into array of digits ; count of 0 s , 1 s , and 2 s ; traverse the array ; find the sum of digits % 3 ; cases to find minimum number of digits to be removed ; cases to find maximum number of digits to be removed ; 
def minMaxDigits(str, N):
    arr = [0] * N
    for i in range(N):
        arr[i] = (ord(str[i]) - ord('0')) % 3
    zero = 0
    one = 0
    two = 0
    for i in range(N):
        if (arr[i] == 0):
            zero += 1
        if (arr[i] == 1):
            one += 1
        if (arr[i] == 2):
            two += 1
    sum = 0
    for i in range(N):
        sum = (sum + arr[i]) % 3
    if (sum == 0):
        print("0", end=" ")
    if (sum == 1):
        if (one and N > 1):
            print("1", end=" ")
        elif (two > 1 and N > 2):
            print("2", end=" ")
        else:
            print("-1", end=" ")
    if (sum == 2):
        if (two and N > 1):
            print("1", end=" ")
        elif (one > 1 and N > 2):
            print("2", end=" ")
        else:
            print("-1", end=" ")
    if (zero > 0):
        print(N - 1, end=" ")
    elif (one > 0 and two > 0):
        print(N - 2, end=" ")
    elif (one > 2 or two > 2):
        print(N - 3, end=" ")
    else:
        print("-1", end=" ")


str = "12345"
N = len(str)
minMaxDigits(str, N)

# Expected output:
0 4
# minimum replacements required to obtain a k | python3 program for the above approach ; function to find the minimum number of changes to make the string k - periodic and palindrome ; initialize ans with 0 ; iterate from 0 to ( k + 1 ) / 2 ; store frequency of character ; iterate through all indices , i , i + k , i + 2 k ... . and store the frequency of character ; increase the frequency of current character ; iterate through all indices k - i , 2 k - i , 3 k - i ... . and store the frequency of character ; if k is odd & i is samw as k / 2 , break the loop ; increase the frequency of current character ; find the maximum frequency of a character among all visited characters ; if k is odd and i is same as k / 2 then , only n / k characters is visited ; otherwise n / k * 2 characters has visited ; return the result ; 

import sys


def findMinimumChanges(N, K, S):
    ans = 0
    for i in range((K + 1) // 2):
        mp = {}
        for j in range(i, N, K):
            mp[S[j]] = mp .get(S[j], 0) + 1
        j = N - i - 1
        while (j >= 0):
            if ((K & 1) and (i == K // 2)):
                break
            mp[S[j]] = mp .get(S[j], 0) + 1
            j -= K
        curr_max = -sys .maxsize - 1
        for key, value in mp .items():
            curr_max = max(curr_max, value)
        if ((K & 1) and (i == K // 2)):
            ans += (N // K - curr_max)
        else:
            ans += (N // K * 2 - curr_max)
    return ans


if __name__ == '__main__':
    S = "aabbcbbcb"
    N = len(S)
    K = 3
    print(findMinimumChanges(N, K, S))

# Expected output:
2
# check if a string contains any index with more than k active characters | function to check if any index contains more than k active characters ; store the last occurrence of each character ; stores the active characters ; insert the character ; if the size of set exceeds k ; remove the character from set if i is the last index of the current character ; 
def checkString(s, K):
    n = len(s)
    dict = {}
    for i in range(n):
        dict[s[i]] = i
    st = set()
    for i in range(n):
        st .add(s[i])
        if len(st) > K:
            print("Yes")
            return
        if dict[s[i]] == i:
            st .remove(s[i])
    print("No")


s = "aabbcdca"
K = 2
checkString(s, K)

# Expected output:
Yes
# count the number of strings in an array whose distinct characters are less than equal to m | function to count the strings whose distinct characters count is less than m ; loop to iterate over all the strings of the array ; distinct characters in the string with the help of set ; checking if its less than or equal to m ; 
def distinct(S, M):
    count = 0
    for i in range(len(S)):
        c = len(set([d for d in S[i]]))
        if (c <= M):
            count += 1
    print(count)


if __name__ == '__main__':
    S = ["HERBIVORES", "AEROPLANE", "GEEKSFORGEEKS"]
    M = 7
    distinct(S, M)

# Expected output:
2
# remove odd frequency characters from the string | function to remove the characters which have odd frequencies in the string ; create a map to store the frequency of each character ; to store the new string ; remove the characters which have odd frequencies ; if the character has odd frequency then skip ; else concatenate the character to the new string ; return the modified string ; 
def removeOddFrequencyCharacters(s):
    m = dict()
    for i in s:
        m[i] = m .get(i, 0) + 1
    new_s = ""
    for i in s:
        if (m[i] & 1):
            continue
        new_s += i
    return new_s


if __name__ == '__main__':
    str = "geeksforgeeks"
    str = removeOddFrequencyCharacters(str)
    print(str)

# Expected output:
geeksgeeks
# product of nodes at k | recursive function to find product of elements at k - th level ; if subtree is null , just like if root == null ; consider only level k node to be part of the product ; recur for left subtree ; recur for right subtree ; taking care of ' ) ' after left and right subtree ; 
def productAtKthLevel(tree, k, i, level):
    if (tree[i[0]] == '('):
        i[0] += 1
        if (tree[i[0]] == ')'):
            return 1
        product = 1
        if (level == k):
            product = int(tree[i[0]])
        i[0] += 1
        leftproduct = productAtKthLevel(tree, k, i, level + 1)
        i[0] += 1
        rightproduct = productAtKthLevel(tree, k, i, level + 1)
        i[0] += 1
        return product * leftproduct * rightproduct


if __name__ == "__main__":
    tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"
    k = 2
    i = [0]
    print(productAtKthLevel(tree, k, i, 0))

# Expected output:
72
# print the most occurring character in an array of strings | function to print the most occurring character ; creating a hash of size 26 ; for loop to iterate through every string of the array ; for loop to iterate through every character of the string ; incrementing the count of the character in the hash ; finding the character with the maximum count ; 
def findMostOccurringChar(string):
    hash = [0] * 26
    for i in range(len(string)):
        for j in range(len(string[i])):
            hash[ord(string[i][j]) - ord('a')] += 1
    max = 0
    for i in range(26):
        max = i if hash[i] > hash[max]else max
    print((chr)(max + 97))


if __name__ == "__main__":
    string = []
    string .append("animal")
    string .append("zebra")
    string .append("lion")
    string .append("giraffe")
    findMostOccurringChar(string)

# Expected output:
a
# check whether the given floating point number is a palindrome | function that returns true if num is palindrome ; convert the given floating point number into a string ; pointers pointing to the first and the last character of the string ; not a palindrome ; update the pointers ; 
def isPalindrome(num):
    s = str(num)
    low = 0
    high = len(s) - 1
    while (low < high):
        if (s[low] != s[high]):
            return False
        low += 1
        high -= 1
    return True


n = 123.321
if (isPalindrome(n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# maximum number of times str1 appears as a non | python3 implementation of the approach ; function to return the maximum number of times str1 can appear as a non - overlapping substring bin str2 ; str1 cannot never be substring of str2 ; store the frequency of the characters of str1 ; store the frequency of the characters of str2 ; to store the required count of substrings ; current character doesn 't appear  in str1 ; frequency of the current character in str1 is greater than its frequency in str2 ; update the count of possible substrings ; 

import sys
MAX = 26


def maxSubStr(str1, len1, str2, len2):
    if (len1 > len2):
        return 0
    freq1 = [0] * MAX
    for i in range(len1):
        freq1[ord(str1[i]) - ord('a')] += 1
    freq2 = [0] * MAX
    for i in range(len2):
        freq2[ord(str2[i]) - ord('a')] += 1
    minPoss = sys .maxsize
    for i in range(MAX):
        if (freq1[i] == 0):
            continue
        if (freq1[i] > freq2[i]):
            return 0
        minPoss = min(minPoss, freq2[i] / freq1[i])
    return int(minPoss)


str1 = "geeks"
str2 = "gskefrgoekees"
len1 = len(str1)
len2 = len(str2)
print(maxSubStr(str1, len1, str2, len2))

# Expected output:
2
# number of ways to insert two pairs of parentheses into a string of n characters | function to return the number of ways to insert the bracket pairs ; 
def cntWays(string, n):
    x = n + 1
    ways = x * x * (x * x - 1) // 12
    return ways


if __name__ == "__main__":
    string = "ab"
    n = len(string)
    print(cntWays(string, n))

# Expected output:
6
# minimum number of substrings the given string can be splitted into that satisfy the given conditions | python3 implementation of the approach ; set to store all the strings from the given array ; to store the required count ; recursive function to find the count of substrings that can be splitted starting from the index start such that all the substrings are present in the map ; all the chosen substrings are present in the map ; update the minimum count of substrings ; starting from the substrings of length 1 that start with the given index ; get the substring ; if the substring is present in the set ; recursive call for the rest of the string ; function that inserts all the strings from the given array in a set and calls the recursive function to find the minimum count of substrings str can be splitted into that satisfy the given condition ; insert all the strings from the given array in a set ; find the required count ; 

import sys
uSet = set()
minCnt = sys .maxsize


def findSubStr(string, cnt, start):
    global minCnt
    if (start == len(string)):
        minCnt = min(cnt, minCnt)
    for length in range(1, len(string) - start + 1):
        subStr = string[start:start + length]
        if subStr in uSet:
            findSubStr(string, cnt + 1, start + length)


def findMinSubStr(arr, n, string):
    for i in range(n):
        uSet .add(arr[i])
    findSubStr(string, 0, 0)


if __name__ == "__main__":
    string = "123456"
    arr = ["1", "12345", "2345", "56", "23", "456"]
    n = len(arr)
    findMinSubStr(arr, n, string)
    print(minCnt)

# Expected output:
3
# number of substrings that start with " geeks " and end with " for " | function to return the count of required substrings ; for every index of the string ; if the substring starting at the current index is " geeks " ; if the substring is " for " ; 
def countSubStr(s, n):
    c1 = 0
    c2 = 0
    for i in range(n):
        if (s[i:i + 5] == "geeks"):
            c1 += 1
        if (s[i:i + 3] == "for"):
            c2 = c2 + c1
    return c2


if __name__ == "__main__":
    s = "geeksforgeeksisforgeeks"
    n = len(s)
    print(countSubStr(s, n))

# Expected output:
3
# encrypt the given string with the following operations | python3 implementation of the above approach : ; function to return the encrypted string ; reduce x because rotation of length 26 is unnecessary ; calculate the frequency of characters ; if the frequency of current character is even then increment it by x ; else decrement it by x ; return the count ; 

MAX = 26


def encryptstrr(strr, n, x):
    x = x % MAX
    arr = list(strr)
    freq = [0] * MAX
    for i in range(n):
        freq[ord(arr[i]) - ord('a')] += 1
    for i in range(n):
        if (freq[ord(arr[i]) - ord('a')] % 2 == 0):
            pos = (ord(arr[i]) - ord('a') + x) % MAX
            arr[i] = chr(pos + ord('a'))
        else:
            pos = (ord(arr[i]) - ord('a') - x)
            if (pos < 0):
                pos += MAX
            arr[i] = chr(pos + ord('a'))
    return "".join(arr)


s = "abcda"
n = len(s)
x = 3
print(encryptstrr(s, n, x))

# Expected output:
dyzad
# rearrange characters in a string such that no two adjacent are same using hashing | function that returns true if it is possible to rearrange the characters of the string such that no two consecutive characters are same ; to store the frequency of each of the character ; to store the maximum frequency so far ; if possible ; 
def isPossible(Str):
    freq = dict()
    max_freq = 0
    for j in range(len(Str)):
        freq[Str[j]] = freq .get(Str[j], 0) + 1
        if (freq[Str[j]] > max_freq):
            max_freq = freq[Str[j]]
    if (max_freq <= (len(Str) - max_freq + 1)):
        return True
    return False


Str = "geeksforgeeks"
if (isPossible(Str)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# find uncommon characters of the two strings | set 2 | function to print the uncommon characters in the given string in sorted order ; converting character to ascii code ; bit operation ; converting character to ascii code ; bit operation ; xor operation leaves only uncommon characters in the ans variable ; 
def printUncommon(str1, str2):
    a1 = 0
    a2 = 0
    for i in range(len(str1)):
        ch = ord(str1[i]) - ord('a')
        a1 = a1 | (1 << ch)
    for i in range(len(str2)):
        ch = ord(str2[i]) - ord('a')
        a2 = a2 | (1 << ch)
    ans = a1 ^ a2
    i = 0
    while (i < 26):
        if (ans % 2 == 1):
            print(chr(ord('a') + i), end="")
        ans = ans // 2
        i += 1


if __name__ == "__main__":
    str1 = "geeksforgeeks"
    str2 = "geeksquiz"
    printUncommon(str1, str2)

# Expected output:
fioqruz
# minimum number of bracket reversals needed to make an expression balanced | set | returns count of minimum reversals for making expr balanced . returns - 1 if expr cannot be balanced . ; length of expression must be even to make it balanced by using reversals . ; to store number of reversals required . ; to store number of unbalanced opening brackets . ; to store number of unbalanced closing brackets . ; if current bracket is open then increment open count . ; if current bracket is close , check if it balances opening bracket . if yes then decrement count of unbalanced opening bracket else increment count of closing bracket . ; for the case : " " or when one closing and one opening bracket remains for pairing , then both need to be reversed . ; 
def countMinReversals(expr):
    length = len(expr)
    if length % 2:
        return -1
    ans = 0
    open = 0
    close = 0
    for i in range(0, length):
        if expr[i] == "":
            open += 1
        else:
            if not open:
                close += 1
            else:
                open -= 1
    ans = (close // 2) + (open // 2)
    close %= 2
    open %= 2
    if close > 0:
        ans += 2
    return ans


if __name__ == "__main__":
    expr = "}}{{"
    print(countMinReversals(expr))

# Expected output:
2
# character pairs from two strings with even sum | function to return the total number of valid pairs ; count total number of even and odd ascii values for string s1 ; count total number of even and odd ascii values for string s2 ; return total valid pairs ; 
def totalPairs(s1, s2):
    a1 = 0
    b1 = 0
    for i in range(len(s1)):
        if (ord(s1[i]) % 2 != 0):
            a1 += 1
        else:
            b1 += 1
    a2 = 0
    b2 = 0
    for i in range(len(s2)):
        if (ord(s2[i]) % 2 != 0):
            a2 += 1
        else:
            b2 += 1
    return ((a1 * a2) + (b1 * b2))


if __name__ == "__main__":
    s1 = "geeks"
    s2 = "for"
    print(totalPairs(s1, s2))

# Expected output:
5
# maximum occurrence of prefix in the array | function to return the count of the required prefix ; find the frequency of first character of str1ing ; 
def prefixOccurrences(str1):
    c = str1[0]
    countc = 0
    for i in range(len(str1)):
        if (str1[i] == c):
            countc += 1
    return countc


str1 = "abbcdabbcd"
print(prefixOccurrences(str1))

# Expected output:
2
# minimum number of given operations required to convert a string to another string | function to return the minimum operations of the given type required to convert string s to string t ; characters are already equal ; increment count of 0 s ; increment count of 1 s ; 
def minOperations(s, t, n):
    ct0 = 0
    ct1 = 0
    for i in range(n):
        if (s[i] == t[i]):
            continue
        if (s[i] == '0'):
            ct0 += 1
        else:
            ct1 += 1
    return max(ct0, ct1)


if __name__ == "__main__":
    s = "010"
    t = "101"
    n = len(s)
    print(minOperations(s, t, n))

# Expected output:
2
# decrypt a string encrypted by repeating i | function to return the decrypted string ; initial jump will be 1 ; increment jump by 1 with every character ; 
def decryptString(str, n):
    i = 0
    jump = 1
    decryptedStr = ""
    while (i < n):
        decryptedStr += str[i]
        i += jump
        jump += 1
    return decryptedStr


if __name__ == '__main__':
    str = "geeeeekkkksssss"
    n = len(str)
    print(decryptString(str, n))

# Expected output:
geeks
# find bit whose minimum sequence flips makes all bits same | function to check which bit is to be flipped ; variable to store first and last character of string ; check if first and last characters are equal , if yes , then return the character which is not at last ; else return last ; 
def bitToBeFlipped(s):
    last = s[len(s) - 1]
    first = s[0]
    if (last == first):
        if (last == '0'):
            return '1'
        else:
            return '0'
    elif (last != first):
        return last


if __name__ == "__main__":
    s = "1101011000"
    print(bitToBeFlipped(s))

# Expected output:
0
# sum and product of prime frequencies of characters in a string | function to create sieve to check primes ; false here indicates that it is not prime ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p , set them to non - prime ; function to find the sum of prime frequencies of the characters of the given string ; map is used to store character frequencies ; traverse the map ; if the frequency is prime ; 
def SieveofEratosthenes(prime, p_size):
    prime[0] = False
    prime[1] = False
    for p in range(2, p_size + 1):
        if prime[p]:
            for i in range(p * 2, p_size + 1, p):
                prime[i] = False


def sumProdOfPrimeFreq(s):
    prime = [True] * (len(s) + 2)
    SieveofEratosthenes(prime, len(s) + 1)
    i = 0
    j = 0
    m = dict()
    for i in range(len(s)):
        m[s[i]] = (m[s[i]] + 1)if s[i] in m else 1
    s = 0
    product = 1
    for it in m:
        if prime[m[it]]:
            s += m[it]
            product *= m[it]
    print("Sum =", s)
    print("Product =", product)


if __name__ == "__main__":
    s = "geeksforgeeks"
    sumProdOfPrimeFreq(s)

# Expected output:
Sum = 6
Product = 8