giulio98/xlcost-single-prompt huggingface dataset:
# rearrange array to maximize sum of gcd of array elements with their respective indices | function to find the maximum sum of gcd ( arr [ i ] , i ) by rearranging the array ; sort the array in ascending order ; stores maximum sum of gcd ( arr [ i ] , i ) by rearranging the array elements ; generate all possible permutations of the array ; stores sum of gcd ( arr [ i ] , i ) ; traverse the array ; update sum ; update res ; 
def __gcd(a, b):
    if b == 0:
        return a
    else:
        return __gcd(b, a % b)


def next_permutation(p):
    for a in range(len(p) - 2, -1, -1):
        if (p[a] < p[a + 1]):
            b = len(p) - 1
            while True:
                if (p[b] > p[a]):
                    t = p[a]
                    p[a] = p[b]
                    p[b] = t
                    a += 1
                    b = len(p) - 1
                    while a < b:
                        t = p[a]
                        p[a] = p[b]
                        p[b] = t
                        a += 1
                        b -= 1
                    return True
                b -= 1
    return False

def findMaxValByRearrArr(arr, N):
    arr .sort()
    res = 0
    while (True):
        Sum = 0
        for i in range(N):
            Sum += __gcd(i + 1, arr[i])
        res = max(res, Sum)
        if (not next_permutation(arr)):
            break
    return res


arr = [3, 2, 1]
N = len(arr)
print(findMaxValByRearrArr(arr, N))

# Expected output:
6
# minimum removals required to make frequency of each array element equal to its value | function to find the minimum count of elements required to be removed such that frequency of arr [ i ] equal to arr [ i ] ; stores frequency of each element of the array ; traverse the array ; update frequency of arr [ i ] ; stores minimum count of removals ; traverse the map ; stores key value of the map ; if frequency of i is less than i ; update cntminrem ; if frequency of i is greater than i ; update cntminrem ; 
def min_elements(arr, N):
    mp = {}
    for i in range(N):
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    cntMinRem = 0
    for it in mp:
        i = it
        if (mp[i] < i):
            cntMinRem += mp[i]
        elif (mp[i] > i):
            cntMinRem += (mp[i] - i)
    return cntMinRem


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

# Expected output:
2
# minimum increments to make all array elements equal with sum same as the given array after exactly one removal | function to check if an array of equal elements with sum equal to the given array can be obtained or not ; base case ; stores sum of array elements ; stores second largest array element ; stores the largest array element ; traverse the array ; update secmax ; update max ; update secmax ; update totalsum ; if totalsum is less than secmax * ( n - 1 ) ) ; if totalsum is not divisible by ( n - 1 ) ; 
def CheckAllarrayEqual(arr, N):
    if (N == 1):
        return True
    totalSum = arr[0]
    secMax = -10 ** 19
    Max = arr[0]
    for i in range(1, N):
        if (arr[i] >= Max):
            secMax = Max
            Max = arr[i]
        elif (arr[i] > secMax):
            secMax = arr[i]
        totalSum += arr[i]
    if ((secMax * (N - 1)) > totalSum):
        return False
    if (totalSum % (N - 1)):
        return False
    return True


if __name__ == '__main__':
    arr = [6, 2, 2, 2]
    N = len(arr)
    if (CheckAllarrayEqual(arr, N)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# count ways to make bitwise xor of odd and even indexed elements equal by removing an array element | function to count ways to make bitwise xor of odd and even indexed elements equal by removing an array element ; stores xor of odd and even indexed elements from the end ; stores xor of odd and even indexed elements from the start ; stores the required count ; traverse the array in reverse ; if i is odd ; if i is even ; traverse the array ; if i is odd ; if i is even ; removing arr [ i ] , post_even stores xor of odd indexed elements ; removing arr [ i ] , post_odd stores xor of even indexed elements ; check if they are equal ; if i is odd , xor it with curr_odd ; if i is even , xor it with curr_even ; finally print res ; 
def Remove_one_element(arr, n):
    post_odd = 0
    post_even = 0
    curr_odd = 0
    curr_even = 0
    res = 0
    for i in range(n - 1, -1, -1):
        if (i % 2):
            post_odd ^= arr[i]
        else:
            post_even ^= arr[i]
    for i in range(n):
        if (i % 2):
            post_odd ^= arr[i]
        else:
            post_even ^= arr[i]
        X = curr_odd ^ post_even
        Y = curr_even ^ post_odd
        if (X == Y):
            res += 1
        if (i % 2):
            curr_odd ^= arr[i]
        else:
            curr_even ^= arr[i]
    print(res)


if __name__ == "__main__":
    arr = [1, 0, 1, 0, 1]
    N = len(arr)
    Remove_one_element(arr, N)

# Expected output:
3
# count ways to make sum of odd and even indexed elements equal by removing an array element | function to count array indices whose removal makes sum of odd and even indexed elements equal ; if size of the array is 1 ; if size of the array is 2 ; stores sum of even - indexed elements of the given array ; stores sum of odd - indexed elements of the given array ; traverse the array ; if i is an even number ; update sumeven ; if i is an odd number ; update sumodd ; stores sum of even - indexed array elements till i - th index ; stores sum of odd - indexed array elements till i - th index ; stores count of indices whose removal makes sum of odd and even indexed elements equal ; stores sum of even - indexed elements after removing the i - th element ; stores sum of odd - indexed elements after removing the i - th element ; traverse the array ; if i is an odd number ; update currodd ; update newevensum ; update newoddsum ; if i is an even number ; update curreven ; update newoddsum ; update newevensum ; if newevensum is equal to newoddsum ; increase the count ; if sum of even - indexed and odd - indexed elements is equal by removing the first element ; increase the count ; if length of the array is an odd number ; if sum of even - indexed and odd - indexed elements is equal by removing the last element ; increase the count ; if length of the array is an even number ; if sum of even - indexed and odd - indexed elements is equal by removing the last element ; increase the count ; 
def cntIndexesToMakeBalance(arr, n):
    if (n == 1):
        return 1
    if (n == 2):
        return 0
    sumEven = 0
    sumOdd = 0
    for i in range(n):
        if (i % 2 == 0):
            sumEven += arr[i]
        else:
            sumOdd += arr[i]
    currOdd = 0
    currEven = arr[0]
    res = 0
    newEvenSum = 0
    newOddSum = 0
    for i in range(1, n - 1):
        if (i % 2):
            currOdd += arr[i]
            newEvenSum = (currEven + sumOdd - currOdd)
            newOddSum = (currOdd + sumEven - currEven - arr[i])
        else:
            currEven += arr[i]
            newOddSum = (currOdd + sumEven - currEven)
            newEvenSum = (currEven + sumOdd - currOdd - arr[i])
        if (newEvenSum == newOddSum):
            res += 1
    if (sumOdd == sumEven - arr[0]):
        res += 1
    if (n % 2 == 1):
        if (sumOdd == sumEven - arr[n - 1]):
            res += 1
    else:
        if (sumEven == sumOdd - arr[n - 1]):
            res += 1
    return res


if __name__ == "__main__":
    arr = [1, 1, 1]
    n = len(arr)
    print(cntIndexesToMakeBalance(arr, n))

# Expected output:
3
# find two numbers from their sum and xor | set 2 | function to find the value of a and b whose sum is x and xor is y ; initialize the two numbers ; case 1 : x < y ; case 2 : x - y is odd ; case 3 : if both sum and xor are equal ; case 4 : if above cases fails ; update the value of a ; check if a & y value is 0 ; if true , update b ; otherwise assign - 1 to a , - 1 to b ; prthe numbers a and b ; 
def findNums(X, Y):
    A = 0
    B = 0
    if (X < Y):
        A = -1
        B = -1
    elif (((abs(X - Y)) & 1) != 0):
        A = -1
        B = -1
    elif (X == Y):
        A = 0
        B = Y
    else:
        A = (X - Y) // 2
        if ((A & Y) == 0):
            B = (A + Y)
        else:
            A = -1
            B = -1
    print(A)
    print(B)


if __name__ == '__main__':
    X = 17
    Y = 13
    findNums(X, Y)

# Expected output:
2
15
# queries to check if count of increasing and decreasing subarrays is same in given range | function to check if given range have equal number of increasing as well as decreasing subarrays ; traverse each query ; for 0 - based indexing ; condition for same count of increasing & decreasing subarray ; 
def checkCount(A, Q, q):
    for i in range(q):
        L = Q[i][0]
        R = Q[i][1]
        L -= 1
        R -= 1
        if ((A[L] < A[L + 1]) != (A[R - 1] < A[R])):
            print("Yes")
        else:
            print("No")


if __name__ == '__main__':
    arr = [11, 13, 12, 14]
    Q = [[1, 4], [2, 4]]
    q = len(Q)
    checkCount(arr, Q, q)

# Expected output:
No
Yes
# mean of array generated by products of all pairs of the given array | function to find the mean of pair product array of arr ; store product of pairs ; generate all unordered pairs ; store product of pairs ; size of pairarray ; store sum of pairarray ; stores the mean of pairarray ; find mean of pairarray ; return the resultant mean ; 
def pairProductMean(arr, N):
    pairArray = []
    for i in range(N):
        for j in range(i + 1, N):
            pairProduct = arr[i] * arr[j]
            pairArray .append(pairProduct)
    length = len(pairArray)
    sum = 0
    for i in range(length):
        sum += pairArray[i]
    mean = 0
    if (length != 0):
        mean = sum / length
    else:
        mean = 0
    return mean


if __name__ == '__main__':
    arr = [1, 2, 4, 8]
    N = len(arr)
    print("{0:.2f}".format(pairProductMean(arr, N)))

# Expected output:
11.67
# smallest number exceeding n whose kth bit is set | function to find the number greater than n whose kth bit is set ; iterate from n + 1 ; check if kth bit is set or not ; increment m for next number ; return the minimum value ; 
def find_next(n, k):
    M = n + 1
    while (True):
        if ((M & (1 << k)) > 0):
            break
        M += 1
    return M


if __name__ == '__main__':
    N = 15
    K = 2
    print(find_next(N, K))

# Expected output:
20
# smallest number exceeding n whose kth bit is set | function to find the number greater than n whose kth bit is set ; stores the resultant number ; if kth bit is not set ; cur will be the sum of all powers of 2 < k ; if the current bit is set ; add kth power of 2 to n and subtract the all powers of 2 less than k that are set ; if the kth bit is set ; first unset bit position ; sum of bits that are set ; add kth power of 2 to n and subtract the all powers of 2 less than k that are set ; if kth bit became unset then set it again ; return the resultant number ; 
def find_next(n, k):
    ans = 0
    if ((n & (1 << k)) == 0):
        cur = 0
        for i in range(k):
            if (n & (1 << i)):
                cur += 1 << i
        ans = n - cur + (1 << k)
    else:
        first_unset_bit, cur = -1, 0
        for i in range(64):
            if ((n & (1 << i)) == 0):
                first_unset_bit = i
                break
            else:
                cur += (1 << i)
        ans = n - cur + (1 << first_unset_bit)
        if ((ans & (1 << k)) == 0):
            ans += (1 << k)
    return ans


N, K = 15, 2
print(find_next(N, K))

# Expected output:
20
# lexicographically largest possible string after removal of k characters | python3 program to implement the above approach ; final result string ; if the current char exceeds the character at the top of the stack ; remove from the end of the string ; decrease k for the removal ; insert current character ; perform remaining k deletions from the end of the string ; return the string ; 
def largestString(num, k):
    ans = []
    for i in range(len(num)):
        while (len(ans) and ans[-1] < num[i] and k > 0):
            ans .pop()
            k -= 1
        ans .append(num[i])
    while (len(ans) and k):
        k -= 1
        ans .pop()
    return ans


str = "zyxedcba"
k = 1
print(*largestString(str, k), sep="")

# Expected output:
zyxedcb
# maximum length of subarray consisting of same type of element on both halves of sub | function that finds the maximum length of the sub - array that contains equal element on both halves of sub - array ; to store continuous occurence of the element ; to store continuous forward occurence ; to store continuous backward occurence ; to store the maximum length ; find maximum length ; print the result ; 
def maxLengthSubArray(A, N):
    forward = [0] * N
    backward = [0] * N
    for i in range(N):
        if i == 0 or A[i] != A[i - 1]:
            forward[i] = 1
        else:
            forward[i] = forward[i - 1] + 1
    for i in range(N - 1, -1, -1):
        if i == N - 1 or A[i] != A[i + 1]:
            backward[i] = 1
        else:
            backward[i] = backward[i + 1] + 1
    ans = 0
    for i in range(N - 1):
        if (A[i] != A[i + 1]):
            ans = max(ans, min(forward[i], backward[i + 1]) * 2)
    print(ans)


arr = [1, 2, 3, 4, 4, 4, 6, 6, 6, 9]
N = len(arr)
maxLengthSubArray(arr, N)

# Expected output:
6
# smallest n digit number divisible by all possible prime digits | python3 implementation of the above approach ; function to find the minimum number of n digits divisible by all prime digits . ; 

from math import *


def minNum(n):
    if n < 3:
        print(-1)
    else:
        print(210 * (10 ** (n - 1) // 210 + 1))


n = 5
minNum(n)

# Expected output:
10080
# smallest number greater than y with sum of digits equal to x | function to return the minimum string of length d having the sum of digits s ; return a string of length d ; greedily put 9 's  in the end ; put remaining sum ; function to find the smallest number greater than y whose sum of digits is x ; convert number y to string ; maintain prefix sum of digits ; iterate over y from the back where k is current length of suffix ; stores current digit ; increase current digit ; sum upto current prefix ; return answer if remaining sum can be obtained in suffix ; find suffix of length k having sum of digits x - r ; append current character ; return the result ; 
def helper(d, s):
    ans = ['0'] * d
    for i in range(d - 1, -1, -1):
        if (s >= 9):
            ans[i] = '9'
            s -= 9
        else:
            c = chr(s + ord('0'))
            ans[i] = c
            s = 0
    return ''.join(ans)


def findMin(x, Y):
    y = str(Y)
    n = len(y)
    p = [0] * n
    for i in range(n):
        p[i] = (ord(y[i]) - ord('0'))
        if (i > 0):
            p[i] += p[i - 1]
    n - 1
    k = 0
    while True:
        d = 0
        if (i >= 0):
            d = (ord(y[i]) - ord('0'))
        for j in range(d + 1, 10):
            r = ((i > 0) * p[i - 1] + j)
            if (x - r >= 0 and x - r <= 9 * k):
                suf = helper(k, x - r)
                pre = ""
                if (i > 0):
                    pre = y[0:i]
                cur = chr(j + ord('0'))
                pre += cur
                return pre + suf
        i -= 1
        k += 1


if __name__ == "__main__":
    x = 18
    y = 99
    print(findMin(x, y))

# Expected output:
189
# largest number made up of x and y with count of x divisible by y and of y by x | function to generate and return the largest number ; store the smaller in y ; store the larger in x ; stores respective counts ; if n is divisible by y ; append x , n times to the answer ; reduce n to zero ; reduce n by x ; append y , x times to the answer ; if number can be formed ; otherwise ; 
def largestNumber(n, X, Y):
    maxm = max(X, Y)
    Y = X + Y - maxm
    X = maxm
    Xs = 0
    Ys = 0
    while (n > 0):
        if (n % Y == 0):
            Xs += n
            n = 0
        else:
            n -= X
            Ys += X
    if (n == 0):
        while (Xs > 0):
            Xs -= 1
            print(X, end='')
        while (Ys > 0):
            Ys -= 1
            print(Y, end='')
    else:
        print("-1")


n = 19
X = 7
Y = 5
largestNumber(n, X, Y)

# Expected output:
7777755555555555555
# minimum flips required to generate continuous substrings of 0 â €™ s and 1 â €™ s | python3 implementation of the above approach ; traverse input string and store the count of 0 ; traverse the input string again to find minimum number of flips ; 
def minChanges(str, N):
    count0 = 0
    count1 = 0
    for x in str:
        count0 += (x == '0')
    res = count0
    for x in str:
        count0 -= (x == '0')
        count1 += (x == '1')
        res = min(res, count1 + count0)
    return res


N = 9
str = "000101001"
print(minChanges(str, N))

# Expected output:
2
# missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum | python3 implementation of the missing number such that maximum absolute difference between adjacent element is minimum ; function to find the missing number such that maximum absolute difference is minimum ; loop to find the maximum and minimum adjacent element to missing number ; 

import sys


def missingnumber(n, arr) -> int:
    mn = sys .maxsize
    mx = -sys .maxsize - 1
    for i in range(n):
        if (i > 0 and arr[i] == -1 and arr[i - 1] != -1):
            mn = min(mn, arr[i - 1])
            mx = max(mx, arr[i - 1])
        if (i < (n - 1) and arr[i] == -1 and arr[i + 1] != -1):
            mn = min(mn, arr[i + 1])
            mx = max(mx, arr[i + 1])
    res = (mx + mn) / 2
    return res


if __name__ == '__main__':
    n = 5
    arr = [-1, 10, -1, 12, -1]
    res = missingnumber(n, arr)
    print(res)

# Expected output:
11.0
# maximize [ length ( x ) / 2 ^ ( xor ( x , y ) ) ] by choosing substrings x and y from string a and b respectively | function to find the length of the longest common substring of the string x and y ; lcsuff [ i ] [ j ] stores the lengths of the longest common suffixes of substrings ; itearate over strings a and b ; if first row or column ; if matching is found ; otherwise , if matching is not found ; finally , return the resultant maximum value lcs ; 
def LCSubStr(A, B, m, n):
    LCSuff = [[0 for i in range(n + 1)]for j in range(m + 1)]
    result = 0
    for i in range(m + 1):
        for j in range(n + 1):
            if (i == 0 or j == 0):
                LCSuff[i][j] = 0
            elif (A[i - 1] == B[j - 1]):
                LCSuff[i][j] = LCSuff[i - 1][j - 1] + 1
                result = max(result, LCSuff[i][j])
            else:
                LCSuff[i][j] = 0
    return result


if __name__ == '__main__':
    A = "0110"
    B = "1101"
    M = len(A)
    N = len(B)
    print(LCSubStr(A, B, M, N))

# Expected output:
3
# count ways to split array into pair of subsets with difference between their sum equal to k | python program for the above approach ; to store the states of dp ; function to find count of subsets with a given sum ; base case ; if an already computed subproblem occurs ; set the state as solved ; recurrence relation ; function to count ways to split array into pair of subsets with difference k ; store the total sum of element of the array ; traverse the array ; calculate sum of array elements ; store the required sum ; prthe number of subsets with sum equal to s1 ; 

maxN = 20
maxSum = 50
minSum = 50
Base = 50
dp = [[0 for i in range(maxSum + minSum)]for j in range(maxN)]
v = [[False for i in range(maxSum + minSum)]for j in range(maxN)]


def findCnt(arr, i, required_sum, n):
    if (i == n):
        if (required_sum == 0):
            return 1
        else:
            return 0
    if (v[i][required_sum + Base]):
        return dp[i][required_sum + Base]
    v[i][required_sum + Base] = True
    dp[i][required_sum + Base] = findCnt(arr,
                                         i + 1,
                                         required_sum,
                                         n) + findCnt(arr,
                                                      i + 1,
                                                      required_sum - arr[i],
                                                      n)
    return dp[i][required_sum + Base]


def countSubsets(arr, K, n):
    sum = 0
    for i in range(n):
        sum += arr[i]
    S1 = (sum + K) // 2
    print(findCnt(arr, 0, S1, n))


if __name__ == '__main__':
    arr = [1, 1, 2, 3]
    N = len(arr)
    K = 1
    countSubsets(arr, K, N)

# Expected output:
3
# probability that the sum of all numbers obtained on throwing a dice n times lies between two given integers | python program for above approach ; function to calculate the probability for the given sum to be equal to sum in n throws of dice ; base cases ; 

dp = [[0 for i in range(605)]for j in range(105)]


def find(N, sum):
    if (N < 0 | sum < 0):
        return 0
    if (dp[N][sum] > 0):
        return dp[N][sum]
    if (sum > 6 * N or sum < N):
        return 0
    if (N == 1):
        if (sum >= 1 and sum <= 6):
            return (float)(1.0 / 6)
        else:
            return 0
    for i in range(1, 7):
        dp[N][sum] = dp[N][sum] + find(N - 1, sum - i) / 6
    return dp[N][sum]


if __name__ == '__main__':
    N = 4
    a = 13
    b = 17
    probability = 0.0
    f = 0
    for sum in range(a, b + 1):
        probability = probability + find(N, sum)
    print("%.6f" % probability)

# Expected output:
0.505401
# minimum steps to reduce n to 0 by given operations | function to find the minimum number to steps to reduce n to 0 ; dictionary for storing the precomputed sum ; bases cases ; check if n is not in dp then only call the function so as to reduce no of recursive calls ; return the answer ; 
def count(n):
    dp = dict()
    dp[0] = 0
    dp[1] = 1
    if n not in dp:
        dp[n] = 1 + min(n % 2 + count(n // 2), n % 3 + count(n // 3))
    return dp[n]


N = 6
print(str(count(N)))

# Expected output:
3
# minimum count of increment of k size subarrays required to form a given array | function to find the minimum number of operations required to change all the array of zeros such that every element is greater than the given array ; declaring the difference array of size n ; number of operations ; first update the d [ i ] value with the previous value ; the index i has to be incremented ; we have to perform ( b [ i ] - d [ i ] ) operations more ; increment the range i to i + k by need ; check if i + k is valid index ; 
def find_minimum_operations(n, b, k):
    d = [0 for i in range(n + 1)]
    operations = 0
    for i in range(n):
        d[i] += d[i - 1]
        if b[i] > d[i]:
            operations += (b[i] - d[i])
            need = (b[i] - d[i])
            d[i] += need
            if i + k <= n:
                d[i + k] -= need
    return operations


if __name__ == "__main__":
    n = 5
    b = [1, 2, 3, 4, 5]
    k = 2
    print(find_minimum_operations(n, b, k))

# Expected output:
9