giulio98/xlcost-single-prompt huggingface dataset:
# longest non | function to find the length of the longest non - increasing subsequence ; stores the prefix and suffix count of 1 s and 0 s respectively ; store the number of '1' s up to current index i in pre ; find the prefix sum ; if the current element is '1' , update the pre [ i ] ; store the number of '0' s over the range [ i , n - 1 ] ; find the suffix sum ; if the current element is '0' , update post [ i ] ; stores the maximum length ; find the maximum value of pre [ i ] + post [ i ] ; return the answer ; 
def findLength(str, n):
    pre = [0] * n
    post = [0] * n
    for i in range(n):
        if (i != 0):
            pre[i] += pre[i - 1]
        if (str[i] == '1'):
            pre[i] += 1
    for i in range(n - 1, -1, -1):
        if (i != (n - 1)):
            post[i] += post[i + 1]
        if (str[i] == '0'):
            post[i] += 1
    ans = 0
    for i in range(n):
        ans = max(ans, pre[i] + post[i])
    return ans


S = "0101110110100001011"
n = len(S)
print(findLength(S, n))

# Expected output:
12
# number of substrings having an equal number of lowercase and uppercase letters | function to find the count of substrings having an equal number of uppercase and lowercase characters ; stores the count of prefixes having sum s considering uppercase and lowercase characters as 1 and - 1 ; stores the count of substrings having equal number of lowercase and uppercase characters ; stores the sum obtained so far ; if the character is uppercase ; otherwise ; if currsum is o ; if the current sum exists in the hashmap prevsum ; increment the resultant count by 1 ; update the frequency of the current sum by 1 ; return the resultant count of the subarrays ; 
def countSubstring(S, N):
    prevSum = {}
    res = 0
    currentSum = 0
    for i in range(N):
        if (S[i] >= 'A' and S[i] <= 'Z'):
            currentSum += 1
        else:
            currentSum -= 1
        if (currentSum == 0):
            res += 1
        if (currentSum in prevSum):
            res += (prevSum[currentSum])
        if currentSum in prevSum:
            prevSum[currentSum] += 1
        else:
            prevSum[currentSum] = 1
    return res


if __name__ == '__main__':
    S = "gEEk"
    print(countSubstring(S, len(S)))

# Expected output:
3
# number of substrings with each character occurring even times | function to count substrings having even frequency of each character ; stores the total count of substrings ; traverse the range [ 0 , n ] : ; traverse the range [ i + 1 , n ] ; stores the substring over the range of indices [ i , len ] ; stores the frequency of characters ; count frequency of each character ; traverse the dictionary ; if any of the keys have odd count ; otherwise ; return count ; 
def subString(s, n):
    count = 0
    for i in range(n):
        for len in range(i + 1, n + 1):
            test_str = (s[i:len])
            res = {}
            for keys in test_str:
                res[keys] = res .get(keys, 0) + 1
            flag = 0
            for keys in res:
                if res[keys] % 2 != 0:
                    flag = 1
                    break
            if flag == 0:
                count += 1
    return count


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

# Expected output:
4
# count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array | function to count new pairs of strings that can be obtained by swapping first characters of any pair of strings ; stores the count of pairs ; generate all possible pairs of strings from the array arr [ ] ; stores the current pair of strings ; swap the first characters ; check if they are already present in the array or not ; if both the strings are not present ; increment the ans by 1 ; print the resultant count ; 
def countStringPairs(a, n):
    ans = 0
    for i in range(n):
        for j in range(i + 1, n, 1):
            p = a[i]
            q = a[j]
            if (p[0] != q[0]):
                p = list(p)
                q = list(q)
                temp = p[0]
                p[0] = q[0]
                q[0] = temp
                p = ''.join(p)
                q = ''.join(q)
                flag1 = 0
                flag2 = 0
                for k in range(n):
                    if (a[k] == p):
                        flag1 = 1
                    if (a[k] == q):
                        flag2 = 1
                if (flag1 == 0 and flag2 == 0):
                    ans = 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 reach any point on the circumference of a given circle from origin | function to check if it is possible to reach any point on circumference of the given circle from ( 0 , 0 ) ; stores the count of ' l ' , 'r ; stores the count of ' u ' , 'd ; traverse the string s ; update the count of l ; update the count of r ; update the count of u ; update the count of d ; condition 1 for reaching the circumference ; store the the value of ( i * i ) in the map ; check if ( r_square - i * i ) already present in hashmap ; if it is possible to reach the point ( mp [ r_square - i * i ] , i ) ; if it is possible to reach the point ( i , mp [ r_square - i * i ] ) ; if it is impossible to reach ; 
def isPossible(S, R, N):
    cntl = 0
    cntr = 0
    cntu = 0
    cntd = 0
    for i in range(N):
        if (S[i] == 'L'):
            cntl += 1
        elif (S[i] == 'R'):
            cntr += 1
        elif (S[i] == 'U'):
            cntu += 1
        else:
            cntd += 1
    if (max(max(cntl, cntr), max(cntu, cntd)) >= R):
        return "Yes"
    mp = {}
    r_square = R * R
    i = 1
    while i * i <= r_square:
        mp[i * i] = i
        if ((r_square - i * i) in mp):
            if (max(cntl, cntr) >= mp[r_square - i * i] and max(cntu, cntd) >= i):
                return "Yes"
            if (max(cntl, cntr) >= i and max(cntu, cntd) >= mp[r_square - i * i]):
                return "Yes"
        i += 1
    return "No"


if __name__ == "__main__":
    S = "RDLLDDLDU"
    R = 5
    N = len(S)
    print((isPossible(S, R, N)))

# Expected output:
Yes
# modify characters of a string by adding integer values of same | function to modify a given string by adding ascii value of characters from a string s to integer values of same indexed characters in string n ; traverse the string ; stores integer value of character in string n ; stores ascii value of character in string s ; if b exceeds 122 ; replace the character ; print resultant string ; 
def addASCII(S, N):
    for i in range(len(S)):
        a = ord(N[i]) - ord('0')
        b = ord(S[i]) + a
        if (b > 122):
            b -= 26
        S = S .replace(S[i], chr(b))
    print(S)


if __name__ == "__main__":
    S = "sun"
    N = "966"
    addASCII(S, N)

# Expected output:
bat
# modify array by removing characters from their hexadecimal representations which are present in a given string | function to convert a decimal number to its equivalent hexadecimal number ; function to convert hexadecimal number to its equavalent decimal number ; stores characters with their respective hexadecimal values ; stores answer ; traverse the string ; if digit ; if character ; return the answer ; function to move all the alphabets to front ; function to modify each array element by removing characters from their hexadecimal representation which are present in a given string ; traverse the array ; stores hexadecimal value ; remove the characters from hexadecimal representation present in string s ; stores decimal value ; replace array element ; print the modified array ; given array ; given string ; function call to modify array by 
def decHex(n):
    alpha = ['A', 'B', 'C', 'D', 'E', 'F']
    ans = ''
    while n:
        if n % 16 < 10:
            ans += str(n % 16)
        else:
            ans += alpha[n % 16 - 10]
        n //= 16
    ans = ans[::-1]
    return ans


def hexDec(convertedHex):
    mp = {"A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15}
    ans = 0
    pos = 0
    for i in convertedHex[::-1]:
        if i .isdigit():
            ans += (16 ** pos) * int(i)
        else:
            ans += (16 ** pos) * mp[i]
        pos += 1
    return ans


def removeChars(hexaVal, S):
    setk = set()
    for i in S:
        setk .add(i)
    ans = ''
    for i in hexaVal:
        if i in setk:
            continue
        ans += i
    return ans


def convertArr(arr, S):
    for i in range(len(arr)):
        hexaVal = decHex(arr[i])
        convertedHex = removeChars(hexaVal, S)
        decVal = hexDec(convertedHex)
        arr[i] = decVal
    print(arr)


arr = [74, 91, 31, 122]
S = "1AB"
convertArr(arr, S)

# Expected output:
[4, 5, 15, 7]
# modify string by inserting characters such that every k | function to replace all ' ? ' characters in a string such that the given conditions are satisfied ; traverse the string to map the characters with respective positions ; traverse the string again and replace all unknown characters ; if i % k is not found in the map m , then return - 1 ; update s [ i ] ; print the string s ; 
def fillString(s, k):
    mp = {}
    for i in range(len(s)):
        if (s[i] != '?'):
            mp[i % k] = s[i]
    s = list(s)
    for i in range(len(s)):
        if ((i % k)not in mp):
            print(-1)
            return
        s[i] = mp[i % k]
    s = ''.join(s)
    print(s)


if __name__ == '__main__':
    S = "????abcd"
    K = 4
    fillString(S, K)

# Expected output:
abcdabcd
# rearrange a string s1 such that another given string s2 is not its subsequence | function to rearrange characters in s1 such that s2 is not a subsequence of it ; store the frequencies of characters of s2 ; traverse the s2 ; update the frequency ; find the number of unique characters in s2 ; increment unique by 1 if the condition satisfies ; check if the number of unique characters in s2 is 1 ; store the unique character frequency ; store occurence of it in s1 ; find count of that character in the s1 ; increment count by 1 if that unique character is same as current character ; if count count_in_s1 is less than count_in_s2 , then prs1 and return ; otherwise , there is no possible arrangement ; checks if any character in s2 is less than its next character ; iterate the string , s2 ; if s [ i ] is greater than the s [ i + 1 ] ; set inc to 0 ; if inc = 1 , prs1 in decreasing order ; otherwise , prs1 in increasing order ; 
def rearrangeString(s1, s2):
    cnt = [0] * 26
    for i in range(len(s2)):
        cnt[ord(s2[i]) - ord('a')] += 1
    unique = 0
    for i in range(26):
        if (cnt[i] != 0):
            unique += 1
    if (unique == 1):
        count_in_s2 = len(s2)
        count_in_s1 = 0
        for i in range(len(s1)):
            if (s1[i] == s2[0]):
                count_in_s1 += 1
        if (count_in_s1 < count_in_s2):
            print(s1, end="")
            return
        print(-1, end="")
    else:
        inc = 1
        for i in range(len(s2) - 1):
            if (s2[i] > s2[i + 1]):
                inc = 0
        if (inc == 1):
            s1 = sorted(s1)[::-1]
            print("".join(s1), end="")
        else:
            s1 = sorted(s1)
            print("".join(s1), end="")


if __name__ == '__main__':
    s1, s2 = "abcd", "ab"
    rearrangeString(s1, s2)

# Expected output:
dcba
# check if a string can be emptied by removing all subsequences of the form "10" | function to find if string is reducible to null ; length of string ; stack to store all 1 s ; iterate over the characters of the string ; if current character is 1 ; push it into the stack ; pop from the stack ; if the stack is empty ; 
def isReducible(Str):
    N = len(Str)
    s = []
    for i in range(N):
        if (Str[i] == '1'):
            s .append(Str[i])
        elif (len(s) > 0):
            del s[len(s) - 1]
        else:
            return False
    if (len(s) == 0):
        return True
    else:
        return False


Str = "11011000"
if (isReducible(Str)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# rearrange a string to maximize the minimum distance between any pair of vowels | function to rearrange the string such that the minimum distance between any of vowels is maximum . ; store vowels and consonants ; iterate over the characters of string ; if current character is a vowel ; if current character is consonant ; store count of vowels and consonants respectively ; store the resultant string ; store count of consonants append into ans ; append vowel to ans ; append consonants ; appendconsonant to ans ; update temp ; remove the taken elements of consonant ; return final answer ; 
def solution(S):
    vowels = []
    consonants = []
    for i in S:
        if (i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u'):
            vowels .append(i)
        else:
            consonants .append(i)
    Nc = len(consonants)
    Nv = len(vowels)
    M = Nc // (Nv - 1)
    ans = ""
    consonant_till = 0
    for i in vowels:
        ans += i
        temp = 0
        for j in range(consonant_till, min(Nc, consonant_till + M)):
            ans += consonants[j]
            temp += 1
        consonant_till += temp
    return ans


S = "aaaabbbcc"
print(solution(S))

# Expected output:
abababac
# lexicographically smallest string possible by performing k operations on a given string | function to find the lexicographically smallest possible string by performing k operations on string s ; store the size of string , s ; check if k >= n , if true , convert every character to 'a ; iterate in range [ 0 , n - 1 ] using i ; when k reaches 0 , break the loop ; if current character is ' a ' , continue ; otherwise , iterate in the range [ i + 1 , n - 1 ] using j ; check if s [ j ] > s [ i ] ; if true , set s [ j ] = s [ i ] and break out of the loop ; check if j reaches the last index ; update s [ i ] ; decrement k by 1 ; print string ; 
def smallestlexicographicstring(s, k):
    n = len(s)

    if (k >= n):
        for i in range(n):

            s[i] = 'a'

        print(s, end='')
        return
    for i in range(n):
        if (k == 0):
            break

        if (s[i] == 'a'):
            continue
        for j in range(i + 1, n):

            if (s[j] > s[i]):

                s[j] = s[i]
                break

            elif (j == n - 1):
                s[j] = s[i]

        s[i] = 'a'

        k -= 1
    print(''.join(s), end='')


if __name__ == '__main__':

    s = list("geeksforgeeks")

    k = 6

    smallestlexicographicstring(s, k)

# Expected output:
aaaaaaeegeeks
# maximize palindromic strings of length 3 possible from given count of alphabets | function to count maximum number of palindromic string of length 3 ; stores the final count of palindromic strings ; traverse the array ; increment res by arr [ i ] / 3 , i . e forming string of only i + ' a ' character ; store remainder ; increment c1 by one , if current frequency is 1 ; increment c2 by one , if current frequency is 2 ; count palindromic strings of length 3 having the character at the ends different from that present in the middle ; update c1 and c2 ; increment res by 2 * c2 / 3 ; finally print the result ; 
def maximum_pallindromic(arr):
    res = 0
    c1 = 0
    c2 = 0
    for i in range(26):
        res += arr[i] // 3
        arr[i] = arr[i] % 3
        if (arr[i] == 1):
            c1 += 1
        elif (arr[i] == 2):
            c2 += 1
    res += min(c1, c2)
    t = min(c1, c2)
    c1 -= t
    c2 -= t
    res += 2 * (c2 // 3)
    c2 %= 3
    res += c2 // 2
    print(res)


if __name__ == "__main__":
    arr = [4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    maximum_pallindromic(arr)

# Expected output:
3
# find the winner of game of repeatedly removing the first character to empty given string | function to find the winner of a game of repeatedly removing the first character to empty a string ; store characters of each string of the array arr [ ] ; stores count of strings in arr [ ] ; traverse the array arr [ ] ; stores length of current string ; traverse the string ; insert arr [ i ] [ j ] ; 1 st player starts the game ; stores the player number for the next turn ; remove 1 st character of current string ; update player number for the next turn ; 
def find_Winner(arr, N):
    Q = [0] * N
    for i in range(N):
        Q[i] = []
    M = len(arr)
    for i in range(M):
        Len = len(arr[i])
        for j in range(Len):
            Q[i].append(ord(arr[i][j]) - 1)
    player = 0
    while (len(Q[player]) > 0):
        nextPlayer = Q[player][0] - ord('0')
        del Q[player][0]
        player = nextPlayer
    print("Player", (player + 1))


N = 3
arr = ["323", "2", "2"]
find_Winner(arr, N)

# Expected output:
Player 2
# longest substring that can be made a palindrome by swapping of characters | function to find the longest substring that can be made a palindrome by swapping of characters ; initialize dp array of size 1024 ; initializing mask and res ; traverse the string ; find the mask of the current character ; finding the length of the longest substring in s which is a palindrome for even count ; finding the length of the longest substring in s which is a palindrome for one odd count ; finding maximum length of substring having one odd count ; dp [ mask ] is minimum of current i and dp [ mask ] ; return longest length of the substring which forms a palindrome with swaps ; 
def longestSubstring(s):
    dp = [1024 for i in range(1024)]
    res, mask = 0, 0
    dp[0] = -1
    for i in range(len(s)):
        mask ^= 1 << (ord(s[i]) - ord('0'))
        res = max(res, i - dp[mask])
        for j in range(10):
            res = max(res, i - dp[mask ^ (1 << j)])
        dp[mask] = min(dp[mask], i)
    return res


if __name__ == '__main__':
    s = "3242415"
    print(longestSubstring(s))

# Expected output:
5
# convert given string to a valid mobile number | function to print valid and formatted phone number ; length of given ; store digits in temp ; iterate given m ; if any digit : append it to temp ; find new length of ; if length is not equal to 10 ; store final result ; make groups of 3 digits and enclose them within ( ) and separate them with " - " 0 to 2 index 1 st group ; 3 to 5 index 2 nd group ; 6 to 8 index 3 rd group ; 9 to 9 index last group ; print final result ; 
def Validate(M):
    lenn = len(M)
    temp = ""
    for i in range(lenn):
        if (M[i].isdigit()):
            temp += M[i]
    nwlenn = len(temp)
    if (nwlenn != 10):
        print("Invalid")
        return
    res = ""
    x = temp[0:3]
    res += "(" + x + ")-"
    x = temp[3:3 + 3]
    res += "(" + x + ")-"
    x = temp[6:3 + 6]
    res += "(" + x + ")-"
    x = temp[9:1 + 9]
    res += "(" + x + ")"
    print(res)


if __name__ == '__main__':
    M = "91 234rt5%34*0 3"
    Validate(M)

# Expected output:
(912)-(345)-(340)-(3)
# modulus of two hexadecimal numbers | function to calculate modulus of two hexadecimal numbers ; store all possible hexadecimal digits ; iterate over the range [ '0' , '9' ] ; convert given string to long ; base to get 16 power ; store n % k ; iterate over the digits of n ; stores i - th digit of n ; update ans ; update base ; print the answer converting into hexadecimal ; 
def hexaModK(s, k):
    mp = {}
    for i in range(1, 10):
        mp[chr(i + ord('0'))] = i
    mp['A'] = 10
    mp['B'] = 11
    mp['C'] = 12
    mp['D'] = 13
    mp['E'] = 14
    mp['F'] = 15
    m = int(k)
    base = 1
    ans = 0
    for i in range(len(s) - 1, -1, -1):
        n = mp[s[i]] % m
        ans = (ans + (base % m * n % m) % m) % m
        base = (base % m * 16 % m) % m
    ans = hex(int(ans))[-1].upper()
    print(ans)


if __name__ == "__main__":
    n = "3E8"
    k = "13"
    hexaModK(n, k)

# Expected output:
C
# count distinct strings present in an array using polynomial rolling hash function | function to find the hash value of a ; traverse the ; update hash_val ; update mul ; return hash_val of str ; function to find the count of distinct strings present in the given array ; store the hash values of the strings ; traverse the array ; stores hash value of arr [ i ] ; sort hash [ ] array ; stores count of distinct strings in the array ; traverse hash [ ] array ; update cntelem ; 
def compute_hash(str):
    p = 31
    MOD = 10 ** 9 + 7
    hash_val = 0
    mul = 1
    for ch in str:
        hash_val = (hash_val + (ord(ch) - ord('a') + 1) * mul) % MOD
        mul = (mul * p) % MOD
    return hash_val


def distinct_str(arr, n):
    hash = [0] * (n)
    for i in range(n):
        hash[i] = compute_hash(arr[i])
    hash = sorted(hash)
    cntElem = 1
    for i in range(1, n):
        if (hash[i] != hash[i - 1]):
            cntElem += 1
    return cntElem


if __name__ == '__main__':
    arr = ["abcde", "abcce", "abcdf", "abcde"]
    N = len(arr)
    print(distinct_str(arr, N))

# Expected output:
3
# remove characters from given string whose frequencies are a prime number | function to perform the seive of eratosthenes algorithm ; initialize all entries in prime [ ] as true ; initialize 0 and 1 as non prime ; traversing the prime array ; if i is prime ; all multiples of i must be marked false as they are non prime ; function to remove characters which have prime frequency in the string ; length of the string ; create a bool array prime ; sieve of eratosthenes ; stores the frequency of character ; storing the frequencies ; new string that will be formed ; removing the characters which have prime frequencies ; if the character has prime frequency then skip ; else concatenate the character to the new string ; print the modified string ; 
def SieveOfEratosthenes(prime, n):
    for i in range(n + 1):
        prime[i] = True
    prime[0] = prime[1] = False
    i = 2
    while i * i <= n:
        if (prime[i]):
            j = 2
            while i * j <= n:
                prime[i * j] = False
                j += 1
        i += 1


def removePrimeFrequencies(s):
    n = len(s)
    prime = [False] * (n + 1)
    SieveOfEratosthenes(prime, n)
    m = {}
    for i in range(len(s)):
        if s[i] in m:
            m[s[i]] += 1
        else:
            m[s[i]] = 1
    new_String = ""
    for i in range(len(s)):
        if (prime[m[s[i]]]):
            continue
        new_String += s[i]
    print(new_String, end="")


Str = "geeksforgeeks"
removePrimeFrequencies(list(Str))

# Expected output:
eeforee
# rearrange string such that no pair of adjacent characters are of the same type | function to rearrange given alphanumeric such that no two adjacent characters are of the same type ; stores alphabets and digits ; store the alphabets and digits separately in the strings ; stores the count of alphabets and digits ; if respective counts differ by 1 ; desired arrangement not possible ; stores the indexes ; check if first character should be alphabet or digit ; place alphabets and digits alternatively ; if current character needs to be alphabet ; if current character needs to be a digit ; flip flag for alternate arrangement ; return resultant string ; 
def rearrange(s):
    s1 = []
    s2 = []
    for x in s:
        if x .isalpha():
            s1 .append(x)
        else:
            s2 .append(x)
    n = len(s1)
    m = len(s2)
    if (abs(n - m) > 1):
        return "-1"
    i = 0
    j = 0
    k = 0
    flag = 0
    if (n >= m):
        flag = 1
    else:
        flag = 0
    while (i < n and j < m):
        if (flag):
            s[k] = s1[i]
            k += 1
            i += 1
        else:
            s[k] = s2[j]
            k += 1
            j += 1
        flag = not flag
    return "".join(s)


if __name__ == '__main__':
    str = "geeks2020"
    str1 = [i for i in str]
    print(rearrange(str1))

# Expected output:
g2e0e2k00