giulio98/xlcost-single-prompt huggingface dataset:
# minimum cost to sort an array such that swapping x and y costs xy | function returns the minimum cost to sort the given array ; create array of pairs in which 1 st element is the array element and 2 nd element is index of first ; initialize the total cost ; sort the array with respect to array value ; initialize the overall minimum which is the 1 st element ; to keep track of visited elements create a visited array & initialize all elements as not visited ; iterate over every element of the array ; if the element is visited or in the sorted position , and check for next element ; create a vector which stores all elements of a cycle ; it covers all the elements of a cycle ; if cycle is found then the swapping is required ; initialize local minimum with 1 st element of the vector as it contains the smallest element in the beginning ; stores the cost with using only local minimum value . ; stores the cost of using both local minimum and overall minimum ; update the result2 ; store the minimum of the two result to total cost ; return the minimum cost ; 
def minCost(arr, n):
    sortedarr = []
    total_cost = 0
    for i in range(n):
        sortedarr .append([arr[i], i])
    sortedarr .sort()
    overall_minimum = sortedarr[0][0]
    vis = [False] * n
    for i in range(n):
        if vis[i] and sortedarr[i][1] == i:
            continue
        v = []
        j = i
        size = 0
        while vis[j] == False:
            vis[j] = True
            v .append(sortedarr[j][0])
            j = sortedarr[j][1]
            size += 1
        if size != 0:
            local_minimum = v[0]
            result1 = 0
            result2 = 0
            for k in range(1, size):
                result1 += local_minimum * v[k]
            for k in range(size):
                result2 += overall_minimum * v[k]
            result2 += (overall_minimum * local_minimum)
            total_cost += min(result1, result2)
    return total_cost


A = [1, 8, 9, 7, 6]
ans = minCost(A, len(A))
print(ans)

# Expected output:
36
# maximize the last array element as per the given conditions | function to find the maximum possible value that can be placed at the last index ; sort the array elements in ascending order ; if the first element is is not equal to 1 ; traverse the array to make difference between adjacent elements <= 1 ; 
def maximizeFinalElement(arr, n):
    arr .sort()
    if (arr[0] != 1):
        arr[0] = 1
    for i in range(1, n):
        if (arr[i] - arr[i - 1] > 1):
            arr[i] = arr[i - 1] + 1
    return arr[n - 1]


if __name__ == '__main__':
    n = 4
    arr = [3, 1, 3, 4]
    max = maximizeFinalElement(arr, n)
    print(max)

# Expected output:
4
# find the point on x | function to find median of the array ; sort the given array ; if number of elements are even ; return the first median ; otherwise ; 
def findLeastDist(A, N):
    A .sort()
    if (N % 2 == 0):
        return A[(N - 1) // 2]
    else:
        return A[N // 2]


A = [4, 1, 5, 10, 2]
N = len(A)
print("(", findLeastDist(A, N), ", ", 0, ")")

# Expected output:
( 4 ,  0 )
# maximum sum of any submatrix of a matrix which is sorted row | function that finds the maximum sub - matrix sum ; number of rows in the matrix ; number of columns in the matrix ; dp [ ] [ ] matrix to store the results of each iteration ; base case - the largest element in the matrix ; to stores the final result ; find the max sub matrix sum for the last row ; check whether the current sub - array yields maximum sum ; calculate the max sub matrix sum for the last column ; check whether the current sub - array yields maximum sum ; build the dp [ ] [ ] matrix from bottom to the top row ; update sum at each cell in dp [ ] [ ] ; update the maximum sum ; return the maximum sum ; 
def maxSubMatSum(mat):
    n = len(mat)
    m = len(mat[0])
    dp = [[0] * m for _ in range(n)]
    dp[n - 1][m - 1] = mat[n - 1][m - 1]
    res = dp[n - 1][m - 1]
    for i in range(m - 2, -1, -1):
        dp[n - 1][i] = (mat[n - 1][i] + dp[n - 1][i + 1])
        res = max(res, dp[n - 1][i])
    for i in range(n - 2, -1, -1):
        dp[i][m - 1] = (mat[i][m - 1] + dp[i + 1][m - 1])
        res = max(res, dp[i][m - 1])
    for i in range(n - 2, -1, -1):
        for j in range(m - 2, -1, -1):
            dp[i][j] = (mat[i][j] + dp[i][j + 1] +
                        dp[i + 1][j] - dp[i + 1][j + 1])
            res = max(res, dp[i][j])
    return res


if __name__ == '__main__':
    mat = [[-6, -4, -1], [-3, 2, 4], [2, 5, 8]]
    print(maxSubMatSum(mat))

# Expected output:
19
# arrange the numbers in the array as per given inequalities | function to place the integers in between the inequality signs ; sort the integers array and set the index of smallest and largest element ; iterate over the inequalities ; append the necessary integers per symbol ; add the final integer ; return the answer ; 
def formAnInequality(integers, inequalities):
    integers .sort()
    lowerIndex = 0
    higherIndex = len(integers) - 1
    sb = ""
    for ch in inequalities:
        if (ch == '<'):
            sb += (" " + chr(integers[lowerIndex]) + " " + ch)
            lowerIndex += 1
        else:
            sb += (" " + chr(integers[higherIndex]) + " " + ch)
            higherIndex -= 1
    sb += (" " + chr(integers[lowerIndex]))
    return sb


if __name__ == "__main__":
    integers = [2, 5, 1, 0]
    inequalities = ['<', '>', '<']
    output = formAnInequality(integers, inequalities)
    print(output)

# Expected output:
  <  >  <
# check if two arrays can be made equal by reversing subarrays multiple times | function to check if array b can be made equal to array a ; sort both the arrays ; check if both the arrays are equal or not ; 
def canMadeEqual(A, B, n):
    A .sort()
    B .sort()
    for i in range(n):
        if (A[i] != B[i]):
            return False
    return True


if __name__ == "__main__":
    A = [1, 2, 3]
    B = [1, 3, 2]
    n = len(A)
    if (canMadeEqual(A, B, n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimize difference between maximum and minimum of array by at most k replacements | function to find minimum difference between the maximum and the minimum elements arr [ ] by at most k replacements ; check if turns are more than or equal to n - 1 then simply return zero ; sort the array ; set difference as the maximum possible difference ; iterate over the array to track the minimum difference in k turns ; return the answer ; 
def maxMinDifference(arr, n, k):
    if (k >= n - 1):
        return 0
    arr .sort()
    ans = arr[n - 1] - arr[0]
    i = k
    j = n - 1
    while i >= 0:
        ans = min(arr[j] - arr[i], ans)
        i -= 1
        j -= 1
    return ans


if __name__ == '__main__':
    arr = [1, 4, 6, 11, 15]
    N = len(arr)
    K = 3
    print(maxMinDifference(arr, N, K))

# Expected output:
2
# check if a decreasing array can be sorted using triple cyclic shift | python3 program for the above approach ; if array is 3 2 1 can ' t ▁ ▁ be ▁ sorted ▁ because ▁ 2 ▁ is ▁ in ▁ ▁ its ▁ correct ▁ position , ▁ 1 ▁ ▁ and ▁ 3 ▁ can ' t shift right because cyclic right shift takes place between 3 elements ; check if its possible to sort ; number of swap is n / 2 always for this approach ; printing index of the cyclic right shift ; 
def sortarray(arr, N):
    if (N == 3):
        print("NO")
    elif (N % 4 == 0 or N % 4 == 1):
        print("YES")
        print(N // 2)
        k = 1
        for l in range(N // 4):
            print(k, k + 1, N)
            print(k + 1, N, N - 1)
            k = k + 2
            N = N - 2
    else:
        print("NO")


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

# Expected output:
YES
2
1 2 5
2 5 4
# find least non | python3 program to find the least non - overlapping number from a given set intervals ; function to find the smallest non - overlapping number ; create a visited array ; find the first missing value ; 

MAX = int(1e5 + 5)


def find_missing(interval):
    vis = [0] * (MAX)
    for i in range(len(interval)):
        start = interval[i][0]
        end = interval[i][1]
        vis[start] += 1
        vis[end + 1] -= 1
    for i in range(1, MAX):
        vis[i] += vis[i - 1]
        if (vis[i] == 0):
            print(i)
            return


interval = [[0, 14], [86, 108], [22, 30], [5, 17]]
find_missing(interval)

# Expected output:
18
# find least non | function to find the smallest non - overlapping number ; sort the intervals based on their starting value ; check if any missing value exist ; finally print the missing value ; 
def find_missing(interval):
    interval .sort()
    mx = 0
    for i in range(len(interval)):
        if (interval[i][0] > mx):
            print(mx)
            return
        else:
            mx = max(mx, interval[i][1] + 1)
    print(mx)


if __name__ == "__main__":
    interval = [[0, 14], [86, 108], [22, 30], [5, 17]]
    find_missing(interval)

# Expected output:
18
# maximum bitwise or value of subsequence of length k | function to convert bit array to decimal number ; return the final result ; function to find the maximum bitwise or value of subsequence of length k ; initialize bit array of size 32 with all value as 0 ; iterate for each index of bit [ ] array from 31 to 0 , and check if the ith value of bit array is 0 ; check for maximum contributing element ; update the bit array if max_contributing element is found ; decrement the value of k ; return the result ; 
def build_num(bit):
    ans = 0
    for i in range(0, 32):
        if (bit[i]):
            ans += (1 << i)
    return ans


def maximumOR(arr, n, k):
    bit = [0] * 32
    for i in range(31, -1, -1):
        if (bit[i] == 0 and k > 0):
            temp = build_num(bit)
            temp1 = temp
            val = -1
            for j in range(0, n):
                if (temp1 < (temp | arr[j])):
                    temp1 = temp | arr[j]
                    val = arr[j]
            if (val != -1):
                k -= 1
                for j in range(0, 32):
                    if (val & (1 << j)):
                        bit[j] += 1
    return build_num(bit)


arr = [5, 9, 7, 19]
k = 3
n = len(arr)
print(maximumOR(arr, n, k))

# Expected output:
31
# lexicographically smallest string after m operations | function to find the lexicographical smallest string after performing m operations ; size of the given string ; declare an array a ; for each i , a [ i ] contain number of operations to update s [ i ] to 'a ; check if m >= ar [ i ] , then update s [ i ] to ' a ' decrement k by a [ i ] ; form a cycle of 26 ; return the answer ; 
def smallest_string(s, m):
    n = len(s)
    l = list(s)
    a = [0] * n

    for i in range(n):
        distance = ord(s[i]) - ord('a')
        if (distance == 0):
            a[i] = 0
        else:
            a[i] = 26 - distance
    for i in range(n):
        if (m >= a[i]):
            l[i] = 'a'
            m = m - a[i]
    m = m % 26
    for i in range(len(l) - 1):
        print(l[i], end="")
    print(chr(ord(l[n - 1]) + m))


str = "aazzx"
m = 6
smallest_string(str, m)

# Expected output:
aaaab
# maximize jobs that can be completed under given constraint | function to find maxiumum number of jobs ; min heap ; sort ranges by start day ; stores the minimum and maximum day in the ranges ; iterating from min_day to max_day ; insert the end day of the jobs which can be completed on i - th day in a priority queue ; pop all jobs whose end day is less than current day ; if queue is empty , no job can be completed on the i - th day ; increment the count of jobs completed ; pop the job with least end day ; return the jobs on the last day ; 
def find_maximum_jobs(N, ranges):
    queue = []
    ranges.sort()
    min_day = ranges[0][0]
    max_day = 0
    for i in range(N):
        max_day = max(max_day, ranges[i][1])
    index, count_jobs = 0, 0
    for i in range(min_day, max_day + 1):
        while (index < len(ranges) and ranges[index][0] <= i):

            queue.append(ranges[index][1])
            index += 1

        queue.sort()
        while (len(queue) > 0 and queue[0] < i):
            queue.pop(0)
        if (len(queue) == 0):
            continue
        count_jobs += 1
        queue.pop(0)
    return count_jobs


N = 5
ranges = []
ranges .append((1, 5))
ranges .append((1, 5))
ranges .append((1, 5))
ranges .append((2, 3))
ranges .append((2, 3))
print(find_maximum_jobs(N, ranges))

# Expected output:
5
# minimize number of boxes by putting small box inside bigger one | function to minimize the count ; initial number of box ; sort array of box size in increasing order ; check is current box size is smaller than next box size ; decrement box count increment current box count increment next box count ; check if both box have same size ; print the result ; 
def minBox(arr, n):
    box = n
    arr .sort()
    curr_box, next_box = 0, 1
    while (curr_box < n and next_box < n):
        if (arr[curr_box] < arr[next_box]):
            box = box - 1
            curr_box = curr_box + 1
            next_box = next_box + 1
        elif (arr[curr_box] == arr[next_box]):
            next_box = next_box + 1
    print(box)


size = [1, 2, 3]
n = len(size)
minBox(size, n)

# Expected output:
1
# sort a string lexicographically using triple cyclic shifts | python3 program for sorting a string using cyclic shift of three indices ; store the indices which haven 't attained  its correct position ; store the indices undergoing cyclic shifts ; if the element is not at it 's correct position ; check if all 3 indices can be placed to respective correct indices in a single move ; if the i - th index is still not present in its correct position , store the index ; to check if swapping two indices places them in their correct position ; for i in range len ( indices ) : print ( indices [ i ] [ 0 ] , indices [ i ] [ 1 ] , indices [ i ] [ 2 ] ) ; 

import math


def sortString(arr, n, moves):
    pos = []
    indices = []
    flag = False
    for i in range(n):
        if (arr[i] != i):
            if (arr[arr[arr[i]]] == i and arr[arr[i]] != i):
                temp = arr[arr[i]]
                indices .append([i, arr[i], arr[arr[i]]])
                sw = arr[i]
                arr[i] = arr[arr[i]]
                arr[sw] = sw
                sw = arr[i]
                arr[i] = arr[temp]
                arr[temp] = sw
        if (arr[i] != i):
            pos .append(i)
    for i in range(n):
        if (arr[i] != i):
            pos1 = i
            pos2 = arr[i]
            pos3 = arr[arr[i]]
            if (pos3 != pos1):
                indices .append([pos1, pos2, pos3])
                arr[pos1], arr[pos2] = arr[pos2], arr[pos1]
                arr[pos1], arr[pos3] = arr[pos3], arr[pos1]
                pos .remove(pos2)
                if pos3 in pos:
                    pos .remove(pos3)
                if (arr[pos1] == pos1):
                    pos .remove(pos1)
            else:
                if (pos3 == pos[0]):
                    it = 0
                    if (pos[0] != pos[-1]):
                        it = it + 1
                        pos3 = pos[it]
                        if (pos[it] != pos[-1] and pos3 == pos2):
                            it = it + 1
                            pos3 = pos[it]
                        elif (pos[it] == pos[-1] and pos3 == pos2):
                            flag = True
                            break
                    else:
                        flag = True
                        break
                indices .append([pos1, pos2, pos3])
                arr[pos1], arr[pos2] = arr[pos2], arr[pos1]
                arr[pos1], arr[pos3] = arr[pos3], arr[pos1]
                pos .remove(pos2)
        if (arr[i] != i):
            i = i - 1
    if (flag or len(indices) > moves):
        print("Not Possible")
    else:
        print(len(indices))


s = "adceb"
arr = []
for i in s:
    arr .append(ord(i) - ord('a'))
sortString(arr, len(s), math .floor(len(s) / 2))

# Expected output:
1
# count of minimum reductions required to get the required sum k | python3 program to find the count of minimum reductions required to get the required sum k ; function to return the count of minimum reductions ; if the sum is already less than k ; sort in non - increasing order of difference ; 

from typing import Any, List


def countReductions(v: List[Any], K: int) -> int:
    sum = 0
    for i in v:
        sum += i[0]
    if (sum <= K):
        return 0
    v .sort(key=lambda a: a[0] - a[1])
    i = 0
    while (sum > K and i < len(v)):
        sum -= (v[i][0] - v[i][1])
        i += 1
    if (sum <= K):
        return i
    return -1


if __name__ == "__main__":
    N = 4
    K = 25
    v = [[0, 0]for _ in range(N)]
    v[0] = [10, 5]
    v[1] = [20, 9]
    v[2] = [12, 10]
    v[3] = [4, 2]
    print(countReductions(v, K))

# Expected output:
-1
# find k elements whose absolute difference with median of array is maximum | function for calculating median ; check for even case ; function to find the k maximum absolute difference with the median of the array ; sort the array ; store median ; find and store difference ; if diff [ i ] is greater print it . else print diff [ j ] ; 
def findMedian(a, n):
    if (n % 2 != 0):
        return a[int(n / 2)]
    return (a[int((n - 1) / 2)] + a[int(n / 2)]) / 2.0


def kStrongest(arr, n, k):
    arr .sort()
    median = findMedian(arr, n)
    diff = [0] * (n)
    for i in range(n):
        diff[i] = abs(median - arr[i])
    i = 0
    j = n - 1
    while (k > 0):
        if (diff[i] > diff[j]):
            print(arr[i], end=" ")
            i += 1
        else:
            print(arr[j], end=" ")
            j -= 1
        k -= 1


arr = [1, 2, 3, 4, 5]
k = 3
n = len(arr)
kStrongest(arr, n, k)

# Expected output:
5 1 4
# sort an array by swapping elements of different type specified by another array | function to check if it is possible to sort the array in non - decreasing order by swapping elements of different types ; consider the array to be already sorted ; checking if array is already sorted ; check for a pair which is in decreasing order ; count the frequency of each type of element ; type0 stores count of elements of type 0 ; type1 stores count of elements of type 1 ; return true if array is already sorted ; return false if all elements are of same type and array is unsorted ; possible for all other cases ; 
def sorting_possible(a, b, n):
    sorted = True
    type1 = 0
    type0 = 0
    for i in range(1, n):
        if (a[i] < a[i - 1]):
            sorted = False
            break
    for i in range(n):
        if (b[i] == 0):
            type0 += 1
        else:
            type1 += 1
    if (sorted):
        return True
    elif (type1 == n or type0 == n):
        return False
    else:
        return True


a = [15, 1, 2, 17, 6]
b = [1, 1, 0, 1, 1]
n = len(a)
res = sorting_possible(a, b, n)
if (res):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# sort permutation of n natural numbers using triple cyclic right swaps | function to sort the permutation with the given operations ; visited array to check the array element is at correct position or not ; loop to iterate over the elements of the given array ; condition to check if the elements is at its correct position ; condition to check if the element is included in any previous cyclic rotations ; loop to find the cyclic rotations in required ; condition to check if the cyclic rotation is a valid rotation ; loop to find the index of the cyclic rotation for the current index ; condition to if the cyclic rotation is a valid rotation ; loop to find athe valid operations required to sort the permutation ; total operation required ; 
def sortPermutation(arr, n):
    ans = []
    p = []
    visited = [0] * 200005
    for i in range(1, n + 1):
        if (arr[i] == i):
            visited[i] = 1
            continue
        else:
            if (visited[i] == False):
                x = i
                v = []
                while (visited[x] == False):
                    visited[x] = 1
                    v .append(x)
                    x = arr[x]
                if ((len(v) - 3) % 2 == 0):
                    for i in range(1, len(v), 2):
                        ans .append([v[0], v[i], v[i + 1]])
                    continue
                p .append(v[0])
                p .append(v[len(v) - 1])
                for i in range(1, len(v) - 1, 2):
                    ans .append([v[0], v[i], v[i + 1]])
    if (len(p) % 4):
        print(-1)
        return
    for i in range(0, len(p), 4):
        ans .append([p[i], p[i + 1], p[i + 2]])
        ans .append(p[i[+2], p[i], p[i + 3]])
    print(len(ans))
    for i in ans:
        print(i[0], i[1], i[2])


if __name__ == '__main__':
    arr = [0, 3, 2, 4, 1]
    n = 4
    sortPermutation(arr, n)

# Expected output:
1
1 3 4
# maximize array sum by x increments when each element is divided by 10 | python3 program for the above problem ; initialize variables ; add the current contribution of the element to the answer ; if the value is already maximum then we can 't  change it ; moves required to move to the next multiple of 10 ; no of times we can add 10 to this value so that its value does not exceed 1000. ; sort the array ; adding the values to increase the numbers to the next multiple of 10 ; if the total moves are less than x then increase the answer ; if the moves exceed x then we cannot increase numbers ; if there still remain some moves ; remaining moves ; add minimim of increments and remaining / 10 to the answer ; output the final answer ; 
def maximizeval10(a, n, k):
    increments = 0
    ans = 0
    v = []
    for i in range(n):
        ans += (a[i] // 10)
        if (a[i] == 1000):
            continue
        else:
            v .append(10 - a[i] % 10)
            increments += (100 - ((a[i]) // 10) - 1)
    v .sort()
    sum = 0
    for i in range(len(v)):
        sum += v[i]
        if (sum <= k):
            ans += 1
        else:
            break
    if (sum < k):
        remaining = k - sum
        ans += min(increments, remaining // 10)
    print(ans)


if __name__ == "__main__":
    N = 4
    X = 6
    A = [4, 8, 8, 8]
    maximizeval10(A, N, X)

# Expected output:
3
# split array into two subarrays such that difference of their maximum is minimum | python3 program to split a given array such that the difference between their maximums is minimized . ; sort the array ; return the difference between two highest elements ; 
def findMinDif(arr, N):
    arr .sort()
    return (arr[N - 1] - arr[N - 2])


arr = [7, 9, 5, 10]
N = len(arr)
print(findMinDif(arr, N))

# Expected output:
1
# maximum items that can be bought from the cost array based on given conditions | function to find the maximum number of items that can be bought from the given cost array ; sort the given array ; variables to store the prefix sum , answer and the counter variables ; initializing the first element of the prefix array ; if we can buy at least one item ; iterating through the first k items and finding the prefix sum ; check the number of items that can be bought ; finding the prefix sum for the remaining elements ; check the number of iteams that can be bought ; 
def number(a, n, p, k):
    a .sort()
    pre = []
    for i in range(n):
        pre .append(0)
    ans = 0
    val = 0
    i = 0
    j = 0
    pre[0] = a[0]
    if pre[0] <= p:
        ans = 1
    for i in range(1, k - 1):
        pre[i] = pre[i - 1] + a[i]
        if pre[i] <= p:
            ans = i + 1
    pre[k - 1] = a[k - 1]
    for i in range(k - 1, n):
        if i >= k:
            pre[i] += pre[i - k] + a[i]
        if pre[i] <= p:
            ans = i + 1
    return ans


n = 5
arr = [2, 4, 3, 5, 7]
p = 11
k = 2
print(number(arr, n, p, k))

# Expected output:
4