giulio98/xlcost-single-prompt huggingface dataset:
# find if given number is sum of first n natural numbers | function to find no . of elements to be added to get s ; apply binary search ; find mid ; find sum of 1 to mid natural numbers using formula ; if sum is equal to n return mid ; if greater than n do r = mid - 1 ; else do l = mid + 1 ; if not possible , return - 1 ; 
def findS(s):
    l = 1
    r = int(s / 2) + 1
    while (l <= r):
        mid = int((l + r) / 2)
        sum = int(mid * (mid + 1) / 2)
        if (sum == s):
            return mid
        elif (sum > s):
            r = mid - 1
        else:
            l = mid + 1
    return -1


s = 15
n = findS(s)
if (n == -1):
    print("-1")
else:
    print(n)

# Expected output:
5
# search in an array of strings where non | compare two string equals are not ; main function to find string location ; move mid to the middle ; if mid is empty , find closest non - empty string ; if mid is empty , search in both sides of mid and find the closest non - empty string , and set mid accordingly . ; if str is found at mid ; if str is greater than mid ; if str is smaller than mid ; 
def compareStrings(str1, str2):
    i = 0
    while i < len(str1) - 1 and str1[i] == str2[i]:
        i += 1
    if str1[i] > str2[i]:
        return -1
    return str1[i] < str2[i]


def searchStr(arr, string, first, last):
    if first > last:
        return -1
    mid = (last + first) // 2
    if len(arr[mid]) == 0:
        left, right = mid - 1, mid + 1
        while True:
            if left < first and right > last:
                return -1
            if right <= last and len(arr[right]) != 0:
                mid = right
                break
            if left >= first and len(arr[left]) != 0:
                mid = left
                break
            right += 1
            left -= 1
    if compareStrings(string, arr[mid]) == 0:
        return mid
    if compareStrings(string, arr[mid]) < 0:
        return searchStr(arr, string, mid + 1, last)
    return searchStr(arr, string, first, mid - 1)


if __name__ == "__main__":
    arr = [
        "for",
        "",
        "",
        "",
        "geeks",
        "ide",
        "",
        "practice",
        "",
        "",
        "quiz",
        "",
        ""]
    string = "quiz"
    n = len(arr)
    print(searchStr(arr, string, 0, n - 1))

# Expected output:
10
# rearrange array elements to maximize the sum of mex of all prefix arrays | function to find the maximum sum of mex of prefix arrays for any arrangement of the given array ; stores the final arrangement ; sort the array in increasing order ; iterate over the array arr [ ] ; iterate over the array , arr [ ] and push the remaining occurrences of the elements into ans [ ] ; prthe array , ans [ ] ; 
def maximumMex(arr, N):
    ans = []
    arr = sorted(arr)
    for i in range(N):
        if (i == 0 or arr[i] != arr[i - 1]):
            ans .append(arr[i])
    for i in range(N):
        if (i > 0 and arr[i] == arr[i - 1]):
            ans .append(arr[i])
    for i in range(N):
        print(ans[i], end=" ")


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

# Expected output:
0 1 0
# sort an array using bubble sort without using loops | function to implement bubble sort without using loops ; base case : if array contains a single element ; base case : if array contains two elements ; store the first two elements of the list in variables a and b ; store remaining elements in the list bs ; store the list after each recursive call ; if a < b ; otherwise , if b >= a ; recursively call for the list less than the last element and and return the newly formed list ; 
def bubble_sort(ar):
    if len(ar) <= 1:
        return ar
    if len(ar) == 2:
        return ar if ar[0] < ar[1]else [ar[1], ar[0]]
    a, b = ar[0], ar[1]
    bs = ar[2:]
    res = []
    if a < b:
        res = [a] + bubble_sort([b] + bs)
    else:
        res = [b] + bubble_sort([a] + bs)
    return bubble_sort(res[:-1]) + res[-1:]


arr = [1, 3, 4, 5, 6, 2]
res = bubble_sort(arr)
print(*res)

# Expected output:
1 2 3 4 5 6
# modify a given matrix by placing sorted boundary elements in clockwise manner | function to print the elements of the matrix in row - wise manner ; function to sort boundary elements of a matrix starting from the outermost to the innermost boundary and place them in a clockwise manner ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; stores the current boundary elements ; push the first row ; push the last column ; push the last row ; push the first column ; sort the boundary elements ; update the first row ; update the last column ; update the last row ; update the first column ; print the resultant matrix ; 
def printMatrix(a):
    for x in a:
        for y in x:
            print(y, end=" ")
        print()


def sortBoundaryWise(a):
    k = 0
    l = 0
    m = len(a)
    n = len(a[0])
    n_k = 0
    n_l = 0
    n_m = m
    n_n = n
    while (k < m and l < n):
        boundary = []
        for i in range(l, n):
            boundary .append(a[k][i])
        k += 1
        for i in range(k, m):
            boundary .append(a[i][n - 1])
        n -= 1
        if (k < m):
            for i in range(n - 1, l - 1, -1):
                boundary .append(a[m - 1][i])
            m -= 1
        if (l < n):
            for i in range(m - 1, k - 1, -1):
                boundary .append(a[i][l])
            l += 1
        boundary .sort()
        ind = 0
        for i in range(n_l, n_n):
            a[n_k][i] = boundary[ind]
            ind += 1
        n_k += 1
        for i in range(n_k, n_m):
            a[i][n_n - 1] = boundary[ind]
            ind += 1
        n_n -= 1
        if (n_k < n_m):
            for i in range(n_n - 1, n_l - 1, -1):
                a[n_m - 1][i] = boundary[ind]
                ind += 1
            n_m -= 1
        if (n_l < n_n):
            for i in range(n_m - 1, n_k - 1, -1):
                a[i][n_l] = boundary[ind]
                ind += 1
            n_l += 1
    printMatrix(a)


if __name__ == "__main__":
    matrix = [[9, 7, 4, 5], [1, 6, 2, -6], [12, 20, 2, 0], [-5, -6, 7, -2]]
    sortBoundaryWise(matrix)

# Expected output:
-6 -6 -5 -2 
12 2 2 0 
9 20 6 1 
7 7 5 4
# minimum sum of absolute differences between pairs of a triplet from an array | python 3 program for the above approach ; function to find minimum sum of absolute differences of pairs of a triplet ; sort the array ; stores the minimum sum ; traverse the array ; update the minimum sum ; print the minimum sum ; 

import sys


def minimum_sum(A, N):
    A .sort(reverse=False)
    sum = sys .maxsize
    for i in range(N - 2):
        sum = min(sum, abs(A[i] - A[i + 1]) + abs(A[i + 1] - A[i + 2]))
    print(sum)


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

# Expected output:
1
# make all characters of a string same by minimum number of increments or decrements of ascii values of characters | function to check if all characters of the string can be made the same ; sort the string ; calculate ascii value of the median character ; stores the minimum number of operations required to make all characters equal ; traverse the string ; calculate absolute value of current character and median character ; print the minimum number of operations required ; 
def sameChar(S, N):
    S = ''.join(sorted(S))
    mid = ord(S[N // 2])
    total_operations = 0
    for i in range(N):
        total_operations += abs(ord(S[i]) - mid)
    print(total_operations)


S = "geeks"
N = len(S)
sameChar(S, N)

# Expected output:
20
# maximum score possible from an array with jumps of at most length k | python program for the above approach ; function to count the maximum score of an index ; base case ; if the value for the current index is pre - calculated ; calculate maximum score for all the steps in the range from i + 1 to i + k ; score for index ( i + j ) ; update dp [ i ] and return the maximum value ; function to get maximum score possible from the array a ; array to store memoization ; initialize dp with - 1 ; 

import sys


def maxScore(i, A, K, N, dp):
    if (i >= N - 1):
        return A[N - 1]
    if (dp[i] != -1):
        return dp[i]
    score = 1 - sys .maxsize
    for j in range(1, K + 1):
        score = max(score, maxScore(i + j, A, K, N, dp))
    dp[i] = score + A[i]
    return dp[i]


def getScore(A, N, K):
    dp = [0] * N
    for i in range(N):
        dp[i] = -1
    print(maxScore(0, A, K, N, dp))


if __name__ == '__main__':
    A = [100, -30, -50, -15, -20, -30]
    K = 3
    N = len(A)
    getScore(A, N, K)

# Expected output:
55
# check if all array elements can be reduced to less than x | function to check if all array elements can be reduced to less than x or not ; checks if all array elements are already a x or not ; traverse every possible pair ; calculate gcd of two array elements ; if gcd is a 1 ; if gcd is a x , then a pair is present to reduce all array elements to a x ; if no pair is present with gcd is a x ; function to check if all array elements area x ; function to calculate gcd of two numbers ; 
def check(A, X):
    for i in range(len(A)):
        if (A[i] > X):
            return False
    return True


def GCD(a, b):
    if (b == 0):
        return a
    return GCD(b, a % b)


def findAns(A, N, X):
    if (check(A, X)):
        return True
    for i in range(N):
        for j in range(i + 1, N):
            gcd = GCD(A[i], A[j])
        if (gcd != 1):
            if (gcd <= X):
                return True
    return False


X = 4
A = [2, 1, 5, 3, 6]
N = 5
print(findAns(A, N, X))

# Expected output:
True
# check if x and y elements can be selected from two arrays respectively such that the maximum in x is less than the minimum in y | function to check if it is possible to choose x and y elements from a [ ] and b [ ] such that maximum element among x element is less than minimum element among y elements ; check if there are atleast x elements in arr1 [ ] and atleast y elements in arr2 [ ] ; sort arrays in ascending order ; check if ( x - 1 ) - th element in arr1 [ ] is less than from m - yth element in arr2 [ ] ; return false ; 
def check(a, b, Na, Nb, k, m):
    if (Na < k or Nb < m):
        return "No"
    a .sort()
    a .sort()
    if (a[k - 1] < b[Nb - m]):
        return "Yes"
    return "No"


arr1 = [1, 2, 3]
arr2 = [3, 4, 5]
N = len(arr1)
M = len(arr2)
X = 2
Y = 1
print(check(arr1, arr2, N, M, X, Y))

# Expected output:
Yes
# partition array into two subsets with minimum bitwise xor between their maximum and minimum | function to split the array into two subset such that the bitwise xor between the maximum of one subset and minimum of other is minimum ; sort the array in increasing order ; calculating the min bitwise xor between consecutive elements ; return the final minimum bitwise xor ; 
def splitArray(arr, N):
    arr = sorted(arr)
    result = 10 ** 9
    for i in range(1, N):
        result = min(result, arr[i] ^ arr[i - 1])
    return result


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

# Expected output:
1
# sort an array by left shifting digits of array elements | function to check if an array is sorted in increasing order or not ; traverse the array ; function to sort the array by left shifting digits of array elements ; stores previous array element ; traverse the array arr [ ] ; stores current element ; stores current element in string format ; left - shift digits of current element in all possible ways ; left - shift digits of current element by idx ; if temp greater than or equal to prev and temp less than optele ; update arr [ i ] ; update prev ; if arr is in increasing order ; otherwise ; 
def isIncreasing(arr):
    for i in range(len(arr) - 1):
        if arr[i] > arr[i + 1]:
            return False
    return True


def sortArr(arr):
    prev = -1
    for i in range(len(arr)):
        optEle = arr[i]
        strEle = str(arr[i])
        for idx in range(len(strEle)):
            temp = int(strEle[idx:] + strEle[:idx])
            if temp >= prev and temp < optEle:
                optEle = temp
        arr[i] = optEle
        prev = arr[i]
    if isIncreasing(arr):
        return arr
    else:
        return "-1"


if __name__ == '__main__':
    arr = [511, 321, 323, 432, 433]
    res = sortArr(arr)
    for i in res:
        print(i, end=" ")

# Expected output:
115 132 233 243 334
# activity selection problem with k persons | python3 program for the above approach ; function to find maximum shops that can be visited by k persons ; store opening and closing time of shops ; sort the pair of array ; stores the result ; stores current number of persons visiting some shop with their ending time ; check if current shop can be assigned to a person who 's  already visiting any other shop ; checks if there is any person whose closing time <= current shop opening time ; erase previous shop visited by the person satisfying the condition ; insert new closing time of current shop for the person satisfying a1he condition ; increment the count by one ; in case if no person have closing time <= current shop opening time but there are some persons left ; finally pr the ans ; 

from bisect import bisect_left


def maximumShops(opening, closing, n, k):
    a = [[0, 0]for i in range(n)]
    for i in range(n):
        a[i][0] = opening[i]
        a[i][1] = closing[i]
    a = sorted(a)
    count = 1
    st = {}
    for i in range(n):
        flag = False
        if (len(st) == 0):
            ar = list(st .keys())
            it = bisect_left(ar, a[i][0])
            if (it != 0):
                it -= 1
                if (ar[it] <= a[i][0]):
                    del st[it]
                    st[a[i][1]] = 1
                    count += 1
                    flag = True
        if (len(st) < k and flag == False):
            st[a[i][1]] = 1
            count += 1
    return count


if __name__ == '__main__':
    S = [1, 8, 3, 2, 6]
    E = [5, 10, 6, 5, 9]
    K, N = 2, len(S)
    print(maximumShops(S, E, N, K))

# Expected output:
4
# maximize maximum possible subarray sum of an array by swapping with elements from another array | function to find the maximum subarray sum possible by swapping elements from array arr [ ] with that from array brr [ ] ; stores elements from the arrays arr [ ] and brr [ ] ; store elements of array arr [ ] and brr [ ] in the vector crr ; sort the vector crr in descending order ; stores maximum sum ; calculate the sum till the last index in crr [ ] which is less than n which contains a positive element ; print the sum ; 
def maxSum(arr, brr, N, K):
    crr = []
    for i in range(N):
        crr .append(arr[i])
    for i in range(K):
        crr .append(brr[i])
    crr = sorted(crr)[::-1]
    sum = 0
    for i in range(N):
        if (crr[i] > 0):
            sum += crr[i]
        else:
            break
    print(sum)


if __name__ == '__main__':
    arr = [7, 2, -1, 4, 5]
    N = len(arr)
    brr = [1, 2, 3, 2]
    K = len(brr)
    maxSum(arr, brr, N, K)

# Expected output:
21
# count pairs with bitwise xor greater than both the elements of the pair | function that counts the pairs whose bitwise xor is greater than both the elements of pair ; stores the count of pairs ; generate all possible pairs ; find the bitwise xor ; find the maximum of two ; if xo < mx , increment count ; print the value of count ; 
def countPairs(A, N):
    count = 0
    for i in range(0, N):
        for j in range(i + 1, N):
            xo = (A[i] ^ A[j])
            mx = max(A[i], A[j])
            if (xo > mx):
                count += 1
    print(count)


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

# Expected output:
2
# possible arrangement of persons waiting to sit in a hall | function to find the arrangement of seating ; stores the row in which the ith person sits ; stores the width of seats along with their index or row number ; sort the array ; store the seats and row for boy 's seat ; stores the index of row upto which boys have taken seat ; iterate the string ; push the row number at index in vector and heap ; increment the index to let the next boy in the next minimum width vacant row ; otherwise ; if girl then take top of element of the max heap ; pop from queue ; print the values ; 
def findTheOrder(arr, s, N):
    ans = []
    A = [[]for i in range(N)]
    for i in range(N):
        A[i] = [arr[i], i + 1]
    A = sorted(A)
    q = []
    index = 0
    for i in range(2 * N):
        if (s[i] == '0'):
            ans .append(A[index][1])
            q .append(A[index])
            index += 1
        else:
            ans .append(q[-1][1])
            del q[-1]
        q = sorted(q)
    for i in ans:
        print(i, end=" ")


if __name__ == '__main__':
    N = 3
    arr = [2, 1, 3]
    s = "001011"
    findTheOrder(arr, s, N)

# Expected output:
2 1 1 3 3 2
# difference between sum of k maximum even and odd array elements | function to find the absolute difference between sum of first k maximum even and odd numbers ; stores index from where odd number starts ; segregate even and odd number ; if current element is even ; sort in decreasing order even part ; sort in decreasing order odd part ; calculate sum of k maximum even number ; calculate sum of k maximum odd number ; print the absolute difference ; 
def evenOddDiff(a, n, k):
    j = -1
    even = []
    odd = []
    for i in range(n):
        if (a[i] % 2 == 0):
            even .append(a[i])
        else:
            odd .append(a[i])
    j += 1
    even .sort()
    even .reverse()
    odd .sort()
    odd .reverse()
    evenSum, oddSum = 0, 0
    for i in range(k):
        evenSum += even[i]
    for i in range(k):
        oddSum += odd[i]
    print(abs(evenSum - oddSum))


arr = [1, 8, 3, 4, 5]
N = len(arr)
K = 2
evenOddDiff(arr, N, K)

# Expected output:
4
# rearrange array to make product of prefix sum array non zero | function to rearrange array that satisfies the given condition ; stores sum of elements of the given array ; calculate totalsum ; if the totalsum is equal to 0 ; no possible way to rearrange array ; if totalsum exceeds 0 ; rearrange the array in descending order ; otherwise ; rearrange the array in ascending order ; 
def rearrangeArr(arr, N):
    totalSum = 0
    for i in range(N):
        totalSum += arr[i]
    if (totalSum == 0):
        print(-1)
    elif (totalSum > 0):
        arr .sort(reverse=True)
        print(*arr, sep=' ')
    else:
        arr .sort()
        print(*arr, sep=' ')


arr = [1, -1, -2, 3]
N = len(arr)
rearrangeArr(arr, N)

# Expected output:
3 1 -1 -2
# count ways to distribute exactly one coin to each worker | python3 program for the above approach ; function to find number of way to distribute coins giving exactly one coin to each person ; sort the given arrays ; start from bigger salary ; increment the amount ; reduce amount of valid coins by one each time ; return the result ; 

MOD = 1000000007


def solve(values, salary):
    ret = 1
    amt = 0
    values = sorted(values)
    salary = sorted(salary)
    while (len(salary) > 0):
        while ((len(values) and values[-1] >= salary[-1])):
            amt += 1
            del values[-1]
        if (amt == 0):
            return 0
        ret *= amt
        amt -= 1
        ret %= MOD
        del salary[-1]
    return ret


if __name__ == '__main__':
    values = [1, 2]
    salary = [2]
    print(solve(values, salary))

# Expected output:
1
# count of index pairs with equal elements in an array | set 2 | function that counts the pair in the array arr [ ] ; sort the array ; initialize two pointers ; add all valid pairs to answer ; return the answer ; 
def countPairs(arr, n):
    ans = 0
    arr .sort()
    left = 0
    right = 1
    while (right < n):
        if (arr[left] == arr[right]):
            ans += right - left
        else:
            left = right
        right += 1
    return ans


if __name__ == "__main__":
    arr = [2, 2, 3, 2, 3]
    N = len(arr)
    print(countPairs(arr, N))

# Expected output:
4
# maximize the sum of the given array using given operations | comparator to sort the array in ascending order ; function to maximise the sum of the given array ; stores { a [ i ] , b [ i ] } pairs ; sort in descending order of the values in the array a [ ] ; stores the maximum sum ; if b [ i ] is equal to 0 ; simply add a [ i ] to the sum ; add the highest k numbers ; subtract from the sum ; return the sum ; 
def compare(p1, p2):
    return p1[0] > p2[0]


def maximiseScore(A, B, K, N):
    pairs = []
    for i in range(N):
        pairs .append([A[i], B[i]])
    pairs .sort(key=lambda x: x[0], reverse=True)
    Sum = 0
    for i in range(N):
        if (pairs[i][1] == 0):
            Sum += pairs[i][0]
        elif (pairs[i][1] == 1):
            if (K > 0):
                Sum += pairs[i][0]
                K -= 1
            else:
                Sum -= pairs[i][0]
    return Sum


A = [5, 4, 6, 2, 8]
B = [1, 0, 1, 1, 0]
K = 2
N = len(A)
print(maximiseScore(A, B, K, N))

# Expected output:
21
# minimize cost to sort a string in increasing order of frequencies of characters | python3 program to implement the above approach ; for a single character ; stores count of repetitions of a character ; if repeating character ; otherwise ; store frequency ; reset count ; insert the last character block ; sort the frequencies ; stores the minimum cost of all operations ; store the absolute difference of i - th frequencies of ordered and unordered sequences ; return the minimum cost ; 
def sortString(S):
    sorted1 = []
    original = []
    insert = False
    if (len(S) == 1):
        print(0)
    curr = 1
    for i in range(len(S) - 1):
        if (S[i] == S[i + 1]):
            curr += 1
            insert = False
        else:
            sorted1 .append(curr)
            original .append(curr)
            curr = 1
            insert = True
    if ((S[(len(S) - 1)] != S[(len(S) - 2)]) or insert == False):
        sorted1 .append(curr)
        original .append(curr)
    sorted1 .sort()
    t_cost = 0
    for i in range(len(sorted1)):
        t_cost += abs(sorted1[i] - original[i])
    return (t_cost // 2)


if __name__ == "__main__":
    S = "aabbcccdeffffggghhhhhii"
    print(sortString(S))

# Expected output:
5
# sort numbers based on count of letters required to represent them in words | letters [ i ] stores the count of letters required to represent the digit i ; function to return the sum of letters required to represent n ; function to sort the array according to the sum of letters to represent n ; list to store the digit sum with respective elements ; inserting digit sum with elements in the list pair ; making the vector pair ; sort the list , this will sort the pair according to the sum of letters to represent n ; print the sorted list content ; 

letters = [4, 3, 3, 3, 4, 4, 3, 5, 5, 4]


def sumOfLetters(n):
    sum = 0
    while (n > 0):
        sum += letters[n % 10]
        n = n // 10
    return sum


def sortArr(arr, n):
    vp = []
    for i in range(n):
        vp .append([sumOfLetters(arr[i]), arr[i]])
    vp .sort(key=lambda x: x[0])
    for i in vp:
        print(i[1], end=" ")


if __name__ == '__main__':
    arr = [12, 10, 31, 18]
    n = len(arr)
    sortArr(arr, n)

# Expected output:
12 31 10 18
# divide a sorted array in k parts with sum of difference of max and min minimized in each part | function to find the minimum sum of differences possible for the 
def calculate_minimum_split(a, k):
    p = []
    n = len(a)
    for i in range(1, n):
        p .append(a[i] - a[i - 1])
    p .sort(reverse=True)
    min_sum = sum(p[:k - 1])
    res = a[n - 1] - a[0] - min_sum
    return res


if __name__ == "__main__":
    arr = [4, 8, 15, 16, 23, 42]
    K = 3
    print(calculate_minimum_split(arr, K))

# Expected output:
12