giulio98/xlcost-single-prompt huggingface dataset:
# minimum number of removals required such that no subsequence of length 2 occurs more than once | function to remove the minimum count of characters from the string such that no subsequence of length 2 repeats ; initialize the final string ; stores if any character occurs in the final string or not ; store the index of the last character added in the string ; traverse the string ; add all the unique characters ; check if s [ 0 ] appears in the range [ pos + 1 , n - 1 ] ; if the characters are the same ; print the resultant string ; 
def RemoveCharacters(s):
    ans = ""
    c = [0 for i in range(26)]
    pos = 0
    for i in range(len(s)):
        if (c[ord(s[i]) - 97] == 0):
            c[ord(s[i]) - 97] = 1
            pos = i
            ans += s[i]
    for i in range(pos + 1, len(s), 1):
        if (s[i] == s[0]):
            ans += s[i]
            break
    print(ans)


if __name__ == '__main__':
    S = "abcaadbcd"
    RemoveCharacters(S)

# Expected output:
abcd
# check if a numeric string can be split into substrings having difference between consecutive numbers equal to k | function to check if a numeric string can be split into substrings such that the difference between the consecutive substrings is k ; stores the size of the string ; iterate over the range [ 1 , n ] and try each possible starting number ; convert the number to string ; build up a sequence starting with the number ; compare it with the original string s ; print the result ; 
def isPossible(s, K):
    valid = False
    firstx = -1
    n = len(s)
    for i in range(1, n // 2 + 1, 1):
        x = int(s[0:i])
        firstx = x
        test = str(x)
        while (len(test) < len(s)):
            x -= K
            test += str(x)
        if (test == s):
            valid = True
            break
    print("Yes")if valid else print("No")


if __name__ == '__main__':
    S = "8642"
    K = 2
    isPossible(S, K)

# Expected output:
Yes
# convert given binary string s to all 1 s by changing all 0 s to 1 s in range [ i + 1 , i + k ] if s [ i ] is 1 | function to check whether all 0 s in the string can be changed into 1 s ; store the count of 0 s converted for the last occurrence of 1 ; declere a stack ; traverse the string , s ; if stack is empty ; there is no 1 that can change this 0 to 1 ; push 1 into the stack ; the last 1 has reached its limit ; new 1 has been found which can now change at most k 0 s ; if flag is 1 , pr " yes " else pr " no " ; 
def changeCharacters(S, N, K):
    flag = 1
    count = 0
    st = []
    for i in range(N):
        if len(st) == 0:
            if (S[i] == '0'):
                flag = 0
                break
            count = 0
            st .append(S[i])
        else:
            if (S[i] == '0'):
                count += 1
                if (count == K):
                    del st[-1]
                    count = 0
            else:
                count = 0
    if (flag):
        print("YES")
    else:
        print("NO")


if __name__ == '__main__':
    S = "100100"
    N = len(S)
    K = 2
    changeCharacters(S, N, K)

# Expected output:
YES
# check if all prefixes of a number is divisible by remaining count of digits | function to check if all prefixes of a number is divisible by remaining count of digits or not ; traverse and check divisibility for each updated number ; update the original number ; 
def prefixDivisble(n):
    i = 1
    while n > 0:
        if n % i != 0:
            return False
        n = n // 10
        i += 1
    return True


n = 52248
if (prefixDivisble(n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# length of the longest substring that contains even number of vowels | function to find the length of the longest substring having even number of vowels ; create two hashmaps ; keep the track of frequencies of the vowels ; stores the maximum length ; traverse the given string s ; if it is a vowel , then update the frequency ; find the index of occurence of the string evenodd in map ; update the maximum length ; print the maximum length ; 
def longestSubstring(s):
    indexes = {}
    chars = {}
    chars['a'] = 0
    chars['e'] = 1
    chars['i'] = 2
    chars['o'] = 3
    chars['u'] = 4
    evenOdd = "00000"
    evenOdd = [i for i in evenOdd]
    indexes["".join(evenOdd)] = -1
    length = 0
    for i in range(len(s)):
        c = s[i]
        if (c in chars):
            evenOdd[chars[it]] = '1'if evenOdd[chars[it]]else '0'
        if ("".join(evenOdd)not in indexes):
            indexes["".join(evenOdd)] = i
        else:
            length = max(length, i - indexes["".join(evenOdd)])
    print(length)


if __name__ == '__main__':
    S = "bcbcbc"
    longestSubstring(S)

# Expected output:
6
# minimum number whose binary form is not a subsequence of given binary string | function to check if string str1 is a subsequence of string str2 ; store index of str1 ; traverse str2 and str1 , and compare current character of str2 with first unmatched char of str1 ; if matched , move ahead in str1 ; if all characters of str1 were found in str2 ; function to find the minimum number which is not a subsequence of the given binary string in its binary form ; store the decimal number of string , s ; initialize the required result ; iterate in the range [ 0 , r ] ; convert integer i to binary string ; check if the string is not a subsequence ; update ans and break ; print the required result ; 
def isSubsequence(str1, str2, m, n):
    j = 0
    i = 0
    while (i < n and j < m):
        if (str1[j] == str2[i]):
            j += 1
        i += 1
    return (j == m)


def findMinimumNumber(s):
    r = int(s, 2)
    ans = r + 1
    for i in range(r + 1):
        p = ""
        j = i
        while (j > 0):
            p += str(j % 2)
            j = j // 2
        m = len(p)
        n = len(s)
        p = p[::-1]
        if (isSubsequence(p, s, m, n) == False):
            ans = i
            break
    print(ans)


if __name__ == '__main__':
    s = "10101"
    findMinimumNumber(s)

# Expected output:
8
# minimize cost to make all characters of a binary string equal to '1' by reversing or flipping characters of substrings | function to calculate minimum cost to convert all the characters of s to '1 ; stores the result ; stores the number of groups that have 0 as characters ; traverse the s ; if current character is '0 ; if count is greater than 0 ; set the count to 0 ; if the last few consecutive characters are '0 ; if contains all characters as '1 ; minimum cost ; 
def MinimumCost(S, A, B):
    count = 0

    group = 0
    for i in range(len(S)):
        if (S[i] == '0'):
            count += 1
        else:
            if (count > 0):
                group += 1
            count = 0
    if (count > 0):
        group += 1
    if (group == 0):
        print(0)
    else:
        print(min(A, B) * (group - 1) + B)


if __name__ == '__main__':
    A = 1
    B = 5
    S = "01100"
    MinimumCost(S, A, B)

# Expected output:
6
# minimize cost of flipping or swaps to make a binary string balanced | function to find the minimum cost to convert the given into balanced string ; stores count of 1 ' s ▁ and ▁ 0' s in the string ; traverse the string ; increment count1 ; increment count 0 ; stores absolute difference of counts of 0 ' s ▁ and ▁ 1' s ; if consists of only 0 ' s ▁ and ▁ 1' s ; print the minimum cost ; 
def findMinimumCost(s, N):
    count_1, count_0 = 0, 0
    for i in range(N):
        if (s[i] == '1'):
            count_1 += 1
        else:
            count_0 += 1
    k = abs(count_0 - count_1)
    if (count_1 == N or count_0 == N):
        print(-1)
    else:
        print(k // 2)


if __name__ == '__main__':
    S = "110110"
    N = len(S)
    findMinimumCost(S, N)

# Expected output:
1
# minimum time required to complete all tasks with alteration of their order allowed | python3 program for the above approach ; function to find the minimum time required to complete the tasks if the order of tasks can be changed ; if there is no task , print 0 ; store the maximum occurring character and its frequency ; stores the frequency of each character ; traverse the string s ; increment the frequency of the current character ; update maxfreq and maxchar ; store the number of empty slots ; traverse the hashmap , um ; fill the empty slots ; store the required result ; print the result ; 

import sys
from collections import defaultdict


def findMinimumTime(S, N, K):
    if (N == 0):
        print(0)
        return
    maxfreq = -sys .maxsize
    um = defaultdict(int)
    for i in range(N):
        um[S[i]] += 1
        if (um[S[i]] > maxfreq):
            maxfreq = um[S[i]]
            maxchar = S[i]
    emptySlots = (maxfreq - 1) * K
    for it in um:
        if (it == maxchar):
            continue
        emptySlots -= min(um[it], maxfreq - 1)
    ans = N + max(0, emptySlots)
    print(ans)


if __name__ == "__main__":
    S = "AAABBB"
    K = 2
    N = len(S)
    findMinimumTime(S, N, K)

# Expected output:
8
# check if all characters of a string can be made equal by increments or decrements | function to check if it is possible to make all characters of string s same or not ; length of string ; stores the sum of ascii value ; traverse the string s ; update the weightofstring ; if the sum is divisible by n then pr " yes " ; otherwise pr " no " ; 
def canMakeEqual(S):
    N = len(S)
    weightOfString = 0
    for i in range(N):
        weightOfString += ord(S[i]) - ord('a') + 1
    if (weightOfString % N == 0):
        print("Yes")
    else:
        print("No")


S = "beb"
canMakeEqual(S)

# Expected output:
Yes
# modify a string by circularly shifting each character to the right by respective frequencies | function to replace the characters by its frequency of character in it ; stores frequencies of characters in the string s ; traverse the string s ; increment the frequency of each character by 1 ; traverse the string s ; find the frequency of the current character ; update the character ; print the resultant string ; 
def addFrequencyToCharacter(S):
    frequency = [0 for i in range(26)]
    N = len(S)
    S = list(S)
    for i in range(N):
        frequency[ord(S[i]) - ord('a')] += 1
    for i in range(N):
        add = frequency[ord(S[i]) - ord('a')] % 26
        if ord(S[i]) + add <= ord('z'):
            S[i] = chr(ord(S[i]) + add)
        else:
            add = ord(S[i]) + add - ord('z')
            S[i] = chr(ord('a') + add - 1)
    s = ""
    print(s .join(S))


if __name__ == '__main__':
    S = "geeksforgeeks"
    addFrequencyToCharacter(S)

# Expected output:
iiimugpsiiimu
# minimize length of a string by removing pairs of consecutive increasing or decreasing digits | function to find the minimum length of the string possible after removing pairs of consecutive digits ; initialize the stack st ; traverse the string s ; if the stack is empty ; otherwise ; get the top character of the stack ; if cha and top are consecutive digits ; otherwise , push the character ch ; print the size of the stack ; 
def minLength(S):
    st = []
    for ch in S:
        if (len(st) == 0):
            st .append(ch)
        else:
            top = st[-1]
            if (abs(ord(ch) - ord(top)) == 1):
                st .pop()
            else:
                st .append(ch)
    return len(st)


if __name__ == "__main__":
    S = "12213"
    print(minLength(S))

# Expected output:
1
# check if a string is a subsequence of another string ( using stacks ) | function to check if target is a subsequence of string s ; declare a stack ; push the characters of target into the stack ; traverse the string s in reverse ; if the stack is empty ; if s [ i ] is same as the top of the stack ; pop the top of stack ; stack s is empty ; 
def checkforSubsequence(S, target):
    s = []
    for i in range(len(target)):
        s .append(target[i])
    for i in range(len(S) - 1, -1, -1):
        if (len(s) == 0):
            print("Yes")
            return
        if (S[i] == s[-1]):
            s .pop()
    if (len(s) == 0):
        print("Yes")
    else:
        print("No")


if __name__ == "__main__":
    S = "KOTTAYAM"
    target = "KOTA"
    checkforSubsequence(S, target)

# Expected output:
Yes
# program to construct a dfa to check if a given integer is unsigned or not | python3 program for the above approach ; function to construct dfa as per the given conditions ; if at state 0 and a digit has occurred then set it to state 1 ; similarly for all other states ; function to build and connect the dfa states ; connect all the states to the dead state ; function call to make dfa as per the given conditions ; function call to check whether an integer in the form of is unsigned integer or not ; build the dfa ; stores the current state ; traverse the string ; if at a certain state a digit occurs then change the current state according to the dfa ; or + / - sign ; or decimal occurred ; or any other character ; or e / e or exponent sign ; state 1 , 4 , 8 will give the final answer ; 

digits, sign = "0123456789", "+-"
dot, ex = ".", "eE"
dfa = [[0 for i in range(5)]for i in range(11)]


def makeDFA():
    global dfa
    dfa[0][0] = 1
    dfa[1][0] = 1
    dfa[1][2] = 3
    dfa[1][3] = 2
    dfa[1][4] = 6
    dfa[3][0] = 4
    dfa[4][0] = 4
    dfa[4][3] = 5
    dfa[4][4] = 6
    dfa[6][0] = 8
    dfa[6][1] = 7
    dfa[7][0] = 8
    dfa[8][0] = 8
    dfa[8][3] = 9


def buildDFA():
    global dfa
    for i in range(11):
        for j in range(5):
            dfa[i][j] = 10
    makeDFA()


def checkDFA(s):
    buildDFA()
    currentstate = 0
    for i in range(len(s)):
        if (s[i] in digits):
            currentstate = dfa[currentstate][0]
        elif (s[i] in sign):
            currentstate = dfa[currentstate][1]
        elif (s[i] in dot):
            currentstate = dfa[currentstate][2]
        elif (s[i] in ex):
            currentstate = dfa[currentstate][4]
        else:
            currentstate = dfa[currentstate][3]
    if (currentstate == 1 or currentstate == 4 or currentstate == 8):
        print("Unsigned integer")
    else:
        print("Not an unsigned integer")


if __name__ == '__main__':
    S = "1729"
    checkDFA(S)

# Expected output:
Unsigned integer
# convert a mobile numeric keypad sequence to equivalent sentence | function to convert mobile numeric keypad sequence into its equivalent string ; store the mobile keypad mappings ; traverse the str1ing str1 ; if the current character is ' . ' , then continue to the next iteration ; stores the number of continuous clicks ; iterate a loop to find the count of same characters ; 2 , 3 , 4 , 5 , 6 and 8 keys will have maximum of 3 letters ; 7 and 9 keys will have maximum of 4 keys ; handle the end condition ; check if the current pressed key is 7 or 9 ; else , the key pressed is either 2 , 3 , 4 , 5 , 6 or 8 ; 
def printSentence(str1):
    nums = ["", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"]
    i = 0
    while (i < len(str1)):
        if (str1[i] == '.'):
            i += 1
            continue
        count = 0
        while (i + 1 < len(str1) and str1[i + 1] and str1[i] == str1[i + 1]):
            if (count == 2 and (
                    (str1[i] >= '2' and str1[i] <= '6') or (str1[i] == '8'))):
                break
            elif (count == 3 and (str1[i] == '7' or str1[i] == '9')):
                break
            count += 1
            i += 1
            if (i < len(str)):
                break
        if (str1[i] == '7' or str1[i] == '9'):
            print(nums[ord(str1[i]) - 48][count % 4], end="")
        else:
            print(nums[ord(str1[i]) - 48][count % 3], end="")
        i += 1


if __name__ == '__main__':
    str1 = "234"
    printSentence(str1)

# Expected output:
ADG
# lexicographically largest string with sum of characters equal to n | function to construct the lexicographically largest string having sum of characters as n ; stores the resulting string ; iterate until n is at least 26 ; append ' z ' to the string ans ; decrement n by 26 ; append character at index ( n + ' a ' ) ; return the resultant string ; 
def getString(N):
    ans = ""
    while (N >= 26):
        ans += 'z'
        N -= 26
    ans += chr(N + ord('a') - 1)
    return ans


if __name__ == '__main__':
    N = 30
    print(getString(N))

# Expected output:
zd
# length of all prefixes that are also the suffixes of given string | function to find the length of all prefixes of the given that are also suffixes of the same string ; stores the prefix string ; traverse the s ; add the current character to the prefix string ; store the suffix string ; check if both the strings are equal or not ; 
def countSamePrefixSuffix(s, n):
    prefix = ""
    for i in range(n - 1):
        prefix += s[i]
        suffix = s[n - 1 - i:2 * n - 2 - i]
        if (prefix == suffix):
            print(len(prefix), end=" ")


if __name__ == '__main__':
    S = "ababababab"
    N = len(S)
    countSamePrefixSuffix(S, N)

# Expected output:
2 4 6 8
# count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array | function to count newly created pairs by swapping the first characters of any pairs of strings ; stores the count all possible pair of strings ; push all the strings into the unordered map ; generate all possible pairs of strings from the array arr [ ] ; store the current pair of strings ; swap the first character ; check if both string are not present in map ; print the result ; 
def countStringPairs(a, n):
    ans = 0
    s = {}
    for i in range(n):
        s[a[i]] = s .get(a[i], 0) + 1
    for i in range(n):
        for j in range(i + 1, n):
            p = [i for i in a[i]]
            q = [j for j in a[j]]
            if (p[0] != q[0]):
                p[0], q[0] = q[0], p[0]
                if (("".join(p)not in s) and ("".join(q)not in s)):
                    ans += 1
    print(ans)


if __name__ == '__main__':
    arr = ["good", "bad", "food"]
    N = len(arr)
    countStringPairs(arr, N)

# Expected output:
2
# check if it is possible to obtain a balanced parenthesis by shifting brackets to either end at most k times | function to check if a valid parenthesis can be obtained by moving characters to either end at most k number of times ; base case 1 ; count of ' ( ' and ') ; base case 2 ; store the count of moves required to make a valid parenthesis ; traverse the string ; increment cnt if opening bracket has occurred ; otherwise , decrement cnt by 1 ; decrement cnt by 1 ; if cnt is negative ; update the cnt ; increment the ans ; if ans is at most k , then print yes . otherwise print no ; 
def minimumMoves(s, n, k):
    if (n & 1):
        print("No")
        return

    countOpen = s .count('(')
    countClose = s .count(')')
    if (countOpen != countClose):
        print("No")
        return
    ans = 0
    cnt = 0
    for i in range(n):
        if (s[i] == '('):
            cnt += 1
        else:
            cnt -= 1
            if (cnt < 0):
                cnt = 0
                ans += 1
    if (ans <= k):
        print("Yes")
    else:
        print("No")


if __name__ == "__main__":
    S = ")("
    K = 1
    minimumMoves(S, len(S), K)

# Expected output:
Yes
# partition a string into palindromic strings of at least length 2 with every character present in a single string | function to check if a string can be split into palindromic strings of at least length 2 by including every character exactly once ; stores the frequency of each character ; store the frequency of characters with frequencies 1 and even respectively ; traverse the string s ; iterate over all the characters ; if the frequency is 1 ; if frequency is even ; print the result ; stores the number of characters with frequency equal to 1 that are not part of a palindromic string ; iterate over all the characters ; if o becomes less than 0 , then break out of the loop ; if frequency of the current character is > 2 and is odd ; update the value of o ; if a single character is still remaining ; increment o by 1 ; set a [ i ] to 1 ; print the result ; 
def checkPalindrome(s):
    a = [0] * 26
    o, e = 0, 0
    for i in s:
        a[ord(i) - 97] += 1
    for i in range(26):
        if (a[i] == 1):
            o += 1
        elif (a[i] % 2 == 0 and a[i] != 0):
            e += (a[i] // 2)
    if (e >= o):
        print("Yes")
    else:
        o = o - e
        for i in range(26):
            if (o <= 0):
                break
            if (o > 0 and a[i] % 2 == 1 and a[i] > 2):
                k = o
                o = o - a[i] // 2
                if (o > 0 or 2 * k + 1 == a[i]):
                    o += 1
                    a[i] = 1
        if (o <= 0):
            print("Yes")
        else:
            print("No")


if __name__ == '__main__':
    S = "abbbaddzcz"
    checkPalindrome(S)

# Expected output:
Yes
# maximize time by replacing ' _ ' in a given 24 hour format time | function to find the maximum time possible by replacing each ' _ ' with any digit ; if the first character is '_ ; if s [ 1 ] is ' _ ' or s [ 1 ] is less than 4 ; update s [ 0 ] as 2 ; otherwise , update s [ 0 ] = 1 ; if s [ 1 ] is equal to '_ ; if s [ 0 ] is equal to '2 ; otherwise ; if s [ 3 ] is equal to '_ ; if s [ 4 ] is equal to '_ ; return the modified string ; 
def maximumTime(s):

    s = list(s)
    if (s[0] == '_'):
        if ((s[1] == '_') or (s[1] >= '0' and
                              s[1] < '4')):
            s[0] = '2'
        else:
            s[0] = '1'
    if (s[1] == '_'):
        if (s[0] == '2'):
            s[1] = '3'
        else:
            s[1] = '9'
    if (s[3] == '_'):
        s[3] = '5'
    if (s[4] == '_'):
        s[4] = '9'
    s = ''.join(s)
    return s


if __name__ == '__main__':

    S = "0_:4_"

    print(maximumTime(S))

# Expected output:
09:49
# nearest power of 2 of frequencies of each digit of a given number | python3 program for the above approach ; function to find the nearest power of 2 for all frequencies in the map freq ; traverse the map ; calculate log of the current array element ; find the nearest power of 2 for the current frequency ; function to find nearest power of 2 for frequency of each digit of num ; length of string ; stores the frequency of each character in the string ; traverse the string s ; function call to generate nearest power of 2 for each frequency ; 

from math import log2, pow


def nearestPowerOfTwoUtil(freq):
    temp = {}
    for key, value in freq .items():
        lg = int(log2(value))
        a = int(pow(2, lg))
        b = int(pow(2, lg + 1))
        if ((value - a) < (b - value)):
            temp[(int(a))] = key
        else:
            temp[(int(b))] = key
    for key, value in temp .items():
        print(value, "->", key)


def nearestPowerOfTwo(S):
    N = len(S)
    freq = {}
    for i in range(N):
        if (S[i] in freq):
            freq[S[i]] += 1
        else:
            freq[S[i]] = 1
    nearestPowerOfTwoUtil(freq)


if __name__ == '__main__':
    N = "16333331163"
    nearestPowerOfTwo(N)

# Expected output:
1 -> 4
6 -> 2
3 -> 8
# smallest string divisible by two given strings | function to calculate gcd of two numbers ; function to calculate lcm of two numbers ; function to find the smallest string which is divisible by strings s and t ; store the length of both strings ; store lcm of n and m ; temporary strings to store concatenated strings ; concatenate s1 ( l / n ) times ; concatenate t1 ( l / m ) times ; if s1 and t1 are equal ; otherwise , pr - 1 ; 
def gcd(a, b):
    if (b == 0):
        return a
    return gcd(b, a % b)


def lcm(a, b):
    return (a // gcd(a, b)) * b


def findSmallestString(s, t):
    n, m = len(s), len(t)
    l = lcm(n, m)
    s1, t1 = "", ""
    for i in range(l // n):
        s1 += s
    for i in range(l // m):
        t1 += t
    if (s1 == t1):
        print(s1)
    else:
        print(-1)


if __name__ == '__main__':
    S, T = "baba", "ba"
    findSmallestString(S, T)

# Expected output:
baba