giulio98/xlcost-single-prompt huggingface dataset:
# program to build a dfa to accept strings that start and end with same character | function for the state q1 ; condition to check end of string ; state transitions ' a ' takes to q1 , and ' b ' takes to q2 ; function for the state q2 ; condition to check end of string ; state transitions ' a ' takes to q1 , and ' b ' takes to q2 ; function for the state q3 ; condition to check end of string ; state transitions ' a ' takes to q4 , and ' b ' takes to q3 ; function for the state q4 ; condition to check end of string ; state transitions ' a ' takes to q4 , and ' b ' takes to q3 ; function for the state q0 ; condition to check end of string ; state transitions ' a ' takes to q1 , and ' b ' takes to q3 ; 
def q1(s, i):
    if (i == len(s)):
        print("Yes")
        return
    if (s[i] == 'a'):
        q1(s, i + 1)
    else:
        q2(s, i + 1)


def q2(s, i):
    if (i == len(s)):
        print("No")
        return
    if (s[i] == 'a'):
        q1(s, i + 1)
    else:
        q2(s, i + 1)


def q3(s, i):
    if (i == len(s)):
        print("Yes")
        return
    if (s[i] == 'a'):
        q4(s, i + 1)
    else:
        q3(s, i + 1)


def q4(s, i):
    if (i == s .length()):
        print("No")
        return
    if (s[i] == 'a'):
        q4(s, i + 1)
    else:
        q3(s, i + 1)


def q0(s, i):
    if (i == len(s)):
        print("No")
        return
    if (s[i] == 'a'):
        q1(s, i + 1)
    else:
        q3(s, i + 1)


if __name__ == '__main__':
    s = "abbaabb"
    q0(s, 0)

# Expected output:
No
# longest prefix in a string with highest frequency | function to find longest prefix string with the highest frequency ; storing all indices where first element is found ; if the first letter in the string does not occur again then answer will be the whole string ; loop till second appearance of the first element ; check one letter after every stored index ; if there is no mismatch we move forward ; otherwise we stop ; 
def prefix(string):
    k = 1
    n = len(string)
    g = []
    flag = 0
    for i in range(1, n):
        if (string[i] == string[0]):
            g .append(i)
            flag = 1
    if (flag == 0):
        print(string)
    else:
        length = len(g)
        while (k < g[0]):
            cnt = 0
            for j in range(length):
                if (string[g[j] + k] == string[k]):
                    cnt += 1
            if (cnt == len):
                k += 1
            else:
                break
        for i in range(k + 1):
            print(string[i], end="")
        print()


if __name__ == "__main__":
    string = "abcab"
    prefix(string)

# Expected output:
ab
# generate permutation of 1 to n such that absolute difference of consecutive numbers give k distinct integers | function to generate a permutation of integers from 1 to n such that the absolute difference of all the two consecutive integers give k distinct integers ; to store the permutation ; for sequence 1 2 3. . . ; for sequence n , n - 1 , n - 2. . . ; flag is used to alternate between the above if else statements ; if last element added was r + 1 ; if last element added was l - 1 ; print the permutation ; 
def printPermutation(N, K):
    res = list()
    l, r, flag = 1, N, 0
    for i in range(K):
        if not flag:
            res .append(l)
            l += 1
        else:
            res .append(r)
            r -= 1
        flag = flag ^ 1
    if not flag:
        for i in range(r, 2, -1):
            res .append(i)
    else:
        for i in range(l, r):
            res .append(i)
    for i in res:
        print(i, end=" ")


N, K = 10, 4
printPermutation(N, K)

# Expected output:
1 10 2 9 8 7 6 5 4 3
# find nth term of the series 1 , 8 , 54 , 384. . . | calculate factorial of n ; calculate nth term of series ; 
def fact(N):
    product = 1
    for i in range(1, N + 1):
        product = product * i
    return product


def nthTerm(N):
    return (N * N) * fact(N)


if __name__ == "__main__":
    N = 4
    print(nthTerm(N))

# Expected output:
384
# rabin | d is the number of characters in the input alphabet ; pat -> pattern txt -> text q -> a prime number ; hash value for pattern t = 0 hash value for txt ; the value of h would be " pow ( d , ▁ m - 1 ) % q " ; calculate the hash value of pattern and first window of text ; slide the pattern over text one by one ; check the hash values of current window of text and pattern if the hash values match then only check for characters on by one ; check for characters one by one ; if p == t and pat [ 0. . . m - 1 ] = txt [ i , i + 1 , ... i + m - 1 ] ; calculate hash value for next window of text : remove leading digit , add trailing digit ; we might get negative values of t , converting it to positive ; 

d = 256


def search(pat, txt, q):
    M = len(pat)
    N = len(txt)
    i = 0
    j = 0
    h = 1
    p = 0
    t = 0
    for i in range(M - 1):
        h = (h * d) % q
    for i in range(M):
        p = (d * p + ord(pat[i])) % q
        t = (d * t + ord(txt[i])) % q
    for i in range(N - M + 1):
        if p == t:
            for j in range(M):
                if txt[i + j] != pat[j]:
                    break
                else:
                    j += 1
            if j == M:
                print("Pattern found at index " + str(i))
        if i < N - M:
            t = (d * (t - ord(txt[i]) * h) + ord(txt[i + M])) % q
            if t < 0:
                t = t + q


txt = "GEEKS FOR GEEKS"
pat = "GEEK"
q = 101
search(pat, txt, q)

# Expected output:
Pattern found at index 0
Pattern found at index 10
# find the final string after flipping bits at the indices that are multiple of prime factors of array elements | python program for the above approach ; stores smallest prime factor ; function to find the smallest prime factor for every number till maxn ; marking smallest prime factor for every number to be itself ; separately marking spf for every even number as 2 ; checking if i is prime ; marking spf for all numbers divisible by i ; function to find all the distinct prime factors of the given number x ; find the prime factors for x ; find the spf [ ] of x ; return the prime factors for x ; function to find string after flipping the characters at indices of prime factors of array elements arr [ ] ; precalculating smallest prime factor ; stores the frequency of each prime factor ; iterate over all elements of the array arr [ ] ; stores prime factors of arr [ i ] ; increment the frequency of all prime factors of arr [ i ] ; iterate over all elements of the array frequency [ ] ; if frequency [ i ] is odd ; flip bits of all indices that are multiple of i ; return answer ; 

MAXN = 100001
spf = [0] * MAXN


def sieve():
    spf[1] = 1
    for i in range(2, MAXN):
        spf[i] = i
    for i in range(4, MAXN, 2):
        spf[i] = 2
    i = 3
    while (i * 8 < MAXN):
        i += 1
        if (spf[i] == i):
            for j in range(i * i, MAXN, i):
                if (spf[j] == j):
                    spf[j] = i


def getFactorization(x):
    ret = []
    while (x != 1):
        ret .append(spf[x])
        value = spf[x]
        while (x % value == 0):
            x = x // value
    return ret


def flipString(S, arr, M):
    sieve()
    frequency = [0] * MAXN
    for i in range(0, M):
        primeFactors = getFactorization(arr[i])
        for factors in primeFactors:
            frequency[factors] += 1
            frequency[factors] %= 2
    N = len(S)
    for i in range(0, MAXN):
        if (frequency[i] & 1):
            for j in range(i, N + 1, i):
                S[j - 1] = ('0'if S[j - 1] == '1'else '1')
    return S


S = "000000"
S = list(S)
arr = [2, 4, 6]
M = len(arr)
print("".join(flipString(S, arr, M)))

# Expected output:
011100
# check if count of 1 s can be made greater in a binary string by changing 0 s adjacent to 1 s | function to check whether in a given binary string can we make number of 1 ' s ▁ greater ▁ than ▁ the ▁ number ▁ of ▁ 0' s by doing the given operation ; stores the count of 0 's ; stores the count of 1 's ; traverse through the string s ; check current character is 1 ; update cnt1 ; update cnt0 ; traverse through the string s ; check curretn character is 1 ; check if left adjacent character is 0 ; change the left adjacent character to _ ; update the cnt0 ; check if right adjacent character is 0 ; change the right adjacent character to _ ; update the cnt0 ; check count of 1 ' s ▁ is ▁ greater ▁ ▁ than ▁ the ▁ count ▁ of ▁ 0' s ; 
def isOnesGreater(S, N):
    S = list(S)
    cnt0 = 0
    cnt1 = 0
    for i in range(N):
        if (S[i] == '1'):
            cnt1 += 1
        else:
            cnt0 += 1
    for i in range(N):
        if (S[i] == '1'):
            if (i > 0 and S[i - 1] == '0'):
                S[i - 1] = '_'
                cnt0 -= 1
            elif (i < N and S[i + 1] == '0'):
                S[i + 1] = '_'
                cnt0 -= 1
    if (cnt1 > cnt0):
        print("Yes")
    else:
        print("No")


S = "01"
N = len(S)
isOnesGreater(S, N)

# Expected output:
Yes
# minimize flips to make binary string as all 1 s by flipping characters in substring of size k repeatedly | function to find the minimum number of operations required to convert all the characters to 1 by flipping the substrings of size k ; stores the minimum number of operations required ; traverse the string s ; if the character is 0 ; flip the substrings of size k starting from i ; increment the minimum count of operations required ; after performing the operations check if string s contains any 0 s ; if s contains only 1 's ; 
def minOperation(St, K, N):
    S = list(St)
    min = 0
    i = 0
    for i in range(0, N):
        if (S[i] == '0' and i + K <= N):
            j = i
            while (j < i + K):
                if (S[j] == '1'):
                    S[j] = '0'
                else:
                    S[j] = '1'
                j += 1
            min += 1
    temp = 0
    for i in range(0, N):
        temp += 1
        if (S[i] == '0'):
            break
    if (temp == N):
        print(min)
    else:
        print(-1)


S = "00010110"
K = 3
N = len(S)
minOperation(S, K, N)

# Expected output:
3
# check if string s1 can be formed using repeated insertions of another string s2 | function to check a valid insertion ; store the size of string ; maintain a stack for characters ; iterate through the string ; push the current character on top of the stack ; if the current character is the last character of string s2 then pop characters until s2 is not formed ; index of last character of the string s2 ; pop characters till 0 - th index ; check if stack in non - empty ; 
def validInsertionstring(S1, S2):
    N = len(S1)
    M = len(S2)
    st = []
    for i in range(N):
        st .append(S1[i])
        if (S1[i] == S2[M - 1]):
            idx = M - 1
            while (idx >= 0):
                if (len(st) == 0):
                    return False
                c = st[-1]
                st .pop()
                if (c != S2[idx]):
                    return False
                idx -= 1
    if (len(st) != 0):
        return False
    else:
        return True


S1 = "aabb"
S2 = "ab"
if validInsertionstring(S1, S2):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check if rearranging array elements can form a palindrome or not | function to check whether elements of an array can form a palindrome ; create an empty string to append elements of an array ; append each element to the string str to form a string so that we can solve it in easy way ; create a freq array and initialize all values as 0 ; for each character in formed string , increment freq in the corresponding freq array ; count odd occurring characters ; return true if odd count is 0 or 1 , ; 
def can_form_palindrome(arr, n):
    MAX = 256
    s = ""
    for i in range(n):
        s = s + str(arr[i])
    freq = [0] * MAX
    for i in range(N):
        freq[arr[i]] = freq[arr[i]] + 1
    count = 0
    for i in range(MAX):
        if (freq[i] & 1):
            count = count + 1
        if (count > 1):
            return False
    return True


if __name__ == "__main__":
    arr = [1, 2, 3, 1, 2]
    N = len(arr)
    if (can_form_palindrome(arr, N)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# minimum number of flips to make a binary string increasing | function to find the minimum number of flips required to make string increasing ; length of s ; total number of zero in s ; stores count of 1 s till ith index ; stores the minimum count of flips ; traverse the given string s ; update the value of res and count of 1 s ; return the minimum number of flips ; 
def minimumFlips(s):
    n = len(s)
    cnt0 = s .count('0')
    cnt1 = 0
    res = n - cnt0
    for i in range(n):
        if s[i] == '0':
            cnt0 -= 1
        elif s[i] == '1':
            res = min(res, cnt1 + cnt0)
            cnt1 += 1
    return res


S = '000110'
print(minimumFlips(S))

# Expected output:
1
# maximum length of a substring required to be flipped repeatedly to make all characters of binary string equal to 0 | function to find the maximum value of k such that flipping substrings of size at least k make all characters 0 s ; stores the maximum value of k ; traverse the given string s ; store the minimum of the maximum of lhs and rhs length ; flip performed ; if no flips performed ; return the possible value of k ; 
def maximumK(S):
    N = len(S)
    ans = N
    flag = 0
    for i in range(N - 1):
        if (S[i] != S[i + 1]):
            flag = 1
            ans = min(ans, max(i + 1, N - i - 1))
    if (flag == 0):
        return 0
    return ans


if __name__ == '__main__':
    S = "010"
    print(maximumK(S))

# Expected output:
2
# check if a pair of strings exists that starts with and without the character k or not | function to check whether a pair of strings exists satisfying the conditions ; stores the visited strings ; iterate over the array arr [ ] ; if first character of current string is k ; otherwise ; adding to the visited ; 
def checkhappy(arr, K, N):
    visited = set()
    for s in arr:
        if (s[0] == K):
            if s[1:] in visited:
                return 'Yes'
        else:
            if (K + s) in visited:
                return 'Yes'
        visited .add(s)
    return "No"


if __name__ == '__main__':
    arr = ['a', '! a', 'b', '! c', 'd', '! d']
    K = '!'
    N = len(arr)
    print(checkhappy(arr, K, N))

# Expected output:
No
# minimum moves to make count of lowercase and uppercase letters equal | function to calculate minimum number of moves required to convert the string ; stores count of upper and lower case characters ; traverse the s ; if current character is uppercase ; increment count of uppercase characters ; otherwise , ; increment count of lowercase characters ; stores minimum number of moves needed ; if there are more upper case characters ; iterate until upper is greater than n / 2 ; convert uppercase into lowercase until upper = n / 2 ; increment the pointer ; if there are more lower case characters ; iterate until lower is greater than n / 2 ; convert lowercase into uppercase until lower = n / 2 ; increment the pointer ; print moves required ; print resultant string ; 
def minimumTimeToConvertString(S, N):
    S = [i for i in S]
    upper = 0
    lower = 0
    for i in range(N):
        c = S[i]
        if (c .isupper()):
            upper += 1
        else:
            lower += 1
    moves = 0
    if (upper > N // 2):
        i = 0
        while (upper > N // 2 and i < N):
            if (S[i].isupper()):
                S[i] += 32
                moves += 1
                upper -= 1
                lower += 1
            i += 1
    elif (lower > N // 2):
        i = 0
        while (lower > N // 2 and i < N):
            if (S[i].islower()):
                S[i] = chr(ord(S[i]) - 32)
                moves += 1
                upper += 1
                lower -= 1
            i += 1
    print(moves)
    print("".join(S))


if __name__ == '__main__':
    S = "AbcdEf"
    N = len(S)
    minimumTimeToConvertString(S, N)

# Expected output:
1
ABcdEf
# program to print a string in vertical zigzag manner | function to print any string in zigzag fashion ; store the gap between the major columns ; traverse through rows ; store the step value for each row ; iterate in the range [ 1 , n - 1 ] ; print the character ; print the spaces before character s [ j + step ] ; print the character ; print the spaces after character after s [ j + step ] ; print the spaces for first and last rows ; 
def zigzag(s, rows):
    interval = 2 * rows - 2
    for i in range(rows):
        step = interval - 2 * i
        for j in range(i, len(s), interval):
            print(s[j], end="")
            if (step > 0 and step < interval and step + j < len(s)):
                for k in range((interval - rows - i)):
                    print(end=" ")
                print(s[j + step], end="")
                for k in range(i - 1):
                    print(end=" ")
            else:
                for k in range(interval - rows):
                    print(end=" ")
        print()


if __name__ == '__main__':
    s = "123456789ABCDEFGHIJKL"
    rows = 9
    zigzag(s, rows)

# Expected output:
1       H       
2      GI       
3     F J       
4    E  K       
5   D   L       
6  C    
7 B     
8A      
9
# number of substrings with each character occurring even times | function to count substrings having even frequency of each character ; stores the count of a character ; stores bitmask ; stores the count of substrings with even count of each character ; traverse the string s ; flip the ord ( i ) - 97 bits in pre ; increment the count by hash [ pre ] ; increment count of pre in hash ; return the total count obtained ; 
def subString(s, n):
    hash = {0: 1}
    pre = 0
    count = 0
    for i in s:
        pre ^= (1 << ord(i) - 97)
        count += hash .get(pre, 0)
        hash[pre] = hash .get(pre, 0) + 1
    return count


S = "abbaa"
N = len(S)
print(subString(S, N))

# Expected output:
4
# rearrange characters of a string to make it a concatenation of palindromic substrings | function to check if a string can be modified such that it can be split into palindromic substrings of length >= 2 ; stores frequencies of characters ; traverse the string ; update frequency of each character ; traverse the frequency array ; update values of odd and eve ; print the result ; 
def canSplit(S):
    frequency = [0] * 26
    cnt_singles = 0
    k = 0
    for i in range(len(S)):
        frequency[ord(S[i]) - ord('a')] += 1
    odd = 0
    eve = 0
    for i in range(26):
        if (frequency[i]):
            odd += (frequency[i] & 1)
            eve += frequency[i] // 2
    if (eve >= odd):
        print("Yes")
    else:
        print("No")


if __name__ == "__main__":
    S = "aaabbbccc"
    canSplit(S)

# Expected output:
Yes
# smallest element in an array that is repeated exactly ' k ' times . | python program to find smallest number in array that is repeated exactly ' k ' times . ; computing frequencies of all elements ; finding the smallest element with frequency as k ; if frequency of any of the number is equal to k starting from 0 then return the number ; 

MAX = 1000


def findDuplicate(arr, n, k):
    freq = [0 for i in range(MAX)]
    for i in range(n):
        if (arr[i] < 1 and arr[i] > MAX):
            print("Out of range")
            return -1
        freq[arr[i]] += 1
    for i in range(MAX):
        if (freq[i] == k):
            return i
    return -1


arr = [2, 2, 1, 3, 1]
k = 2
n = len(arr)
print(findDuplicate(arr, n, k))

# Expected output:
1
# minimum removals required such that a string can be rearranged to form a palindrome | function to find the number of deletions required such that characters of the string can be rearranged to form a palindrome ; stores frequency of characters ; store the frequency of each character in frequency array ; count number of characters with odd frequency ; if count is 1 or 0 , return 0 ; otherwise , return count - 1 ; 
def minDeletions(str):
    fre = [0] * 26
    n = len(str)
    for i in range(n):
        fre[ord(str[i]) - ord('a')] += 1
    count = 0
    for i in range(26):
        if (fre[i] % 2):
            count += 1
    if (count == 0 or count == 1):
        return 0
    else:
        return count - 1


if __name__ == '__main__':
    str = "ababbccca"
    print(minDeletions(str))

# Expected output:
2
# calculate score of parentheses from a given string | function to calculate the score of the parentheses using stack ; to keep track of the score ; initially , push 0 to stack ; traverse the string s ; if ' ( ' is encountered , then push 0 to stack ; otherwise ; balance the last ' ( ' , and store the score of inner parentheses ; if tmp is not zero , it means inner parentheses exists ; otherwise , it means no inner parentheses exists ; pass the score of this level to parent parentheses ; print the score ; 
def scoreOfParentheses(s):
    stack = []
    stack .append(0)
    for c in s:
        if (c == '('):
            stack .append(0)
        else:
            tmp = stack[len(stack) - 1]
            stack = stack[:-1]
            val = 0
            if (tmp > 0):
                val = tmp * 2
            else:
                val = 1
            stack[len(stack) - 1] += val
    print(stack[len(stack) - 1])


if __name__ == '__main__':
    S = "(()(()))"
    scoreOfParentheses(S)

# Expected output:
6
# count unique substrings of a string s present in a wraparound string | function to find the count of non - empty substrings of p present in s ; stores the required answer ; stores the length of substring present in p ; stores the current length of substring that is present in string s starting from each character of p ; iterate over the characters of the string ; check if the current character can be added with previous substring to form the required substring ; increment current length ; to avoid repetition ; update arr [ cur ] ; print the answer ; 
def findSubstringInWraproundString(p):
    ans = 0
    curLen = 0
    arr = [0] * 26
    for i in range(0, len(p)):
        curr = ord(p[i]) - ord('a')
        if (i > 0 and (ord(p[i - 1]) != ((curr + 26 - 1) % 26 + ord('a')))):
            curLen = 0
        curLen += 1
        if (curLen > arr[curr]):
            ans += (curLen - arr[curr])
            arr[curr] = curLen
    print(ans)


p = "zab"
findSubstringInWraproundString(p)

# Expected output:
6
# minimize sum of given array by removing all occurrences of a single digit | function to remove each digit from the given integer ; convert into string ; stores final string ; traverse the string ; append it to the final string ; return integer value ; function to find the minimum sum by removing occurences of each digit ; iterate in range [ 0 , 9 ] ; traverse the array ; update the minimum sum ; print the minimized sum ; 
def remove(N, digit):
    strN = str(N)
    ans = ''
    for i in strN:
        if int(i) == digit:
            continue
        ans += i
    return int(ans)


def getMin(arr):
    minSum = float('inf')
    for i in range(10):
        curSum = 0
        for num in arr:
            curSum += remove(num, i)
        minSum = min(minSum, curSum)
    print(minSum)


arr = [34, 23, 85, 93]
getMin(arr)

# Expected output:
100