giulio98/xlcost-single-prompt huggingface dataset:
# check whether two strings can be made equal by reversing substring of equal length from both strings | function to count inversion count of the string ; for storing frequency ; we 'll add all the characters  which are less than the ith  character before i. ; adding the count to inversion count ; updating the character in the frequency array ; function to check whether any of the string have a repeated character ; function to check whether the string s1 and s2 can be made equal by reversing sub strings ofsame size in both strings ; frequency array to check whether both string have same character or not ; adding the frequency ; ; if the character is not in s1 ; decrementing the frequency ; if both string does not have same characters or not ; finding inversion count of both strings ; if inversion count is same , or have same parity or if any of the string have a repeated character then the answer is yes else no ; 
def inversionCount(s):
    freq = [0 for _ in range(26)]
    inv = 0
    for i in range(len(s)):
        temp = 0
        for j in range(ord(s[i]) - ord('a')):
            temp += freq[j]
        inv += (i - temp)
        freq[ord(s[i]) - ord('a')] += 1
    return inv


def haveRepeated(S1, S2):
    freq = [0 for _ in range(26)]
    for i in range(len(S1)):
        if freq[ord(S1[i]) - ord('a')] > 0:
            return 1
        freq[ord(S1[i]) - ord('a')] += 1
    for i in range(26):
        freq[i] = 0
    for i in range(len(S2)):
        if freq[ord(S2[i]) - ord('a')] > 0:
            return 1
        freq[ord(S2[i]) - ord('a')] += 1
    return 0


def checkToMakeEqual(S1, S2):
    freq = [0 for _ in range(26)]
    for i in range(len(S1)):
        freq[ord(S1[i]) - ord('a')] += 1
    flag = 0
    for i in range(len(S2)):
        if freq[ord(S2[i]) - ord('a')] == 0:
            flag = 1
            break
        freq[ord(S2[i]) - ord('a')] -= 1
    if flag == 1:
        print("No")
        return
    invCount1 = inversionCount(S1)
    invCount2 = inversionCount(S2)
    if ((invCount1 == invCount2) or ((invCount1 % 2) ==
                                     (invCount2 % 2)) or haveRepeated(S1, S2) == 1):
        print("Yes")
    else:
        print("No")


S1 = "abbca"
S2 = "acabb"
checkToMakeEqual(S1, S2)

# Expected output:
Yes
# sort a bitonic array | python3 program for the above approach ; function to sort bitonic array in constant space ; initialize thevalue of k ; in each iteration compare elements k distance apart and swap it they are not in order ; k is reduced to half after every iteration ; print the array elements ; 

import math


def sortArr(a, n):
    k = int(math .log(n, 2))
    k = int(pow(2, k))
    while (k > 0):
        i = 0
        while i + k < n:
            if a[i] > a[i + k]:
                a[i], a[i + k] = a[i + k], a[i]
            i = i + 1
        k = k // 2
    for i in range(n):
        print(a[i], end=" ")


a = [5, 20, 30, 40, 36, 33, 25, 15, 10]
n = len(a)
sortArr(a, n)

# Expected output:
5 10 15 20 25 30 33 36 40
# split array into k subsets to maximize their sum of maximums and minimums | function that prints the maximum sum possible ; find elements in each group ; sort all elements in non - descending order ; add k largest elements ; for sum of minimum elements from each subset ; printing the maximum sum ; 
def maximumSum(arr, n, k):
    elt = n // k
    sum = 0
    arr .sort()
    count = 0
    i = n - 1
    while (count < k):
        sum += arr[i]
        i -= 1
        count += 1
    count = 0
    i = 0
    while (count < k):
        sum += arr[i]
        i += elt - 1
        count += 1
    print(sum)


if __name__ == '__main__':
    Arr = [1, 13, 7, 17, 6, 5]
    K = 2
    size = len(Arr)
    maximumSum(Arr, size, K)

# Expected output:
37
# minimize sum of smallest elements from k subsequences of length l | function to find the minimum sum ; sort the array ; calculate sum of smallest k elements ; return the sum ; 
def findMinSum(arr, K, L, size):
    if (K * L > size):
        return -1
    minsum = 0
    arr .sort()
    for i in range(K):
        minsum += arr[i]
    return minsum


if __name__ == '__main__':
    arr = [2, 15, 5, 1, 35, 16, 67, 10]
    K = 3
    L = 2
    length = len(arr)
    print(findMinSum(arr, K, L, length))

# Expected output:
8
# kth smallest or largest element in unsorted array | set 4 | function to find the kth smallest element in unsorted array ; initialize the max element as 0 ; iterate arr [ ] and find the maximum element in it ; frequency array to store the frequencies ; counter variable ; counting the frequencies ; iterate through the freq [ ] ; check if num is present in the array ; increment the counter with the frequency of num ; checking if we have reached the kth smallest element ; return the kth smallest element ; 
def findKthSmallest(arr, n, k):
    max = 0
    for i in range(n):
        if (arr[i] > max):
            max = arr[i]
    counter = [0] * (max + 1)
    smallest = 0
    for i in range(n):
        counter[arr[i]] += 1
    for num in range(1, max + 1):
        if (counter[num] > 0):
            smallest += counter[num]
        if (smallest >= k):
            return num


if __name__ == "__main__":
    arr = [7, 1, 4, 4, 20, 15, 8]
    N = len(arr)
    K = 5
    print(findKthSmallest(arr, N, K))

# Expected output:
8
# generate all numbers up to n in lexicographical order | function to print all the numbers up to n in lexicographical order ; 
def lexNumbers(n):
    s = []
    for i in range(1, n + 1):
        s .append(str(i))
    s .sort()
    ans = []
    for i in range(n):
        ans .append(int(s[i]))
    for i in range(n):
        print(ans[i], end=' ')


if __name__ == "__main__":
    n = 15
    lexNumbers(n)

# Expected output:
1 10 11 12 13 14 15 2 3 4 5 6 7 8 9
# sort matrix in alternating ascending and descending order rowwise | python3 implementation to print row of matrix in ascending or descending order alternatively ; iterate matrix rowwise ; sort even rows in ascending order ; compare adjacent elements ; swap adjacent element ; sort even rows in descending order ; compare adjacent elements ; swap adjacent element ; printing the final output ; 

N = 4


def func(a):
    for i in range(N):
        if i % 2 == 0:
            for j in range(N):
                for k in range(j + 1, N):
                    if a[i][j] > a[i][k]:
                        temp = a[i][j]
                        a[i][j] = a[i][k]
                        a[i][k] = temp
        else:
            for j in range(N):
                for k in range(j + 1, N):
                    if a[i][j] < a[i][k]:
                        temp = a[i][j]
                        a[i][j] = a[i][k]
                        a[i][k] = temp
    for i in range(N):
        for j in range(N):
            print(a[i][j], end=" ")
        print()


if __name__ == '__main__':
    a = [[5, 7, 3, 4], [9, 5, 8, 2], [6, 3, 8, 1], [5, 8, 9, 3]]
    func(a)

# Expected output:
3 4 5 7 
9 8 5 2 
1 3 6 8 
9 8 5 3
# find weight of mst in a complete graph with edge | to store the edges of the given graph ; a utility function to perform dfs traversal ; check those vertices which are stored in the set ; vertices are included if the weight of edge is 0 ; a utility function to find the weight of minimum spanning tree ; to count the connected components ; inserting the initial vertices in the set ; traversing vertices stored in the set and run dfs traversal for each vertices ; incrementing the zero weight connected components ; dfs traversal for every vertex remove ; 

g = [dict()for i in range(200005)]
s = set()
ns = set()


def dfs(x):
    global s, g, ns
    v = []
    v .clear()
    ns .clear()
    for it in s:
        if (x in g and not g[x][it]):
            v .append(it)
        else:
            ns .add(it)
    s = ns
    for i in v:
        dfs(i)


def weightOfMST(N):
    cnt = 0
    for i in range(1, N + 1):
        s .add(i)
    while (len(s) != 0):
        cnt += 1
        t = list(s)[0]
        s .discard(t)
        dfs(t)
    print(cnt)


if __name__ == '__main__':
    N = 6
    M = 11
    edges = [
        [
            1, 3], [
            1, 4], [
                1, 5], [
                    1, 6], [
                        2, 3], [
                            2, 4], [
                                2, 5], [
                                    2, 6], [
                                        3, 4], [
                                            3, 5], [
                                                3, 6]]
    for i in range(M):
        u = edges[i][0]
        v = edges[i][1]
        g[u][v] = 1
        g[v][u] = 1
    weightOfMST(N)

# Expected output:
2
# count of distinct possible pairs such that the element from a is greater than the element from b | function to return the count of pairs ; 
def countPairs(A, B):
    n = len(A)
    A .sort()
    B .sort()
    ans = 0
    for i in range(n):
        if (A[i] > B[ans]):
            ans += 1
    return ans


if __name__ == '__main__':
    A = [30, 28, 45, 22]
    B = [35, 25, 22, 48]
    print(countPairs(A, B))

# Expected output:
3
# maximum possible remainder when an element is divided by other element in the array | function to return the maximum mod value for any pair from the array ; find the second maximum element from the array ; 
def maxMod(arr, n):
    maxVal = max(arr)
    secondMax = 0
    for i in range(0, n):
        if (arr[i] < maxVal and arr[i] > secondMax):
            secondMax = arr[i]
    return secondMax


arr = [2, 4, 1, 5, 3, 6]
n = len(arr)
print(maxMod(arr, n))

# Expected output:
5
# choose x elements from a [ ] and y elements from b [ ] which satisfy the given condition | function to that returns true if it possible to choose the elements ; if elements can 't be chosen ; sort both the arrays ; if xth smallest element of a [ ] is smaller than the yth greatest element of b [ ] ; 
def isPossible(A, B, n, m, x, y):
    if (x > n or y > m):
        return False
    A .sort()
    B .sort()
    if (A[x - 1] < B[m - y]):
        return True
    else:
        return False


A = [1, 1, 1, 1, 1]
B = [2, 2]
n = len(A)
m = len(B)
x = 3
y = 1
if (isPossible(A, B, n, m, x, y)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# find minimum changes required in an array for it to contain k distinct elements | python 3 program to minimum changes required in an array for k distinct elements . ; function to minimum changes required in an array for k distinct elements . ; store the frequency of each element ; store the frequency of elements ; sort frequencies in descending order ; to store the required answer ; return the required answer ; 

MAX = 100005


def Min_Replace(arr, n, k):
    arr .sort(reverse=False)
    freq = [0 for i in range(MAX)]
    p = 0
    freq[p] = 1
    for i in range(1, n, 1):
        if (arr[i] == arr[i - 1]):
            freq[p] += 1
        else:
            p += 1
            freq[p] += 1
    freq .sort(reverse=True)
    ans = 0
    for i in range(k, p + 1, 1):
        ans += freq[i]
    return ans


if __name__ == '__main__':
    arr = [1, 2, 7, 8, 2, 3, 2, 3]
    n = len(arr)
    k = 2
    print(Min_Replace(arr, n, k))

# Expected output:
3
# maximum number of elements without overlapping in a line | function to find maximum number of elements without overlapping in a line ; if n = 1 , then answer is one ; we can always make 1 st element to cover left segment and nth the right segment ; if left segment for ith element doesnt overlap with i - 1 th element then do left ; else try towards right if possible ; update x [ i ] to right endpoof segment covered by it ; return the required answer ; 
def Segment(x, l, n):
    if (n == 1):
        return 1
    ans = 2
    for i in range(1, n - 1):
        if (x[i] - l[i] > x[i - 1]):
            ans += 1
        elif (x[i] + l[i] < x[i + 1]):
            x[i] = x[i] + l[i]
            ans += 1
    return ans


x = [1, 3, 4, 5, 8]
l = [10, 1, 2, 2, 5]
n = len(x)
print(Segment(x, l, n))

# Expected output:
4
# delete odd and even numbers at alternate step such that sum of remaining elements is minimized | function to find the minimized sum ; if more odd elements ; sort the elements ; left - over elements ; find the sum of leftover elements ; return the sum ; if more even elements ; sort the elements ; left - over elements ; find the sum of leftover elements ; return the sum ; if same elements ; 
def MinimizeleftOverSum(a, n):
    v1, v2 = [], []
    for i in range(n):
        if (a[i] % 2):
            v1 .append(a[i])
        else:
            v2 .append(a[i])
    if (len(v1) > len(v2)):
        v1 .sort()
        v2 .sort()
        x = len(v1) - len(v2) - 1
        sum = 0
        i = 0
        while (i < x):
            sum += v1[i]
            i += 1
        return sum
    elif (len(v2) > len(v1)):
        v1 .sort()
        v2 .sort()
        x = len(v2) - len(v1) - 1
        sum = 0
        i = 0
        while (i < x):
            sum += v2[i]
            i += 1
        return sum
    else:
        return 0


if __name__ == "__main__":
    a = [2, 2, 2, 2]
    n = len(a)
    print(MinimizeleftOverSum(a, n))

# Expected output:
6
# minimum operations to make frequency of all characters equal k | function to find the minimum number of operations to convert the given string ; check if n is divisible by k ; array to store frequency of characters in given string ; two arrays with number of operations required ; checking for all possibility ; 
def minOperation(S, N, K):
    if N % K:
        print("Not Possible")
        return
    count = [0] * 26
    for i in range(0, N):
        count[ord(S[i]) - 97] += 1
    E = N // K
    greaterE = []
    lessE = []
    for i in range(0, 26):
        if count[i] < E:
            lessE .append(E - count[i])
        else:
            greaterE .append(count[i] - E)
    greaterE .sort()
    lessE .sort()
    mi = float('inf')
    for i in range(0, K + 1):
        set1, set2 = i, K - i
        if (len(greaterE) >= set1 and len(lessE) >= set2):
            step1, step2 = 0, 0
            for j in range(0, set1):
                step1 += greaterE[j]
            for j in range(0, set2):
                step2 += lessE[j]
            mi = min(mi, max(step1, step2))
    print(mi)


if __name__ == "__main__":
    S = "accb"
    N = len(S)
    K = 2
    minOperation(S, N, K)

# Expected output:
1
# minimum range increment operations to sort an array | function to find minimum range increments to sort an array ; if current element is found greater than last element increment all terms in range i + 1 to n - 1 ; mn = arr [ i ] minimum in range i to n - 1 ; 
def minMovesToSort(arr, n):
    moves = 0
    mn = arr[n - 1]
    for i in range(n - 1, -1, -1):
        if (arr[i] > mn):
            moves += arr[i] - mn
    return moves


if __name__ == "__main__":
    arr = [3, 5, 2, 8, 4]
    n = len(arr)
    print(minMovesToSort(arr, n))

# Expected output:
5
# sort prime numbers of an array in descending order | python3 implementation of the approach ; false here indicates that it is not prime ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p , set them to non - prime ; function that sorts all the prime numbers from the array in descending ; this vector will contain prime numbers to sort ; if the element is prime ; update the array elements ; 
def SieveOfEratosthenes(n):
    prime[1] = False
    p = 2
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 1


def sortPrimes(arr, n):
    SieveOfEratosthenes(100005)
    v = []
    for i in range(0, n):
        if prime[arr[i]]:
            v .append(arr[i])
    v .sort(reverse=True)
    j = 0
    for i in range(0, n):
        if prime[arr[i]]:
            arr[i] = v[j]
            j += 1
    return arr


if __name__ == "__main__":
    arr = [4, 3, 2, 6, 100, 17]
    n = len(arr)
    prime = [True] * 100006
    arr = sortPrimes(arr, n)
    for i in range(0, n):
        print(arr[i], end=" ")

# Expected output:
4 17 3 6 100 2
# pair formation such that maximum pair sum is minimized | python 3 program to divide the array into n pairs such that maximum pair is minimized ; after sorting maintain two variables i and j pointing to start and end of array such that smallest element of array pairs with largest element ; 
def findOptimalPairs(arr, N):
    arr .sort(reverse=False)
    i = 0
    j = N - 1
    while (i <= j):
        print("(", arr[i], ",", arr[j], ")", end=" ")
        i += 1
        j -= 1


if __name__ == '__main__':
    arr = [9, 6, 5, 1]
    N = len(arr)
    findOptimalPairs(arr, N)

# Expected output:
( 1 , 9 ) ( 5 , 6 )
# lexicographically smallest binary string formed by flipping bits at indices not divisible k1 or k2 such that count of 1 s is always greater than 0 s from left | function to find lexicographically smallest string having number of 1 s greater than number of 0 s ; c1s and c0s stores the count of 1 s and 0 s at every position ; traverse the string s ; if the position is not divisible by k1 and k2 ; if c0s >= c1s and pos [ ] is empty then the string can 't  be formed ; if pos [ ] is not empty then flip the bit of last position present in pos [ ] ; print the result ; 
def generateString(k1, k2, s):
    s = list(s)
    C1s = 0
    C0s = 0
    flag = 0
    pos = []
    for i in range(len(s)):
        if (s[i] == '0'):
            C0s += 1
            if ((i + 1) % k1 != 0 and (i + 1) % k2 != 0):
                pos .append(i)
        else:
            C1s += 1
        if (C0s >= C1s):
            if (len(pos) == 0):
                print(-1)
                flag = 1
                break
            else:
                k = pos[len(pos) - 1]
                s[k] = '1'
                C0s -= 1
                C1s += 1
                pos = pos[:-1]
    s = ''.join(s)
    if (flag == 0):
        print(s)


if __name__ == '__main__':
    K1 = 2
    K2 = 4
    S = "11000100"
    generateString(K1, K2, S)

# Expected output:
11100110
# find a pair of numbers with set bit count as at most that of n and whose bitwise xor is n | python 3 program for the above approach ; function to find the pair ( x , y ) such that x xor y = n and the count of set bits in x and y is less than count of set bit in n ; stores msb ( most significant bit ) ; stores the value of x ; / stores the value of y ; traversing over all bits of n ; if ith bit of n is 0 ; / set ith bit of x to 1 ; set ith bit of y to 1 ; print answer ; 

import math


def maximizeProduct(N):
    MSB = (int)(math .log2(N))
    X = 1 << MSB
    Y = N - (1 << MSB)
    for i in range(MSB):
        if (not (N & (1 << i))):
            X += 1 << i
            Y += 1 << i
    print(X, Y)


if __name__ == "__main__":
    N = 45
    maximizeProduct(N)

# Expected output:
50 31
# count of numbers in range [ l , r ] having sum of digits of its square equal to square of sum of digits | python 3 program for the above approach ; function to check if the number is valid ; sum of digits of num ; squared number ; sum of digits of ( num * num ) ; function to convert a string to an integer ; function to generate all possible strings of length len ; desired string ; take only valid numbers ; recurse for all possible digits ; function to calculate unique numbers in range [ l , r ] ; initialize a variable to store the answer ; calculate the maximum possible length ; set to store distinct valid numbers ; generate all possible strings of length i ; iterate the set to get the count of valid numbers in the range [ l , r ] ; 

from math import log10


def check(num):
    sm = 0
    num2 = num * num
    while (num):
        sm += num % 10
        num //= 10
    sm2 = 0
    while (num2):
        sm2 += num2 % 10
        num2 //= 10
    return ((sm * sm) == sm2)


def convert(s):
    val = 0
    s = s[::-1]
    cur = 1
    for i in range(len(s)):
        val += (ord(s[i]) - ord('0')) * cur
        cur *= 10
    return val


def generate(s, len1, uniq):
    if (len(s) == len1):
        if (check(convert(s))):
            uniq .add(convert(s))
        return
    for i in range(4):
        generate(s + chr(i + ord('0')), len1, uniq)


def totalNumbers(L, R):
    ans = 0
    max_len = int(log10(R)) + 1
    uniq = set()
    for i in range(1, max_len + 1, 1):
        generate("", i, uniq)
    for x in uniq:
        if (x >= L and x <= R):
            ans += 1
    return ans


if __name__ == '__main__':
    L = 22
    R = 22
    print(totalNumbers(L, R))

# Expected output:
1
# convert x into y by repeatedly multiplying x with 2 or appending 1 at the end | function to check if x can be converted to y by multiplying x by 2 or appending 1 at the end ; iterate until y is at least x ; if y is even ; if the last digit of y is 1 ; otherwise ; check if x is equal to y ; 
def convertXintoY(X, Y):
    while (Y > X):
        if (Y % 2 == 0):
            Y //= 2
        elif (Y % 10 == 1):
            Y //= 10
        else:
            break
    if (X == Y):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    X, Y = 100, 40021
    convertXintoY(X, Y)

# Expected output:
Yes
# lexicographically smallest string of maximum length made up of first k alphabets that does not contain any repeating substring | function to find the lexicographically smallest string of the first k lower case alphabets having unique substrings ; stores the resultant string ; iterate through all the characters ; inner loop for making pairs and adding them into string ; adding first character so that substring consisting of the last the first alphabet is present ; print the resultant string ; 
def generateString(K):
    s = ""
    for i in range(97, 97 + K, 1):
        s = s + chr(i)
        for j in range(i + 1, 97 + K, 1):
            s += chr(i)
            s += chr(j)
    s += chr(97)
    print(s)


if __name__ == '__main__':
    K = 4
    generateString(K)

# Expected output:
aabacadbbcbdccdda
# generate quadratic equation having given sum and product of roots | function to find the quadratic equation from the given sum and products of roots ; print the coefficients ; 
def findEquation(S, M):
    print("1 ", ((-1) * S), " ", M)


S = 5
M = 6
findEquation(S, M)

# Expected output:
1  -5   6
# make all array elements equal by replacing adjacent pairs by their sum | function to count the minimum number of pairs of adjacent elements required to be replaced by their sum to make all arrat elements equal ; stores the prefix sum of the array ; calculate the prefix sum array ; stores the maximum number of subarrays into which the array can be split ; iterate over all possible sums ; traverse the array ; if the sum is equal to the current prefix sum ; increment count of groups by 1 ; otherwise discard this subgroup sum ; update the maximum this of subarrays ; return the minimum number of operations ; 
def minSteps(a, n):
    prefix_sum = a[:]
    for i in range(1, n):
        prefix_sum[i] += prefix_sum[i - 1]
    mx = -1
    for subgroupsum in prefix_sum:
        sum = 0
        i = 0
        grp_count = 0
        while i < n:
            sum += a[i]
            if sum == subgroupsum:
                grp_count += 1
                sum = 0
            elif sum > subgroupsum:
                grp_count = -1
                break
            i += 1
        if grp_count > mx:
            mx = grp_count
    return n - mx


if __name__ == '__main__':
    A = [1, 2, 3, 2, 1, 3]
    N = len(A)
    print(minSteps(A, N))

# Expected output:
2
# maximize count of sheets possible by repeatedly reducing its area to half | function to calculate the maximum number of sheets possible by given operations ; initial count of sheets ; keep dividing the sheets into half ; reduce area by half ; increase count by twice ; 
def maxSheets(A, B):
    area = A * B
    count = 1
    while (area % 2 == 0):
        area //= 2
        count *= 2
    return count


A = 5
B = 10
print(maxSheets(A, B))

# Expected output:
2