giulio98/xlcost-single-prompt huggingface dataset:
# maximum even sum subsequence of length k | function to find the maximum even sum of any subsequence of length k ; if count of elements is less than k ; stores maximum even subsequence sum ; stores even numbers ; stores odd numbers ; traverse the array ; if current element is an odd number ; insert odd number ; insert even numbers ; sort odd [ ] array ; sort even [ ] array ; stores current index of even [ ] array ; stores current index of odd [ ] array ; if k is odd ; if count of elements in even [ ] >= 1 ; update maxsum ; update i ; if count of elements in even [ ] array is 0. ; update k ; if count of elements in even [ ] and odd [ ] >= 2 ; update maxsum ; update j . ; update maxsum ; update i ; update k ; if count of elements in even [ ] array >= 2. ; update maxsum ; update i . ; update k . ; if count of elements in odd [ ] array >= 2 ; update maxsum ; update i . ; update k . ; 
def evenSumK(arr, N, K):
    if (K > N):
        return -1
    maxSum = 0
    Even = []
    Odd = []
    for i in range(N):
        if (arr[i] % 2):
            Odd .append(arr[i])
        else:
            Even .append(arr[i])
    Odd .sort(reverse=False)
    Even .sort(reverse=False)
    i = len(Even) - 1
    j = len(Odd) - 1
    while (K > 0):
        if (K % 2 == 1):
            if (i >= 0):
                maxSum += Even[i]
                i -= 1
            else:
                return -1
            K -= 1
        elif (i >= 1 and j >= 1):
            if (Even[i] + Even[i - 1] <= Odd[j] + Odd[j - 1]):
                maxSum += Odd[j] + Odd[j - 1]
                j -= 2
            else:
                maxSum += Even[i] + Even[i - 1]
                i -= 2
            K -= 2
        elif (i >= 1):
            maxSum += Even[i] + Even[i - 1]
            i -= 2
            K -= 2
        elif (j >= 1):
            maxSum += Odd[j] + Odd[j - 1]
            j -= 2
            K -= 2
    return maxSum


if __name__ == '__main__':
    arr = [2, 4, 10, 3, 5]
    N = len(arr)
    K = 3
    print(evenSumK(arr, N, K))

# Expected output:
18
# program to find weighted median of a given array | function to calculate weighted median ; store pairs of arr [ i ] and w [ i ] ; sort the list of pairs w . r . t . to their arr [ ] values ; if n is odd ; traverse the set pairs from left to right ; update sums ; if sum becomes > 0.5 ; if n is even ; for lower median traverse the set pairs from left ; update sums ; when sum >= 0.5 ; for upper median traverse the set pairs from right ; update sums ; when sum >= 0.5 ; 
def weightedMedian(arr, W):
    pairs = []
    for index in range(len(arr)):
        pairs .append([arr[index], W[index]])
    pairs .sort(key=lambda p: p[0])
    if len(arr) % 2 != 0:
        sums = 0
        for element, weight in pairs:
            sums += weight
            if sums > 0.5:
                print("The Weighted Median", end=' ')
                print("is element {}".format(element))
    else:
        sums = 0
        for element, weight in pairs:
            sums += weight
            if sums >= 0.5:
                print("Lower Weighted Median", end=' ')
                print("is element {}".format(element))
                break
        sums = 0
        for index in range(len(pairs) - 1, -1, -1):
            element = pairs[index][0]
            weight = pairs[index][1]
            sums += weight
            if sums >= 0.5:
                print("Upper Weighted Median", end=' ')
                print("is element {}".format(element))
                break


if __name__ == "__main__":
    arr = [4, 1, 3, 2]
    W = [0.25, 0.49, 0.25, 0.01]
    weightedMedian(arr, W)

# Expected output:
Lower Weighted Median is element 2
Upper Weighted Median is element 3
# kth smallest element from an array of intervals | function to get the kth smallest element from an array of intervals ; store all the intervals so that it returns the minimum element in o ( 1 ) ; insert all intervals into the minheap ; stores the count of popped elements ; iterate over minheap ; stores minimum element from all remaining intervals ; remove minimum element ; check if the minimum of the current interval is less than the maximum of the current interval ; insert new interval ; 
def KthSmallestNum(arr, n, k):
    pq = []
    for i in range(n):
        pq .append([arr[i][0], arr[i][1]])
    cnt = 1
    while (cnt < k):
        pq .sort(reverse=True)
        interval = pq[0]
        pq .remove(pq[0])
        if (interval[0] < interval[1]):
            pq .append([interval[0] + 1, interval[1]])
        cnt += 1
    pq .sort(reverse=True)
    return pq[0][0] + 1


if __name__ == '__main__':
    arr = [[5, 11], [10, 15], [12, 20]]
    n = len(arr)
    k = 12
    print(KthSmallestNum(arr, n, k))

# Expected output:
13
# maximum manhattan distance between a distinct pair from n coordinates | python3 program for the above approach ; function to calculate the maximum manhattan distance ; stores the maximum distance ; find manhattan distance using the formula | x1 - x2 | + | y1 - y2 | ; updating the maximum ; 

import sys


def MaxDist(A, N):
    maximum = -sys .maxsize
    for i in range(N):
        sum = 0
        for j in range(i + 1, N):
            Sum = (abs(A[i][0] - A[j][0]) + abs(A[i][1] - A[j][1]))
            maximum = max(maximum, Sum)
    print(maximum)


N = 3
A = [[1, 2], [2, 3], [3, 4]]
MaxDist(A, N)

# Expected output:
4
# longest increasing subsequence which forms a subarray in the sorted representation of the array | function to find the length of the longest increasing sorted sequence ; stores the count of all elements ; store the original array ; sort the array ; if adjacent element are not same ; increment count ; store frequency of each element ; initialize a dp array ; iterate over the array ar [ ] ; length of the longest increasing sorted sequence ; iterate over the array ; current element ; if the element has been encountered the first time ; if all the x - 1 previous elements have already appeared ; otherwise ; if all x - 1 elements have already been encountered ; increment the count of the current element ; update maximum subsequence size ; return the maximum subsequence size ; 
def LongestSequence(a, n):
    m = {i: 0 for i in range(100)}

    ar = [0 for i in range(n + 1)]
    for i in range(1, n + 1):
        ar[i] = a[i - 1]
    a.sort(reverse=False)

    c = 1
    m[a[0]] = c

    for i in range(1, n):
        if (a[i] != a[i - 1]):
            c += 1
            m[a[i]] = c
    cnt = {i: 0 for i in range(100)}
    dp = [[0 for i in range(3)]
          for j in range(n + 1)]

    cnt[0] = 0
    for i in range(1, n + 1):

        ar[i] = m[ar[i]]
        cnt[ar[i]] += 1
    ans = 0
    for i in range(1, n + 1):
        x = ar[i]
        if (dp[x][0] == 0):
            if (dp[x - 1][0] == cnt[x - 1]):
                dp[x][1] = dp[x - 1][1]
                dp[x][2] = dp[x - 1][1]
            else:
                dp[x][1] = dp[x - 1][0]

            dp[x][2] = max(dp[x - 1][0], dp[x][2])

            if (dp[x - 1][0] == cnt[x - 1]):
                dp[x][2] = max(dp[x][2], dp[x - 1][1])

            for j in range(3):
                dp[x][j] += 1
                ans = max(ans, dp[x][j])
    return ans


if __name__ == '__main__':

    arr = [2, 6, 4, 8, 2, 9]

    N = len(arr)
    print(LongestSequence(arr, N))

# Expected output:
3
# range sum queries based on given conditions | function to calculate the sum between the given range as per value of m ; stores the sum ; condition for a to print the sum between ranges [ a , b ] ; return sum ; function to precalculate the sum of both the vectors ; make prefix sum array ; function to compute the result for each query ; take a dummy vector and copy the element of arr in brr ; sort the dummy vector ; compute prefix sum of both vectors ; performs operations ; function call to find sum ; function call to find sum ; 
def range_sum(arr, a, b):
    sum = 0
    if (a - 2 < 0):
        sum = arr[b - 1]
    else:
        sum = (arr[b - 1] - arr[a - 2])
    return sum


def precompute_sum(arr, brr):
    N = len(arr)
    for i in range(1, N):
        arr[i] = arr[i] + arr[i - 1]
        brr[i] = brr[i] + brr[i - 1]


def find_sum(arr, q, Queries):
    brr = arr .copy()
    N = len(arr)
    brr .sort()
    precompute_sum(arr, brr)
    for i in range(q):
        m = Queries[i][0]
        a = Queries[i][1]
        b = Queries[i][2]
        if (m == 1):
            print(range_sum(arr, a, b), end=' ')
        elif (m == 2):
            print(range_sum(brr, a, b), end=' ')


if __name__ == "__main__":
    arr = [0, 6, 4, 2, 7, 2, 7]
    Q = 1
    Queries = [[2, 3, 6]]
    find_sum(arr, Q, Queries)

# Expected output:
19
# xor of all possible pairwise sum from two given arrays | python3 program to implement the above approach ; function to calculate the xor of the sum of every pair ; stores the maximum bit ; look for all the k - th bit ; stores the modulo of elements b [ ] with ( 2 ^ ( k + 1 ) ) ; calculate modulo of array b [ ] with ( 2 ^ ( k + 1 ) ) ; sort the array c [ ] ; stores the total number whose k - th bit is set ; calculate and store the modulo of array a [ ] with ( 2 ^ ( k + 1 ) ) ; lower bound to count the number of elements having k - th bit in the range ( 2 ^ k - x , 2 * 2 ^ ( k ) - x ) ; add total number i . e ( r - l ) whose k - th bit is one ; lower bound to count the number of elements having k - th bit in range ( 3 * 2 ^ k - x , 4 * 2 ^ ( k ) - x ) ; if count is even , xor of k - th bit becomes zero , no need to add to the answer . if count is odd , only then , add to the final answer ; return answer ; 

from bisect import bisect, bisect_left, bisect_right


def XorSum(A, B, N):
    maxBit = 29
    ans = 0
    for k in range(maxBit):
        C = [0] * N
        for i in range(N):
            C[i] = B[i] % (1 << (k + 1))
        C = sorted(C)
        count = 0
        l, r = 0, 0
        for i in range(N):
            x = A[i] % (1 << (k + 1))
            l = bisect_left(C, (1 << k) - x)
            r = bisect_left(C, (1 << k) * 2 - x)
            count += (r - l)
            l = bisect_left(C, (1 << k) * 3 - x)
            r = bisect_left(C, (1 << k) * 4 - x)
            count += (r - l)
        if (count & 1):
            ans += (1 << k)
    return ans


if __name__ == '__main__':
    A = [4, 6, 0, 0, 3, 3]
    B = [0, 5, 6, 5, 0, 3]
    N = len(A)
    print(XorSum(A, B, N))

# Expected output:
8
# minimize count of subsets with difference between maximum and minimum element not exceeding k | function to find the minimum count of subsets of required type ; stores the result ; store the maximum and minimum element of the current subset ; update current maximum ; if difference exceeds k ; update count ; update maximum and minimum to the current subset ; 
def findCount(arr, N, K):
    arr .sort()
    result = 1
    cur_max = arr[0]
    cur_min = arr[0]
    for i in range(1, N):
        cur_max = arr[i]
        if (cur_max - cur_min > K):
            result += 1
            cur_max = arr[i]
            cur_min = arr[i]
    return result


arr = [1, 10, 8, 3, 9]
K = 3
N = len(arr)
print(findCount(arr, N, K))

# Expected output:
2
# minimize the sum of all the subarrays made up of the products of same | python3 program to implement the above approach ; function to rearrange the second array such that the sum of its product of same indexed elements from both the arrays is minimized ; stores ( i - 1 ) * ( n - i ) * a [ i ] for every i - th element ; updating the value of pro according to the function ; sort the array in reverse order ; sort the products ; updating the ans ; return the ans ; 

mod = 1e9 + 7


def findMinValue(a, b):
    n = len(a)
    pro = [0] * (n)
    for i in range(n):
        pro[i] = ((i + 1) * (n - i))
        pro[i] *= (a[i])
    b .sort(reverse=True)
    pro .sort()
    ans = 0
    for i in range(n):
        ans += (pro[i] % mod * b[i]) % mod
        ans %= mod
    return ans


if __name__ == "__main__":
    a = [1, 2, 3]
    b = [2, 3, 2]
    print(int(findMinValue(a, b)))

# Expected output:
43
# sort array such that smallest is at 0 th index and next smallest it at last index and so on | python3 program for the above approach function to perform the rearrangement ; initialize variables ; loop until i crosses j ; this check is to find the minimum values in the ascending order ; condition to alternatively iterate variable i and j ; perform swap operation ; increment i ; assign the value of min ; perform swap ; decrement i ; assign the value of min ; print the array ; 
def rearrange(a, N):
    i = 0
    j = N - 1
    min = 0
    x = 0
    while (i < j):
        for k in range(i, j + 1):
            if (a[k] < a[min]):
                min = k
        if (x % 2 == 0):
            temp = a[i]
            a[i] = a[min]
            a[min] = temp
            i += 1
            min = i
        else:
            temp = a[j]
            a[j] = a[min]
            a[min] = temp
            j -= 1
            min = j
        x += 1
    for i in range(N):
        print(a[i], end=" ")


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

# Expected output:
1 3 5 4 3
# maximum number of elements greater than x after equally distributing subset of array | function to find the maximum number of elements greater than x by equally distributing ; sorting the array ; loop to iterate over the elements of the array ; if no more elements can become larger than x ; 
def redistribute(arr, n, x):
    arr .sort(reverse=True)
    sum = 0
    for i in range(n):
        sum += arr[i]
        if (sum / (i + 1) < x):
            print(i)
            break
    if (i == n):
        print(n)


arr = [5, 1, 2, 1]
x = 3
redistribute(arr, 4, x)

# Expected output:
2
# last element remaining by deleting two largest elements and replacing by their absolute difference if they are unequal | python3 program for the above approach ; function to print the remaining element ; priority queue can be used to construct max - heap ; insert all element of arr [ ] into priority queue . default priority queue in python is min - heap so use - 1 * arr [ i ] ; perform operation until heap size becomes 0 or 1 ; remove largest element ; remove 2 nd largest element ; if extracted elements are not equal ; find x - y and push it to heap ; if heap size is 1 , then print the remaining element ; else print " - 1" ; 

from queue import PriorityQueue


def final_element(arr, n):
    heap = PriorityQueue()
    for i in range(n):
        heap .put(-1 * arr[i])
    while (heap .qsize() > 1):
        X = -1 * heap .get()
        Y = -1 * heap .get()
        if (X != Y):
            diff = abs(X - Y)
            heap .put(-1 * diff)
    if (heap .qsize() == 1):
        print(-1 * heap .get())
    else:
        print("-1")


if __name__ == '__main__':
    arr = [3, 5, 2, 7]
    n = len(arr)
    final_element(arr, n)

# Expected output:
1
# sort a string according to the frequency of characters | returns count of character in the string ; check for vowel ; function to sort the string according to the frequency ; vector to store the frequency of characters with respective character ; inserting frequency with respective character in the vector pair ; sort the vector , this will sort the pair according to the number of characters ; print the sorted vector content ; 
def countFrequency(string, ch):
    count = 0
    for i in range(len(string)):
        if (string[i] == ch):
            count += 1
    return count


def sortArr(string):
    n = len(string)
    vp = []
    for i in range(n):
        vp .append((countFrequency(string, string[i]), string[i]))
    vp .sort()
    for i in range(len(vp)):
        print(vp[i][1], end="")


if __name__ == "__main__":
    string = "geeksforgeeks"
    sortArr(string)

# Expected output:
forggkksseeee
# maximum sum after rearranging the array for k queries | function to find maximum sum after rearranging array elements ; auxiliary array to find the count of each selected elements initialize with 0 ; finding count of every element to be selected ; making it to 0 - indexing ; prefix sum array concept is used to obtain the count array ; iterating over the count array to get the final array ; variable to store the maximum sum ; sorting both the arrays ; loop to find the maximum sum ; 
def maxSumArrangement(A, R, N, M):
    count = [0 for i in range(N)]
    for i in range(M):
        l = R[i][0]
        r = R[i][1] + 1
        l = l - 1
        r = r - 1
        count[l] = count[l] + 1
        if (r < N):
            count[r] = count[r] - 1
    for i in range(1, N):
        count[i] = count[i] + count[i - 1]
    ans = 0
    count .sort()
    A .sort()
    for i in range(N - 1, -1, -1):
        ans = ans + A[i] * count[i]
    return ans


A = [2, 6, 10, 1, 5, 6]
R = [[1, 3], [4, 6], [3, 4]]
N = len(A)
M = len(R)
print(maxSumArrangement(A, R, N, M))

# Expected output:
46
# sum of m maximum distinct digit sum from 1 to n that are factors of k | python 3 implementation to find the sum of maximum distinct digit sum of at most m numbers from 1 to n that are factors of k ; function to find the factors of k in n ; initialise a vector ; find out the factors of k less than n ; find the digit sum of each factor ; sum of digits for each element in vector ; find the largest m distinct digit sum from the digitsum vector ; find the sum of last m numbers . ; find the at most m numbers from n natural numbers whose digit sum is distinct and those m numbers are factors of k ; find out the factors of k less than n ; sum of digits for each element in vector ; sorting the digitsum vector ; removing the duplicate elements ; finding the sum and returning it ; 

import math


def findFactors(n, k):
    factors = []
    sqt = (int)(math .sqrt(k))
    for i in range(1, sqt):
        if (k % i == 0):
            if (k // i == i and i <= n):
                factors .append(i)
            else:
                if (i <= n):
                    factors .append(i)
                if (k // i <= n):
                    factors .append(k // i)
    return factors


def findDigitSum(a):
    for i in range(len(a)):
        c = 0
        while (a[i] > 0):
            c += a[i] % 10
            a[i] = a[i] // 10
        a[i] = c
    return a


def findMMaxDistinctDigitSum(distinctDigitSum, m):
    sum = 0
    i = len(distinctDigitSum) - 1
    while (i >= 0 and m > 0):
        sum += distinctDigitSum[i]
        i -= 1
        m -= 1
    return sum


def findDistinctMnumbers(n, k, m):
    factors = findFactors(n, k)
    digitSum = sorted(findDigitSum(factors))
    ip = list(set(digitSum))
    return findMMaxDistinctDigitSum(ip, m)


if __name__ == "__main__":
    n = 100
    k = 80
    m = 4
    print(findDistinctMnumbers(n, k, m))

# Expected output:
24
# Sorting objects using In | Partition function which will partition the array and into two parts ; Compare hash values of objects ; Classic quicksort algorithm ; Function to sort and print the objects ; As the sorting order is blue objects , red objects and then yellow objects ; Quick sort function ; Printing the sorted array ; Let 's represent objects as strings

objects = []
hash = dict()


def partition(l, r):
    global objects, hash
    j = l - 1
    last_element = hash[objects[r]]
    for i in range(l, r):
        if (hash[objects[i]] <= last_element):
            j += 1
            (objects[i], objects[j]) = (objects[j], objects[i])
    j += 1
    (objects[j], objects[r]) = (objects[r], objects[j])
    return j


def quicksort(l, r):
    if (l < r):
        mid = partition(l, r)
        quicksort(l, mid - 1)
        quicksort(mid + 1, r)


def sortObj():
    global objects, hash
    hash["blue"] = 1
    hash["red"] = 2
    hash["yellow"] = 3
    quicksort(0, int(len(objects) - 1))
    for i in objects:
        print(i, end=" ")


objects = ["red", "blue", "red", "yellow", "blue"]
sortObj()

# Expected output:
blue blue red red yellow
# sort the numbers according to their product of digits | function to return the product of the digits of n ; function to sort the array according to the product of the digits of elements ; vector to store the digit product with respective elements ; inserting digit product with elements in the vector pair ; sort the vector , this will sort the pair according to the product of the digits ; print the sorted vector content ; 
def productOfDigit(n):
    product = 1
    while (n > 0):
        product *= (n % 10)
        n = n // 10
    return product


def sortArr(arr, n):
    vp = []
    for i in range(n):
        vp .append((productOfDigit(arr[i]), arr[i]))
    vp .sort()
    for i in range(len(vp)):
        print(vp[i][1], end=" ")


if __name__ == "__main__":
    arr = [12, 10, 102, 31, 15]
    n = len(arr)
    sortArr(arr, n)

# Expected output:
10 102 12 31 15
# minimum steps required to reduce all the elements of the array to zero | function to return the minimum steps required to reduce all the elements to 0 ; maximum element from the array ; 
def minSteps(arr, n):
    maxVal = max(arr)
    return maxVal


arr = [1, 2, 4]
n = len(arr)
print(minSteps(arr, n))

# Expected output:
4
# maximum water that can be stored between two buildings | return the maximum water that can be stored ; check all possible pairs of buildings ; maximum so far ; 
def maxWater(height, n):
    maximum = 0
    for i in range(n - 1):
        for j in range(i + 1, n):
            current = min(height[i], height[j]) * (j - i - 1)
            maximum = max(maximum, current)
    return maximum


if __name__ == "__main__":
    height = [2, 1, 3, 4, 6, 5]
    n = len(height)
    print(maxWater(height, n))

# Expected output:
8
# check if the given array contains all the divisors of some integer | python 3 implementation of the approach ; function that returns true if arr [ ] contains all the divisors of some integer ; maximum element from the array ; vector to store divisors of the maximum element i . e . x ; store all the divisors of x ; if the lengths of a [ ] and b are different return false ; sort a [ ] and b ; if divisors are not equal return false ; 

from math import sqrt


def checkDivisors(a, n):
    X = max(a)
    b = []
    for i in range(1, int(sqrt(X)) + 1):
        if (X % i == 0):
            b .append(i)
            if (X // i != i):
                b .append(X // i)
    if (len(b) != n):
        return False
    a .sort(reverse=False)
    b .sort(reverse=False)
    for i in range(n):
        if (b[i] != a[i]):
            return False
    return True


if __name__ == '__main__':
    arr = [8, 1, 2, 12, 48, 6, 4, 24, 16, 3]
    N = len(arr)
    if (checkDivisors(arr, N)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# kth largest node among all directly connected nodes to the given node in an undirected graph | function to print kth node for each node ; vector to store nodes directly connected to ith node along with their values ; add edges to the vector along with the values of the node ; sort neighbors of every node and find the kth node ; get the kth node ; if total nodes are < k ; 
def findKthNode(u, v, n, val, V, k):
    g = [[]for i in range(V)]
    for i in range(0, n):
        g[u[i]].append((val[v[i]], v[i]))
        g[v[i]].append((val[u[i]], u[i]))
    for i in range(0, V):
        if len(g[i]) > 0:
            g[i].sort()
        if k <= len(g[i]):
            print(g[i][-k][1])
        else:
            print("-1")
    return


if __name__ == "__main__":
    V = 3
    val = [2, 4, 3]
    u = [0, 0, 1]
    v = [2, 1, 2]
    n, k = len(u), 2
    findKthNode(u, v, n, val, V, k)

# Expected output:
2
0
0
# minimum length of square to contain at least half of the given coordinates | function to calculate the minimum value of m ; to store the minimum m for each point in array ; sort the array ; index at which atleast required point are inside square of length 2 * m ; 
def findSquare(n):
    points = [[1, 2], [-3, 4], [1, 78], [-3, -7]]
    a = [None] * n
    for i in range(0, n):
        x = points[i][0]
        y = points[i][1]
        a[i] = max(abs(x), abs(y))
    a .sort()
    index = n // 2 - 1
    print("Minimum M required is:", a[index])


if __name__ == "__main__":
    N = 4
    findSquare(N)

# Expected output:
Minimum M required is: 4