giulio98/xlcost-single-prompt huggingface dataset:
# queries to calculate difference between the frequencies of the most and least occurring characters in specified substring | python3 program for the above approach ; function to update frequency of a character in fenwick tree ; update frequency of ( idx + ' a ' ) ; update i ; function to find the frequency of a character ( idx + ' a ' ) in range [ 1 , i ] ; stores frequency of character , ( idx + ' a ' ) in range [ 1 , i ] ; update ans ; update i ; function to find difference between maximum and minimum frequency of a character in given range ; bit [ i ] [ j ] : stores frequency of ( i + ' a ' ) if j is a power of 2 , then it stores the frequency ( i + ' a ' ) of from [ 1 ] [ j ] ; stores length of string ; iterate over the characters of the string ; update the frequency of s [ i ] in fenwick tree ; stores count of queries ; iterate over all the queries ; stores maximum frequency of a character in range [ l , r ] ; stores minimum frequency of a character in range [ l , r ] ; iterate over all possible characters ; stores frequency of ( j + ' a ' ) in range [ 1 , r ] ; stores frequency of ( j + ' a ' ) in range [ 1 , l - 1 ] ; update mx ; if a character ( i + ' a ' ) present in range [ l , r ] ; update mn ; print the difference between max and min freq ; given string ; 

import sys


def update(BIT, idx, i, val):
    while (i < 10005):
        BIT[idx][i] += val
        i = i + (i & (-i))


def query(BIT, idx, i):
    ans = 0
    while (i > 0):
        ans += BIT[idx][i]
        i = i - (i & (-i))

    return ans


def maxDiffFreq(s, queries):
    BIT = [[0 for i in range(10005)] for j in range(26)]
    n = len(s)
    for i in range(n):
        update(BIT, ord(s[i]) - ord('a'), i + 1, 1)
    Q = len(queries)
    for i in range(Q):
        mx = 0
        mn = sys.maxsize
        l = queries[i][0]
        r = queries[i][1]
        for j in range(26):
            p = query(BIT, j, r)
            q = query(BIT, j, l - 1)
            mx = max(mx, p - q)
            if (p > 0):
                mn = min(mn, p - q)
        print(mx - mn)


S = "abaabac"
queries = [[2, 6], [1, 7]]
maxDiffFreq(S, queries)

# Expected output:
1
3
# make all strings from a given array equal by replacing minimum number of characters | function to find the minimum count of operations required to make all strings equal by replacing characters of strings ; stores minimum count of operations required to make all strings equal ; stores length of the string ; hash [ i ] [ j ] : stores frequency of character i present at j - th index of all strings ; traverse the array arr ; iterate over characters of current string ; update frequency of arr [ i ] [ j ] ; traverse hash array ; stores sum of i - th column ; stores the largest element of i - th column ; iterate over all possible characters ; update sum ; update max ; update cntminop ; 
def minOperation(arr, N):
    cntMinOP = 0
    M = len(arr[0])
    hash = [[0 for i in range(M)]for j in range(256)]
    for i in range(N):
        for j in range(M):
            hash[ord(arr[i][j])][j] += 1
    for i in range(M):
        Sum = 0
        Max = 0
        for j in range(256):
            Sum += hash[j][i]
            Max = max(Max, hash[j][i])
        cntMinOP += (Sum - Max)
    return cntMinOP


if __name__ == '__main__':
    arr = ["abcd", "bcde", "cdef"]
    N = len(arr)
    print(minOperation(arr, N))

# Expected output:
8
# maximize count of distinct strings generated by replacing similar adjacent digits having sum k with k | function to find the desired number of strings ; store the count of strings ; store the length of the string ; initialize variable to indicate the start of the substring ;  ; traverse the string ; if sum of adjacent characters is k mark the starting index and set flag to 1 ; if sum of adjacent characters is not k and the flag variable is set , end the substring here ; set flag to 0 denoting the end of substring ; check if the length of the substring formed is odd ; update the answer ; if flag is set and end of string is reached , mark the end of substring ; update the answer ; print the answer ; 
def countStrings(s, k):
    ans = 1
    lenn = len(s)
    flag = 0
    for i in range(lenn - 1):
        if (ord(s[i]) - ord('0') + ord(s[i + 1]) -
                ord('0') == k and flag == 0):
            flag = 1
            start_ind = i
        if (flag == 1 and ord(s[i]) - ord('0') +
                ord(s[i + 1]) - ord('0') != k):
            flag = 0
            if ((i - start_ind + 1) % 2 != 0):
                ans *= (i - start_ind + 1 - 1) // 2 + 1
    if (flag == 1 and (lenn - start_ind) % 2 != 0):
        ans *= (lenn - start_ind)//2 + 1
    print(ans)


S = "313"
K = 4
countStrings(S, K)

# Expected output:
2
# smallest number whose product with n has sum of digits equal to that of n | function to find the minimum integer having sum of digits of a number multiplied by n equal to sum of digits of n ; initialize answer ; convert string to character array ; find sum of digits of n ; multiply n with x ; sum of digits of the new number ; if condition satisfies ; print answer ; 
def find_num(n):
    ans = 0
    digitsOfN = str(n)
    sumOfDigitsN = 0
    for c in digitsOfN:
        sumOfDigitsN += int(c)
    for x in range(11, 50):
        newNum = x * int(n)
        tempSumDigits = 0
        temp = str(newNum)
        for c in temp:
            tempSumDigits += int(c)
        if (tempSumDigits == sumOfDigitsN):
            ans = x
            break
    print(ans)


if __name__ == '__main__':
    N = "3029"
    find_num(N)

# Expected output:
37
# reverse substrings of given string according to specified array indices | function to perform the reversal operation on the given string ; size of string ; stores the count of indices ; count the positions where reversals will begin ; store the count of reversals beginning at position i ; check if the count [ i ] is odd the swap the character ; return the updated string ; 
def modifyString(A, str, K):
    N = len(str)
    count = [0] * (N + 1)
    for i in range(K):
        count[A[i]] += 1
    for i in range(1, N // 2 + 1):
        count[i] = count[i] + count[i - 1]
        if (count[i] & 1):
            str[i - 1], str[N - i] = str[N - i], str[i - 1]
    return "".join(str)


if __name__ == '__main__':
    str1 = "abcdef"
    str = [i for i in str1]
    arr = [1, 2, 3]
    K = len(arr)
    print(modifyString(arr, str, K))

# Expected output:
fbdcea
# convert given float value to equivalent fraction | python3 program for the above approach ; function to convert the floating values into fraction ; initialize variables ; traverse the floating string ; check if decimal part exist ; check if recurrence sequence exist ; retrieve decimal part and recurrence resquence ; traverse the string ; convert to integer ; if no recurrence sequence exist ; initialize numerator & denominator ; no reccuring term ; print the result ; if reccuring term exist ; convert reccuring term to integer ; reccu . size ( ) is num of digit in reccur term ; eq 2 - eq 1 ; print the result ; 

from math import gcd


def findFraction(s):
    be_deci = ""
    af_deci = ""
    reccu = ""
    x = True
    y = False
    z = False
    for i in range(len(s)):
        if (s[i] == '.'):
            x = False
            y = True
            continue
        if (s[i] == '('):
            z = True
            y = False
            continue
        if (x):
            be_deci += s[i]
        if (y):
            af_deci += s[i]
        if (z):
            while i < len(s) and s[i] != ')':
                reccu += s[i]
                i += 1
            break
    num_be_deci = int(be_deci)
    num_af_deci = 0
    if len(af_deci) != 0:
        num_af_deci = int(af_deci)
    numr = (num_be_deci * pow(10, len(af_deci)) + num_af_deci)
    deno = pow(10, len(af_deci))
    if len(reccu) == 0:
        gd = gcd(numr, deno)
        print(numr // gd, "/", deno // gd)
    else:
        reccu_num = int(reccu)
        numr1 = (numr * pow(10, len(reccu)) + reccu_num)
        deno1 = deno * pow(10, len(reccu))
        res_numr = numr1 - numr
        res_deno = deno1 - deno
        gd = gcd(res_numr, res_deno)
        print(res_numr // gd, " / ", res_deno // gd)


if __name__ == '__main__':
    str = "23.98(231)"
    findFraction(str)

# Expected output:
798611  /  33300
# lexicographically largest string possible for a given cost of appending characters | function to find the lexicographically largest string possible ; if sum is less than 0 ; if sum is equal to 0 ; if sum is less than 0 ; add current character ; check if selecting current character generates lexicographically largest string ; backtrack if solution not found ; find the lexicographically largest string excluding the current character ; function to print the lexicographically largest string generated ; function call ; stores the string ; print the lexicographically largest string formed ; 
def lexi_largest_string(a, i, sum, v):
    if (sum < 0):
        return False
    if (sum == 0):
        return True
    if (i < 0):
        return False
    v .append(i)
    if (lexi_largest_string(a, i, sum - a[i], v)):
        return True
    v .pop(-1)
    return lexi_largest_string(a, i - 1, sum, v)


def generateString(a, sum):
    v = []
    lexi_largest_string(a, 25, sum, v)
    s = ""
    for j in range(len(v)):
        s += chr(v[j] + ord('a'))
    print(s)


if __name__ == '__main__':
    a = [1, 1, 2, 33, 4, 6, 9, 7, 36, 32, 58, 32, 28, 904,
         22, 255, 47, 69, 558, 544, 21, 36, 48, 85, 48, 58]
    sum = 236
    generateString(a, sum)

# Expected output:
zzzze
# count of distinct permutations of every possible length of given string | function to find the factorial of a number ; loop to find the factorial of the given number ; function to find the number of permutations possible for a given string ; function to find the total number of combinations possible ; 
def fact(a):
    f = 1
    for i in range(2, a + 1):
        f = f * i
    return f


def permute(n, r):
    ans = 0
    ans = fact(n) // fact(n - r)
    return ans


def findPermutations(n):
    sum = 0
    for r in range(1, n + 1):
        P = permute(n, r)
        sum = sum + P
    return sum


str = "xz"
n = len(str)
print(findPermutations(n))

# Expected output:
4
# Cycles of length n in an undirected and connected graph | Number of vertices ; mark the vertex vert as visited ; if the path of length ( n - 1 ) is found ; mark vert as un - visited to make it usable again . ; Check if vertex vert can end with vertex start ; For searching every possible path of length ( n - 1 ) ; DFS for searching path by decreasing length by 1 ; marking vert as unvisited to make it usable again . ; Counts cycles of length N in an undirected and connected graph . ; all vertex are marked un - visited initially . ; Searching for cycle by using v - n + 1 vertices ; ith vertex is marked as visited and will not be visited again . ; main :

V = 5


def DFS(graph, marked, n, vert, start, count):
    marked[vert] = True
    if n == 0:
        marked[vert] = False
        if graph[vert][start] == 1:
            count = count + 1
            return count
        else:
            return count
    for i in range(V):
        if marked[i] == False and graph[vert][i] == 1:
            count = DFS(graph, marked, n - 1, i, start, count)
    marked[vert] = False
    return count


def countCycles(graph, n):
    marked = [False] * V
    count = 0
    for i in range(V - (n - 1)):
        count = DFS(graph, marked, n - 1, i, i, count)
        marked[i] = True
    return int(count / 2)


graph = [[0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [
    0, 1, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 1, 0]]
n = 4
print("Total cycles of length ", n, " are ", countCycles(graph, n))

# Expected output:
Total cycles of length  4  are  3
# string hashing using polynomial rolling hash function | function to calculate the hash of a string ; p and m ; loop to calculate the hash value by iterating over the elements of string ; 
def polynomialRollingHash(str):
    p = 31
    m = 1e9 + 9
    power_of_p = 1
    hash_val = 0
    for i in range(len(str)):
        hash_val = ((hash_val + (ord(str[i]) - ord('a') + 1) * power_of_p) % m)
        power_of_p = (power_of_p * p) % m
    return int(hash_val)


if __name__ == '__main__':
    str1 = "geeksforgeeks"
    print("Hash of '{}' = {}".format(str1, polynomialRollingHash(str1)))

# Expected output:
Hash of 'geeksforgeeks' = 111226362
# find first non | python3 implementation to find the first non - repeating element of the string using linked list ; function to find the first non - repeating element of the given string using linked list ; 

import collections


def firstNonRepElement(str):
    list = collections.deque()

    list.append(str[0])

    for i in range(len(str)):
        if str[i] in list:
            list.remove(str[i])
        else:
            list.append(str[i])

    print(list[0])


if __name__ == '__main__':

    str = "geeksforgeeks"
    firstNonRepElement(str)

# Expected output:
f
# dfa that begins with ' a ' but does not contain substring ' aab ' | function for state a transition ; if at index 0 ' a ' if found then call stateb function with passing n [ 1 : ] to it ; if at index 0 ' b ' if found then call stateq function with passing n to it ; function for state b transition ; length of string become 0 then print accepted ; if at index 0 ' a ' if found then call statec function with passing n [ 1 : ] to it ; if at index 0 ' b ' if found then call stated function with passing n [ 1 : ] to it ; function for state c transition ; length of string become 0 then print accepted ; if at index 0 ' a ' if found then call statec function with passing n [ 1 : ] to it ; if at index 0 ' b ' if found then call stateq function with passing n to it ; function for state d transition ; length of string become 0 then print accepted ; if at index 0 ' a ' if found then call stateb function with passing n [ 1 : ] to it ; if at index 0 ' b ' if found then call stated function with passing n [ 1 : ] to it ; function for state q transition ; in dead state it shows string not accepted ; take string input ; call statea to check the 
def stateA(n):
    if (n[0] == 'a'):
        stateB(n[1:])
    else:
        stateQ(n)


def stateB(n):
    if (len(n) == 0):
        print("Accepted")
    else:
        if (n[0] == 'a'):
            stateC(n[1:])
        else:
            stateD(n[1:])


def stateC(n):
    if (len(n) == 0):
        print("Accepted")
    else:
        if (n[0] == 'a'):
            stateC(n[1:])
        else:
            stateQ(n)


def stateD(n):
    if (len(n) == 0):
        print("Accepted")
    else:
        if (n[0] == 'a'):
            stateB(n[1:])
        else:
            stateD(n[1:])


def stateQ(n):
    print("Not Accepted")


n = "aaaba"
stateA(n)

# Expected output:
Not Accepted
# count of substrings of length k with exactly k distinct characters | function to return the required count of substrings ; store the count ; store the count of distinct characters in every window ; store the frequency of the first k length substring ; increase frequency of i - th character ; if k distinct characters exist ; traverse the rest of the substring ; increase the frequency of the last character of the current substring ; decrease the frequency of the first character of the previous substring ; if the character is not present in the current substring ; if the count of distinct characters is 0 ; return the count ; 
def countSubstrings(str, K):
    N = len(str)
    answer = 0
    map = {}
    for i in range(K):
        map[str[i]] = map .get(str[i], 0) + 1
    if (len(map) == K):
        answer += 1
    for i in range(K, N):
        map[str[i]] = map .get(str[i], 0) + 1
        map[str[i - K]] -= 1
        if (map[str[i - K]] == 0):
            del map[str[i - K]]
        if (len(map) == K):
            answer += 1
    return answer


if __name__ == '__main__':
    str = "aabcdabbcdc"
    K = 3
    print(countSubstrings(str, K))

# Expected output:
5
# check if a string is a scrambled form of another string | declaring unordered map globally ; python3 program to check if a given string is a scrambled form of another string ; strings of non - equal length cant ' be scramble strings ; empty strings are scramble strings ; equal strings are scramble strings ; check for the condition of anagram ;  ; checking if both substrings are in map or are already calculated or not ; declaring a flag variable ; check if s2 [ 0. . . i ] is a scrambled string of s1 [ 0. . . i ] and if s2 [ i + 1. . . n ] is a scrambled string of s1 [ i + 1. . . n ] ; check if s2 [ 0. . . i ] is a scrambled string of s1 [ n - i ... n ] and s2 [ i + 1. . . n ] is a scramble string of s1 [ 0. . . n - i - 1 ] ; storing calculated value to map ; if none of the above conditions are satisfied ; 

map = {}


def isScramble(S1: str, S2: str):
    if len(S1) != len(S2):
        return False
    n = len(S1)
    if not n:
        return True
    if S1 == S2:
        return True
    if sorted(S1) != sorted(S2):
        return False
    if (S1 + ' ' + S2 in map):
        return map[S1 + ' ' + S2]
    flag = False
    for i in range(1, n):
        if (isScramble(S1[:i], S2[:i]) and isScramble(S1[i:], S2[i:])):
            flag = True
            return True
        if (isScramble(S1[-i:], S2[:i]) and isScramble(S1[:-i], S2[i:])):
            flag = True
            return True
    map[S1 + " "+S2] = flag
    return False


if __name__ == "__main__":
    S1 = "great"
    S2 = "rgate"
    if (isScramble(S1, S2)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# print the longest palindromic prefix of a given string | function to find the longest prefix which is palindrome ; find the length of the given string ; for storing the length of longest prefix palindrome ; loop to check the substring of all length from 1 to n which is palindrome ; string of length i ; to store the value of temp ; reversing the value of temp ; if string temp is palindromic then update the length ; print the palindromic string of max_len ; 
def LongestPalindromicPrefix(string):
    n = len(string)
    max_len = 0
    for length in range(0, n + 1):
        temp = string[0:length]
        temp2 = temp
        temp3 = temp2[::-1]
        if temp == temp3:
            max_len = length
    print(string[0:max_len])


if __name__ == '__main__':
    string = "abaac"
    LongestPalindromicPrefix(string)

# Expected output:
aba
# k | python program to find the k - th lexicographical string of length n ; initialize the array to store the base 26 representation of k with all zeroes , that is , the initial string consists of n a 's ; start filling all the n slots for the base 26 representation of k ; store the remainder ; reduce k ; if k is greater than the possible number of strings that can be represented by a string of length n ; store the kth lexicographical string ; 
def find_kth_string_of_n(n, k):
    d = [0 for i in range(n)]
    for i in range(n - 1, -1, -1):
        d[i] = k % 26
        k //= 26
    if k > 0:
        return -1
    s = ""
    for i in range(n):
        s += chr(d[i] + ord('a'))
    return s


n = 3
k = 10
k -= 1
print(find_kth_string_of_n(n, k))

# Expected output:
aaj
# length of the smallest substring which contains all vowels | python3 program to find the length of the smallest substring of which contains all vowels ; map to store the frequency of vowels ; store the indices which contains the vowels ; if all vowels are not present in the string ; if the frequency of the vowel at i - th index exceeds 1 ; decrease the frequency of that vowel ; move to the left ; otherwise set flag1 ; if the frequency of the vowel at j - th index exceeds 1 ; decrease the frequency of that vowel ; move to the right ; otherwise set flag2 ; if both flag1 and flag2 are set , break out of the loop as the substring length cannot be minimized ; return the length of the substring ; 

from collections import defaultdict


def findMinLength(s):

    n = len(s)
    counts = defaultdict(int)
    indices = []

    for i in range(n):

        if (s[i] == 'a' or s[i] == 'e' or
            s[i] == 'o' or s[i] == 'i' or
                s[i] == 'u'):

            counts[s[i]] += 1
            indices.append(i)
    if len(counts) < 5:
        return -1

    flag1 = 0
    flag2 = 0
    i = 0
    j = len(indices) - 1

    while (j - i) >= 4:
        if (~flag1 and
                counts[s[indices[i]]] > 1):
            counts[s[indices[i]]] -= 1
            i += 1
        else:
            flag1 = 1
        if (~flag2 and
                counts[s[indices[j]]] > 1):
            counts[s[indices[j]]] -= 1
            j -= 1
        else:
            flag2 = 1
        if (flag1 and flag2):
            break
    return (indices[j] - indices[i] + 1)


s = "aaeebbeaccaaoiuooooooooiuu"
print(findMinLength(s))

# Expected output:
9
# longest subsequence of a string containing only consonants | returns true if x is consonants . ; '' function to check whether a character  is consonants or not  ; function to find the longest subsequence which contain all consonants ; 
def isComsomamts(x):
    x = x .lower()
    return not (x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u')


def longestConsonantsSubsequence(s):
    answer = ''
    n = len(s)
    for i in range(n):
        if isComsomamts(s[i]):
            answer += s[i]
    return answer


s = 'geeksforgeeks'
print(longestConsonantsSubsequence(s))

# Expected output:
gksfrgks
# find the length of the longest subsequence with first k alphabets having same frequency | python3 program to find the longest subsequence with first k alphabets having same frequency ; function to return the length of the longest subsequence with first k alphabets having same frequency ; map to store frequency of all characters in the string ; variable to store the frequency of the least frequent of first k alphabets ; 

from collections import defaultdict


def lengthOfSubsequence(st, K):
    mp = defaultdict(int)
    for ch in st:
        mp[ch] += 1
    minimum = mp['A']
    for i in range(1, K):
        minimum = min(minimum, mp[chr(i + ord('A'))])
    return (minimum * K)


if __name__ == "__main__":
    st = "ACAABCCAB"
    K = 3
    print(lengthOfSubsequence(st, K))

# Expected output:
6
# detecting negative cycle using floyd warshall | number of vertices in the graph ; define infinite as a large enough value . this value will be used for vertices not connected to each other ; returns true if graph has negative weight cycle else false . ; dist [ ] [ ] will be the output matrix that will finally have the shortest distances between every pair of vertices ; initialize the solution matrix same as 

V = 4
INF = 99999


def negCyclefloydWarshall(graph):
    dist = [[0 for i in range(V + 1)]for j in range(V + 1)]
    for i in range(V):
        for j in range(V):
            dist[i][j] = graph[i][j]
    for k in range(V):
        for i in range(V):
            for j in range(V):
                if (dist[i][k] + dist[k][j] < dist[i][j]):
                    dist[i][j] = dist[i][k] + dist[k][j]
    for i in range(V):
        if (dist[i][i] < 0):
            return True
    return False


graph = [[0, 1, INF, INF], [INF, 0, -1, INF],
         [INF, INF, 0, -1], [-1, INF, INF, 0]]
if (negCyclefloydWarshall(graph)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes