giulio98/xlcost-single-prompt huggingface dataset:
# sum of specially balanced nodes from a given binary tree | structure of binary tree ; function to create a new node ; return the created node ; function to insert a node in the tree ; left insertion ; right insertion ; return the root node ; function to find sum of specially balanced nodes in the tree ; base case ; find the left subtree sum ; find the right subtree sum ; condition of specially balanced node ; condition of specially balanced node ; return the sum ; function to build the binary tree ; form root node of the tree ; insert nodes into tree ; create a new node ; insert the node ; return the root of the tree ; function to find the sum of specially balanced nodes ; build tree ; stores the sum of specially balanced node ; function call ; print required sum ; 

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


def newnode(data):
    temp = Node(data)
    return temp


def insert(s, i, N, root, temp):
    if (i == N):
        return temp
    if (s[i] == 'L'):
        root .left = insert(s, i + 1, N, root .left, temp)
    else:
        root .right = insert(s, i + 1, N, root .right, temp)
    return root


def SBTUtil(root, sum):
    if (root is None):
        return [0, sum]
    if (root .left is None and root .right is None):
        return [root .data, sum]
    left, sum = SBTUtil(root .left, sum)
    right, sum = SBTUtil(root .right, sum)
    if (root .left and root .right):
        if ((left %
             2 == 0 and right %
             2 != 0) or (left %
                         2 != 0 and right %
                         2 == 0)):
            sum += root .data
    return [left + right + root .data, sum]


def build_tree(R, N, str, values):
    root = newnode(R)
    for i in range(0, N - 1):
        s = str[i]
        x = values[i]
        temp = newnode(x)
        root = insert(s, 0, len(s), root, temp)
    return root


def speciallyBalancedNodes(R, N, str, values):
    root = build_tree(R, N, str, values)
    sum = 0
    tmp, sum = SBTUtil(root, sum)
    print(sum, end=' ')


if __name__ == "__main__":
    N = 7
    R = 12
    str = ["L", "R", "RL", "RR", "RLL", "RLR"]
    values = [17, 16, 4, 9, 2, 3]
    speciallyBalancedNodes(R, N, str, values)

# Expected output:
16
# pair having all other given pairs lying between its minimum and maximum | function to find the position of the pair that covers every pair in the array arr ; stores the index of the resultant pair ; to count the occurences ; iterate to check every pair ; set count to 0 ; condition to checked for overlapping of pairs ; if that pair can cover all other pairs then store its position ; if position not found ; otherwise ; 
def position(arr, N):
    pos = -1
    count = 0
    for i in range(N):
        count = 0
        for j in range(N):
            if (arr[i][0] <= arr[j][0] and arr[i][1] >= arr[j][1]):
                count += 1
        if (count == N):
            pos = i
    if (pos == -1):
        print(pos)
    else:
        print(pos + 1)


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

# Expected output:
2
# pair having all other given pairs lying between its minimum and maximum | python3 program for the above approach ; function to find the position of the pair that covers every pair in the array arr [ ] [ ] ; position to store the index ; stores the minimum second value ; stores the maximum first value ; iterate over the array of pairs ; update right maximum ; update left minimum ; iterate over the array of pairs ; if any pair exists with value { left , right then store it ; print the answer ; 

import sys


def position(arr, N):
    pos = -1
    right = -sys .maxsize - 1
    left = sys .maxsize
    for i in range(N):
        if (arr[i][1] > right):
            right = arr[i][1]
        if (arr[i][0] < left):
            left = arr[i][0]
    for i in range(N):
        if (arr[i][0] == left and arr[i][1] == right):
            pos = i + 1
    print(pos)


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

# Expected output:
2
# minimize count of given operations required to make two given strings permutations of each other | function to minimize the count of operations to make str1 and str2 permutations of each other ; store the frequency of each character of str1 ; store the frequency of each character of str2 ; traverse the freq1 [ ] and freq2 [ ] ; if frequency of character in str1 is greater than str2 ; otherwise ; store sum of freq1 [ ] ; store sum of freq2 [ ] ; 
def ctMinEdits(str1, str2):
    N1 = len(str1)
    N2 = len(str2)
    freq1 = [0] * 256
    for i in range(N1):
        freq1[ord(str1[i])] += 1
    freq2 = [0] * 256
    for i in range(N2):
        freq2[ord(str2[i])] += 1
    for i in range(256):
        if (freq1[i] > freq2[i]):
            freq1[i] = freq1[i] - freq2[i]
            freq2[i] = 0
        else:
            freq2[i] = freq2[i] - freq1[i]
            freq1[i] = 0
    sum1 = 0
    sum2 = 0
    for i in range(256):
        sum1 += freq1[i]
        sum2 += freq2[i]
    return max(sum1, sum2)


str1 = "geeksforgeeks"
str2 = "geeksforcoder"
print(ctMinEdits(str1, str2))

# Expected output:
4
# count pairs ( i , j ) from arrays arr [ ] & brr [ ] such that arr [ i ] | function to count the pairs such that given condition is satisfied ; stores the sum of element at each corresponding index ; find the sum of each index of both array ; stores frequency of each element present in sumarr ; initialize number of pairs ; add possible vaid pairs ; return number of pairs ; given array arr [ ] and brr [ ] ; size of 
def CountPairs(a, b, n):
    C = [0] * n
    for i in range(n):
        C[i] = a[i] + b[i]
    freqCount = dict()
    for i in range(n):
        if C[i] in freqCount .keys():
            freqCount[C[i]] += 1
        else:
            freqCount[C[i]] = 1
    NoOfPairs = 0
    for x in freqCount:
        y = freqCount[x]
        NoOfPairs = (NoOfPairs + y * (y - 1) // 2)
    print(NoOfPairs)


arr = [1, 4, 20, 3, 10, 5]
brr = [9, 6, 1, 7, 11, 6]
N = len(arr)
CountPairs(arr, brr, N)

# Expected output:
4
# change in median of given array after deleting given elements | function to find the median change after removing elements from arr2 [ ] ; to store the median ; if n is odd ; if n is even ; find the current element in arr1 ; erase the element ; decrement n ; if n is odd ; if n is even ; print the corresponding difference of median ; 
def medianChange(arr1, arr2):
    N = len(arr1)
    median = []
    if (N & 1):
        median .append(arr1[N // 2] * 1)
    else:
        median .append((arr1[N // 2] + arr1[(N - 1) // 2]) // 2)
    for x in arr2:
        it = arr1 .index(x)
        arr1 .pop(it)
        N -= 1
        if (N & 1):
            median .append(arr1[N // 2] * 1)
        else:
            median .append((arr1[N // 2] + arr1[(N - 1) // 2]) // 2)
    for i in range(len(median) - 1):
        print(median[i + 1] - median[i], end=' ')


if __name__ == "__main__":
    arr1 = [2, 4, 6, 8, 10]
    arr2 = [4, 6]
    medianChange(arr1, arr2)

# Expected output:
1 1
# count positions such that all elements before it are greater | function to count positions such that all elements before it are greater ; count is initially 1 for the first element ; initial minimum ; traverse the array ; if current element is new minimum ; update minimum ; increment count ; 
def getPositionCount(a, n):
    count = 1
    min = a[0]
    for i in range(1, n):
        if (a[i] <= min):
            min = a[i]
            count += 1
    return count


if __name__ == "__main__":
    a = [5, 4, 6, 1, 3, 1]
    n = len(a)
    print(getPositionCount(a, n))

# Expected output:
4
# maximum length l such that the sum of all subarrays of length l is less than k | function to return the maximum sum in a subarray of size k ; k must be greater ; compute sum of first window of size k ; compute sums of remaining windows by removing first element of previous window and adding last element of current window . ; function to return the length of subarray sum of all the subarray of this length is less than or equal to k ; binary search from l to r as all the array elements are positive so that the maximum subarray sum is monotonically increasing ; check if the subarray sum is greater than k or not ; update the maximum length ; 
def maxSum(arr, n, k):
    if (n < k):
        return -1
    res = 0
    for i in range(k):
        res += arr[i]
    curr_sum = res
    for i in range(k, n):
        curr_sum += arr[i] - arr[i - k]
        res = max(res, curr_sum)
    return res


def solve(arr, n, k):
    max_len = 0
    l = 0
    r = n
    while (l <= r):
        m = (l + r) // 2
        if (maxSum(arr, n, m) > k):
            r = m - 1
        else:
            l = m + 1
            max_len = m
    return max_len


if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5]
    n = len(arr)
    k = 10
    print(solve(arr, n, k))

# Expected output:
2
# count of triplets in an array that satisfy the given conditions | python3 implementation of the approach ; all possible solutions of the equation 1 / a + 1 / b + 1 / c = 1 ; function to find the triplets ; storing indices of the elements ; check if y can act as the middle element of triplet with the given solution of 1 / a + 1 / b + 1 / c = 1 ; binary search to find the number of possible values of the first element ; binary search to find the number of possible values of the third element ; contribution to the answer would be the multiplication of the possible values for the first and the third element ; 

MAX = 100001
ROW = 10
COL = 3
indices = [0] * MAX
test = [
    [
        2, 3, 6], [
            2, 4, 4], [
                2, 6, 3], [
                    3, 2, 6], [
                        3, 3, 3], [
                            3, 6, 2], [
                                4, 2, 4], [
                                    4, 4, 2], [
                                        6, 2, 3], [
                                            6, 3, 2]]


def find_triplet(array, n):
    answer = 0
    for i in range(MAX):
        indices[i] = []
    for i in range(n):
        indices[array[i]].append(i)
    for i in range(n):
        y = array[i]
        for j in range(ROW):
            s = test[j][1] * y
            if s % test[j][0] != 0:
                continue
            if s % test[j][2] != 0:
                continue
            x = s // test[j][0]
            z = s // test[j][2]
            if x > MAX or z > MAX:
                continue
            l = 0
            r = len(indices[x]) - 1
            first = -1
            while l <= r:
                m = (l + r) // 2
                if indices[x][m] < i:
                    first = m
                    l = m + 1
                else:
                    r = m - 1
            l = 0
            r = len(indices[z]) - 1
            third = -1
            while l <= r:
                m = (l + r) // 2
                if indices[z][m] > i:
                    third = m
                    r = m - 1
                else:
                    l = m + 1
            if first != -1 and third != -1:
                answer += (first + 1) * (len(indices[z]) - third)
    return answer


if __name__ == "__main__":
    array = [2, 4, 5, 6, 7]
    n = len(array)
    print(find_triplet(array, n))

# Expected output:
1
# distinct adjacent elements in a binary array | python3 implementation of the above approach ; if array has only one element , return 1 ; for first element compare with only next element ; for remaining elements compare with both prev and next elements ; for last element compare with only prev element ; 
def distinct(arr):
    count = 0
    if len(arr) == 1:
        return 1
    for i in range(0, len(arr) - 1):
        if (i == 0):
            if (arr[i] != arr[i + 1]):
                count += 1
        elif (i > 0 & i < len(arr) - 1):
            if (arr[i] != arr[i + 1] or arr[i] != arr[i - 1]):
                count += 1
    if (arr[len(arr) - 1] != arr[len(arr) - 2]):
        count += 1
    return count


arr = [0, 0, 0, 0, 0, 1, 0]
print(distinct(arr))

# Expected output:
3
# check if an array of pairs can be sorted by swapping pairs with different first elements | function to check if an array is sorted or not ; traverse the array arr [ ] ; return true ; function to check if it is possible to sort the array w . r . t . first element ; stores the id of the first element ; traverse the array arr [ ] ; if arr [ i ] [ 1 ] is not equal to that of the group ; if array is sorted ; 
def isSorted(arr, N):
    for i in range(1, N):
        if (arr[i][0] > arr[i - 1][0]):
            return False
    return True


def isPossibleToSort(arr, N):
    group = arr[0][1]
    for i in range(1, N):
        if (arr[i][1] != group):
            return "Yes"
    if (isSorted(arr, N)):
        return "Yes"
    else:
        return "No"


if __name__ == '__main__':
    arr = [[340000, 2], [45000, 1], [30000, 2], [50000, 4]]
    N = len(arr)
    print(isPossibleToSort(arr, N))

# Expected output:
Yes
# check if n rectangles of equal area can be formed from ( 4 * n ) integers | function to check whether we can make n rectangles of equal area ; sort the array ; find the area of any one rectangle ; check whether we have two equal sides for each rectangle and that area of each rectangle formed is the same ; update the answer to false if any condition fails ; if possible ; 
def checkRectangles(arr, n):
    ans = True
    arr .sort()
    area = arr[0] * arr[4 * n - 1]
    for i in range(0, 2 * n, 2):
        if (arr[i] != arr[i + 1] or arr[4 * n - i - 1] !=
                arr[4 * n - i - 2] or arr[i] * arr[4 * n - i - 1] != area):
            ans = False
            break
    if (ans):
        return True
    return False


arr = [1, 8, 2, 1, 2, 4, 4, 8]
n = 2
if (checkRectangles(arr, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# count of elements which are not at the correct position | function to return the count of elements which are not in the correct position when sorted ; to store a copy of the original array ; copy the elements of the given array to the new array ; to store the required count ; sort the original array ; if current element was not at the right position ; 
def cntElements(arr, n):
    copy_arr = [0] * n
    for i in range(n):
        copy_arr[i] = arr[i]
    count = 0
    arr .sort()
    for i in range(n):
        if (arr[i] != copy_arr[i]):
            count += 1
    return count


arr = [1, 2, 6, 2, 4, 5]
n = len(arr)
print(cntElements(arr, n))

# Expected output:
4
# find k ordered pairs in array with minimum difference d | function to find the required pairs ; there has to be atleast 2 * k elements ; to store the pairs ; sort the given array ; for every possible pair ; if the current pair is valid ; insert it into the pair vector ; if k pairs are not possible ; print the pairs ; 
def findPairs(arr, n, k, d):
    if (n < 2 * k):
        print("-1")
        return
    pairs = []
    arr = sorted(arr)
    for i in range(k):
        if (arr[n - k + i] - arr[i] >= d):
            pairs .append([arr[i], arr[n - k + i]])
    if (len(pairs) < k):
        print("-1")
        return
    for v in pairs:
        print("(", v[0], ", ", v[1], ")")


arr = [4, 6, 10, 23, 14, 7, 2, 20, 9]
n = len(arr)
k = 4
d = 3
findPairs(arr, n, k, d)

# Expected output:
( 2 ,  10 )
( 4 ,  14 )
( 6 ,  20 )
( 7 ,  23 )
# count pairs with given sum | set 2 | function to return the count of pairs from arr with the given sum ; to store the count of pairs ; sort the given array ; take two pointers ; if sum is greater ; if sum is lesser ; if sum is equal ; find the frequency of arr [ i ] ; find the frequency of arr [ j ] ; if arr [ i ] and arr [ j ] are same then remove the extra number counted ; return the required answer ; 
def pairs_count(arr, n, sum):
    ans = 0
    arr = sorted(arr)
    i, j = 0, n - 1
    while (i < j):
        if (arr[i] + arr[j] < sum):
            i += 1
        elif (arr[i] + arr[j] > sum):
            j -= 1
        else:
            x = arr[i]
            xx = i
            while (i < j and arr[i] == x):
                i += 1
            y = arr[j]
            yy = j
            while (j >= i and arr[j] == y):
                j -= 1
            if (x == y):
                temp = i - xx + yy - j - 1
                ans += (temp * (temp + 1)) // 2
            else:
                ans += (i - xx) * (yy - j)
    return ans


arr = [1, 5, 7, 5, -1]
n = len(arr)
sum = 6
print(pairs_count(arr, n, sum))

# Expected output:
3
# check if the string contains consecutive letters and each letter occurs exactly once | python3 program to implement the above approach ; for all the characters of the string ; find the ascii value of the character ; check if if its a valid character , if not then return false ; calculate sum of all the characters ascii values ; find minimum ascii value from the string ; find maximum ascii value from the string ; to get the previous element of the minimum ascii value ; take the expected sum from the above equation ; check if the expected sum is equals to the calculated sum or not ; 

import sys


def check(str):
    min = sys .maxsize
    max = -sys .maxsize - 1
    sum = 0
    for i in range(len(str)):
        ascii = str[i]
        if (ord(ascii) < 96 or ord(ascii) > 122):
            return False
        sum += ord(ascii)
        if (min > ord(ascii)):
            min = ord(ascii)
        if (max < ord(ascii)):
            max = ord(ascii)
    min -= 1
    eSum = (((max * (max + 1)) // 2) - ((min * (min + 1)) // 2))
    return sum == eSum


if __name__ == '__main__':
    str = "dcef"
    if (check(str)):
        print("Yes")
    else:
        print("No")
    str1 = "xyza"
    if (check(str1)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
No
# k | function to find the sum of minimum of all subarrays ; insert all the elements in a set ; find the maximum and minimum element ; traverse from the minimum to maximum element ; check if " i " is missing ; check if it is kth missing ; if no kth element is missing ; 
def findKth(arr, n, k):
    missing = dict()
    count = 0
    for i in range(n):
        missing[arr[i]] = 1
    maxm = max(arr)
    minm = min(arr)
    for i in range(minm + 1, maxm):
        if (i not in missing .keys()):
            count += 1
        if (count == k):
            return i
    return -1


arr = [2, 10, 9, 4]
n = len(arr)
k = 5
print(findKth(arr, n, k))

# Expected output:
8
# rearrange an array to minimize sum of product of consecutive pair elements | python 3 program to sort an array such that sum of product of alternate element is minimum . ; create evenarr [ ] and oddarr [ ] ; sort main array in ascending order ; put elements in oddarr [ ] and evenarr [ ] as per desired value . ; sort evenarr [ ] in descending order ; merge both sub - array and calculate minimum sum of product of alternate elements ; 
def minSum(arr, n):
    evenArr = []
    oddArr = []
    arr .sort()
    for i in range(n):
        if (i < n // 2):
            oddArr .append(arr[i])
        else:
            evenArr .append(arr[i])
    evenArr .sort(reverse=True)
    i = 0
    sum = 0
    for j in range(len(evenArr)):
        arr[i] = evenArr[j]
        i += 1
        arr[i] = oddArr[j]
        i += 1
        sum += evenArr[j] * oddArr[j]
    return sum


if __name__ == "__main__":
    arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]
    n = len(arr)
    print("Minimum required sum =", minSum(arr, n))
    print("Sorted array in required format : ", end="")
    for i in range(n):
        print(arr[i], end=" ")

# Expected output:
Minimum required sum = 60
Sorted array in required format : 9 0 8 1 7 2 6 3 5 4
# minimum time required to print given string from a circular container based on given conditions | function to calculate minimum time to print all characters in the string ; current element where the pointer is pointing ; find index of that element ; calculate absolute difference between pointer index and character index as clockwise distance ; subtract clockwise time from 26 to get anti - clockwise time ; add minimum of both times to the answer ; add one unit time to print the character ; print the final answer ; 
def minTime(word):
    ans = 0
    curr = 0
    for i in range(len(word)):
        k = ord(word[i]) - 97
        a = abs(curr - k)
        b = 26 - abs(curr - k)
        ans += min(a, b)
        ans += 1
        curr = ord(word[i]) - 97
    print(ans)


if __name__ == '__main__':
    str = "zjpc"
    minTime(str)

# Expected output:
34
# minimum decrements or division by a proper divisor required to reduce n to 1 | function to find the minimum number of steps required to reduce n to 1 ; stores the number of steps required ; if the value of n is equal to 2 or n is odd ; decrement n by 1 ; increment cnt by 1 ; if n is even ; update n ; increment cnt by 1 ; return the number of steps obtained ; 
def reduceToOne(N):
    cnt = 0
    while (N != 1):
        if (N == 2 or (N % 2 == 1)):
            N = N - 1
            cnt += 1
        elif (N % 2 == 0):
            N = N / (N / 2)
            cnt += 1
    return cnt


if __name__ == '__main__':
    N = 35
    print(reduceToOne(N))

# Expected output:
3
# maximum number of diamonds that can be gained in k minutes | function to find the maximum number of diamonds that can be gained in exactly k minutes ; stores all the array elements ; push all the elements to the priority queue ; stores the required result ; loop while the queue is not empty and k is positive ; store the top element from the pq ; pop it from the pq ; add it to the answer ; divide it by 2 and push it back to the pq ; print the answer ; 
def maxDiamonds(A, N, K):
    pq = []
    for i in range(N):
        pq .append(A[i])
    pq .sort()
    ans = 0
    while (len(pq) > 0 and K > 0):
        pq .sort()
        top = pq[len(pq) - 1]
        pq = pq[0:len(pq) - 1]
        ans += top
        top = top // 2
        pq .append(top)
        K -= 1
    print(ans)


if __name__ == '__main__':
    A = [2, 1, 7, 4, 2]
    K = 3
    N = len(A)
    maxDiamonds(A, N, K)

# Expected output:
14
# minimize cost of increments or decrements such that same indexed elements become multiple of each other | function to find the minimum cost to make a [ i ] multiple of b [ i ] or vice - versa for every array element ; stores the minimum cost ; traverse the array ; case 1 : update a [ i ] ; case 2 : update b [ i ] ; add the minimum of the above two cases ; return the resultant cost ; 
def MinimumCost(A, B, N):
    totalCost = 0
    for i in range(N):
        mod_A = B[i] % A[i]
        totalCost_A = min(mod_A, A[i] - mod_A)
        mod_B = A[i] % B[i]
        totalCost_B = min(mod_B, B[i] - mod_B)
        totalCost += min(totalCost_A, totalCost_B)
    return totalCost


A = [3, 6, 3]
B = [4, 8, 13]
N = len(A)
print(MinimumCost(A, B, N))

# Expected output:
4
# largest number divisible by 50 that can be formed from a given set of n digits consisting of 0 s and 7 s only | print the largest number divisible by 50 ; counting number of 0 s and 7 s ; if count of 7 is divisible by 50 ; if count of 7 is less than 5 ; if count of 7 is not divisible by 50 ; count of groups of 5 in which count of 7 s can be grouped ; 
def printLargestDivisible(arr, N):
    count0 = 0
    count7 = 0
    for i in range(N):
        if (arr[i] == 0):
            count0 += 1
        else:
            count7 += 1
    if (count7 % 50 == 0):
        while (count7):
            count7 -= 1
            print(7, end="")
        while (count0):
            count0 -= 1
            print(count0, end="")
    elif (count7 < 5):
        if (count0 == 0):
            print("No", end="")
        else:
            print("0", end="")
    else:
        count7 = count7 - count7 % 5
        while (count7):
            count7 -= 1
            print(7, end="")
        while (count0):
            count0 -= 1
            print(0, end="")


if __name__ == "__main__":
    arr = [0, 7, 0, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 7, 7, 7]
    N = len(arr)
    printLargestDivisible(arr, N)

# Expected output:
7777700000000