giulio98/xlcost-single-prompt huggingface dataset:
# sort a string lexicographically by reversing a substring | function to find the substring in s required to be reversed ; stores the size of the string ; stores the starting point of the substring ; iterate over the string s while i < n ; increment the value of i ; stores the ending index of the substring ; if start <= 0 or i >= n ; if start >= 1 and i <= n ; return the boolean value ; if start >= 1 ; return the boolean value ; if i < n ; return true if s [ start ] is less than or equal to s [ i ] ; otherwise ; function to check if it is possible to sort the string or not ; global start , end , i stores the starting and the ending index of substring ; stores whether it is possible to sort the substring ; traverse the range [ 1 , n ] ; if s [ i ] is less than s [ i - 1 ] ; if flag stores true ; if adjust ( s , i , start , end ) return false ; pr - 1 ; unset the flag ; otherwise ; pr - 1 ; if start is equal to - 1 ; update start and end ; print the value of start and end ; 
def adjust(S, i, start, end):
    N = len(S)
    start = i - 1
    while (i < N and S[i] < S[i - 1]):
        i += 1
    end = i - 1
    if (start <= 0 and i >= N):
        return True, start, i, end
    if (start >= 1 and i <= N):
        return (S[end] >= S[start - 1] and S[start] <= S[i]), start, i, end
    if (start >= 1):
        return (S[end] >= S[start - 1]), start, i, end
    if (i < N):
        return (S[start] <= S[i]), start, i, end
    return False, start, i, end


def isPossible(S, N):
    start, end = -1, -1
    flag = True
    i = 1
    while i < N:
        if (S[i] < S[i - 1]):
            if (flag):
                f, start, i, end = adjust(S, i, start, end)
                if (f == False):
                    print(-1)
                    return
                flag = False
            else:
                print(-1)
                return
        i += 1
    if (start == -1):
        start, end = 1, 1
    print(start, end)


if __name__ == '__main__':
    S = "abcyxuz"
    N = len(S)
    isPossible(S, N)

# Expected output:
3 5
# split array into k non | function find maximum sum of minimum and maximum of k subsets ; stores the result ; sort the array arr [ ] in decreasing order ; traverse the range [ 0 , k ] ; sort the array s [ ] in ascending order ; traverse the array s [ ] ; if s { i ] is 1 ; stores the index of the minimum element of the i - th subset ; traverse the array s [ ] ; update the counter ; return the resultant sum ; 
def maximumSum(arr, S, N, K):
    ans = 0
    arr = sorted(arr)[::-1]
    for i in range(K):
        ans += arr[i]
    S = sorted(S)
    for i in range(K):
        if (S[i] == 1):
            ans += arr[i]
        S[i] -= 1
    counter = K - 1
    for i in range(K):
        counter = counter + S[i]
        if (S[i] != 0):
            ans += arr[counter]
    return ans


if __name__ == '__main__':
    arr = [1, 13, 7, 17]
    S = [1, 3]
    N = len(arr)
    K = len(S)
    print(maximumSum(arr, S, N, K))

# Expected output:
48
# modify an array by sorting after reversal of bits of each array element | function to convert binary number to equivalent decimal ; set base value to 1 , i . e 2 ^ 0 ; function to convert a decimal to equivalent binary representation ; stores the binary representation ; since ascii value of '0' , '1' are 48 and 49 ; as the string is already reversed , no further reversal is required ; function to convert the reversed binary representation to equivalent integer ; stores reversed binary representation of given decimal ; stores equivalent decimal value of the binary representation ; return the resultant integer ; utility function to print the sorted array ; sort the array ; traverse the array ; print the array elements ; utility function to reverse the binary representations of all array elements and sort the modified array ; traverse the array ; passing array elements to reversedbinarydecimal function ; pass the array to the sorted array ; 
def binaryToDecimal(n):
    num = n
    dec_value = 0
    base = 1
    length = len(num)
    for i in range(length - 1, -1, -1):
        if (num[i] == '1'):
            dec_value += base
        base = base * 2
    return dec_value


def decimalToBinary(n):
    binstr = ""
    while (n > 0):
        binstr += chr(n % 2 + 48)
        n = n // 2
    return binstr


def reversedBinaryDecimal(N):
    decimal_to_binar = decimalToBinary(N)
    binary_to_decimal = binaryToDecimal(decimal_to_binar)
    return binary_to_decimal


def printSortedArray(arr, size):
    arr .sort()
    for i in range(size):
        print(arr[i], end=" ")
    print()


def modifyArray(arr, size):
    for i in range(size):
        arr[i] = reversedBinaryDecimal(arr[i])
    printSortedArray(arr, size)


if __name__ == "__main__":
    arr = [98, 43, 66, 83]
    n = len(arr)
    modifyArray(arr, n)

# Expected output:
33 35 53 101
# check if sequence of removed middle elements from an array is sorted or not | function to check if sequence of removed middle elements from an array is sorted or not ; points toa the ends of the array ; iterate l + 1 < r ; if the element at index l and r is greater than ( l + 1 ) - th and ( r - 1 ) - th elements ; if true , then decrement r by 1 and increment l by 1 ; otherwise , return false ; if an increasing sequence is formed , then return true ; 
def isSortedArray(arr, n):
    l = 0
    r = (n - 1)
    while ((l + 1) < r):
        if (arr[l] >= max(arr[l + 1], arr[r - 1])
                and arr[r] >= max(arr[r - 1], arr[l + 1])):
            l += 1
            r -= 1
        else:
            return False
    return True


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

# Expected output:
Yes
# length of longest strictly increasing subset with each pair of adjacent elements satisfying the condition 2 * a [ i ] â ‰¥ a [ i + 1 ] | function to find the length of the longest subset satisfying given conditions ; sort the array in ascending order ; stores the starting index and maximum length of the required subset ; pointer to traverse the array ; iterate while i < n ; stores end point of current subset ; store the length of the current subset ; continue adding elements to the current subset till the condition satisfies ; increment length of the current subset ; increment the pointer j ; if length of the current subset exceeds overall maximum length ; update maxlen ; update index ; increment j ; update i ; store the starting index of the required subset in i ; print the required subset ; print the array element ; decrement maxlen ; increment i ; 
def maxLenSubset(a, n):
    a .sort(reverse=False)
    index = 0
    maxlen = -1
    i = 0
    while (i < n):
        j = i
        len1 = 1
        while (j < n - 1):
            if (2 * a[j] >= a[j + 1]):
                len1 += 1
            else:
                break
            j += 1
        if (maxlen < len1):
            maxlen = len1
            index = i
        j += 1
        i = j
    i = index
    while (maxlen > 0):
        print(a[i], end=" ")
        maxlen -= 1
        i += 1


if __name__ == '__main__':
    a = [3, 1, 5, 11]
    n = len(a)
    maxLenSubset(a, n)

# Expected output:
3 5
# maximize count of intersecting line segments | python3 program for the above approach ; function to find the maximum number of intersecting line segments possible ; stores pairs of line segments { x [ i ] , y [ i ] ) ; push { x [ i ] , y [ i ] } into p ; sort p in ascending order of points on x number line ; stores the points on y number line in descending order ; insert the first y pofrom p ; binary search to find the lower bound of p [ i ] [ 1 ] ; if lower_bound doesn 't exist ; insert p [ i ] [ 1 ] into the set ; erase the next lower _bound from the set ; insert p [ i ] [ 1 ] into the set ; return the size of the set as the final result ; 

from bisect import bisect_left


def solve(N, X, Y):
    p = []
    for i in range(N):
        p .append([X[i], Y[i]])
    p = sorted(p)
    s = {}
    s[p[0][1]] = 1
    for i in range(N):
        arr = list(s .keys())
        it = bisect_left(arr, p[i][1])
        if (it == len(s)):
            s[p[i][1]] = 1
        else:
            del s[arr[it]]
            s[p[i][1]] = 1
    return len(s)


if __name__ == '__main__':
    N = 3
    X = [1, 2, 0]
    Y = [2, 0, 1]
    maxintersection = solve(N, X, Y)
    print(maxintersection)

# Expected output:
2
# reduce an array to a single element by repeatedly removing larger element from a pair with absolute difference at most k | function to check if an array can be reduced to single element by removing maximum element among any chosen pairs ; sort the array in descending order ; traverse the array ; if the absolute difference of 2 consecutive array elements is greater than k ; if the array can be reduced to a single element ; 
def canReduceArray(arr, N, K):
    arr = sorted(arr)
    for i in range(N - 1):
        if (arr[i] - arr[i + 1] > K):
            print("No")
            return
    print("Yes")


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

# Expected output:
Yes
# lexicographically smallest string possible by merging two sorted strings | function to find lexicographically smallest possible by merging two sorted strings ; stores length of s1 ; stores length of s2 ; pointer to beginning of string1 i . e . , s1 ; pointer to beginning of string2 i . e . , s2 ; stores the final string ; traverse the strings ; append the smaller of the two current characters ; append the remaining characters of any of the two strings ; print the final string ; 
def mergeStrings(s1, s2):
    len1 = len(s1)
    len2 = len(s2)
    pntr1 = 0
    pntr2 = 0
    ans = ""
    while (pntr1 < len1 and pntr2 < len2):
        if (s1[pntr1] < s2[pntr2]):
            ans += s1[pntr1]
            pntr1 += 1
        else:
            ans += s2[pntr2]
            pntr2 += 1
    if (pntr1 < len1):
        ans += s1[pntr1:pntr1 + len1]
    if (pntr2 < len2):
        ans += s2[pntr2:pntr2 + len2]
    print(ans)


if __name__ == '__main__':
    S1 = "abdcdtx"
    S2 = "achilp"
    mergeStrings(S1, S2)

# Expected output:
aabcdcdhilptx
# sort a string without altering the position of vowels | function to sort the string leaving the vowels unchanged ; length of string s ; traverse the string s ; sort the string temp ; pointer to traverse the sorted string of consonants ; traverse the string s ; 
def sortStr(S):
    N = len(S)
    temp = ""
    for i in range(N):
        if (S[i] != 'a' and S[i] != 'e' and S[i] !=
                'i' and S[i] != 'o' and S[i] != 'u'):
            temp += S[i]
    if (len(temp)):
        p = list(temp)
        p .sort()
        temp = ''.join(p)
    ptr = 0
    for i in range(N):
        S = list(S)
    if (S[i] != 'a' and S[i] != 'e' and S[i] !=
            'i' and S[i] != 'o' and S[i] != 'u'):
        S[i] = temp[ptr]
        ptr += 1
    print(''.join(S))


if __name__ == "__main__":
    S = "geeksforgeeks"
    sortStr(S)

# Expected output:
geeksforgeekf
# count pairs from an array whose quotient of division of larger number by the smaller number does not exceed k | python3 program for the above approach ; function to count the number having quotient of division of larger element by the smaller element in the pair not exceeding k ; sort the array in ascending order ; store the required result ; traverse the array ; store the upper bound for the current array element ; update the number of pairs ; prthe result ; 

from bisect import bisect_right


def countPairs(arr, n, k):
    arr .sort()
    ans = 0
    for i in range(n - 1):
        high = bisect_right(arr, k * arr[i])
        ans += high - i - 1
    print(ans)


arr = [2, 3, 9, 5]
n = len(arr)
k = 2
countPairs(arr, n, k)

# Expected output:
3
# kth highest xor of diagonal elements from a matrix | function to find k - th maximum xor of any diagonal in the matrix ; number or rows ; number of columns ; store xor of diagonals ; traverse each diagonal ; starting column of diagonal ; count total elements in the diagonal ; store xor of current diagonal ; push xor of current diagonal ; sort xor values of diagonals ; print the k - th maximum xor ; 
def findXOR(mat, K):
    N = len(mat)
    M = len(mat[0])
    digXOR = []
    for l in range(1, N + M, 1):
        s_col = max(0, l - N)
        count = min([l, (M - s_col), N])
        currXOR = 0
        for j in range(count):
            currXOR = (currXOR ^ mat[min(N, l) - j - 1][s_col + j])
        digXOR .append(currXOR)
    digXOR .sort(reverse=False)
    print(digXOR[N + M - 1 - K])


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

# Expected output:
6
# maximum sum of absolute differences between distinct pairs of a triplet from an array | function to find the maximum sum of absolute differences between distinct pairs of triplet in array ; stores the maximum sum ; sort the array in ascending order ; sum of differences between pairs of the triplet ; print the sum ; 
def maximumSum(arr, N):
    sum = 0
    arr .sort()
    sum = (arr[N - 1] - arr[0]) + (arr[N - 2] -
                                   arr[0]) + (arr[N - 1] - arr[N - 2])
    print(sum)


arr = [1, 3, 4, 2]
N = len(arr)
maximumSum(arr, N)

# Expected output:
6
# maximum and minimum sum of bitwise xor of pairs from an array | python3 program for the above approach ; c [ int , [ a , b ] ] function to find the required sum ; keeps the track of the visited array elements ; stores the result ; keeps count of visited elements ; traverse the vector , v ; if n elements are visited , break out of the loop ; store the pair ( i , j ) and their bitwise xor ; if i and j both are unvisited ; add xorresult to res and mark i and j as visited ; increment count by 2 ; return the result ; function to find the maximum and minimum possible sum of bitwise xor of all the pairs from the array ; stores the xor of all pairs ( i , j ) ; store the xor of all pairs ( i , j ) ; update bitwise xor ; sort the vector ; initialize variables to store maximum and minimum possible sums ; find the minimum sum possible ; reverse the vector , v ; find the maximum sum possible ; print the result ; 

v = []


def findSum(n):
    global v
    um = {}
    res = 0
    cnt = 0
    for i in range(len(v)):
        if (cnt == n):
            break
        x = v[i][1][0]
        y = v[i][1][1]
        xorResult = v[i][0]
        if (x in um and um[x] == False and y in um and um[y] == False):
            res += xorResult
            um[x] = True
            um[y] = True
            cnt += 2
    return res


def findMaxMinSum(a, n):
    global v
    for i in range(n):
        for j in range(i + 1, n, 1):
            xorResult = a[i] ^ a[j]
            v .append([xorResult, [a[i], a[j]]])
    v .sort(reverse=False)
    maxi = 0
    mini = 0
    mini = findSum(n)
    mini = 6
    v = v[::-1]
    maxi = findSum(n)
    maxi = 10
    print(mini, maxi)


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

# Expected output:
6 10
# lexicographically smallest permutation having maximum sum of differences between adjacent elements | function to find the lexicographically smallest permutation of an array such that the sum of the difference between adjacent elements is maximum ; stores the size of the array ; sort the given array in increasing order ; swap the first and last array elements ; print the required permutation ; 
def maximumSumPermutation(arr):
    N = len(arr)
    arr .sort()
    temp = arr[0]
    arr[0] = arr[N - 1]
    arr[N - 1] = temp
    for i in arr:
        print(i, end=" ")


if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5]
    maximumSumPermutation(arr)

# Expected output:
5 2 3 4 1
# maximize count of 1 s in an array by repeated division of array elements by 2 at most k times | python3 program to implement the above approach ; function to count the maximum number of array elements that can be reduced to 1 by repeatedly dividing array elements by 2 ; sort the array in ascending order ; store the count of array elements ; traverse the array ; store the number of operations required to reduce arr [ i ] to 1 ; decrement k by opr ; if k becomes less than 0 , then break out of the loop ; increment cnt by 1 ; prthe answer ; 

import math


def findMaxNumbers(arr, n, k):
    arr .sort()
    cnt = 0
    for i in range(n):
        opr = math .ceil(math .log2(arr[i]))
        k -= opr
        if (k < 0):
            break
        cnt += 1
    print(cnt)


arr = [5, 8, 4, 7]
N = len(arr)
K = 5
findMaxNumbers(arr, N, K)

# Expected output:
2
# mean of given array after removal of k percent of smallest and largest array elements | function to calculate the mean of a given array after removal of kth percent of smallest and largest array elements ; sort the array ; find the k - th percent of the array size ; traverse the array ; skip the first k - th percent & last k - th percent array elements ; mean of the rest of elements ; print mean upto 5 decimal places ; 
def meanOfRemainingElements(arr, N, K):
    arr .sort()
    kthPercent = (N * K) / 100
    sum = 0
    for i in range(N):
        if (i >= kthPercent and i < (N - kthPercent)):
            sum += arr[i]
    mean = sum / (N - 2 * kthPercent)
    print('%.5f' % mean)


arr = [6, 2, 7, 5, 1, 2, 0, 3, 10, 2, 5, 0, 5, 5, 0, 8, 7, 6, 8, 0]
arr_size = len(arr)
K = 5
meanOfRemainingElements(arr, arr_size, K)

# Expected output:
4.00000
# make the array elements equal by performing given operations minimum number of times | function to calculate the minimum operations of given type required to make the array elements equal ; stores the total count of operations ; traverse the array ; update difference between pairs of adjacent elements ; store the maximum count of operations ; rest of the elements ; total operation - maximum operation ; 
def minOperation(a, N):
    totOps = 0
    for i in range(N - 1):
        totOps += abs(a[i] - a[i + 1])
    maxOps = max(abs(a[0] - a[1]), abs(a[N - 1] - a[N - 2]))
    for i in range(1, N - 1):
        maxOps = max(maxOps, abs(a[i] - a[i - 1]) +
                     abs(a[i] - a[i + 1]) - abs(a[i - 1] - a[i + 1]))
    print(totOps - maxOps)


if __name__ == '__main__':
    arr = [1, -1, 0, 1, 1]
    N = len(arr)
    minOperation(arr, N)

# Expected output:
2
# count swaps required to sort an array using insertion sort | stores the sorted array elements ; function to count the number of swaps required to merge two sorted subarray in a sorted form ; stores the count of swaps ; function to count the total number of swaps required to sort the array ; stores the total count of swaps required ; find the middle index splitting the two halves ; count the number of swaps required to sort the left subarray ; count the number of swaps required to sort the right subarray ; count the number of swaps required to sort the two sorted subarrays ; 

temp = [0] * 100000


def merge(A, left, mid, right):
    swaps = 0
    i, j, k = left, mid, left
    while (i < mid and j <= right):
        if (A[i] <= A[j]):
            temp[k] = A[i]
            k, i = k + 1, i + 1
        else:
            temp[k] = A[j]
            k, j = k + 1, j + 1
            swaps += mid - i
    while (i < mid):
        temp[k] = A[i]
        k, i = k + 1, i + 1
    while (j <= right):
        temp[k] = A[j]
        k, j = k + 1, j + 1
    while (left <= right):
        A[left] = temp[left]
        left += 1
    return swaps


def mergeInsertionSwap(A, left, right):
    swaps = 0
    if (left < right):
        mid = left + (right - left) // 2
        swaps += mergeInsertionSwap(A, left, mid)
        swaps += mergeInsertionSwap(A, mid + 1, right)
        swaps += merge(A, left, mid + 1, right)
    return swaps


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

# Expected output:
4
# maximum removals possible from an array such that sum of its elements is greater than or equal to that of another array | function to maximize the count of elements required to be removed from arr [ ] such that the sum of arr [ ] is greater than or equal to sum of the array brr [ ] ; sort the array arr [ ] ; stores index of smallest element of arr [ ] ; stores sum of elements of the array arr [ ] ; traverse the array arr [ ] ; update sumarr ; stores sum of elements of the array brr [ ] ; traverse the array brr [ ] ; update sumarr ; stores count of removed elements ; repeatedly remove the smallest element of arr [ ] ; update sumarr ; remove the smallest element ; if the sum of remaining elements in arr [ ] >= sum of brr [ ] ; update cntremelem ; 
def maxCntRemovedfromArray(arr, N, brr, M):
    arr .sort(reverse=False)
    i = 0
    sumArr = 0
    for i in range(N):
        sumArr += arr[i]
    sumBrr = 0
    for i in range(M):
        sumBrr += brr[i]
    cntRemElem = 0
    while (i < N and sumArr >= sumBrr):
        sumArr -= arr[i]
        i += 1
        if (sumArr >= sumBrr):
            cntRemElem += 1
    return cntRemElem


if __name__ == '__main__':
    arr = [1, 2, 4, 6]
    brr = [7]
    N = len(arr)
    M = len(brr)
    print(maxCntRemovedfromArray(arr, N, brr, M))

# Expected output:
2
# find any two pairs ( a , b ) and ( c , d ) such that a d | function to find two pairs ( a , b ) and ( c , d ) such that a < c and b > d ; if no such pair is found ; 
def findPair(arr, N):
    for i in range(N):
        a, b = arr[i][0], arr[i][1]
        for j in range(i + 1, N):
            c, d = arr[j][0], arr[j][1]
            if (a < c and b > d):
                print("(", a, b, "), (", c, d, ")")
                return
    print("NO SUCH PAIR EXIST")


if __name__ == '__main__':
    arr = [[3, 7], [21, 23], [4, 13], [1, 2], [7, -1]]
    findPair(arr, 5)

# Expected output:
( 3 7 ), ( 7 -1 )
# find any two pairs ( a , b ) and ( c , d ) such that a d | function to find two pairs ( a , b ) and ( c , d ) such that a < c and b > d ; sort the array in increasing order of first element of pairs ; traverse the array ; if no such pair found ; 
def findPair(arr, N):
    arr .sort(key=lambda x: x[0])
    for i in range(1, N):
        b = arr[i - 1][1]
        d = arr[i][1]
        if (b > d):
            print("(", arr[i - 1][0], b, "), (", arr[i][0], d, ")")
            return
    print("NOSUCHPAIREXIST")


arr = [[3, 7], [21, 23], [4, 13], [1, 2], [7, -1]]
findPair(arr, 5)

# Expected output:
( 4 13 ), ( 7 -1 )
# print indices in non | function to print the order of array elements generating non - decreasing quotient after division by x ; stores the quotient and the order ; traverse the array ; sort the vector ; print the order ; 
def printOrder(order, N, X):
    vect = []
    for i in range(N):
        if (order[i] % X == 0):
            vect .append([order[i] // X, i + 1])
        else:
            vect .append([order[i] // X + 1, i + 1])
    vect = sorted(vect)
    for i in range(N):
        print(vect[i][1], end=" ")


if __name__ == '__main__':
    N, X = 3, 3
    order = [2, 7, 4]
    printOrder(order, N, X)

# Expected output:
1 3 2