giulio98/xlcost-single-prompt huggingface dataset:
# minimize array sum by replacing greater and smaller elements of pairs by half and double of their values respectively atmost k times | function to find the minimum sum of array elements by given operations ; base case ; return 0 ; base case ; perform k operations ; stores smallest element in the array ; stores index of the smallest array element ; stores largest element in the array ; stores index of the largest array element ; traverse the array elements ; if current element exceeds largest_element ; update the largest element ; update index of the largest array element ; if current element is smaller than smallest_element ; update the smallest element ; update index of the smallest array element ; stores the value of smallest element by given operations ; stores the value of largest element by given operations ; if the value of a + b less than the sum of smallest and largest element of the array ; update smallest element of the array ; update largest element of the array ; stores sum of elements of the array by given operations ; traverse the array ; update ans ; 
def minimum_possible_sum(arr, n, k):
    if (n == 0):
        return 0
    if (n == 1):
        return arr[0]
    for i in range(k):
        smallest_element = arr[0]
        smallest_pos = 0
        largest_element = arr[0]
        largest_pos = 0
        for i in range(1, n):
            if (arr[i] >= largest_element):
                largest_element = arr[i]
                largest_pos = i
            if (arr[i] < smallest_element):
                smallest_element = arr[i]
                smallest_pos = i
        a = smallest_element * 2
        b = largest_element // 2
        if (a + b < smallest_element + largest_element):
            arr[smallest_pos] = a
            arr[largest_pos] = b
    ans = 0
    for i in range(n):
        ans += arr[i]
    return ans


if __name__ == '__main__':
    arr = [50, 1, 100, 100, 1]
    K = 2
    n = len(arr)
    print(minimum_possible_sum(arr, n, K))

# Expected output:
154
# count pairs with bitwise xor greater than both the elements of the pair | python3 program for the above approach ; function to count pairs whose xor is greater than the pair itself ; stores the count of pairs ; sort the array ; traverse the array ; if current element is 0 , then ignore it ; traverse all the bits of element a [ i ] ; if current bit is set then update the count ; update bits [ ] at the most significant bit of a [ i ] ; print the count ; 

import math


def countPairs(A, N):
    count = 0
    A .sort()
    bits = [0] * 32
    for i in range(0, N):
        if (A[i] == 0):
            continue
        for j in range(0, 32):
            if (((1 << j) & A[i]) == 0):
                count += bits[j]
        bits[(int)(math .log(A[i], 2))] += 1
    print(count)


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

# Expected output:
2
# maximum occurred integers after m circular operations in given range | function to find the maximum occurred integer after completing all circular operations ; stores the highest visit count for any element ; stors the number of times an element is visited ; iterate over the array ; iterate over the range circularly form start to end ; count number of times an element is visited ; increment frequency of n ; update maxvisited ; increment frequency of start ; update maxvisited ; increment the start ; increment the count for the last visited element ; print most visited elements ; 
def mostvisitedsector(N, A):
    maxVisited = 0
    mp = {}
    for i in range(0, len(A) - 1):
        start = A[i] % N
        end = A[i + 1] % N
        while (start != end):
            if (start == 0):
                if N in mp:
                    mp[N] = mp[N] + 1
                else:
                    mp[N] = 1
                if (mp[N] > maxVisited):
                    maxVisited = mp[N]
            else:
                if start in mp:
                    mp[start] = mp[start] + 1
                else:
                    mp[start] = 1
                if (mp[start] > maxVisited):
                    maxVisited = mp[start]
            start = (start + 1) % N
    if A[-1] in mp:
        mp[A[-1]] = mp[A[-1]] + 1
    if (mp[A[-1]] > maxVisited):
        maxVisited = mp[A[-1]]
    for x in mp:
        if (mp[x] == maxVisited):
            print(x, end=' ')


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

# Expected output:
1 2
# area of the largest rectangle formed by lines parallel to x and y axis from given set of points | function to return the area of the largest rectangle formed by lines parallel to x and y axis from given set of points ; initialize two arrays ; store x and y coordinates ; sort arrays ; initialize max differences ; find max adjacent differences ; return answer ; 
def maxRectangle(sequence, size):
    X_Cord = [0] * size
    Y_Cord = [0] * size
    for i in range(size):
        X_Cord[i] = sequence[i][0]
        Y_Cord[i] = sequence[i][1]
    X_Cord .sort()
    Y_Cord .sort()
    X_Max = 0
    Y_Max = 0
    for i in range(size - 1):
        X_Max = max(X_Max, X_Cord[i + 1] - X_Cord[i])
        Y_Max = max(Y_Max, Y_Cord[i + 1] - Y_Cord[i])
    return X_Max * Y_Max


if __name__ == "__main__":
    point = [[-2, 0], [2, 0], [4, 0], [4, 2]]
    n = len(point)
    print(maxRectangle(point, n))

# Expected output:
8
# rearrange two given arrays such that sum of same indexed elements lies within given range | function to check if there exists any arrangements of the arrays such that sum of element lie in the range [ k / 2 , k ] ; sort the array arr1 [ ] in increasing order ; sort the array arr2 [ ] in decreasing order ; traverse the array ; if condition is not satisfied break the loop ; print the result ; 
def checkArrangement(A1, A2, n, k):
    A1 = sorted(A1)
    A2 = sorted(A2)
    A2 = A2[::-1]
    flag = 0
    for i in range(n):
        if ((A1[i] + A2[i] > k) or (A1[i] + A2[i] < k // 2)):
            flag = 1
            break
    if (flag == 1):
        print("No")
    else:
        print("Yes")


if __name__ == '__main__':
    arr1 = [1, 3, 4, 5]
    arr2 = [2, 0, 1, 1]
    K = 6
    N = len(arr1)
    checkArrangement(arr1, arr2, N, K)

# Expected output:
Yes
# rearrange two given arrays to maximize sum of same indexed elements | function to find the maximum possible sum by rearranging the given array elements ; sort the array a [ ] in ascending order ; sort the array b [ ] in descending order ; stores maximum possible sum by rearranging array elements ; traverse both the arrays ; update maxsum ; 
def MaxRearrngeSum(A, B, N):
    A .sort()
    B .sort(reverse=True)
    maxSum = 0
    for i in range(N):
        maxSum += abs(A[i] - B[i])
    return maxSum


if __name__ == "__main__":
    A = [1, 2, 2, 4, 5]
    B = [5, 5, 5, 6, 6]
    N = len(A)
    print(MaxRearrngeSum(A, B, N))

# Expected output:
13
# area of the largest rectangle possible from given coordinates | function to find the maximum possible area of a rectangle ; initialize variables ; sort array arr1 [ ] ; sort array arr2 [ ] ; traverse arr1 [ ] and arr2 [ ] ; if arr1 [ i ] is same as arr2 [ j ] ; if no starting point is found yet ; update maximum end ; if arr [ i ] > arr2 [ j ] ; if no rectangle is found ; return the area ; 
def largestArea(arr1, n, arr2, m):
    end = 0
    start = 0
    i = 0
    j = 0
    arr1 .sort(reverse=False)
    arr2 .sort(reverse=False)
    while (i < n and j < m):
        if (arr1[i] == arr2[j]):
            if (start == 0):
                start = arr1[i]
            else:
                end = arr1[i]
            i += 1
            j += 1
        elif (arr1[i] > arr2[j]):
            j += 1
        else:
            i += 1
    if (end == 0 or start == 0):
        return 0
    else:
        return (end - start)


if __name__ == '__main__':
    arr1 = [1, 2, 4]
    N = len(arr1)
    arr2 = [1, 3, 4]
    M = len(arr2)
    print(largestArea(arr1, N, arr2, M))

# Expected output:
3
# count pairs from two arrays with difference exceeding k | function to count pairs that satisfy the given conditions ; stores index of the left pointer . ; stores index of the right pointer ; stores count of total pairs that satisfy the conditions ; sort arr [ ] array ; sort brr [ ] array ; traverse both the array and count then pairs ; if the value of ( brr [ j ] - arr [ i ] ) exceeds k ; update cntpairs ; update ; update j ; 
def count_pairs(arr, brr, N, M, K):
    i = 0
    j = 0
    cntPairs = 0
    arr = sorted(arr)
    brr = sorted(brr)
    while (i < N and j < M):
        if (brr[j] - arr[i] > K):
            cntPairs += (M - j)
            i += 1
        else:
            j += 1
    return cntPairs


if __name__ == '__main__':
    arr = [5, 9, 1, 8]
    brr = [10, 12, 7, 4, 2, 3]
    K = 3
    N = len(arr)
    M = len(brr)
    print(count_pairs(arr, brr, N, M, K))

# Expected output:
6
# merge two sorted arrays in o ( 1 ) extra space using quicksort partition | function to perform the partition around the pivot element ; stores index of each element of the array , arr [ ] ; stores index of each element of the array , brr [ ] ; traverse both the array ; if pivot is smaller than arr [ l ] ; if pivot is greater than brr [ r ] ; if either arr [ l ] > pivot or brr [ r ] < pivot ; function to merge the two sorted array ; stores index of each element of the array arr [ ] ; stores index of each element of the array brr [ ] ; stores index of each element the final sorted array ; stores the pivot element ; traverse both the array ; if pivot element is not found or index < n ; if pivot element is not found or index < n ; place the first n elements of the sorted array into arr [ ] and the last m elements of the sorted array into brr [ ] ; sort both the arrays ; print the first n elements in sorted order ; print the last m elements in sorted order ; 
def partition(arr, N, brr, M, Pivot):
    l = N - 1
    r = 0
    while (l >= 0 and r < M):
        if (arr[l] < Pivot):
            l -= 1
        elif (brr[r] > Pivot):
            r += 1
        else:
            arr[l], brr[r] = brr[r], arr[l]
            l -= 1
            r += 1


def Merge(arr, N, brr, M):
    l = 0
    r = 0
    index = -1
    Pivot = 0
    while (index < N and l < N and r < M):
        if (arr[l] < brr[r]):
            Pivot = arr[l]
            l += 1
        else:
            Pivot = brr[r]
            r += 1
        index += 1
    while (index < N and l < N):
        Pivot = arr[l]
        l += 1
        index += 1
    while (index < N and r < M):
        Pivot = brr[r]
        r += 1
        index += 1
    partition(arr, N, brr, M, Pivot)
    arr = sorted(arr)
    brr = sorted(brr)
    for i in range(N):
        print(arr[i], end=" ")
    for i in range(M):
        print(brr[i], end=" ")


if __name__ == '__main__':
    arr = [1, 5, 9]
    brr = [2, 4, 7, 10]
    N = len(arr)
    M = len(brr)
    Merge(arr, N, brr, M)

# Expected output:
1 2 4 5 7 9 10
# count array elements with rank not exceeding k | function to find count of array elements with rank less than or equal to k ; initialize rank and position ; sort the given array ; traverse array from right to left ; update rank with position , if adjacent elements are unequal ; return position - 1 , if rank greater than k ; increase position ; 
def rankLessThanK(arr, k, n):
    rank = 1
    position = 1
    arr = sorted(arr)
    for i in range(n - 1, -1, -1):
        if (i == n - 1 or arr[i] != arr[i + 1]):
            rank = position
            if (rank > k):
                return position - 1
        position += 1
    return n


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

# Expected output:
5
# remove sub | function to remove sub - directories from the given lists dir ; store final result ; sort the given directories ; insert 1 st directory ; iterating in directory ; current directory ; our previous valid directory ; find length of previous directory ; if subdirectory is found ; else store it in result valid directory ; 
def eraseSubdirectory(dir):
    res = []
    dir .sort()
    res .append(dir[0])
    print("{", dir[0], end=", ")
    for i in range(1, len(dir)):
        curr = dir[i]
        prev = res[len(res) - 1]
        l = len(prev)
        if (len(curr) > l and curr[l] == '/' and prev == curr[:l]):
            continue
        res .append(curr)
        print(curr, end=", ")
    print("}")


if __name__ == '__main__':
    dir = ["/a", "/a/j", "/c/d/e", "/c/d", "/b"]
    eraseSubdirectory(dir)

# Expected output:
{ /a, /b, /c/d, }
# maximize count of pairs ( i , j ) from two arrays having element from first array not exceeding that from second array | function to return the maximum number of required pairs ; max heap to add values of arr2 [ ] ; sort the array arr1 [ ] ; push all arr2 [ ] into max heap ; initialize the ans ; traverse the arr1 [ ] in decreasing order ; remove element until a required pair is found ; return maximum number of pairs ; 
def numberOfPairs(arr1, n, arr2, m):
    pq = []
    arr1 .sort(reverse=False)
    for j in range(m):
        pq .append(arr2[j])
    ans = 2
    i = n - 1
    while (i >= 0):
        pq .sort(reverse=False)
        if (pq[0] >= 2 * arr1[i]):
            ans += 1
            print(pq[0])
            pq .remove(pq[0])
        i -= 1
    return ans


if __name__ == '__main__':
    arr1 = [3, 2, 1]
    arr2 = [3, 4, 2, 1]
    N = len(arr1)
    M = len(arr2)
    print(numberOfPairs(arr1, N, arr2, M))

# Expected output:
2
# minimum number of operations to convert a given sequence into a geometric progression | set 2 | python3 program for above approach ; function to find minimum cost ; sort the array ; maximum possible common ratios ; iterate over all possible common ratios ; calculate operations required for the current common ratio ; calculate minimum cost ; 

import sys


def minCost(arr, n):
    if (n == 1):
        print(0)
        return
    arr = sorted(arr)
    raised = 1 / (n - 1)
    temp = pow(arr[n - 1], raised)
    r = round(temp) + 1
    min_cost = sys .maxsize
    common_ratio = 1
    for j in range(1, r + 1):
        curr_cost = 0
        prod = 1
        i = 0
        while i < n:
            curr_cost += abs(arr[i] - prod)
            prod *= j
            if (curr_cost >= min_cost):
                break
            i += 1
        if (i == n):
            min_cost = min(min_cost, curr_cost)
            common_ratio = j
    print(min_cost, common_ratio)


if __name__ == '__main__':
    N = 6
    arr = [1, 11, 4, 27, 15, 33]
    minCost(arr, N)

# Expected output:
28 2
# mth bit in nth binary string from a sequence generated by the given operations | python3 program for above approach ; function to calculate n fibonacci numbers ; function to find the mth bit in the string sn ; base case ; length of left half ; length of the right half ; recursive check in the left half ; recursive check in the right half ; 

maxN = 10


def calculateFib(fib, n):
    fib[0] = fib[1] = 1
    for x in range(2, n):
        fib[x] = (fib[x - 1] + fib[x - 2])


def find_mth_bit(n, m, fib):
    if (n <= 1):
        return n
    len_left = fib[n - 2]
    len_right = fib[n - 1]
    if (m <= len_left):
        return find_mth_bit(n - 2, len_left + 1 - m, fib)
    else:
        return find_mth_bit(n - 1, len_right + 1 - (m - len_left), fib)


def find_mth_bitUtil(n, m):
    fib = [0 for i in range(maxN)]
    calculateFib(fib, maxN)
    ans = find_mth_bit(n, m, fib)
    print(ans)


if __name__ == '__main__':
    n = 5
    m = 3
    find_mth_bitUtil(n, m)

# Expected output:
1
# minimize count of adjacent row swaps to convert given matrix to a lower triangular matrix | function to count the minimum number of adjacent swaps ; stores the size of the given matrix ; stores the count of zero at the end of each row ; traverse the given matrix ; count of 0 s at the end of the ith row ; stores the count of swaps ; traverse the cntzero array ; if count of zero in the i - th row < ( n - i - 1 ) ; stores the index of the row where count of zero > ( n - i - 1 ) ; if no row found that satisfy the condition ; swap the adjacent row ; 
def minAdjSwaps(mat):
    N = len(mat)
    cntZero = [0] * (N)
    for i in range(N):
        for j in range(N - 1, -1, -1):
            if mat[i][j] != 0:
                break
            cntZero[i] += 1
    cntSwaps = 0
    for i in range(N):
        if (cntZero[i] < (N - i - 1)):
            First = i
            while (First < N and cntZero[First] < (N - i - 1)):
                First += 1
            if (First == N):
                return -1
            while (First > i):
                cntZero[First] = cntZero[First - 1]
                cntZero[First - 1] = cntZero[First]
                First -= 1
                cntSwaps += 1
    return cntSwaps


if __name__ == '__main__':
    mat = [[0, 0, 2], [3, 1, 0], [4, 0, 0]]
    print(minAdjSwaps(mat))

# Expected output:
3
# largest area in a grid unbounded by towers | function to calculate the largest area unguarded by towers ; sort the x - coordinates of the list ; sort the y - coordinates of the list ; dx -- > maximum uncovered tiles in x coordinates ; dy -- > maximum uncovered tiles in y coordinates ; calculate the maximum uncovered distances for both x and y coordinates ; largest unguarded area is max ( dx ) - 1 * max ( dy ) - 1 ; 
def maxArea(point_x, point_y, n, length, width):
    point_x .sort()
    point_y .sort()
    dx = point_x[0]
    dy = point_y[0]
    for i in range(1, n):
        dx = max(dx, point_x[i] - point_x[i - 1])
        dy = max(dy, point_y[i] - point_y[i - 1])
    dx = max(dx, (length + 1) - point_x[n - 1])
    dy = max(dy, (width + 1) - point_y[n - 1])
    print((dx - 1) * (dy - 1))


if __name__ == "__main__":
    length = 15
    width = 8
    n = 3
    point_x = [3, 11, 8]
    point_y = [8, 2, 6]
    maxArea(point_x, point_y, n, length, width)

# Expected output:
12
# split an array to maximize subarrays having equal count of odd and even elements for a cost not exceeding k | function to find the cost of splitting the arrays into subarray with cost less than k ; store the possible splits ; stores the cost of each split ; stores the count of even numbers ; stores the count of odd numbers ; count of odd & even elements ; check the required conditions for a valid split ; sort the cost of splits ; find the minimum split costs adding up to sum less than k ; 
def make_cuts(arr, n, K):
    ans = 0
    poss = []
    ce = 0
    co = 0
    for x in range(n - 1):
        if (arr[x] % 2 == 0):
            ce += 1
        else:
            co += 1
        if (ce == co and co > 0 and ce > 0):
            poss .append(abs(arr[x] - arr[x + 1]))
    poss .sort()
    for x in poss:
        if (K >= x):
            ans += 1
            K -= x
        else:
            break
    return ans


N = 6
K = 4
arr = [1, 2, 5, 10, 15, 20]
print(make_cuts(arr, N, K))

# Expected output:
1
# cost of rearranging the array such that no element exceeds the sum of its adjacent elements | function to check if given elements can be arranged such that sum of its neighbours is strictly greater ; initialize the total cost ; storing the original index of elements in a hashmap ; sort the given array ; check if a given condition is satisfies or not ; first number ; add the cost to overall cost ; last number ; add the cost to overall cost ; add the cost to overall cost ; printing the cost ; 
def Arrange(arr, n):
    cost = 0
    index = {}
    for i in range(n):
        index[arr[i]] = i
    arr .sort()
    for i in range(n):
        if (i == 0):
            if (arr[i] > arr[i + 1] + arr[-1]):
                print("-1")
                return
            else:
                cost += abs(index[arr[i]] - i)
        elif (i == n - 1):
            if (arr[i] > arr[i - 1] + arr[0]):
                print("-1")
                return
            else:
                cost += abs(index[arr[i]] - i)
        else:
            if (arr[i] > arr[i - 1] + arr[i + 1]):
                print("-1")
                return
            else:
                cost += abs(index[arr[i]] - i)
    print(cost)
    return


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

# Expected output:
10
# xor of all possible pairwise sum from two given arrays | function to calculate the sum of xor of the sum of every pair ; stores the xor of sums of every pair ; iterate to generate all possible pairs ; update xor ; return the answer ; 
def XorSum(A, B, N):
    ans = 0
    for i in range(N):
        for j in range(N):
            ans = ans ^ (A[i] + B[j])
    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
# maximum non | python3 program for the above approach ; function to find maximum distinct character after removing k character ; freq implemented as hash table to store frequency of each character ; store frequency of each character ; insert each frequency in v ; sort the freq of character in non - decreasing order ; traverse the vector ; update v [ i ] and k ; if k is still not 0 ; store the final answer ; count this character if freq 1 ; return count of distinct characters ; 

from collections import defaultdict


def maxDistinctChar(s, n, k):
    freq = defaultdict(int)
    for i in range(n):
        freq[s[i]] += 1
    v = []
    for it in freq .values():
        v .append(it)
    v .sort()
    for i in range(len(v)):
        mn = min(v[i] - 1, k)
        v[i] -= mn
        k -= mn
    if (k > 0):
        for i in range(len(v)):
            mn = min(v[i], k)
            v[i] -= mn
            k -= mn
    res = 0
    for i in range(len(v)):
        if (v[i] == 1):
            res += 1
    return res


if __name__ == "__main__":
    S = "geeksforgeeks"
    N = len(S)
    K = 1
    print(maxDistinctChar(S, N, K))

# Expected output:
4
# split n as the sum of k numbers satisfying the given conditions | list to store prime numbers ; function to generate prime numbers using sieveoferatosthenes ; boolean array to store primes ; if p is a prime ; mark all its multiples as non - prime ; print all prime numbers ; function to generate n as the sum of k numbers where atleast k - 1 are distinct and are product of 2 primes ; stores the product of every pair of prime number ; sort the products ; if sum exceeds n ; otherwise , print the k required numbers ; 

primes = []


def SieveOfEratosthenes():
    prime = [True] * 10005
    p = 2
    while p * p <= 1000:
        if (prime[p]):
            for i in range(p * p, 1001, p):
                prime[i] = False
        p += 1
    for p in range(2, 1001):
        if (prime[p]):
            primes .append(p)


def generate(n, k):
    prod = []
    SieveOfEratosthenes()
    l = len(primes)
    for i in range(l):
        for j in range(i + 1, l):
            if (primes[i] * primes[j] > 0):
                prod .append(primes[i] * primes[j])
    prod .sort()
    sum = 0
    for i in range(k - 1):
        sum += prod[i]
    if (sum > n):
        print("-1")
    else:
        for i in range(k - 1):
            print(prod[i], end=", ")
        print(n - sum)


if __name__ == "__main__":
    n = 52
    k = 5
    generate(n, k)

# Expected output:
6, 10, 14, 15, 7
# maximum modified array sum possible by choosing elements as per the given conditions | function that finds the maximum sum of the array elements according to the given condition ; sort the array ; take the max value from the array ; iterate from the end of the array ; check for the number had come before or not ; take the value which is not occured already ; change max to new value ; return the maximum sum ; 
def findMaxValue(arr, n):
    arr .sort()
    ans = arr[n - 1]
    maxPossible = arr[n - 1]
    for i in range(n - 2, -1, -1):
        if (maxPossible > 0):
            if (arr[i] >= maxPossible):
                ans += (maxPossible - 1)
                maxPossible = maxPossible - 1
            else:
                maxPossible = arr[i]
                ans += maxPossible
    return ans


if __name__ == '__main__':
    arr = [4, 4, 1, 5]
    n = len(arr)
    print(findMaxValue(arr, n))

# Expected output:
13