giulio98/xlcost-single-prompt huggingface dataset:
# maximum length subsequence with alternating sign and maximum sum | function to find the subsequence with alternating sign having maximum size and maximum sum . ; find whether each element is positive or negative ; find the required subsequence ; find the maximum element in the specified range ; print the result ; 
def findSubsequence(arr, n):
    sign = [0] * n
    for i in range(n):
        if (arr[i] > 0):
            sign[i] = 1
        else:
            sign[i] = -1
    k = 0
    result = [0] * n
    i = 0
    while i < n:
        cur = arr[i]
        j = i
        while (j < n and sign[i] == sign[j]):
            cur = max(cur, arr[j])
            j += 1
        result[k] = cur
        k += 1
        i = j - 1
        i += 1
    for i in range(k):
        print(result[i], end=" ")


if __name__ == '__main__':
    arr = [-4, 9, 4, 11, -5, -17, 9, -3, -5, 2]
    n = len(arr)
    findSubsequence(arr, n)

# Expected output:
-4 11 -5 9 -3 2
# longest palindrome in a string formed by concatenating its prefix and suffix | function to check whether the string is a palindrome ; reverse the string to compare with the original string ; check if both are same ; function to find the longest palindrome in a string formed by concatenating its prefix and suffix ; length of the string ; finding the length upto which the suffix and prefix forms a palindrome together ; check whether the string has prefix and suffix substrings which are palindromes . ; removing the suffix and prefix substrings which already forms a palindrome and storing them in separate strings ; check all prefix substrings in the remaining string str ; check if the prefix substring is a palindrome ; if the prefix substring is a palindrome then check if it is of maximum length so far ; check all the suffix substrings in the remaining string str ; check if the suffix substring is a palindrome ; if the suffix substring is a palindrome then check if it is of maximum length so far ; combining all the thee parts of the answer ; 
def isPalindrome(r):
    p = r
    p = "".join(reversed(p))
    return (r == p)


def PrefixSuffixPalindrome(st):
    n = len(st)
    length = 0
    for i in range(n // 2):
        if (st[i] != st[n - i - 1]):
            length = i
            break
    prefix = ""
    suffix = ""
    midPal = ""
    prefix = st[:length]
    suffix = st[n - length:]
    st = st[length:n - 2 * length + length]
    for i in range(1, len(st) + 1):
        y = st[0:i]
        if (isPalindrome(y)):
            if (len(midPal) < len(y)):
                midPal = y
    for i in range(1, len(st) + 1):
        y = st[len(st) - i]
        if (isPalindrome(y)):
            if (len(midPal) < len(y)):
                midPal = y
    answer = prefix + midPal + suffix
    return answer


if __name__ == "__main__":
    st = "abcdfdcecba"
    print(PrefixSuffixPalindrome(st))

# Expected output:
abcdfdcba
# minimize the maximum difference between adjacent elements in an array | python3 implementation to find the minimum of the maximum difference of the adjacent elements after removing k elements from the array ; function to find the minimum of the maximum difference of the adjacent elements after removing k elements from the array ; initialising the minimum difference ; traversing over subsets in iterative manner ; number of elements to be taken in the subset on bits of i represent elements not to be removed ; if the removed set is of size k ; creating the new array after removing elements ; maximum difference of adjacent elements of remaining array ; 

import sys
INT_MAX = sys .maxsize
INT_MIN = -(sys .maxsize - 1)


def minimumAdjacentDifference(a, n, k):
    minDiff = INT_MAX
    for i in range(1 << n):
        cnt = bin(i).count('1')
        if (cnt == n - k):
            temp = []
            for j in range(n):
                if ((i & (1 << j)) != 0):
                    temp .append(a[j])
            maxDiff = INT_MIN
            for j in range(len(temp) - 1):
                maxDiff = max(maxDiff, temp[j + 1] - temp[j])
            minDiff = min(minDiff, maxDiff)
    return minDiff


if __name__ == "__main__":
    n = 5
    k = 2
    a = [3, 7, 8, 10, 14]
    print(minimumAdjacentDifference(a, n, k))

# Expected output:
2
# minimize the maximum difference between adjacent elements in an array | python3 implementation to find the minimum of the maximum difference of the adjacent elements after removing k elements from the array ; function to find the minimum of the maximum difference of the adjacent elements after removing k elements from the array ; initialising the minimum difference ; iterating over all subarrays of size n - k ; maximum difference after removing elements ; minimum adjacent difference ; 

import sys
INT_MAX = sys .maxsize
INT_MIN = -(sys .maxsize - 1)


def minimumAdjacentDifference(a, n, k):
    minDiff = INT_MAX
    for i in range(k + 1):
        maxDiff = INT_MIN
        for j in range(n - k - 1):
            for p in range(i, i + j + 1):
                maxDiff = max(maxDiff, a[p + 1] - a[p])
        minDiff = min(minDiff, maxDiff)
    return minDiff


if __name__ == "__main__":
    n = 5
    k = 2
    a = [3, 7, 8, 10, 14]
    print(minimumAdjacentDifference(a, n, k))

# Expected output:
2
# minimize the maximum difference between adjacent elements in an array | python3 implementation to find the minimum of the maximum difference of the adjacent elements after removing k elements from the array ; function to find the minimum different in the subarrays of size k in the array ; create a double ended queue , qi that will store indexes of array elements , queue will store indexes of useful elements in every window ; process first k ( or first window ) elements of array ; for every element , the previous smaller elements are useless so remove them from qi ; add new element at rear of queue ; process rest of the elements , i . e . , from arr [ k ] to arr [ n - 1 ] ; the element at the front of the queue is the largest element of previous window ; remove the elements which are out of this window ; remove all elements smaller than the currently being added element ( remove useless elements ) ; add current element at the rear of qi ; compare the maximum element of last window ; function to find the minimum of the maximum difference of the adjacent elements after removing k elements from the array ; create the difference array ; find minimum of all maximum of subarray sizes n - k - 1 ; 

import sys


def findKMin(arr, n, k):
    Qi = []
    i = 0

    for j in range(k):
        while ((len(Qi) != 0) and
               arr[i] >= arr[Qi[-1]]):
            Qi.pop()
        Qi.append(i)
        i += 1

    minDiff = sys.maxsize
    for j in range(i, n):
        minDiff = min(minDiff, arr[Qi[0]])
        while ((len(Qi) != 0) and
               Qi[0] <= i - k):
            Qi.pop(0)
        while ((len(Qi) != 0) and
               arr[i] >= arr[Qi[-1]]):
            Qi.pop()
        Qi.append(i)
        i += 1
    minDiff = min(minDiff, arr[Qi[0]])

    return minDiff


def minimumAdjacentDifference(a, n, k):
    diff = [0 for i in range(n - 1)]

    for i in range(n - 1):
        diff[i] = a[i + 1] - a[i]
    answer = findKMin(diff, n - 1,
                      n - k - 1)
    return answer


if __name__ == "__main__":
    n = 5
    k = 2
    a = [3, 7, 8, 10, 14]
    print(minimumAdjacentDifference(a, n, k))

# Expected output:
2
# minimum elements inserted in a sorted array to form an arithmetic progression | function to find the greatest common divisor of two numbers ; function to find the minimum the minimum number of elements required to be inserted into array ; difference array of consecutive elements of the array ; gcd of the difference array ; loop to calculate the minimum number of elements required ; 
def gcdFunc(a, b):
    if (b == 0):
        return a
    return gcdFunc(b, a % b)


def findMinimumElements(a, n):
    b = [0] * (n - 1)
    for i in range(1, n):
        b[i - 1] = a[i] - a[i - 1]
    gcd = b[0]
    for i in range(n - 1):
        gcd = gcdFunc(gcd, b[i])
    ans = 0
    for i in range(n - 1):
        ans += (b[i] // gcd) - 1
    return ans


arr1 = [1, 6, 8, 10, 14, 16]
n1 = len(arr1)
print(findMinimumElements(arr1, n1))

# Expected output:
10
# check if a sequence is a concatenation of two permutations | function to check if a given sequence is a concatenation of two permutations or not ; computing the sum of all the elements in the array ; computing the prefix sum for all the elements in the array ; iterating through the i from lengths 1 to n - 1 ; sum of first i + 1 elements ; sum of remaining n - i - 1 elements ; lengths of the 2 permutations ; checking if the sums satisfy the formula or not ; 
def checkPermutation(arr, n):
    sum = 0
    for i in range(n):
        sum += arr[i]
    prefix = [0] * (n + 1)
    prefix[0] = arr[0]
    for i in range(n):
        prefix[i] = prefix[i - 1] + arr[i]
    for i in range(n - 1):
        lsum = prefix[i]
        rsum = sum - prefix[i]
        l_len = i + 1
        r_len = n - i - 1
        if (((2 * lsum) == (l_len * (l_len + 1)))
                and ((2 * rsum) == (r_len * (r_len + 1)))):
            return True
    return False


if __name__ == '__main__':
    arr = [1, 2, 5, 3, 4, 1, 2]
    n = len(arr)
    if (checkPermutation(arr, n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# find a n | function that prthe answer ; if n == 1 then it is not possible ; loop to n - 1 times ; print as last digit of the number ; 
def findTheNumber(n):
    if (n == 1):
        print("Impossible")
        return
    for i in range(n - 1):
        print("5", end="")
    print("4")


if __name__ == '__main__':
    n = 12
    findTheNumber(n)

# Expected output:
555555555554
# queries to check whether bitwise and of a subarray is even or odd | python implementation of the approach ; function to precompute the count of even and odd numbers ; if the current element is odd then put 1 at odd [ i ] ; if the current element is even then put 1 at even [ i ] ; taking the prefix sums of these two arrays so we can get the count of even and odd numbers in a range [ l , r ] in o ( 1 ) ; function that returns true if the bitwise and of the subarray a [ l ... r ] is odd ; cnt will store the count of odd numbers in the range [ l , r ] ; check if all the numbers in the range are odd or not ; function to perform the queries ; perform queries ; 

MAXN = 1000005
even = [0] * MAXN
odd = [0] * MAXN


def precompute(arr, n):
    for i in range(n):
        if (arr[i] % 2 == 1):
            odd[i] = 1
        if (arr[i] % 2 == 0):
            even[i] = 1
    for i in range(1, n):
        even[i] = even[i] + even[i - 1]
        odd[i] = odd[i] + odd[i - 1]


def isOdd(L, R):
    cnt = odd[R]
    if (L > 0):
        cnt -= odd[L - 1]
    if (cnt == R - L + 1):
        return True
    return False


def performQueries(a, n, q, m):
    precompute(a, n)
    for i in range(m):
        L = q[i][0]
        R = q[i][1]
        if (isOdd(L, R)):
            print("Odd")
        else:
            print("Even")


if __name__ == '__main__':
    a = [2, 1, 5, 7, 6, 8, 9]
    n = len(a)
    q = [[0, 2], [1, 2], [2, 3], [3, 6]]
    m = len(q)
    performQueries(a, n, q, m)

# Expected output:
Even
Odd
Odd
Even
# find distinct integers for a triplet with given product | python3 implementation of the approach ; function to find the required triplets ; to store the factors ; find factors in sqrt ( x ) time ; choose a factor ; choose another factor ; these conditions need to be met for a valid triplet ; print the valid triplet ; triplet found ; triplet not found ; 

from math import sqrt


def findTriplets(x):
    fact = []
    factors = set()
    for i in range(2, int(sqrt(x))):
        if (x % i == 0):
            fact .append(i)
            if (x / i != i):
                fact .append(x // i)
            factors .add(i)
            factors .add(x // i)
    found = False
    k = len(fact)
    for i in range(k):
        a = fact[i]
        for j in range(k):
            b = fact[j]
            if ((a != b) and (x % (a * b) == 0) and (x / (a * b) != a)
                    and (x / (a * b) != b) and (x / (a * b) != 1)):
                print(a, b, x // (a * b))
                found = True
                break
        if (found):
            break
    if (not found):
        print("-1")


if __name__ == "__main__":
    x = 105
    findTriplets(x)

# Expected output:
3 5 7
# count of pairs satisfying the given condition | function to return the number of pairs satisfying the equation ; converting integer b to string by using to_function ; loop to check if all the digits of b are 9 or not ; if '9' doesn 't appear  then break the loop ; if all the digits of b contain 9 then multiply a with length else multiply a with length - 1 ; return the number of pairs ; 
def countPair(a, b):
    s = str(b)
    i = 0
    while i < (len(s)):
        if (s[i] != '9'):
            break
        i += 1
    result = 0
    if (i == len(s)):
        result = a * len(s)
    else:
        result = a * (len(s) - 1)
    return result


a = 5
b = 101
print(countPair(a, b))

# Expected output:
10
# partition the digits of an integer such that it satisfies a given condition | function to generate sequence from the given string ; initialize vector to store sequence ; first add all the digits of group a from left to right ; then add all the digits of group b from left to right ; return the sequence ; function that returns true if the sequence is non - decreasing ; initialize result ; function to partition the digits of an integer such that it satisfies the given conditions ; convert the integer to string ; length of the string ; array to store the digits ; storing the digits of x in array ; initialize the result ; loop through the digits ; put into group a if digit less than d ; put into group b if digit greater than d ; put into group c if digit equal to d ; loop through the digits to decide for group c digits ; set flag equal to true if group b digit present ; if flag is true put in group a or else put in b ; generate the sequence from partition ; check if the sequence is non decreasing ; return - 1 if no such partition is possible ; 
def makeSeq(s, a):
    seq = []
    for i in range(len(s)):
        if (s[i] == 'A'):
            seq .append(a[i])
    for i in range(len(s)):
        if (s[i] == 'B'):
            seq .append(a[i])
    return seq


def checkSeq(v):
    check = True
    for i in range(1, len(v)):
        if (v[i] < v[i - 1]):
            check = False
    return check


def digitPartition(X):
    num = str(X)
    l = len(num)
    a = [0] * l
    for i in range(l):
        a[i] = (ord(num[i]) - ord('0'))
    for D in range(10):
        res = ""
        for i in range(l):
            if (a[i] < D):
                res += 'A'
            elif (a[i] > D):
                res += 'B'
            else:
                res += 'C'
        flag = False
        for i in range(l):
            if (res[i] == 'B'):
                flag = True
            res = list(res)
            if (res[i] == 'C'):
                res[i] = 'A'if flag else 'B'
        seq = makeSeq(res, a)
        if (checkSeq(seq)):
            return "".join(res)
    return "-1"


if __name__ == "__main__":
    X = 777147777
    print(digitPartition(X))

# Expected output:
BBBAABBBB
# area of the circle that has a square and a circle inscribed in it | python3 implementation of the approach ; function to return the required area ; calculate the area ; 

import math


def getArea(a):
    area = (math .pi * a * a) / 4
    return area


a = 3
print('{0:.6f}'.format(getArea(a)))

# Expected output:
7.068583
# check if all the elements can be made of same parity by inverting adjacent elements | function to check if parity can be made same or not ; iterate and count the parity ; odd ; even ; condition check ; 
def flipsPossible(a, n):
    count_odd = 0
    count_even = 0
    for i in range(n):
        if (a[i] & 1):
            count_odd += 1
        else:
            count_even += 1
    if (count_odd % 2 and count_even % 2):
        return False
    else:
        return True


if __name__ == "__main__":
    a = [1, 0, 1, 1, 0, 1]
    n = len(a)
    if (flipsPossible(a, n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# queries on array with disappearing and reappearing elements | function to perform the queries ; size of the array with 1 - based indexing ; number of queries ; iterating through the queries ; if m is more than the size of the array ; count of turns ; find the remainder ; if the remainder is 0 and turn is odd then the array is empty ; if the remainder is 0 and turn is even then array is full and is in its initial state ; if the remainder is not 0 and the turn is even ; current size of the array ; current size of the array ; print the result ; 
def PerformQueries(a, vec):
    ans = []
    n = len(a) - 1
    q = len(vec)
    for i in range(q):
        t = vec[i][0]
        m = vec[i][1]
        if (m > n):
            ans .append(-1)
            continue
        turn = t // n
        rem = t % n
        if (rem == 0 and turn % 2 == 1):
            ans .append(-1)
            continue
        if (rem == 0 and turn % 2 == 0):
            ans .append(a[m])
            continue
        if (turn % 2 == 0):
            cursize = n - rem
            if (cursize < m):
                ans .append(-1)
                continue
            ans .append(a[m + rem])
        else:
            cursize = rem
            if (cursize < m):
                ans .append(-1)
                continue
            ans .append(a[m])
    for i in ans:
        print(i)


if __name__ == "__main__":
    a = [-1, 1, 2, 3, 4, 5]
    vec = [[1, 4], [6, 1], [3, 5]]
    PerformQueries(a, vec)

# Expected output:
5
1
-1
# number of pairs in an array having sum equal to product | function to return the count of the required pairs ; find the count of 0 s and 2 s in the array ; find the count of required pairs ; return the count ; 
def sumEqualProduct(a, n):
    zero = 0
    two = 0
    for i in range(n):
        if a[i] == 0:
            zero += 1
        if a[i] == 2:
            two += 1
    cnt = (zero * (zero - 1)) // 2 + (two * (two - 1)) // 2
    return cnt


a = [2, 2, 3, 4, 2, 6]
n = len(a)
print(sumEqualProduct(a, n))

# Expected output:
3
# minimize the sum of digits of a and b such that a + b = n | function to return the minimum possible sum of digits of a and b such that a + b = n ; find the sum of digits of n ; if num is a power of 10 ; 
def minSum(n):
    sum = 0
    while (n > 0):
        sum += (n % 10)
        n //= 10
    if (sum == 1):
        return 10
    return sum


if __name__ == "__main__":
    n = 1884
    print(minSum(n))

# Expected output:
21
# optimal strategy for a game | special gold coin | function to return the winner of the game ; to store the count of silver coins ; update the position of the gold coin ; first player will win the game ; 
def getWinner(string, length):
    total = 0
    for i in range(length):
        if (string[i] == 'S'):
            total += 1
    if ((total % 2) == 1):
        return "First"
    return "Second"


if __name__ == "__main__":
    string = "GSSS"
    length = len(string)
    print(getWinner(string, length))

# Expected output:
First
# find the coordinates of a triangle whose area = ( s / 2 ) | python3 implementation of the approach ; function to find the triangle with area = ( s / 2 ) ; fix the two pairs of coordinates ; find ( x3 , y3 ) with integer coordinates ; 

MAX = 1000000000


def findTriangle(S):
    X1 = 0
    Y1 = 0
    X2 = MAX
    Y2 = 1
    X3 = (MAX - S % MAX) % MAX
    Y3 = (S + X3) / MAX
    print("(", X1, ",", Y1, ")")
    print("(", X2, ",", Y2, ")")
    print("(", X3, ",", Y3, ")")


if __name__ == "__main__":
    S = 4
    findTriangle(S)

# Expected output:
( 0 , 0 )
( 1000000000 , 1 )
( 999999996 , 1.0 )
# rearrange array elements such that bitwise and of first n | utility function to print the elements of an array ; function to find the required arrangement ; there has to be atleast 2 elements ; minimum element from the array ; swap any occurrence of the minimum element with the last element ; find the bitwise and of the first ( n - 1 ) elements ; if the bitwise and is equal to the last element then print the arrangement ; 
def printArr(arr, n):
    for i in range(n):
        print(arr[i], end=" ")


def findArrangement(arr, n):
    if (n < 2):
        print("-1", end="")
        return
    minVal = min(arr)
    for i in range(n):
        if (arr[i] == minVal):
            arr[i], arr[n - 1] = arr[n - 1], arr[i]
            break
    andVal = arr[0]
    for i in range(1, n - 1):
        andVal &= arr[i]
    if (andVal == arr[n - 1]):
        printArr(arr, n)
    else:
        print("-1")


if __name__ == "__main__":
    arr = [1, 5, 3, 3]
    n = len(arr)
    findArrangement(arr, n)

# Expected output:
3 5 3 1
# maximum prime moves to convert x to y | function to return the maximum operations required to convert x to y ; x cannot be converted to y ; if the difference is 1 ; if the difference is even ; add 3 to x and the new difference will be even ; 
def maxOperations(X, Y):
    if (X > Y):
        return -1
    diff = Y - X
    if (diff == 1):
        return -1
    if (diff % 2 == 0):
        return (diff // 2)
    return (1 + ((diff - 3) // 2))


if __name__ == "__main__":
    X = 5
    Y = 16
    print(maxOperations(X, Y))

# Expected output:
5
# sum of digits of the good strings | python3 implementation of the approach ; to store the states of the dp ; function to fill the dp table ; sum of digits of the string of length 1 is i as i is only number in that string and count of good strings of length 1 that end with i is also 1 ; adjacent digits are different ; increment the count as digit at ( i - 1 ) 'th index is k and count  of good strings is equal to this  because at the end of the strings of  length (i - 1) we are just  putting digit j as the last digit ; 

DIGITS = 10
MAX = 10000
MOD = 1000000007
dp = [[0 for i in range(DIGITS)]for i in range(MAX)]
cnt = [[0 for i in range(DIGITS)]for i in range(MAX)]


def precompute():
    for i in range(DIGITS):
        dp[1][i] = i
        cnt[1][i] = 1
    for i in range(2, MAX):
        for j in range(DIGITS):
            for k in range(DIGITS):
                if (j != k):
                    dp[i][j] = dp[i][j] + \
                        (dp[i - 1][k] + (cnt[i - 1][k] * j) % MOD) % MOD
                    dp[i][j] %= MOD
                    cnt[i][j] += cnt[i - 1][k]
                    cnt[i][j] %= MOD


x = 6
y = 4
precompute()
print(dp[x][y])

# Expected output:
1567751
# count non | python implementation of the approach ; function to pre - compute the sequence ; for n = 1 the answer will be 2 ; starting two terms of the sequence ; compute the rest of the sequence with the relation f [ i ] = f [ i - 1 ] + f [ i - 2 ] ; 

N = 10000
MOD = 1000000007
F = [0] * N


def precompute():
    F[1] = 2
    F[2] = 3
    F[3] = 4
    for i in range(4, N):
        F[i] = (F[i - 1] + F[i - 2]) % MOD


n = 8
precompute()
print(F[n])

# Expected output:
47
# minimize sum by dividing all elements of a subarray by k | python3 implementation of the approach ; function to return the maximum subarray sum ; function to return the minimized sum of the array elements after performing the given operation ; find maximum subarray sum ; find total sum of the array ; maximum subarray sum is already negative ; choose the subarray whose sum is maximum and divide all elements by k ; 

import sys


def maxSubArraySum(a, size):
    max_so_far = -(sys .maxsize - 1)
    max_ending_here = 0
    for i in range(size):
        max_ending_here = max_ending_here + a[i]
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here
        if (max_ending_here < 0):
            max_ending_here = 0
    return max_so_far


def minimizedSum(a, n, K):
    sum = maxSubArraySum(a, n)
    totalSum = 0
    for i in range(n):
        totalSum += a[i]
    if (sum < 0):
        return totalSum
    totalSum = totalSum - sum + sum / K
    return totalSum


if __name__ == "__main__":
    a = [1, -2, 3]
    n = len(a)
    K = 2
    print(minimizedSum(a, n, K))

# Expected output:
0.5