giulio98/xlcost-single-prompt huggingface dataset:
# merging and sorting two unsorted stacks | sorts input stack and returns sorted stack . ; pop out the first element ; while temporary stack is not empty and top of stack is greater than temp ; pop from temporary stack and push it to the input stack ; push temp in temporary of stack ; push contents of both stacks in result ; sort the result stack . ; 
def sortStack(Input):
    tmpStack = []
    while len(Input) != 0:
        tmp = Input[-1]
        Input .pop()
        while len(tmpStack) != 0 and tmpStack[-1] > tmp:
            Input .append(tmpStack[-1])
            tmpStack .pop()
        tmpStack .append(tmp)
    return tmpStack


def sortedMerge(s1, s2):
    res = []
    while len(s1) != 0:
        res .append(s1[-1])
        s1 .pop()
    while len(s2) != 0:
        res .append(s2[-1])
        s2 .pop()
    return sortStack(res)


s1 = []
s2 = []
s1 .append(34)
s1 .append(3)
s1 .append(31)
s2 .append(1)
s2 .append(12)
s2 .append(23)
tmpStack = []
tmpStack = sortedMerge(s1, s2)
print("Sorted and merged stack :")
while len(tmpStack) != 0:
    print(tmpStack[-1], end=" ")
    tmpStack .pop()

# Expected output:
Sorted and merged stack :
34 31 23 12 3 1
# lexicographical concatenation of all substrings of a string | python program to create concatenation of all substrings in lexicographic order . ; creating an array to store substrings ; finding all substrings of string ; sort all substrings in lexicographic order ; concatenating all substrings ; 
def lexicographicSubConcat(s):
    n = len(s)
    sub_count = (n * (n + 1)) // 2
    arr = [0] * sub_count
    index = 0
    for i in range(n):
        for j in range(1, n - i + 1):
            arr[index] = s[i:i + j]
            index += 1
    arr .sort()
    res = ""
    for i in range(sub_count):
        res += arr[i]
    return res


s = "abc"
print(lexicographicSubConcat(s))

# Expected output:
aababcbbcc
# program to sort string in descending order | python program to sort a string in descending order using library function ; 
def descOrder(s):
    s .sort(reverse=True)
    str1 = ''.join(s)
    print(str1)


def main():
    s = list('geeksforgeeks')
    descOrder(s)


if __name__ == "__main__":
    main()

# Expected output:
ssrokkggfeeee
# sort string of characters | python 3 program to sort a string of characters ; function to print string in sorted order ; hash array to keep count of characters . initially count of all charters is initialized to zero . ; traverse string and increment count of characters ; ' a ' - ' a ' will be 0 , ' b ' - ' a ' will be 1 , so for location of character in count array we wil do str [ i ] - ' a ' . ; traverse the hash array and print characters ; 

MAX_CHAR = 26


def sortString(str):
    charCount = [0 for i in range(MAX_CHAR)]
    for i in range(0, len(str), 1):
        charCount[ord(str[i]) - ord('a')] += 1
    for i in range(0, MAX_CHAR, 1):
        for j in range(0, charCount[i], 1):
            print(chr(ord('a') + i), end="")


if __name__ == '__main__':
    s = "geeksforgeeks"
    sortString(s)

# Expected output:
eeeefggkkorss
# smallest element in an array that is repeated exactly ' k ' times . | python program to find smallest number in array that is repeated exactly ' k ' times . ; finds the smallest number in arr [ ] ; computing frequencies of all elements ; finding the smallest element with frequency as k ; if frequency of any of the number is equal to k starting from 0 then return the number ; 

MAX = 1000


def findDuplicate(arr, n, k):
    freq = [0 for i in range(MAX)]
    for i in range(n):
        if (arr[i] < 1 and arr[i] > MAX):
            print("Out of range")
            return -1
        freq[arr[i]] += 1
    for i in range(MAX):
        if (freq[i] == k):
            return i
    return -1


arr = [2, 2, 1, 3, 1]
k = 2
n = len(arr)
print(findDuplicate(arr, n, k))

# Expected output:
1
# find the sub | python3 program to find subarray with sum closest to 0 ; returns subarray with sum closest to 0. ; to consider the case of subarray starting from beginning of the array ; store prefix sum with index ; sort on the basis of sum ; find two consecutive elements with minimum difference ; update minimum difference and starting and ending indexes ; return starting and ending indexes ; 

class prefix:
    def __init__(self, sum, index):
        self .sum = sum
        self .index = index


def findSubArray(arr, n):
    start, end, min_diff = None, None, float('inf')
    pre_sum = [None] * (n + 1)
    pre_sum[0] = prefix(0, -1)
    for i in range(1, n + 1):
        pre_sum[i] = prefix(pre_sum[i - 1].sum + arr[i - 1], i - 1)
    pre_sum .sort(key=lambda x: x .sum)
    for i in range(1, n + 1):
        diff = pre_sum[i].sum - pre_sum[i - 1].sum
        if min_diff > diff:
            min_diff = diff
            start = pre_sum[i - 1].index
            end = pre_sum[i].index
    return (start + 1, end)


if __name__ == "__main__":
    arr = [2, 3, -4, -1, 6]
    n = len(arr)
    point = findSubArray(arr, n)
    print("Subarray starting from", point[0], "to", point[1])

# Expected output:
Subarray starting from 0 to 3
# timsort | python3 program to perform basic timsort ; becomes 1 if any 1 bits are shifted off ; this function sorts array from left index to to right index which is of size atmost run ; merge function merges the sorted runs ; original array is broken in two parts left and right array ; after comparing , we merge those two array in larger sub array ; copy remaining elements of left , if any ; copy remaining element of right , if any ; iterative timsort function to sort the array [ 0. . . n - 1 ] ( similar to merge sort ) ; sort individual subarrays of size run ; start merging from size run ( or 32 ) . it will merge to form size 64 , then 128 , 256 and so on ... . ; pick starting point of left sub array . we are going to merge arr [ left . . left + size - 1 ] and arr [ left + size , left + 2 * size - 1 ] after every merge , we increase left by 2 * size ; find ending point of left sub array mid + 1 is starting point of right sub array ; merge sub array arr [ left ... . . mid ] & arr [ mid + 1. ... right ] ; 

MIN_MERGE = 32


def calcMinRun(n):
    r = 0
    while n >= MIN_MERGE:
        r |= n & 1
        n >>= 1
    return n + r


def insertionSort(arr, left, right):
    for i in range(left + 1, right + 1):
        j = i
        while j > left and arr[j] < arr[j - 1]:
            arr[j], arr[j - 1] = arr[j - 1], arr[j]
            j -= 1


def merge(arr, l, m, r):
    len1, len2 = m - l + 1, r - m
    left, right = [], []
    for i in range(0, len1):
        left .append(arr[l + i])
    for i in range(0, len2):
        right .append(arr[m + 1 + i])
    i, j, k = 0, 0, l
    while i < len1 and j < len2:
        if left[i] <= right[j]:
            arr[k] = left[i]
            i += 1
        else:
            arr[k] = right[j]
            j += 1
        k += 1
    while i < len1:
        arr[k] = left[i]
        k += 1
        i += 1
    while j < len2:
        arr[k] = right[j]
        k += 1
        j += 1


def timSort(arr):
    n = len(arr)
    minRun = calcMinRun(n)
    for start in range(0, n, minRun):
        end = min(start + minRun - 1, n - 1)
        insertionSort(arr, start, end)
    size = minRun
    while size < n:
        for left in range(0, n, 2 * size):
            mid = min(n - 1, left + size - 1)
            right = min((left + 2 * size - 1), (n - 1))
            if mid < right:
                merge(arr, left, mid, right)
        size = 2 * size


if __name__ == "__main__":
    arr = [-2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12]
    print("Given Array is")
    print(arr)
    timSort(arr)
    print("After Sorting Array is")
    print(arr)

# Expected output:
Given Array is
[-2, 7, 15, -14, 0, 15, 0, 7, -7, -4, -13, 5, 8, -14, 12]
After Sorting Array is
[-14, -14, -13, -7, -4, -2, 0, 0, 5, 7, 7, 8, 12, 15, 15]
# program to print an array in pendulum arrangement | prints pendulam arrangement of arr [ ] ; sorting the elements ; auxiliary array to store output ; calculating the middle index ; storing the minimum element in the middle i is index for output array and j is for input array . ; adjustment for when no . of elements is even ; printing the pendulum arrangement ; 
def pendulumArrangement(arr, n):
    arr .sort()
    op = [0] * n
    mid = int((n - 1) / 2)
    j = 1
    i = 1
    op[mid] = arr[0]
    for i in range(1, mid + 1):
        op[mid + i] = arr[j]
        j += 1
        op[mid - i] = arr[j]
        j += 1
    if (int(n % 2) == 0):
        op[mid + i] = arr[j]
    print("Pendulum arrangement:")
    for i in range(0, n):
        print(op[i], end=" ")


arr = [14, 6, 19, 21, 12]
n = len(arr)
pendulumArrangement(arr, n)

# Expected output:
Pendulum arrangement:
21 14 6 12 19
# maximum width of a binary tree | a binary tree node ; function to get the maximum width of a binary tree ; create an array that will store count of nodes at each level ; fill the count array using preorder traversal ; return the maximum value from count array ; a function that fills count array with count of nodes at every level of 

class Node:
    def __init__(self, data):
        self .data = data
        self .left = None
        self .right = None


def getMaxWidthRecur(root, count, level):
    if root is not None:
        count[level] += 1
        getMaxWidthRecur(root .left, count, level + 1)
        getMaxWidthRecur(root .right, count, level + 1)


def height(node):
    if node is None:
        return 0
    else:
        lHeight = height(node .left)
        rHeight = height(node .right)
        return (lHeight + 1)if (lHeight > rHeight)else (rHeight + 1)


def getMax(count, n):
    max = count[0]
    for i in range(1, n):
        if (count[i] > max):
            max = count[i]
    return max

def getMaxWidth(root):
    h = height(root)
    count = [0] * h
    level = 0
    getMaxWidthRecur(root, count, level)
    return getMax(count, h)


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
root .right .right = Node(8)
root .right .right .left = Node(6)
root .right .right .right = Node(7)
print("Maximum width is %d" % (getMaxWidth(root)))

# Expected output:
Maximum width is 3
# minimize the sum of product of two arrays with permutations allowed | returns minimum sum of product of two arrays with permutations allowed ; sort a and b so that minimum and maximum value can easily be fetched . ; multiplying minimum value of a and maximum value of b ; 
def minValue(A, B, n):
    A .sort()
    B .sort()
    result = 0
    for i in range(n):
        result += (A[i] * B[n - i - 1])
    return result


A = [3, 1, 1]
B = [6, 5, 4]
n = len(A)
print(minValue(A, B, n))

# Expected output:
23
# count of numbers in range [ l , r ] which can be represented as sum of two perfect powers | function to find the number of numbers that can be expressed in the form of the sum of two perfect powers ; stores all possible powers ; push 1 and 0 in it ; iterate over all the exponents ; iterate over all possible numbers ; this loop will run for a maximum of sqrt ( r ) times ; push this power in the array pows [ ] ; increase the number ; stores if i can be expressed as the sum of perfect power or not ; int ok [ r + 1 ] ; memset ( ok , 0 , sizeof ( ok ) ) ; iterate over all possible pairs of the array pows [ ] ; the number is valid ; find the prefix sum of the array ok [ ] ; return the count of required number ; 
def TotalPerfectPowerSum(L, R):
    pows = []
    pows .append(0)
    pows .append(1)
    for p in range(2, 25):
        num = 2
        while ((int)(pow(num, p) + 0.5) <= R):
            pows .append((int)(pow(num, p) + 0.5))
            num = num + 1
    ok = [0 for _ in range(R + 1)]
    for i in range(0, int(len(pows))):
        for j in range(0, len(pows)):
            if (pows[i] + pows[j] <= R and pows[i] + pows[j] >= L):
                ok[pows[i] + pows[j]] = 1
    for i in range(0, R + 1):
        ok[i] += ok[i - 1]
    return ok[R] - ok[L - 1]


if __name__ == "__main__":
    L = 5
    R = 8
    print(TotalPerfectPowerSum(L, R))

# Expected output:
2
# Minimize absolute difference between sum of subtrees formed after splitting Binary tree into two | Python3 implementation for the above approach ; Structure of Node ; Function to calculate minimum absolute difference of subtrees after splitting the tree into two parts ; Reference variable to store the answer ; Function to store sum of values of current node , left subtree and right subtree in place of current node 's value ; Function to perform every possible split and calculate absolute difference of subtrees ; Absolute difference in subtrees if left edge is broken ; Absolute difference in subtrees if right edge is broken ; Update minDiff if a difference lesser than it is found ; Construct the tree ; Print the output

import sys


class Node:
    def __init__(self, val):
        self .val = val
        self .left = None
        self .right = None


def postOrder(root):
    if (root is None):
        return 0
    root .val += postOrder(root .left) + postOrder(root .right)
    return root .val


def preOrder(root, minDiff):
    if (root is None):
        return
    leftDiff = abs(root .left .val - (root .val - root .left .val))
    rightDiff = abs(root .right .val - (root .val - root .right .val))
    minDiff[0] = min(minDiff[0], min(leftDiff, rightDiff))
    return

def minAbsDiff(root):
    minDiff = [0] * (1)
    minDiff[0] = sys .maxsize
    postOrder(root)
    preOrder(root, minDiff)
    return minDiff[0]


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
root .right .left = Node(6)
root .right .right = Node(7)
print(minAbsDiff(root))

# Expected output:
4
# maximize array sum after changing sign of any elements for exactly m times | function to find the maximum sum with m flips ; declare a priority queue i . e . min heap ; declare the sum as zero ; push all elements of the array in it ; iterate for m times ; get the top element ; flip the sign of the top element ; remove the top element ; update the sum ; push the temp into the queue ; 
def findMaximumSumWithMflips(arr, N, M):
    pq = []
    sum = 0
    for i in range(N):
        pq .append(arr[i])
        sum += arr[i]
        pq .sort()
    while (M > 0):
        sum -= pq[0]
        temp = -1 * pq[0]
        pq = pq[1:]
        sum += temp
        pq .append(temp)
        pq .sort()
        M -= 1
    print(sum)


if __name__ == '__main__':
    arr = [-3, 7, -1, -5, -3]
    N = len(arr)
    M = 4
    findMaximumSumWithMflips(arr, N, M)

# Expected output:
19
# minimum operations to make array equal by repeatedly adding k from an element and subtracting k from other | function to find the minimum number of operations to make all the elements of the array equal ; store the sum of the array arr [ ] ; traverse through the array ; if it is not possible to make all array element equal ; store the minimum number of operations needed ; traverse through the array ; finally , print the minimum number operation to make array elements equal ; 
def miniOperToMakeAllEleEqual(arr, n, k):
    sum = 0
    for i in range(n):
        sum += arr[i]
    if (sum % n):
        print(-1)
        return
    valueAfterDivision = sum // n
    count = 0
    for i in range(n):
        if (abs(valueAfterDivision - arr[i]) % k != 0):
            print(-1)
            return
        count += abs(valueAfterDivision - arr[i]) // k
    print(count // 2)


if __name__ == '__main__':
    n = 3
    k = 3
    arr = [5, 8, 11]
    miniOperToMakeAllEleEqual(arr, n, k)

# Expected output:
1
# minimum operations to make product of adjacent element pair of prefix sum negative | function to find minimum operations needed to make the product of any two adjacent elements in prefix sum array negative ; stores the minimum operations ; stores the prefix sum and number of operations ; traverse the array ; update the value of sum ; check if i + r is odd ; check if prefix sum is not positive ; update the value of ans and sum ; check if prefix sum is not negative ; update the value of ans and sum ; update the value of res ; print the value of res ; 
def minOperations(a):
    res = 100000000000
    N = len(a)
    for r in range(0, 2):
        sum = 0
        ans = 0
        for i in range(0, N):
            sum += a[i]
            if ((i + r) % 2):
                if (sum <= 0):
                    ans += -sum + 1
                    sum = 1
            else:
                if (sum >= 0):
                    ans += sum + 1
                    sum = -1
        res = min(res, ans)
    print(res)


a = [1, -3, 1, 0]
minOperations(a)

# Expected output:
4
# minimize sum of product of same | function to print the arrays ; function to reverse the subarray ; function to calculate the minimum product of same - indexed elements of two given arrays ; calculate initial product ; traverse all odd length subarrays ; remove the previous product ; add the current product ; check if current product is minimum or not ; traverse all even length subarrays ; remove the previous product ; add to the current product ; check if current product is minimum or not ; update the pointers ; reverse the subarray ; print the subarray ; 
def Print(a, b):
    minProd = 0
    for i in range(len(a)):
        print(a[i], end=" ")
    print()
    for i in range(len(b)):
        print(b[i], end=" ")
        minProd += a[i] * b[i]
    print()
    print(minProd)


def reverse(left, right, arr):
    while (left < right):
        temp = arr[left]
        arr[left] = arr[right]
        arr[right] = temp
        left += 1
        right -= 1


def minimumProdArray(a, b, l):
    total = 0
    for i in range(len(a)):
        total += a[i] * b[i]
    Min = 2147483647
    first = 0
    second = 0
    for i in range(len(a)):
        left = i - 1
        right = i + 1
        total1 = total
        while (left >= 0 and right < len(a)):
            total1 -= a[left] * b[left] + a[right] * b[right]
            total1 += a[left] * b[right] + a[right] * b[left]
            if (Min >= total1):
                Min = total1
                first = left
                second = right
            left -= 1
            right += 1
    for i in range(len(a)):
        left = i
        right = i + 1
        total1 = total
        while (left >= 0 and right < len(a)):
            total1 -= a[left] * b[left] + a[right] * b[right]
            total1 += a[left] * b[right] + a[right] * b[left]
            if (Min >= total1):
                Min = total1
                first = left
                second = right
            left -= 1
            right += 1
    if (Min < total):
        reverse(first, second, a)
        Print(a, b)
    else:
        Print(a, b)


n = 4
a = [2, 3, 1, 5]
b = [8, 2, 4, 3]
minimumProdArray(a, b, n)

# Expected output:
1 3 2 5 
8 2 4 3 
37
# maximize cost of removing all occurrences of substrings " ab " and " ba " | function to find the maximum cost of removing substrings " ab " and " ba " from s ; maxstr is the substring char array with larger cost ; minstr is the substring char array with smaller cost ; ; denotes larger point ; denotes smaller point ; stores cost scored ; stack to keep track of characters ; traverse the string ; if the substring is maxstr ; pop from the stack ; add maxp to cost ; push the character to the stack ; remaining string after removing maxstr ; find remaining string ; reversing the string retrieved from the stack ; removing all occurences of minstr ; if the substring is minstr ; pop from the stack ; add minp to the cost ; otherwise ; return the maximum cost ; 
def MaxCollection(S, P, Q):
    maxstr = [i for i in ("ab"if P >= Q else "ba")]
    minstr = [i for i in ("ba"if P >= Q else "ab")]
    maxp = max(P, Q)
    minp = min(P, Q)
    cost = 0
    stack1 = []
    s = [i for i in S]
    for ch in s:
        if (len(stack1) > 0 and (stack1[-1] == maxstr[0] and ch == maxstr[1])):
            del stack1[-1]
            cost += maxp
        else:
            stack1 .append(ch)
    sb = ""
    while (len(stack1) > 0):
        sb += stack1[-1]
        del stack1[-1]
    sb = sb[::-1]
    remstr = sb
    for ch in remstr:
        if (len(stack1) > 0 and (stack1[-1] == minstr[0] and ch == minstr[1])):
            del stack1[-1]
            cost += minp
        else:
            stack1 .append(ch)
    return cost


if __name__ == '__main__':
    S = "cbbaabbaab"
    P = 6
    Q = 4
    print(MaxCollection(S, P, Q))

# Expected output:
22
# vertical width of binary tree | set 2 | a binary tree node has data , pointer to left child and a pointer to right child ; function to fill hd in set . ; third parameter is horizontal distance ; 

class Node:
    def __init__(self, data):
        self .data = data
        self .left = self .right = None


def fillSet(root, s, hd):
    if (not root):
        return
    fillSet(root .left, s, hd - 1)
    s .add(hd)
    fillSet(root .right, s, hd + 1)


def verticalWidth(root):
    s = set()
    fillSet(root, s, 0)
    return len(s)


if __name__ == '__main__':
    root = Node(1)
    root .left = Node(2)
    root .right = Node(3)
    root .left .left = Node(4)
    root .left .right = Node(5)
    root .right .left = Node(6)
    root .right .right = Node(7)
    root .right .left .right = Node(8)
    root .right .right .right = Node(9)
    print(verticalWidth(root))

# Expected output:
6
# maximum value of ( arr [ i ] * arr [ j ] ) + ( arr [ j ] | function to find the value of the expression a * b + ( b - a ) ; function to find the maximum value of the expression a * b + ( b - a ) possible for any pair ( a , b ) ; sort the vector in ascending order ; stores the maximum value ; update ans by choosing the pair of the minimum and 2 nd minimum ; update ans by choosing the pair of maximum and 2 nd maximum ; return the value of ans ; 
def calc(a, b):
    return a * b + (b - a)


def findMaximum(arr, N):
    arr = sorted(arr)
    ans = -10 ** 9
    ans = max(ans, calc(arr[0], arr[1]))
    ans = max(ans, calc(arr[N - 2], arr[N - 1]))
    return ans


if __name__ == '__main__':
    arr = [0, -47, 12]
    N = len(arr)
    print(findMaximum(arr, N))
    arr = [0, -47, 12]
    N = len(arr)
    print(findMaximum(arr, N))

# Expected output:
47
47
# minimize flips on k |  ; store previous flip events ; remove an item which is out range of window . ; in a window , if a [ i ] is a even number with even times fliped , it need to be fliped again . on other hand , if a [ i ] is a odd number with odd times fliped , it need to be fliped again . ; insert ; 
def minKBitFlips(A, K, N):
    flip = []
    count = 0
    for i in range(N):
        if (len(flip) > 0 and (i - flip[0] >= K)):
            flip .pop(0)
        if (A[i] % 2 == len(flip) % 2):
            if (i + K - 1 >= N):
                return -1
            flip .append(i)
            count += 1
    return count


A = [0, 1, 0]
N = len(A)
K = 1
ans = minKBitFlips(A, K, 3)
print(ans)

# Expected output:
2
# minimize flips on k |  ; we 're flipping the subarray from  a[i] to a[i+k-1] ; ' ' ▁ if ▁ we ▁ can ' t flip the entire subarray , its impossible ; 
def minKBitFlips(A, K):
    temp = [0] * len(A)
    count = 0
    flip = 0
    for i in range(len(A)):
        flip ^= temp[i]
        if (A[i] == flip):
            count += 1
            if (i + K > len(A)):
                return -1
            flip ^= 1
            if (i + K < len(A)):
                temp[i + K] ^= 1
    return count


A = [0, 1, 0]
K = 1
ans = minKBitFlips(A, K)
print(ans)

# Expected output:
2