giulio98/xlcost-single-prompt huggingface dataset:
# minimum swaps required between two strings to make one string strictly greater than the other | function to find the minimum number of steps to make a > b ; if all character are same and m <= n ; if there lies any character in b which is greater than b [ 0 ] ; if there lies any character in a which is smaller than a [ 0 ] ; if there lies a character which is in a and greater than a [ 0 ] ; if there lies a character which is in b and less than b [ 0 ] ; otherwise ; 
def minSteps(A, B, M, N):
    if (A[0] > B[0]):
        return 0
    if (B[0] > A[0]):
        return 1
    if (M <= N and A[0] == B[0] and A .count(
            A[0]) == M and B .count(B[0]) == N):
        return -1
    for i in range(1, N):
        if (B[i] > B[0]):
            return 1
    for i in range(1, M):
        if (A[i] < A[0]):
            return 1
    for i in range(1, M):
        if (A[i] > A[0]):
            A[0], B[i] = B[i], A[0]
            A[0], B[0] = B[0], A[0]
            return 2
    for i in range(1, N):
        if (B[i] < B[0]):
            A[0], B[i] = B[i], A[0]
            A[0], B[0] = B[0], A[0]
            return 2
    return 0


if __name__ == '__main__':
    A = "adsfd"
    B = "dffff"
    M = len(A)
    N = len(B)
    print(minSteps(A, B, M, N))

# Expected output:
1
# maximize sum of pairwise products generated from the given arrays | python3 program for the above approach ; variables which represent the size of the array ; stores the results ; function to return the maximum possible sum ; stores the count of arrays processed ; if more than two arrays have been processed ; if an already computed subproblem occurred ; explore all the possible pairs ; recursive function call ; memoize the maximum ; returning the value ; function to return the maximum sum of products of pairs possible ; initialising the dp array to - 1 ; sort the arrays in descending order ; 

maxN = 201
n1, n2, n3 = 0, 0, 0
dp = [[[0 for i in range(maxN)]for j in range(maxN)]for j in range(maxN)]


def getMaxSum(i, j, k, arr1, arr2, arr3):
    cnt = 0
    if (i >= n1):
        cnt += 1
    if (j >= n2):
        cnt += 1
    if (k >= n3):
        cnt += 1
    if (cnt >= 2):
        return 0
    if (dp[i][j][k] != -1):
        return dp[i][j][k]
    ans = 0
    if (i < n1 and j < n2):
        ans = max(
            ans,
            getMaxSum(
                i +
                1,
                j +
                1,
                k,
                arr1,
                arr2,
                arr3) +
            arr1[i] *
            arr2[j])
    if (i < n1 and k < n3):
        ans = max(
            ans,
            getMaxSum(
                i +
                1,
                j,
                k +
                1,
                arr1,
                arr2,
                arr3) +
            arr1[i] *
            arr3[k])
    if (j < n2 and k < n3):
        ans = max(
            ans,
            getMaxSum(
                i,
                j +
                1,
                k +
                1,
                arr1,
                arr2,
                arr3) +
            arr2[j] *
            arr3[k])
    dp[i][j][k] = ans
    return dp[i][j][k]


def reverse(tmp):
    i, k, t = 0, 0, 0
    n = len(tmp)
    for i in range(n // 2):
        t = tmp[i]
        tmp[i] = tmp[n - i - 1]
        tmp[n - i - 1] = t


def maxProductSum(arr1, arr2, arr3):
    for i in range(len(dp)):
        for j in range(len(dp[0])):
            for k in range(len(dp[j][0])):
                dp[i][j][k] = -1
    arr1 .sort()
    reverse(arr1)
    arr2 .sort()
    reverse(arr2)
    arr3 .sort()
    reverse(arr3)
    return getMaxSum(0, 0, 0, arr1, arr2, arr3)


if __name__ == '__main__':
    n1 = 2
    arr1 = [3, 5]
    n2 = 2
    arr2 = [2, 1]
    n3 = 3
    arr3 = [4, 3, 5]
    print(maxProductSum(arr1, arr2, arr3))

# Expected output:
43
# largest lexicographic triplet from a given array that forms a triangle | function to find lexicographically largest triplet that forms a triangle in the given array ; sort the array ; iterate from the end of the array ; if the triplet forms a triangle ; if triplet found ; print the triplet ; otherwise ; 
def findTriplet(arr, N):
    arr .sort()
    i = N - 1
    while i - 2 >= 0:
        if (arr[i - 2] + arr[i - 1] > arr[i]):
            flag = 1
            break
        i -= 1
    if (flag):
        print(arr[i - 2], arr[i - 1], arr[i])
    else:
        print(-1)


if __name__ == '__main__':
    arr = [4, 2, 10, 3, 5]
    N = len(arr)
    findTriplet(arr, N)

# Expected output:
3 4 5
# count of all pairs in an array with minimum absolute difference | function to return the count of all pairs having minimal absolute difference ; stores the count of pairs ; sort the array ; stores the minimum difference between adjacent pairs ; update the minimum difference between pairs ; increase count of pairs with difference equal to that of minimum difference ; return the final count ; 
def numberofpairs(arr, N):
    answer = 0
    arr .sort()
    minDiff = 10000000
    for i in range(0, N - 1):
        minDiff = min(minDiff, arr[i + 1] - arr[i])
    for i in range(0, N - 1):
        if arr[i + 1] - arr[i] == minDiff:
            answer += 1
    return answer


if __name__ == '__main__':
    arr = [4, 2, 1, 3]
    N = len(arr)
    print(numberofpairs(arr, N))

# Expected output:
3
# maximum size subset with given sum using backtracking | initialise maximum possible length of subsequence ; store elements to compare max_length with its size and change the value of max_length accordingly ; store the elements of the longest subsequence ; function to find the length of longest subsequence ; update max_length ; store the subsequence elements ; recursively proceed with obtained sum ; poping elements from back of vector store ; if sum > 0 then we don 't  required thatsubsequence  so return and continue  with earlier elements ; sort the given array ; traverse the array ; if max_length is already greater than or equal than remaining length ; 

max_length = 0
store = []
ans = []


def find_max_length(arr, index, sum, k):
    global max_length
    sum = sum + arr[index]
    store .append(arr[index])
    if (sum == k):
        if (max_length < len(store)):
            max_length = len(store)
            ans = store
    for i in range(index + 1, len(arr)):
        if (sum + arr[i] <= k):
            find_max_length(arr, i, sum, k)
            store .pop()
        else:
            return
    return


def longestSubsequence(arr, n, k):
    arr .sort()
    for i in range(n):
        if (max_length >= n - i):
            break
        store .clear()
        find_max_length(arr, i, 0, k)
    return max_length


if __name__ == "__main__":
    arr = [-3, 0, 1, 1, 2]
    n = len(arr)
    k = 1
    print(longestSubsequence(arr, n, k))

# Expected output:
5
# sort decreasing permutation of n using triple swaps | function to sort array ; check if possible to sort array ; swapping to bring element at required position bringing at least one element at correct position ; tracing changes in array ; print the sorted array ; if not possible to sort ; 
def sortArray(A, N):
    if (N % 4 == 0 or N % 4 == 1):
        for i in range(N // 2):
            x = i
            if (i % 2 == 0):
                y = N - i - 2
                z = N - i - 1
            A[z] = A[y]
            A[y] = A[x]
            A[x] = x + 1
        print("Sorted Array: ", end="")
        for i in range(N):
            print(A[i], end=" ")
    else:
        print("-1")


A = [5, 4, 3, 2, 1]
N = len(A)
sortArray(A, N)

# Expected output:
Sorted Array: 1 2 3 4 5
# find k such that changing all elements of the array greater than k to k will make array sum n | function to return k such that changing all elements greater than k to k will make array sum n otherwise return - 1 ; sorting the array in increasing order ; loop through all the elements of the array ; checking if sum of array equals n ; 
def findK(arr, size, N):
    arr = sorted(arr)
    temp_sum = 0
    for i in range(size):
        temp_sum += arr[i]
        if (N - temp_sum == arr[i] * (size - i - 1)):
            return arr[i]
    return -1


arr = [3, 1, 10, 4, 8]
size = len(arr)
N = 16
print(findK(arr, size, N))

# Expected output:
4
# find three element from given three arrays such that their sum is x | set 2 | function that returns true if there exists a triplet with sum x ; sorting arrays such that a represents smallest array ; iterating the smallest array ; two pointers on second and third array ; if a valid triplet is found ; 
def existsTriplet(a, b, c, x, l1, l2, l3):
    if (l2 <= l1 and l2 <= l3):
        l1, l2 = l2, l1
        a, b = b, a
    elif (l3 <= l1 and l3 <= l2):
        l1, l3 = l3, l1
        a, c = c, a
    for i in range(l1):
        j = 0
        k = l3 - 1
        while (j < l2 and k >= 0):
            if (a[i] + b[j] + c[k] == x):
                return True
            if (a[i] + b[j] + c[k] < x):
                j += 1
            else:
                k -= 1
    return False


a = [2, 7, 8, 10, 15]
b = [1, 6, 7, 8]
c = [4, 5, 5]
l1 = len(a)
l2 = len(b)
l3 = len(c)
x = 14
if (existsTriplet(a, b, c, x, l1, l2, l3)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# arrange given numbers to form the smallest number | utility function to print the contents of an array ; a comparison function that return true if ' ab ' is smaller than ' ba ' when we concatenate two numbers ' a ' and ' b ' for example , it will return true if we pass 12 and 24 as arguments . this function will be used by sort ( ) function ; convert first number to string format ; convert second number to string format ; check if ' ab ' is smaller or ' ba ' and return bool value since comparison operator ' < = ' returns true or false ;  ; function to print the arrangement with the smallest value ; if we pass the name of the comparison function it will sort the array according to the compare function ; print the sorted array ; 
def printArr(arr, n):
    for i in range(0, n):
        print(arr[i], end="")


def compare(num1, num2):
    A = str(num1)
    B = str(num2)
    return int(A + B) <= int(B + A)


def sort(arr):
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            if compare(arr[i], arr[j]) == False:
                arr[i], arr[j] = arr[j], arr[i]


def printSmallest(N, arr):
    sort(arr)
    printArr(arr, N)


if __name__ == "__main__":
    arr = [5, 6, 2, 9, 21, 1]
    N = len(arr)
    printSmallest(N, arr)

# Expected output:
1212569
# permute two arrays such that sum of every pair is greater or equal to k | check whether any permutation exists which satisfy the condition . ; sort the array a [ ] in decreasing order . ; sort the array b [ ] in increasing order . ; checking condition on each index . ; 
def isPossible(a, b, n, k):
    a .sort(reverse=True)
    b .sort()
    for i in range(n):
        if (a[i] + b[i] < k):
            return False
    return True


a = [2, 1, 3]
b = [7, 8, 9]
k = 10
n = len(a)
if (isPossible(a, b, n, k)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# sort an array according to count of set bits | function to count setbits ; function to sort by setbitcount ; iterate over all values and insert into multimap ; 
def setBitCount(num):
    count = 0
    while (num):
        if (num & 1):
            count += 1
        num = num >> 1
    return count


def sortBySetBitCount(arr, n):
    count = []
    for i in range(n):
        count .append([(-1) * setBitCount(arr[i]), arr[i]])
    count .sort(key=lambda x: x[0])
    for i in range(len(count)):
        print(count[i][1], end=" ")


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

# Expected output:
3 5 6 1 2 4
# check if end of given binary string can be reached by choosing jump value in between given range | function to check if it is possible to reach the end of the binary string using the given jumps ; stores the dp states ; initial state ; stores count of indices from which it is possible to reach index i ; traverse the given string ; update the values of pre accordingly ; if the jump size is out of the range [ l , r ] ; return answer ; 
def canReach(s, L, R):
    dp = [0 for _ in range(len(s))]
    dp[0] = 1
    pre = 0
    for i in range(1, len(s)):
        if (i >= L):
            pre += dp[i - L]
        if (i > R):
            pre -= dp[i - R - 1]
        dp[i] = (pre > 0) and (s[i] == '0')
    return dp[len(s) - 1]


if __name__ == "__main__":
    S = "01101110"
    L = 2
    R = 3
    if canReach(S, L, R):
        print("Yes")
    else:
        print("No")

# Expected output:
No
# split an array into subarrays with maximum bitwise xor of their respective bitwise or values | recursive function to find all the possible breaking of arrays o subarrays and find the maximum bitwise xor ; if the value of n is 0 ; stores the result if the new group is formed with the first element as arr [ i ] ; stores if the result if the arr [ i ] is included in the last group ; returns the maximum of x and y ; function to find the maximum possible bitwise xor of all possible values of the array after breaking the arrays o subarrays ; return the result ; 
def maxXORUtil(arr, N, xrr, orr):
    if (N == 0):
        return xrr ^ orr
    x = maxXORUtil(arr, N - 1, xrr ^ orr, arr[N - 1])
    y = maxXORUtil(arr, N - 1, xrr, orr | arr[N - 1])
    return max(x, y)


def maximumXOR(arr, N):
    return maxXORUtil(arr, N, 0, 0)


arr = 1, 5, 7
N = len(arr)
print(maximumXOR(arr, N))

# Expected output:
7
# construct an n | python3 program to implement the above approach ; keep track of visited nodes ; function to construct a tree such that there are no two adjacent nodes with the same weight ; if minimum and maximum elements are equal , i . e . array contains one distinct element ; tree cannot be constructed ; otherwise ; tree can be constructed ; choose weights [ 0 ] as root ; first node is visited ; traverse the array ; otherwise , make an edge ; mark this node as visited ; find a weight not same as the root & make edges with that node ; join non - roots with remaining nodes ; check if current node ' s ▁ weight ▁ ▁ is ▁ same ▁ as ▁ root ▁ node ' s weight and if it is not visited or not ; 

N = 10 ** 5 + 5
visited = [0] * N


def construct_tree(weights, n):
    minimum = min(weights)
    maximum = max(weights)
    if (minimum == maximum):
        print("No")
        return
    else:
        print("Yes")
    root = weights[0]
    visited[1] = 1
    for i in range(n):
        if (weights[i] != root and visited[i + 1] == 0):
            print(1, i + 1)
            visited[i + 1] = 1
    notroot = 0
    for i in range(n):
        if (weights[i] != root):
            notroot = i + 1
            break
    for i in range(n):
        if (weights[i] == root and visited[i + 1] == 0):
            print(notroot, i + 1)
            visited[i + 1] = 1


if __name__ == '__main__':
    weights = [1, 2, 1, 2, 5]
    N = len(weights)
    construct_tree(weights, N)

# Expected output:
Yes
1 2
1 4
1 5
2 3
# minimize cost to convert given string into concatenation of equal substrings of length k | python3 program for the above approach ; function to find minimum cost to convert given string into string of k length same substring ; stores length of string ; stores the minimum cost ; traverse left substring of k length ; stores the frequency ; stores minimum cost for sequence of s [ i ] % k indices ; check for optimal character ; find sum of distance ' a ' + ch from character s [ i ] % k indices ; choose minimum cost for each index i ; increment ans ; print minimum cost to convert string ; 

import sys


def minCost(s, k):
    n = len(s)
    ans = 0
    for i in range(k):
        a = [0] * 26
        for j in range(i, n, k):
            a[ord(s[j]) - ord('a')] += 1
        min_cost = sys .maxsize - 1
        for ch in range(26):
            cost = 0
            for tr in range(26):
                cost += abs(ch - tr) * a[tr]
            min_cost = min(min_cost, cost)
        ans += min_cost
    print(ans)


S = "abcdefabc"
K = 3
minCost(S, K)

# Expected output:
9
# split first n natural numbers into two sets with minimum absolute difference of their sums | function to split the first n natural numbers into two sets having minimum absolute difference of their sums ; 
def minAbsDiff(N):
    if (N % 4 == 0 or N % 4 == 3):
        return 0
    return 1


N = 6
print(minAbsDiff(N))

# Expected output:
1
# minimize cost to swap two given arrays | python3 program to implement the above approach ; function to calculate and return the minimum cost required to swap two arrays ; return the total minimum cost ; 

import sys


def getMinCost(A, B, N):
    mini = sys .maxsize
    for i in range(N):
        mini = min(mini, min(A[i], B[i]))
    return mini * (2 * N - 1)


N = 3
A = [1, 4, 2]
B = [10, 6, 12]
print(getMinCost(A, B, N))

# Expected output:
5
# print all possible ways to write n as sum of two or more positive integers | function to print the values stored in vector arr ; traverse the vector arr ; recursive function to prdifferent ways in which n can be written as a sum of at 2 or more positive integers ; if n is zero then prthis ways of breaking numbers ; start from previous element in the representation till n ; include current element from representation ; call function again with reduced sum ; backtrack to remove current element from representation ; 
def printVector(arr):
    if (len(arr) != 1):
        for i in range(len(arr)):
            print(arr[i], end=" ")
        print()


def findWays(arr, i, n):
    if (n == 0):
        printVector(arr)
    for j in range(i, n + 1):
        arr .append(j)
        findWays(arr, j, n - j)
        del arr[-1]


if __name__ == '__main__':
    n = 4
    arr = []
    findWays(arr, 1, n)

# Expected output:
1 1 1 1 
1 1 2 
1 3 
2 2
# check if a string can be split into two strings with same number of k | function to print the arrangement of characters ; stores frequency of characters ; count the character having frequency k ; count the character having frequency greater than k and not equal to 2 k ; case 1 ; case 2 ; case 3 ; if all cases fail ; 
def DivideString(s, n, k):
    c = 0
    no = 1
    c1 = 0
    c2 = 0
    fr = [0] * 26
    ans = []
    for i in range(n):
        fr[ord(s[i]) - ord('a')] += 1
    for i in range(26):
        if (fr[i] == k):
            c += 1
        if (fr[i] > k and fr[i] != 2 * k):
            c1 += 1
            ch = chr(ord('a') + i)
        if (fr[i] == 2 * k):
            c2 += 1
            ch1 = chr(ord('a') + i)
    for i in range(n):
        ans .append("1")
    mp = {}
    if (c % 2 == 0 or c1 > 0 or c2 > 0):
        for i in range(n):
            if (fr[ord(s[i]) - ord('a')] == k):
                if (s[i] in mp):
                    ans[i] = '2'
                else:
                    if (no <= (c // 2)):
                        ans[i] = '2'
                        no += 1
                        mp[s[i]] = 1
        if (c % 2 == 1 and c1 > 0):
            no = 1
            for i in range(n):
                if (s[i] == ch and no <= k):
                    ans[i] = '2'
                    no += 1
        if (c % 2 == 1 and c1 == 0):
            no = 1
            flag = 0
            for i in range(n):
                if (s[i] == ch1 and no <= k):
                    ans[i] = '2'
                    no += 1
                if (fr[s[i] - 'a'] == k and flag == 0 and ans[i] == '1'):
                    ans[i] = '2'
                    flag = 1
        print("".join(ans))
    else:
        print("NO")


if __name__ == '__main__':
    S = "abbbccc"
    N = len(S)
    K = 1
    DivideString(S, N, K)

# Expected output:
1111211
# check if two items can be selected from two different categories without exceeding price | function to check if two items can be selected from two different categories without exceeding the total price ; loop to choose two different pairs using two nested loops ; condition to check if the price of these two elements is less than s ; 
def check(S, prices, type1, n):
    for j in range(0, n):
        for k in range(j + 1, n):
            if ((type1[j] == 0 and type1[k] == 1) or (
                    type1[j] == 1 and type1[k] == 0)):
                if (prices[j] + prices[k] <= S):
                    return "Yes"
    return "No"


prices = [3, 8, 6, 5]
type1 = [0, 1, 1, 0]
S = 10
n = 4
print(check(S, prices, type1, n))

# Expected output:
Yes
# find the maximum sum ( a + b ) for a given input integer n satisfying the given condition | function to return the maximum sum of a + b satisfying the given condition ; consider all possible pairs and check the sum divides product property ; to find the largest factor k ; check if the product is divisible by the sum ; storing the maximum sum in the max_sum variable ; return the max_sum value ; 
def getLargestSum(N):
    max_sum = 0
    for i in range(1, int(N ** (1 / 2)) + 1):
        for j in range(i + 1, int(N ** (1 / 2)) + 1):
            k = N // j
            a = k * i
            b = k * j
            if (a <= N and b <= N and a * b % (a + b) == 0):
                max_sum = max(max_sum, a + b)
    return max_sum


if __name__ == "__main__":
    N = 25
    max_sum = getLargestSum(N)
    print(max_sum)

# Expected output:
36
# encrypt a string by repeating i | function to return the encrypted string ; number of times the current character will be repeated ; repeat the current character in the encrypted string ; 
def encryptString(string, n):
    i, cnt = 0, 0
    encryptedStr = ""
    while i < n:
        cnt = i + 1
        while cnt > 0:
            encryptedStr += string[i]
            cnt -= 1
        i += 1
    return encryptedStr


if __name__ == "__main__":
    string = "geeks"
    n = len(string)
    print(encryptString(string, n))

# Expected output:
geeeeekkkksssss
# minimize the difference between the maximum and minimum values of the modified array | function to return required minimum difference ; finding minimum and maximum values ; returning minimum possible difference ; 
def minDiff(n, x, A):
    mn = A[0]
    mx = A[0]
    for i in range(0, n):
        mn = min(mn, A[i])
        mx = max(mx, A[i])
    return max(0, mx - mn - 2 * x)


n = 3
x = 3
A = [1, 3, 6]
print(minDiff(n, x, A))

# Expected output:
0
# minimum swaps for bracket balancing | python3 program to count swaps required to balance string ; stores total number of left and right brackets encountered ; swap stores the number of swaps required imbalance maintains the number of imbalance pair ; increment count of left bracket ; swaps count is last swap count + total number imbalanced brackets ; imbalance decremented by 1 as it solved only one imbalance of left and right ; increment count of right bracket ; imbalance is reset to current difference between left and right brackets ; 
def swapCount(s):
    chars = s
    countLeft = 0
    countRight = 0
    swap = 0
    imbalance = 0
    for i in range(len(chars)):
        if chars[i] == '[':
            countLeft += 1
            if imbalance > 0:
                swap += imbalance
                imbalance -= 1
        elif chars[i] == ']':
            countRight += 1
            imbalance = (countRight - countLeft)
    return swap


s = "[]][]["
print(swapCount(s))
s = "[[][]]"
print(swapCount(s))

# Expected output:
2
0
# longest subsequence from an array of pairs having first element increasing and second element decreasing . | function to find the length of the longest subsequence of pairs whose first element is increasing and second is decreasing ; dp [ i ] : stores the longest subsequence upto i ; base case ; when the conditions hold ; finally , prthe required answer ; 
def longestSubSequence(A, N):
    dp = [0] * N
    for i in range(N):
        dp[i] = 1
        for j in range(i):
            if (A[j][0] < A[i][0] and A[j][1] > A[i][1]):
                dp[i] = max(dp[i], dp[j] + 1)
    print(dp[N - 1])


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

# Expected output:
2