giulio98/xlcost-single-prompt huggingface dataset:
# n / 3 repeated number in an array with o ( 1 ) space | python 3 program to find if any element appears more than n / 3. ; take the integers as the maximum value of integer hoping the integer would not be present in the array ; if this element is previously seen , increment count1 . ; if this element is previously seen , increment count2 . ; if current element is different from both the previously seen variables , decrement both the counts . ; again traverse the array and find the actual counts . ; 

import sys


def appearsNBy3(arr, n):
    count1 = 0
    count2 = 0
    first = sys .maxsize
    second = sys .maxsize
    for i in range(0, n):
        if (first == arr[i]):
            count1 += 1
        elif (second == arr[i]):
            count2 += 1
        elif (count1 == 0):
            count1 += 1
            first = arr[i]
        elif (count2 == 0):
            count2 += 1
            second = arr[i]
        else:
            count1 -= 1
            count2 -= 1
    count1 = 0
    count2 = 0
    for i in range(0, n):
        if (arr[i] == first):
            count1 += 1
        elif (arr[i] == second):
            count2 += 1
    if (count1 > n / 3):
        return first
    if (count2 > n / 3):
        return second
    return -1


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

# Expected output:
1
# count pairs in array whose sum is divisible by 4 | python3 code to count pairs whose sum is divisible by '4 ; function to count pairs whose sum is divisible by '4 ; create a frequency array to count occurrences of all remainders when divided by 4 ; count occurrences of all remainders ; if both pairs are divisible by '4 ; if both pairs are 2 modulo 4 ; if one of them is equal to 1 modulo 4 and the other is equal to 3 modulo 4 ; 
def count4Divisibiles(arr, n):
    freq = [0, 0, 0, 0]
    for i in range(n):
        freq[arr[i] % 4] += 1
    ans = freq[0] * (freq[0] - 1) / 2
    ans += freq[2] * (freq[2] - 1) / 2
    ans += freq[1] * freq[3]
    return int(ans)


arr = [2, 2, 1, 7, 5]
n = len(arr)
print(count4Divisibiles(arr, n))

# Expected output:
3
# find sum of all unique sub | function for finding grandsum ; calculate cumulative sum of array carray [ 0 ] will store sum of zero elements ; store all subarray sum in vector ; sort the vector ; mark all duplicate sub - array sum to zero ; calculate total sum ; return totalsum ; 
def findSubarraySum(arr, n):
    cArray = [0 for i in range(n + 1)]
    for i in range(0, n, 1):
        cArray[i + 1] = cArray[i] + arr[i]
    subArrSum = []
    for i in range(1, n + 1, 1):
        for j in range(i, n + 1, 1):
            subArrSum .append(cArray[j] - cArray[i - 1])
    subArrSum .sort(reverse=False)
    totalSum = 0
    for i in range(0, len(subArrSum) - 1, 1):
        if (subArrSum[i] == subArrSum[i + 1]):
            j = i + 1
            while (subArrSum[j] == subArrSum[i] and j < len(subArrSum)):
                subArrSum[j] = 0
                j += 1
            subArrSum[i] = 0
    for i in range(0, len(subArrSum), 1):
        totalSum += subArrSum[i]
    return totalSum


if __name__ == '__main__':
    arr = [3, 2, 3, 1, 4]
    n = len(arr)
    print(findSubarraySum(arr, n))

# Expected output:
41
# smallest number whose set bits are maximum in a given range | python code to find number whose set bits are maximum among ' l ' and 'r ; returns smallest number whose set bits are maximum in given range . ; initialize the maximum count and final answer as ' num ' ; traverse for every bit of ' i ' number ; if count is greater than previous calculated max_count , update it ; 
def countMaxSetBits(left, right):
    max_count = -1
    for i in range(left, right + 1):
        temp = i
        cnt = 0
        while temp:
            if temp & 1:
                cnt += 1
            temp = temp >> 1
        if cnt > max_count:
            max_count = cnt
            num = i
    return num


l = 1
r = 5
print(countMaxSetBits(l, r))
l = 1
r = 10
print(countMaxSetBits(l, r))

# Expected output:
3
7
# find sum of all unique sub | function for finding grandsum ; go through all subarrays , compute sums and count occurrences of sums . ; print all those sums that appear once . ; 
def findSubarraySum(arr, n):
    res = 0
    m = dict()
    for i in range(n):
        Sum = 0
        for j in range(i, n):
            Sum += arr[j]
            m[Sum] = m .get(Sum, 0) + 1
    for x in m:
        if m[x] == 1:
            res += x
    return res


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

# Expected output:
41
# recaman 's sequence | prints first n terms of recaman sequence ; create an array to store terms ; first term of the sequence is always 0 ; fill remaining terms using recursive formula . ; if arr [ i - 1 ] - i is negative or already exists . ; 
def recaman(n):
    arr = [0] * n
    arr[0] = 0
    print(arr[0], end=", ")
    for i in range(1, n):
        curr = arr[i - 1] - i
        for j in range(0, i):
            if ((arr[j] == curr) or curr < 0):
                curr = arr[i - 1] + i
                break
        arr[i] = curr
        print(arr[i], end=", ")


n = 17
recaman(n)

# Expected output:
0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24, 8,
# print the longest leaf to leaf path in a binary tree | tree node structure used in the program ; function to find height of a tree ; update the answer , because diameter of a tree is nothing but maximum value of ( left_height + right_height + 1 ) for each node ; save the root , this will help us finding the left and the right part of the diameter ; save the height of left & right subtree as well . ; prints the root to leaf path ; print left part of the path in reverse order ; this function finds out all the root to leaf paths ; append this node to the path array ; if it 's a leaf, so print the  path that led to here ; print only one path which is equal to the height of the tree . print ( pathlen , " - - - " , maxm ) ; otherwise try both subtrees ; computes the diameter of a binary tree with given root . ; lh will store height of left subtree rh will store height of right subtree ; f is a flag whose value helps in printing left & right part of the diameter only once ; print the left part of the diameter ; print the right part of the diameter ; 

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


def height(root):
    global ans, k, lh, rh, f
    if (root is None):
        return 0
    left_height = height(root .left)
    right_height = height(root .right)
    if (ans < 1 + left_height + right_height):
        ans = 1 + left_height + right_height
        k = root
        lh = left_height
        rh = right_height
    return 1 + max(left_height, right_height)


def printArray(ints, lenn, f):
    if (f == 0):
        for i in range(lenn - 1, -1, -1):
            print(ints[i], end=" ")
    elif (f == 1):
        for i in range(lenn):
            print(ints[i], end=" ")


def printPathsRecur(node, path, maxm, pathlen):
    global f
    if (node is None):
        return
    path[pathlen] = node .data
    pathlen += 1
    if (node .left is None and node .right is None):
        if (pathlen == maxm and (f == 0 or f == 1)):
            printArray(path, pathlen, f)
            f = 2
    else:
        printPathsRecur(node .left, path, maxm, pathlen)
        printPathsRecur(node .right, path, maxm, pathlen)


def diameter(root):
    if (root is None):
        return
    global ans, lh, rh
    global f, k, pathLen
    height_of_tree = height(root)
    lPath = [0 for i in range(100)]
    printPathsRecur(k .left, lPath, lh, 0)
    print(k .data, end=" ")
    rPath = [0 for i in range(100)]
    f = 1
    printPathsRecur(k .right, rPath, rh, 0)


if __name__ == '__main__':
    k, lh, rh, f, ans, pathLen = None, 0, 0, 0, 0 - 10 ** 19, 0
    root = Node(1)
    root .left = Node(2)
    root .right = Node(3)
    root .left .left = Node(4)
    root .left .right = Node(5)
    root .left .right .left = Node(6)
    root .left .right .right = Node(7)
    root .left .left .right = Node(8)
    root .left .left .right .left = Node(9)
    diameter(root)

# Expected output:
9 8 4 2 5 6
# recaman 's sequence | prints first n terms of recaman sequence ; print first term and store it in a hash ; print remaining terms using recursive formula . ; if arr [ i - 1 ] - i is negative or already exists . ; 
def recaman(n):
    if (n <= 0):
        return
    print(0, ",", end='')
    s = set([])
    s .add(0)
    prev = 0
    for i in range(1, n):
        curr = prev - i
        if (curr < 0 or curr in s):
            curr = prev + i
        s .add(curr)
        print(curr, ",", end='')
        prev = curr


if __name__ == '__main__':
    n = 17
    recaman(n)

# Expected output:
0 ,1 ,3 ,6 ,2 ,7 ,13 ,20 ,12 ,21 ,11 ,22 ,10 ,23 ,9 ,24 ,8 ,
# largest subset whose all elements are fibonacci numbers | prints largest subset of an array whose all elements are fibonacci numbers ; find maximum element in arr [ ] ; generate all fibonacci numbers till max and store them in hash . ; npw iterate through all numbers and quickly check for fibonacci using hash . ; 
def findFibSubset(arr, n):
    m = max(arr)
    a = 0
    b = 1
    hash = []
    hash .append(a)
    hash .append(b)
    while (b < m):
        c = a + b
        a = b
        b = c
        hash .append(b)
    for i in range(n):
        if arr[i] in hash:
            print(arr[i], end=" ")


if __name__ == "__main__":
    arr = [4, 2, 8, 5, 20, 1, 40, 13, 23]
    n = len(arr)
    findFibSubset(arr, n)

# Expected output:
2 8 5 1 13
# pairs of amicable numbers | efficient python3 program to count amicable pairs in an array . ; calculating the sum of proper divisors ; 1 is a proper divisor ; to handle perfect squares ; check if pair is ambicle ; this function prints count of amicable pairs present in the input array ; map to store the numbers ; iterate through each number , and find the sum of proper divisors and check if it 's  also present in the array ; it 's sum of proper divisors ; as the pairs are counted twice , thus divide by 2 ; 

import math


def sumOfDiv(x):
    sum = 1
    for i in range(2, int(math .sqrt(x))):
        if x % i == 0:
            sum += i
            if i != x / i:
                sum += x / i
    return int(sum)


def isAmbicle(a, b):
    return (sumOfDiv(a) == b and sumOfDiv(b) == a)


def countPairs(arr, n):
    s = set()
    count = 0
    for i in range(n):
        s .add(arr[i])
    for i in range(n):
        if sumOfDiv(arr[i]) in s:
            sum = sumOfDiv(arr[i])
            if isAmbicle(arr[i], sum):
                count += 1
    return int(count / 2)


arr1 = [220, 284, 1184, 1210, 2, 5]
n1 = len(arr1)
print(countPairs(arr1, n1))
arr2 = [2620, 2924, 5020, 5564, 6232, 6368]
n2 = len(arr2)
print(countPairs(arr2, n2))

# Expected output:
2
3
# minimum number of characters required to be removed such that every character occurs same number of times | python3 program for the above approach ; function to find minimum number of character removals required to make frequency of all distinct characters the same ; stores the frequency of each character ; traverse the string ; stores the frequency of each charachter in sorted order ; traverse the map ; insert the frequency in multiset ; stores the count of elements required to be removed ; stores the size of multiset ; traverse the multiset ; update the ans ; increment i by 1 ; return ; 

import sys


def minimumDeletion(s, n):
    countMap = {}
    for i in s:
        countMap[i] = countMap .get(i, 0) + 1
    countMultiset = []
    for it in countMap:
        countMultiset .append(countMap[it])
    ans = sys .maxsize + 1
    i = 0
    m = len(countMultiset)
    for j in sorted(countMultiset):
        ans = min(ans, n - (m - i) * j)
        i += 1
    return ans


if __name__ == '__main__':
    S = "geeksforgeeks"
    N = len(S)
    print(minimumDeletion(S, N))

# Expected output:
5
# calculate cost of visiting all array elements in increasing order | function to calculate total cost of visiting array elements in increasing order ; stores the pair of element and their positions ; traverse the array arr [ ] ; push the pair { arr [ i ] , i } in v ; sort the vector in ascending order . ; stores the total cost ; stores the index of last element visited ; traverse the vector v ; increment ans ; assign ; return ans ; 
def calculateDistance(arr, N):
    v = []
    for i in range(N):
        v .append([arr[i], i])
    v .sort()
    ans = 0
    last = 0
    for j in v:
        ans += abs(j[1] - last)
        last = j[1]
    return ans


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

# Expected output:
11
# modify array by sorting nearest perfect squares of array elements having their digits sorted in decreasing order | python 3 program of the above approach ; function to sort array in ascending order after replacing array elements by nearest perfect square of decreasing order of digits ; traverse the array of strings ; convert the current array element to a string ; sort each string in descending order ; convert the string to equivalent integer ; calculate square root of current array element ; calculate perfect square ; find the nearest perfect square ; sort the array in ascending order ; print the array ; 

import math


def sortArr(arr, N):
    for i in range(N):
        s = str(arr[i])
        list1 = list(s)
        list1 .sort(reverse=True)
        s = ''.join(list1)
        arr[i] = int(s)
        sr = int(math .sqrt(arr[i]))
        a = sr * sr
        b = (sr + 1) * (sr + 1)
        if ((arr[i] - a) < (b - arr[i])):
            arr[i] = a
        else:
            arr[i] = b
    arr .sort()
    for i in range(N):
        print(arr[i], end=" ")


if __name__ == "__main__":
    arr = [29, 43, 28, 12]
    N = len(arr)
    sortArr(arr, N)

# Expected output:
25 49 81 100
# minimize cost required to make all array elements greater than or equal to zero | python3 program for the above approach ; function to find the minimum cost to make all array of elements greater than or equal to 0 ; sort the array in ascending order ; stores the count to make current array element >= 0 ; stores the cost to make all array elements >= 0 ; traverse the array and insert all the elements which are <= 0 ; if current array element is negative ; cost to make all array elements >= 0 ; update curr if ans is minimum ; return minimum cost ; given array ; size of the array ; 

import sys


def mincost(arr, N, X):
    arr .sort()
    sum = 0
    cost = 0
    min_cost = sys .maxsize
    for i in range(0, N):
        if (arr[i] < 0):
            cost = abs(arr[i]) * x + (sum - abs(arr[i]) * i)
            sum += abs(arr[i])
            min_cost = min(min_cost, cost)
    return min_cost


arr = [-1, -3, -2, 4, -1]
N = len(arr)
x = 2
print(mincost(arr, N, x))

# Expected output:
5
# count arrays having at least k elements exceeding xor of all given array elements by x given operations | stores the final answer ; utility function to count arrays having at least k elements exceeding xor of all given array elements ; if no operations are left ; stores the count of possible arrays ; count array elements are greater than xor ; stores first element ; delete first element ; recursive call ; insert first element into vector ; stores the last element ; remove last element from vector ; recursive call ; push last element into vector ; increment first element ; recursive call ; decrement first element ; increment last element ; recursive call ; decrement last element ; function to find the count of arrays having atleast k elements greater than xor of array ; stores the xor value of original array ; traverse the vector ; print the answer ; given vector ; 

ans = 0


def countArraysUtil(arr, X, K, xorVal):
    global ans
    if (X == 0):
        cnt = 0
        for i in range(len(arr)):
            if (arr[i] > xorVal):
                cnt += 1
        if (cnt >= K):
            ans += 1
        return
    temp = arr[0]
    arr .pop(0)
    countArraysUtil(arr, X - 1, K, xorVal)
    arr .insert(0, temp)
    temp = arr[-1]
    arr .pop()
    countArraysUtil(arr, X - 1, K, xorVal)
    arr .append(temp)
    arr[0] += 1
    countArraysUtil(arr, X - 1, K, xorVal)
    arr[0] -= 1
    arr[len(arr) - 1] += 1
    countArraysUtil(arr, X - 1, K, xorVal)
    arr[len(arr) - 1] -= 1


def countArrays(arr, X, K):
    xorVal = 0
    for i in range(len(arr)):
        xorVal = xorVal ^ arr[i]
    countArraysUtil(arr, X, K, xorVal)
    print(ans)


arr = [10, 2, 10, 5]
X = 3
K = 3
countArrays(arr, X, K)

# Expected output:
1
# difference between maximum and minimum of a set of anagrams from an array | python3 program for the above approach ; utility function to find the hash value for each element of the given array ; initialize an array with first 10 prime numbers ; iterate over digits of n ; update hash value ; update n ; function to find the set of anagrams in the array and print the difference between the maximum and minimum of these numbers ; map to store the hash value and the array elements having that hash value ; find the hash value for each arr [ i ] by calling hash function ; iterate over the map ; if size of vector at m [ i ] greater than 1 then it must contain the anagrams ; find the minimum and maximum element of this anagrams vector ; display the difference ; if the end of map is reached , then no anagrams are present ; 

import math
from collections import defaultdict


def hashFunction(N):
    prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
    value = 1
    while (N != 0):
        r = N % 10
        value = value * prime[r]
        N = N // 10
    return value


def findDiff(arr, n):
    m = defaultdict(lambda: [])
    for i in range(n):
        h = hashFunction(arr[i])
        m[h].append(arr[i])
    i = 0
    while (i != len(m)):
        if (len(m[i]) > 1):
            minn = min(m[i])
            maxx = max(m[i])
            print(maxx - minn)
            break
        elif (i == (len(m) - 1)):
            print(-1)
        i += 1


arr = [121, 312, 234, 211, 112, 102]
N = len(arr)
findDiff(arr, N)

# Expected output:
99
# maximum number of apples that can be eaten by a person | function to find the maximum number of apples a person can eat such that the person eat at most one apple in a day . ; store count of apples and number of days those apples are edible ; stores indices of the array ; stores count of days ; stores maximum count of edible apples ; traverse both the arrays ; if top element of the apple is not already expired ; insert count of apples and their expiration date ; remove outdated apples ; insert all the apples produces by tree on current day ; stores top element of pq ; remove top element of pq ; if count of apples in curr is greater than 0 ; insert count of apples and their expiration date ; update total_apples ; update index ; 
def cntMaxApples(apples, days):
    pq = []
    i = 0

    n = len(apples)

    total_apples = 0
    while (i < n or len(pq) > 0):
        if (i < n and apples[i] != 0):
            pq.append([i + days[i] - 1, apples[i]])
            pq.sort()
        while (len(pq) > 0 and pq[0][0] < i):
            pq.pop(0)
        if (len(pq) > 0):
            curr = pq[0]
            pq.pop(0)
            if (len(curr) > 1):
                pq.append([curr[0], curr[1] - 1])
                pq.sort()
            total_apples += 1
        i += 1

    return total_apples


apples = [1, 2, 3, 5, 2]
days = [3, 2, 1, 4, 2]

print(cntMaxApples(apples, days))

# Expected output:
7
# maximum area rectangle by picking four sides from array | function for finding max area ; sort array in non - increasing order ; initialize two sides of rectangle ; traverse through array ; if any element occurs twice store that as dimension ; return the product of dimensions ; 
def findArea(arr, n):
    arr .sort(reverse=True)
    dimension = [0, 0]
    i = 0
    j = 0
    while (i < n - 1 and j < 2):
        if (arr[i] == arr[i + 1]):
            dimension[j] = arr[i]
            j += 1
            i += 1
        i += 1
    return (dimension[0] * dimension[1])


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

# Expected output:
24
# maximum of sum of length of rectangles and squares formed by given sticks | python3 implementation of the above approach ; function to find the maximum of sum of lengths of rectangles and squares formed using given set of sticks ; stores the count of frequencies of all the array elements ; stores frequencies which are at least 2 ; convert all frequencies to nearest smaller even values . ; sum of elements up to index of multiples of 4 ; print the sum ; 

from collections import Counter


def findSumLength(arr, n):
    freq = dict(Counter(arr))
    freq_2 = {}
    for i in freq:
        if freq[i] >= 2:
            freq_2[i] = freq[i]
    arr1 = []
    for i in freq_2:
        arr1 .extend([i] * (freq_2[i] // 2) * 2)
    arr1 .sort(reverse=True)
    summ = 0
    for i in range((len(arr1) // 4) * 4):
        summ += arr1[i]
    print(summ)


if __name__ == "__main__":
    arr = [5, 3, 2, 3, 6, 4, 4, 4, 5, 5, 5]
    n = len(arr)
    findSumLength(arr, n)

# Expected output:
34
# maximum area rectangle by picking four sides from array | function for finding max area ; traverse through array ; if this is first occurrence of arr [ i ] , simply insert and continue ; if this is second ( or more ) occurrence , update first and second maximum values . ; return the product of dimensions ; 
def findArea(arr, n):
    s = []
    first = 0
    second = 0
    for i in range(n):
        if arr[i]not in s:
            s .append(arr[i])
            continue
        if (arr[i] > first):
            second = first
            first = arr[i]
        elif (arr[i] > second):
            second = arr[i]
    return (first * second)


if __name__ == "__main__":
    arr = [4, 2, 1, 4, 6, 6, 2, 5]
    n = len(arr)
    print(findArea(arr, n))

# Expected output:
24
# game of replacing array elements | function return which player win the game ; create hash that will stores all distinct element ; traverse an array element ; 
def playGame(arr, n):
    s = set()
    for i in range(n):
        s .add(arr[i])
    return 1 if len(s) % 2 == 0 else 2


arr = [1, 1, 2, 2, 2, 2]
n = len(arr)
print("Player", playGame(arr, n), "Wins")

# Expected output:
Player 1 Wins
# length of longest strict bitonic subsequence | function to find length of longest strict bitonic subsequence ; hash table to map the array element with the length of the longest subsequence of which it is a part of and is the last / first element of that subsequence ; arrays to store the length of increasing and decreasing subsequences which end at them or start from them ; to store the length of longest strict bitonic subsequence ; traverse the array elements from left to right ; initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in 'inc   ; update arr [ i ] subsequence length in ' inc ' and in len_inc [ ] ; traverse the array elements from right to left ; initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in 'dcr   ; update arr [ i ] subsequence length in ' dcr ' and in len_dcr [ ] ; calculating the length of all the strict bitonic subsequence ; required longest length strict bitonic subsequence ; 
def longLenStrictBitonicSub(arr, n):
    inc, dcr = dict(), dict()
    len_inc, len_dcr = [0] * n, [0] * n
    longLen = 0
    for i in range(n):
        len = 0
        if inc .get(arr[i] - 1) in inc .values():
            len = inc .get(arr[i] - 1)
        inc[arr[i]] = len_inc[i] = len + 1
    for i in range(n - 1, -1, -1):
        len = 0
        if dcr .get(arr[i] - 1) in dcr .values():
            len = dcr .get(arr[i] - 1)
        dcr[arr[i]] = len_dcr[i] = len + 1
    for i in range(n):
        if longLen < (len_inc[i] + len_dcr[i] - 1):
            longLen = len_inc[i] + len_dcr[i] - 1
    return longLen


if __name__ == "__main__":
    arr = [1, 5, 2, 3, 4, 5, 3, 2]
    n = len(arr)
    print(
        "Longest length strict bitonic subsequence =",
        longLenStrictBitonicSub(
            arr,
            n))

# Expected output:
Longest length strict bitonic subsequence = 6