giulio98/xlcost-single-prompt huggingface dataset:
# lexicographically largest permutation by sequentially inserting array elements at ends | function to find the lexicographically largest permutation by sequentially inserting the array elements ; stores the current state of the new array ; stores ythe current maximum element of array arr [ ] ; iterate the array elements ; if the current element is smaller than the current maximum , then insert ; if the current element is at least the current maximum ; update the value of the current maximum ; print resultant permutation ; 

from typing import Deque


def largestPermutation(arr, N):
    p = Deque()
    mx = arr[0]
    p .append(arr[0])
    for i in range(1, N):
        if (arr[i] < mx):
            p .append(arr[i])
        else:
            p .appendleft(arr[i])
            mx = arr[i]
    for i in p:
        print(i, end=" ")


if __name__ == "__main__":
    arr = [3, 1, 2, 4]
    N = len(arr)
    largestPermutation(arr, N)

# Expected output:
4 3 1 2
# largest value of k that a set of all possible subset | function to find maximum count of consecutive integers from 0 in set s of all possible subset - sum ; stores the maximum possible integer ; sort the given array in non - decrasing order ; iterate the given array ; if arr [ i ] <= x + 1 , then update x otherwise break the loop ; return answer ; 
def maxConsecutiveCnt(arr):
    X = 0
    arr .sort()
    for i in range(0, len(arr)):
        if (arr[i] <= (X + 1)):
            X = X + arr[i]
        else:
            break
    return X + 1


if __name__ == "__main__":
    arr = [1, 1, 1, 4]
    print(maxConsecutiveCnt(arr))

# Expected output:
8
# minimize product of first 2 ^ kâ €“ 1 natural numbers by swapping bits for any pair any number of times | function to find the minimum positive product after swapping bits at the similar position for any two numbers ; stores the resultant number ; range / 2 numbers will be 1 and range / 2 numbers will be range - 1 ; multiply with the final number ; return the answer ; 
def minimumPossibleProduct(K):
    res = 1
    r = (1 << K) - 1
    for i in range(0, K):
        res *= (r - 1)
    res *= r
    return res


K = 3
print(minimumPossibleProduct(K))

# Expected output:
1512
# maximum size of subset of given array such that a triangle can be formed by any three integers as the sides of the triangle | function to find the maximum size of the subset of the given array such that a triangle can be formed from any three integers of the subset as sides ; sort arr [ ] in increasing order ; stores the maximum size of a valid subset of the given array ; stores the starting index of the current window ; stores the last index of the current window ; iterate over the array arr [ ] ; increment j till the value of arr [ i ] + arr [ i + 1 ] > arr [ j ] holds true ; update the value of maxsize ; return answer ; 
def maximizeSubset(arr, N):
    arr .sort()
    maxSize = 0
    i = 0
    j = i + 2
    while (i < N - 2):
        while (j < N and arr[i] + arr[i + 1] > arr[j]):
            j = j + 1
        maxSize = max(maxSize, j - i)
        i += 1
        j = max(j, i + 2)
    return maxSize


if __name__ == "__main__":
    arr = [2, 7, 4, 1, 6, 9, 5, 3]
    N = len(arr)
    print(maximizeSubset(arr, N))

# Expected output:
4
# maximum possible value of array elements that can be made based on given capacity conditions | function to find the maximum element after shifting operations in arr [ ] ; stores the sum of array element ; stores the maximum element in cap [ ] ; iterate to find maximum element ; return the resultant maximum value ; 
def maxShiftArrayValue(arr, cap, N):
    sumVals = 0
    for i in range(N):
        sumVals += arr[i]
    maxCapacity = 0
    for i in range(N):
        maxCapacity = max(cap[i], maxCapacity)
    return min(maxCapacity, sumVals)


if __name__ == '__main__':
    arr = [2, 3]
    cap = [5, 6]
    N = len(arr)
    print(maxShiftArrayValue(arr, cap, N))

# Expected output:
5
# minimize cost to connect the graph by connecting any pairs of vertices having cost at least 0 | python 3 program for the above approach ; function to perform the find operation to find the parent of a disjoint set ; function to perform union operation of disjoint set union ; update the minimum value such than it should be greater than 0 ; update the minimum value such than it should be greater than 0 ; function to minimize the cost to make the graph connected as per the given condition ; stores the parent elements of sets ; stores the rank of the sets ; stores the minvalue of the sets ; update parent [ i ] to i ; update minvalue [ i ] to cost [ i - 1 ] ; add i . first and i . second elements to the same set ; stores the parent elements of the different components ; insert parent of i to s ; stores the minimum value from s ; flag to mark if any minimum value is negative ; if minval [ i ] is negative ; mark flag as true ; update the minimum value ; stores minimum cost to add the edges ; if the given graph is connected or components minimum values not having any negative edge ; update the mincost ; print the value of mincost ; print - 1 ; 

import sys


def Find(parent, a):
    if parent[parent[a]] != parent[a]:
        parent[a] = Find(parent, parent[a])
    return parent[a]


def Union(parent, rank, minVal, a, b):
    a = Find(parent, a)
    b = Find(parent, b)
    if (rank[a] == rank[b]):
        rank[a] += 1
    if (rank[a] > rank[b]):
        parent[b] = a
        if (minVal[a] >= 0 and minVal[b] >= 0):
            minVal[a] = min(minVal[a], minVal[b])
        elif (minVal[a] >= 0 and minVal[b] < 0):
            minVal[a] = minVal[a]
        elif (minVal[a] < 0 and minVal[b] >= 0):
            minVal[a] = minVal[b]
        else:
            minVal[a] = max(minVal[a], minVal[b])
    else:
        parent[a] = b
        if (minVal[a] >= 0 and minVal[b] >= 0):
            minVal[b] = min(minVal[a], minVal[b])
        elif (minVal[a] >= 0 and minVal[b] < 0):
            minVal[b] = minVal[a]
        elif (minVal[a] < 0 and minVal[b] >= 0):
            minVal[b] = minVal[b]
        else:
            minVal[b] = max(minVal[a], minVal[b])


def findMinCost(G, cost, N, M):
    parent = [0 for i in range(N + 1)]
    rank = [0 for i in range(N + 1)]
    minVal = [0 for i in range(N + 1)]
    for i in range(1, N + 1, 1):
        parent[i] = i
        minVal[i] = cost[i - 1]
    for i in G:
        Union(parent, rank, minVal, i[0], i[1])
    s = set()
    for i in range(1, N + 1, 1):
        s .add(Find(parent, i))
    min1 = [0, sys .maxsize]
    flag = False
    for i in s:
        if (minVal[i] < 0):
            flag = True
        if (min1[1] > minVal[i]):
            min1 = [i, minVal[i]]
    minCost = 0
    if (flag == False or (flag and len(s) == 1)):
        for i in s:
            if (i != min1[0]):
                minCost += (minVal[i] + min1[1])
        print(minCost)
    else:
        print(-1)


if __name__ == '__main__':
    N = 6
    G = [[3, 1], [2, 3], [2, 1], [4, 5], [5, 6], [6, 4]]
    cost = [2, 1, 5, 3, 2, 9]
    M = len(G)
    findMinCost(G, cost, N, M)

# Expected output:
3
# minimum size of array possible with given sum and product values | function to find the minimum size of array with sum s and product p ; base case ; iterate through all values of s and check the mentioned condition ; otherwise , print " - 1" ; 
def minimumSizeArray(S, P):
    if (S == P):
        return 1
    for i in range(2, S + 1):
        d = i
        if ((S / d) >= pow(P, 1.0 / d)):
            return i
    return -1


if __name__ == "__main__":
    S = 5
    P = 6
    print(minimumSizeArray(S, P))

# Expected output:
2
# smallest possible integer to be added to n | function to find the smallest positive integer x such that x is added to every element of a except one element to give array b ; stores the unique elements of array a ; insert a [ i ] into the set s ; sort array a [ ] ; sort array b [ ] ; assume x value as b [ 0 ] - a [ 1 ] ; check if x value assumed is negative or 0 ; update the x value to b [ 0 ] - a [ 0 ] ; if assumed value is wrong ; update x value ; 
def findVal(A, B, N):
    s = set()
    for i in range(N):
        s .add(A[i])
    A .sort()
    B .sort()
    X = B[0] - A[1]
    if (X <= 0):
        X = B[0] - A[0]
    else:
        for i in range(N - 1):
            if (B[i] - X not in s):
                X = B[0] - A[0]
                break
    print(X)


if __name__ == '__main__':
    A = [1, 4, 3, 8]
    B = [15, 8, 11]
    N = len(A)
    findVal(A, B, N)

# Expected output:
7
# count of integral points that lie at a distance d from origin | python 3 program for the above approach ; function to find the total valid integer coordinates at a distance d from origin ; stores the count of valid points ; iterate over possibel x coordinates ; find the respective y coordinate with the pythagoras theorem ; adding 4 to compensate the coordinates present on x and y axes . ; return the answer ; 

from math import sqrt


def countPoints(D):
    count = 0
    for x in range(1, int(sqrt(D * D)), 1):
        y = int(sqrt((D * D - x * x)))
        if (x * x + y * y == D * D):
            count += 4
    count += 4
    return count


if __name__ == '__main__':
    D = 5
    print(countPoints(D))

# Expected output:
12
# sum of the shortest distance between all 0 s to 1 in given binary string | function to find the total sum of the shortest distance between every 0 to 1 in a given binary string ; stores the prefix distance and suffix distance from 0 to 1 ; stores the current distance from 1 to 0 ; marks the 1 ; if current character is 1 ; mark haveone to true ; assign the cnt to 0 ; assign prefixdistance [ i ] as 0 ; if haveone is true ; update the cnt ; update prefixdistance [ i ] ; assign prefixdistance [ i ] as int_max ; assign haveone as false ; if current character is 1 ; mark haveone to true ; assign the cnt to 0 ; assign the suffixdistance [ i ] as 0 ; if haveone is true ; update the cnt ; update suffixdistance [ i ] as cnt ; assign suffixdistance [ i ] as int_max ; stores the total sum of distances between 0 to nearest 1 ; if current character is 0 ; update the value of sum ; print the value of the sum ; 

INT_MAX = 2147483647


def findTotalDistance(S, N):
    prefixDistance = [0 for _ in range(N)]
    suffixDistance = [0 for _ in range(N)]
    cnt = 0
    haveOne = False
    for i in range(0, N):
        if (S[i] == '1'):
            haveOne = True
            cnt = 0
            prefixDistance[i] = 0
        elif (haveOne):
            cnt = cnt + 1
            prefixDistance[i] = cnt
        else:
            prefixDistance[i] = INT_MAX
    haveOne = False
    for i in range(N - 1, -1, -1):
        if (S[i] == '1'):
            haveOne = True
            cnt = 0
            suffixDistance[i] = 0
        elif (haveOne):
            cnt = cnt + 1
            suffixDistance[i] = cnt
        else:
            suffixDistance[i] = INT_MAX
    sum = 0
    for i in range(0, N):
        if (S[i] == '0'):
            sum += min(prefixDistance[i], suffixDistance[i])
    print(sum)


if __name__ == "__main__":
    S = "100100"
    N = len(S)
    findTotalDistance(S, N)

# Expected output:
5
# minimize value of | a | function to find the minimum possible value of | a - x | + | b - y | + | c - z | such that x * y = z for given a , b and c ; stores the minimum value of | a - x | + | b - y | + | c - z | such that x * y = z ; iterate over all values of i in the range [ 1 , 2 * c ] ; iterate over all values of j such that i * j <= 2 * c ; update the value of ans ; return answer ; 
def minimizeCost(A, B, C):
    ans = A + B + C
    for i in range(1, 2 * C + 1):
        j = 0
        while (i * j <= 2 * C):
            ans = min(ans, abs(A - i) + abs(B - j) + abs(i * j - C))
            j += 1
    return ans


A = 19
B = 28
C = 522
print(minimizeCost(A, B, C))

# Expected output:
2
# average value of set bit count in given binary string after performing all possible choices of k operations | function to calculate the average number of set bits after after given operations ; stores the average number of set bits after current operation ; stores the average number of set bits after current operation ; iterate through the array arr [ ] and update the values of p and q ; store the value of p and q of the previous state before their updation ; update average number of set bits after performing the ith operation ; update average number of off bits after performing the ith operation ; return answer ; 
def averageSetBits(N, K, arr):
    p = N
    q = 0
    for i in range(K):
        _p = p
        _q = q
        p = _p - _p * arr[i] / N + _q * arr[i] / N
        q = _q - _q * arr[i] / N + _p * arr[i] / N
    return p


if __name__ == "__main__":
    N = 5
    arr = [1, 2, 3]
    K = len(arr)
    print("%.2f" % averageSetBits(N, K, arr))

# Expected output:
2.44
# find maximum sum of subsequence after flipping signs of at most k elements in given array | function to calculate the max sum of subsequence ; variable to store the max sum ; sort the array ; iterate over the array ; flip sign ; decrement k ; traverse over the array ; add only positive elements ; return the max sum ; 
def maxSubseq(arr, N, K):
    sum = 0
    arr .sort()
    for i in range(N):
        if (K == 0):
            break
        if (arr[i] < 0):
            arr[i] = -arr[i]
            K -= 1
    for i in range(N):
        if (arr[i] > 0):
            sum += arr[i]
    return sum


if __name__ == "__main__":
    arr = [6, -10, -1, 0, -4, 2]
    K = 2
    N = len(arr)
    print(maxSubseq(arr, N, K))

# Expected output:
22
# minimum number of intervals to cover the target interval | function to find the minimum number of intervals in the array a [ ] to cover the entire target interval ; sort the array a [ ] in increasing order of starting point ; insert a pair of int_max to prevent going out of bounds ; stores start of current interval ; stores end of current interval ; stores the count of intervals ; iterate over all the intervals ; if starting point of current index <= start ; update the value of start ; increment the value of count ; if the target interval is already covered or it is not possible to move then break the loop ; if the entire target interval is not covered ; return answer ; 
def minimizeSegment(A, X):
    A .sort()
    INT_MAX = 2147483647
    A .append([INT_MAX, INT_MAX])
    start = X[0]
    end = X[0] - 1
    cnt = 0
    for i in range(0, len(A)):
        if (A[i][0] <= start):
            end = max(A[i][1], end)
            i = i + 1
        else:
            start = end
            cnt = cnt + 1
            if (A[i][0] > end or end >= X[1]):
                break
    if (end < X[1]):
        return -1
    return cnt


if __name__ == "__main__":
    A = [[1, 3], [2, 4], [2, 10], [2, 3], [1, 1]]
    X = [1, 10]
    print(minimizeSegment(A, X))

# Expected output:
2
# k | function to calculate k - th smallest solution ( y ) of equation x + y = x | y ; initialize the variable to store the answer ; the i - th bit of x is off ; the i - bit of k is on ; divide k by 2 ; if k becomes 0 then break ; 
def KthSolution(X, K):
    ans = 0
    for i in range(0, 64):
        if (not (X & (1 << i))):
            if (K & 1):
                ans |= (1 << i)
            K >>= 1
            if (not K):
                break
    return ans


if __name__ == "__main__":
    X = 5
    K = 5
    print(KthSolution(X, K))

# Expected output:
18
# find range of values for s in given array with values satisfying [ arr [ i ] = floor ( ( i * s ) / k ) ] | python 3 program for the above approach ; function to find the range of values for s in a given array that satisfies the given condition ; stores the left range value ; stores the right range value ; find the current left range value for s ; find the current right range value for s ; updating l value ; updating r value ; 

from math import ceil, floor
import sys


def findRange(arr, N, K):
    L = -sys .maxsize - 1
    R = sys .maxsize
    for i in range(N):
        l = ceil(1.0 * arr[i] * K / (i + 1))
        r = ceil((1.0 + arr[i]) * K / (i + 1) - 1)
        L = max(L, l)
        R = min(R, r)
    print(L, R)


if __name__ == '__main__':
    arr = [2, 4, 6, 9, 11]
    K = 10
    N = len(arr)
    findRange(arr, N, K)

# Expected output:
23 23
# find an anagram of given string having different characters at corresponding indices | function to find anagram of string such that characters at the same indices are different ; copying our original string for comparison ; declaring the two pointers ; checking the given condition ; when string length is odd ; the mid element ; if the characters are the same , then perform the swap operation as illustrated ; check if the corresponding indices has the same character or not ; if string follows required condition ; 
def findAnagram(s):
    check = s
    st = list(s)
    i = 0
    j = len(st) - 1
    while (i < len(st) and j >= 0):
        if (st[i] != st[j] and check[i] != st[j] and check[j] != st[i]):
            st[i], st[j] = st[j], st[i]
            i += 1
            j = len(st) - 1
        else:
            j -= 1
    if (len(st) % 2 != 0):
        mid = len(st) / 2
        if (check[mid] == st[mid]):
            for i in range(len(st)):
                if (check[i] != st[mid] and st[i] != st[mid]):
                    st[i], st[mid] = st[mid], st[i]
                    break
    ok = True
    for i in range(len(st)):
        if (check[i] == st[i]):
            ok = False
            break
    if (ok):
        print("".join(st))
    else:
        print(-1)


if __name__ == "__main__":
    S = "geek"
    findAnagram(S)

# Expected output:
egke
# lexicographically smallest permutation of [ 1 , n ] based on given binary string | function to generate the lexicographically smallest permutation according to the given criteria ; stores the resultant permutation ; initialize the first elements to 1 ; traverse the given string s ; number greater than last number ; number equal to the last number ; correct all numbers to the left of the current index ; printing the permutation ; 
def constructPermutation(S, N):
    ans = [0] * N
    ans[0] = 1
    for i in range(1, N):
        if (S[i - 1] == '0'):
            ans[i] = i + 1
        else:
            ans[i] = ans[i - 1]
        for j in range(i):
            if (ans[j] >= ans[i]):
                ans[j] += 1
    for i in range(N):
        print(ans[i], end="")
        if (i != N - 1):
            print(" ", end="")


S = "100101"
constructPermutation(S, len(S) + 1)

# Expected output:
2 1 3 5 4 7 6
# kth smallest positive integer y such that its sum with x is same as its bitwise or with x | function to calculate k - th smallest solution ( y ) of equation x + y = x | y ; initialize the variable to store the answer ; the i - th bit of x is off ; the i - bit of k is on ; divide k by 2 ; if k becomes 0 then break ; 
def KthSolution(X, K):
    ans = 0
    for i in range(64):
        if not (X & (1 << i)):
            if (K & 1):
                ans |= (1 << i)
            K >>= 1
            if not K:
                break
    return ans


X = 10
K = 5
print(KthSolution(X, K))

# Expected output:
17
# count of distinct n | function to find the count of distinct arrays of size n having elements in range [ 1 , k ] and all adjacent elements ( p , q ) follows ( p <= q ) or ( p % q > 0 ) ; stores the divisors of all integers in the range [ 1 , k ] ; calculate the divisors of all integers using the sieve ; stores the dp states such that dp [ i ] [ j ] with i elements having j as the last element of array ; initialize the dp array ; calculate the dp states using the derived relation ; calculate the sum for len - 1 ; subtract dp [ len - 1 ] [ j ] for each factor of j from [ 1 , k ] ; calculate the final result ; return the resultant sum ; 
def countArrays(n, k):
    divisors = [[]for i in range(k + 1)]
    for i in range(1, k + 1, 1):
        for j in range(2 * i, k + 1, i):
            divisors[j].append(i)
    dp = [[0 for i in range(k + 1)]for j in range(n + 1)]
    for j in range(1, k + 1, 1):
        dp[1][j] = 1
    for x in range(2, n + 1, 1):
        sum = 0
        for j in range(1, k + 1, 1):
            sum += dp[x - 1][j]
        for y in range(1, k + 1, 1):
            dp[x][y] = sum
            for d in divisors[y]:
                dp[x][y] = (dp[x][y] - dp[x - 1][d])
    sum = 0
    for j in range(1, k + 1, 1):
        sum += dp[n][j]
    return sum


if __name__ == '__main__':
    N = 2
    K = 3
    print(countArrays(N, K))

# Expected output:
7
# minimize increment | function to calculate the minimum number of operations to convert array a to array b by incrementing and decrementing adjacent elements ; stores the final count ; stores the sum of array a and b respectivelly ; check of the sums are unequall ; pointer to iterate through array ; case 1 where a [ i ] > b [ i ] ; stores the extra values for the current index ; iterate the array from [ i - 1 , 0 ] ; stores the count of values being transfered from a [ i ] to a [ j ] ; add operation count ; iterate the array in right direction id a [ i ] - b [ i ] > 0 ; iterate the array from [ i + 1 , n - 1 ] ; stores the count of values being transfered from a [ i ] to a [ j ] ; add operation count ; return answer ; 
def minimumMoves(A, B, N):
    ans = 0
    sum_A = 0
    sum_B = 0
    for i in range(N):
        sum_A += A[i]
    for i in range(N):
        sum_B += B[i]
    if (sum_A != sum_B):
        return -1
    i = 0
    while (i < N):
        if (A[i] > B[i]):
            temp = A[i] - B[i]
            j = i - 1
            while (j >= 0 and temp > 0):
                if (B[j] > A[j]):
                    cnt = min(temp, (B[j] - A[j]))
                    A[j] += cnt
                    temp -= cnt
                    ans += (cnt * abs(j - i))
                j -= 1
            if (temp > 0):
                j = i + 1
                while (j < N and temp > 0):
                    if (B[j] > A[j]):
                        cnt = min(temp, (B[j] - A[j]))
                        A[j] += cnt
                        temp -= cnt
                        ans += (cnt * abs(j - i))
                    j += 1
        i += 1
    return ans


if __name__ == '__main__':
    A = [1, 5, 7]
    B = [13, 0, 0]
    N = len(A)
    print(minimumMoves(A, B, N))

# Expected output:
19
# check if x can be reduced to 0 in exactly t moves by substracting d or 1 from it | function to check the above problem condition ; check the base case . ; check if x - t is a divisor of d - 1 ; 
def possibleReachingSequence(X, D, T):
    if X < T:
        return "NO"
    if T * D < X:
        return "NO"
    if (X - T) % (D - 1) == 0:
        return "YES"
    return "NO"


X = 10
D = 3
T = 6
print(possibleReachingSequence(X, D, T))

# Expected output:
YES
# maximum number of times array can be reduced in half when its all elements are even | python 3 code implementation for the above approach ; function to return the number of operations possible ; counter to store the number of times the current element is divisible by 2 ; variable to store the final answer ; initialize the counter to zero for each element ; update the counter till the number is divisible by 2 ; update the answer as the minimum of all the counts ; 

import sys


def arrayDivisionByTwo(arr, n):
    cnt = 0
    ans = sys .maxsize
    for i in range(n):
        cnt = 0
        while (arr[i] % 2 == 0):
            arr[i] = arr[i] // 2
            cnt += 1
        ans = min(ans, cnt)
    return ans


if __name__ == '__main__':
    arr = [8, 12, 40]
    n = len(arr)
    print(arrayDivisionByTwo(arr, n))

# Expected output:
2