giulio98/xlcost-single-prompt huggingface dataset:
# minimum insertions to make xor of an array equal to half of its sum | function to make xor of the array equal to half of its sum ; calculate the sum and xor of all the elements ; if the required condition satisfies already , return the original array ; if xor is already zero , insert sum ; otherwise , insert xr and insert sum + xr ; 
def make_xor_half(arr):
    sum = 0
    xr = 0
    for a in arr:
        sum += a
        xr ^= a
    if (2 * xr == sum):
        return -1
    if (xr == 0):
        arr .append(sum)
        return 1
    arr .append(xr)
    arr .append(sum + xr)
    return 2


if __name__ == "__main__":
    N = 7
    nums = [3, 4, 7, 1, 2, 5, 6]
    count = make_xor_half(nums)
    if (count == -1):
        print("-1")
    elif (count == 1):
        print(nums[N])
    else:
        print(nums[N], nums[N + 1])

# Expected output:
28
# count number of triangles possible for the given sides range | function to count the number of possible triangles for the given sides ranges ; iterate for every possible of x ; range of y is [ b , c ] from this range first we will find the number of x + y greater than d ; for x + y greater than d we can choose all z from [ c , d ] total permutation will be ; now we will find the number of x + y in between the [ c , d ] ; [ l , r ] will be the range from total [ c , d ] x + y belongs for any r such that r = x + y we can choose z , in the range [ c , d ] only less than r , thus total permutation be ; 
def count_triangles(a, b, c, d):
    ans = 0
    for x in range(a, b + 1):
        num_greater_than_d = (max(d, c + x) - max(d, b + x - 1))
        ans = (ans + num_greater_than_d * (d - c + 1))
        r = min(max(c, c + x), d) - c
        l = min(max(c, b + x - 1), d) - c
        x1 = int((r * (r + 1)) / 2)
        x2 = int((l * (l + 1)) / 2)
        ans = ans + (x1 - x2)
    return ans


a = 2
b = 3
c = 4
d = 5
print(count_triangles(a, b, c, d), end='')

# Expected output:
7
# minimum number of swaps required to make the string k periodic | python3 code to find the minimum number of swaps required to make the string k periodic ; mark all allowed characters as true ; initialize the freq array to 0 ; increase the frequency of each character ; total number of periods of size k in the string ; check if the current character is present in allowed and whether the current frequency is greater than all previous frequencies for this position ; update the answer by subtracting the maxfrequency from total positions if there exist extra character at the end of the string apart from the n / k characters then add 1. ; 
def minFlip(s, n, k, a, p):
    allowed = [0] * 26
    for i in range(p):
        allowed[ord(a[i]) - ord('a')] = True
    freq = [[0 for x in range(26)]for y in range(k)]
    for i in range(k):
        for j in range(26):
            freq[i][j] = 0
    for i in range(n):
        freq[i % k][ord(s[i]) - ord('a')] += 1
    ans = 0
    totalpositions = n // k
    for i in range(k):
        maxfrequency = 0
        for j in range(26):
            if (freq[i][j] > maxfrequency and allowed[j]):
                maxfrequency = freq[i][j]
        ans += (totalpositions - maxfrequency)
        if (i % k < n % k):
            ans += 1
    print(ans)


if __name__ == "__main__":
    S = "nihsiakyt"
    n = len(S)
    K = 3
    A = ['n', 'i', 'p', 's', 'q']
    p = len(A)
    minFlip(S, n, K, A, p)

# Expected output:
6
# minimum number of colors required to color a circular array | function that finds minimum number of colors required ; to check that if all the elements are same or not ; to check if only one adjacent exist ; traverse the array ; if adjacent elements found different means all are not same ; if two adjacent elements found to be same then make one_adjacent_same true ; if all elements are same then print 1 ; if total number of elements are even or there exist two adjacent elements that are same then print 2 ; else 3 type of colors are required ; 
def colorRequired(arr, n):
    all_same = True
    one_adjacent_same = False
    for i in range(n - 1):
        if (arr[i] != arr[i + 1]):
            all_same = False
        if (arr[i] == arr[i + 1]):
            one_adjacent_same = True
    if (all_same):
        print(1)
        return
    if (n % 2 == 0 or one_adjacent_same):
        print(2)
        return
    print(3)


if __name__ == '__main__':
    arr = [1, 2, 1, 1, 2]
    n = len(arr)
    colorRequired(arr, n)

# Expected output:
2
# maximize the sum of sum of the array by removing end elements | function to find the maximum sum of sum ; compute the sum of whole array ; traverse and remove the minimum value from an end to maximum the sum value ; if the left end element is smaller than right end ; remove the left end element ; if the right end element is smaller than left end ; remove the right end element ; add the remaining element sum in the result ; return the maximum sum of sum ; 
def maxRemainingSum(arr, n):
    sum = 0
    for i in range(n):
        sum += arr[i]
    i = 0
    j = n - 1
    result = 0
    while (i < j):
        if (arr[i] < arr[j]):
            sum -= arr[i]
            i += 1
        else:
            sum -= arr[j]
            j -= 1
        result += sum
    return result


arr = [3, 1, 7, 2, 1]
N = len(arr)
print(maxRemainingSum(arr, N))

# Expected output:
39
# split a number as sum of k numbers which are not divisible by k | function to split into k parts and print them ; print 1 k - 1 times ; print n - k + 1 ; print 1 k - 2 times ; print 2 and n - k ; 
def printKParts(N, K):
    if (N % K == 0):
        for i in range(1, K):
            print("1, ")
        print(N - (K - 1), end="")
    else:
        if (K == 2):
            print("Not Possible", end="")
            return
    for i in range(1, K - 1):
        print(1, end=", ")
    print(2, ", ", (N - K), end="")


if __name__ == '__main__':
    N = 18
    K = 5
    printKParts(N, K)

# Expected output:
1, 1, 1, 2 ,  13
# make the intervals non | function to assign the intervals to two different processors ; loop to pair the interval with their indices ; sorting the interval by their startb times ; loop to iterate over the intervals with their start time ; condition to check if there is a possible solution ; form = ''.join(form) ; 
def assignIntervals(interval, n):
    for i in range(n):
        interval[i].append(i)
    interval .sort(key=lambda x: x[0])
    firstEndTime = -1
    secondEndTime = -1
    fin = ''
    flag = False
    for i in range(n):
        if interval[i][0] >= firstEndTime:
            firstEndTime = interval[i][1]
            interval[i].append('S')
        elif interval[i][0] >= secondEndTime:
            secondEndTime = interval[i][1]
            interval[i].append('F')
        else:
            flag = True
            break
    if flag:
        print(-1)
    else:
        form = [''] * n
        for i in range(n):
            indi = interval[i][2]
            form[indi] = interval[i][3]
        print(form, ", ")


if __name__ == "__main__":
    intervals = [[360, 480], [420, 540], [600, 660]]
    assignIntervals(intervals, len(intervals))

# Expected output:
['S', 'F', 'S'] ,
# minimum operation required to make a balanced sequence | python3 implementation of the approach ; function to return the minimum operations required ; condition where we got only one closing bracket instead of 2 , here we have to add one more closing bracket to make the sequence balanced ; add closing bracket that costs us one operation ; remove the top opening bracket because we got the 1 opening and 2 continuous closing brackets ; inserting the opening bracket to stack ; after making the sequence balanced closing is now set to 0 ; case when there is no opening bracket the sequence starts with a closing bracket and one opening bracket is required now we have one opening and one closing bracket ; add opening bracket that costs us one operation ; assigning 1 to cntclosing because we have one closing bracket ; case where we got two continuous closing brackets need to pop one opening bracket from stack top ; condition where stack is not empty this is the case where we have only opening brackets ( st . size ( ) * 2 ) will give us the total closing bracket needed cntclosing is the count of closing bracket that we already have ; 

from queue import LifoQueue


def minOperations(s, len):
    operationCnt = 0
    st = LifoQueue()
    cntClosing = 0
    for i in range(0, len):
        if (s[i] == '{'):
            if (cntClosing > 0):
                operationCnt += 1
                st .pop()
            st .put(s[i])
            cntClosing = 0
        elif (st .empty()):
            st .put('{')
            operationCnt += 1
            cntClosing = 1
        else:
            cntClosing = (cntClosing + 1) % 2
            if (cntClosing == 0):
                st .pop()
    operationCnt += st .qsize() * 2 - cntClosing + 1
    return operationCnt


if __name__ == '__main__':
    str = "{"
    print(minOperations(str, 1))

# Expected output:
3
# longest subsequence with different adjacent characters | function to find the longest subsequence with different adjacent character ; length of the string s ; previously picked character ; if the current character is different from the previous then include this character and update previous character ; 
def longestSubsequence(s):
    n = len(s)
    answer = 0
    prev = '-'
    for i in range(0, n):
        if (prev != s[i]):
            prev = s[i]
            answer += 1
    return answer


str = "ababa"
print(longestSubsequence(str))

# Expected output:
5
# length of longest subarray of length at least 2 with maximum gcd | function to calculate gcd of two numbers ; function to find maximum size subarray having maximum gcd ; base case ; let the maximum gcd be 1 initially ; loop through array to find maximum gcd of subarray with size 2 ; traverse the array ; is a multiple of k , increase cnt ; else update maximum length with consecutive element divisible by k set cnt to 0 ; update the maxlength ; return the maxlength ; 
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)


def maxGcdSubarray(arr, n):
    if n == 1:
        return 0
    k = 1
    for i in range(1, n):
        k = max(k, gcd(arr[i], arr[i - 1]))
    cnt = 0
    maxLength = 0
    for i in range(n):
        if arr[i] % k == 0:
            cnt += 1
        else:
            maxLength = max(maxLength, cnt)
            cnt = 0
    maxLength = max(maxLength, cnt)
    return maxLength


arr = [18, 3, 6, 9]
n = len(arr)
print(maxGcdSubarray(arr, n))

# Expected output:
4
# split n powers of 2 into two subsets such that their difference of sum is minimum | python3 program to find the minimum difference possible by splitting all powers of 2 up to n into two sets of equal size ; store the largest ; form two separate groups ; initialize the sum for two groups as 0 ; insert 2 ^ n in the first group ; calculate the sum of least n / 2 - 1 elements added to the first set ; sum of remaining n / 2 - 1 elements ; min difference between the two groups ; 
def MinDiff(n):
    val = 2 ** n
    sep = n // 2
    grp1 = 0
    grp2 = 0
    grp1 = grp1 + val
    for i in range(1, sep):
        grp1 = grp1 + 2 ** i
    for i in range(sep, n):
        grp2 = grp2 + 2 ** i
    print(abs(grp1 - grp2))


if __name__ == '__main__':
    n = 4
    MinDiff(n)

# Expected output:
6
# count elements in first array with absolute difference greater than k with an element in second array | function to count the such elements ; store count of required elements in arr1 ; initialise the smallest and the largest value from the second array arr2 [ ] ; find the smallest and the largest element in arr2 ; check if absolute difference of smallest and arr1 [ i ] or largest and arr1 [ i ] is > k then arr [ i ] is a required element ; print final result ; 
def countDist(arr1, n, arr2, m, k):
    count = 0
    smallest = arr2[0]
    largest = arr2[0]
    for i in range(m):
        smallest = max(smallest, arr2[i])
        largest = min(largest, arr1[i])
    for i in range(n):
        if (abs(arr1[i] - smallest) > k or abs(arr1[i] - largest) > k):
            count += 1
    print(count)


if __name__ == '__main__':
    arr1 = [3, 1, 4]
    n = len(arr1)
    arr2 = [5, 1, 2]
    m = len(arr2)
    k = 2
    countDist(arr1, n, arr2, m, k)

# Expected output:
2
# make sum of all subarrays of length k equal by only inserting elements | function that prints another array whose all subarray of length k have an equal sum ; store all distinct elements in the unordered map ; condition if the number of distinct elements is greater than k ; push all distinct elements in a vector ; push 1 while the size of vector not equal to k ; print the vector 2 times ; 
def MakeArray(a, n, k):
    mp = dict()
    for i in a:
        if i not in mp:
            mp[a[i]] = 1
    if (len(mp) > k):
        print("Not possible")
        return
    ans = []
    for i in mp:
        ans .append(i)
    while (len(ans) < k):
        ans .append(1)
    for i in range(2):
        for j in range(k):
            print(ans[j], end=" ")


if __name__ == '__main__':
    arr = [1, 2, 2, 1]
    K = 2
    size = len(arr)
    MakeArray(arr, size, K)

# Expected output:
2 1 2 1
# longest substring with atmost k characters from the given set of characters | function to find the longest substring in the string which contains atmost k characters from the given set of characters ; base condition ; count for characters from set in substring ; two pointers ; loop to iterate until right pointer is not equal to n ; loop to increase the substring length until the characters from set are at most k ; check if current pointer points a character from set ; if the count of the char is exceeding the limit ; update answer with substring length ; increment the left pointer until the count is less than or equal to k ; if the character which comes out then decrement the count by 1 ; 
def maxNormalSubstring(P, Q, K, N):
    if (K == 0):
        return 0
    count = 0
    left = 0
    right = 0
    ans = 0
    while (right < N):
        while (right < N and count <= K):
            if (P[right] in Q):
                if (count + 1 > K):
                    break
                else:
                    count += 1
            right += 1
            if (count <= K):
                ans = max(ans, right - left)
        while (left < right):
            left += 1
            if (P[left - 1] in Q):
                count -= 1
            if (count < K):
                break
    return ans


P = "giraffe"
Q = {chr}
Q .add('a')
Q .add('f')
Q .add('g')
Q .add('r')
K = 2
N = len(P)
print(maxNormalSubstring(P, Q, K, N))

# Expected output:
3
# find the minimum value of the given expression over all pairs of the array | python3 program to find the minimum value of the given expression over all pairs of the array ; function to find the minimum value of the expression ; iterate over all the pairs and find the minimum value ; 

import sys


def MinimumValue(a, n):
    answer = sys .maxsize
    for i in range(n):
        for j in range(i + 1, n, 1):
            answer = min(answer, ((a[i] & a[j]) ^ (a[i] | a[j])))
    return answer


if __name__ == '__main__':
    N = 6
    A = [12, 3, 14, 5, 9, 8]
    print(MinimumValue(A, N))

# Expected output:
1
# number of substrings with length divisible by the number of 1 's in it | function return count of such substring ; mark 1 at those indices where '1' appears ; take prefix sum ; iterate through all the substrings ; 
def countOfSubstrings(s):
    n = len(s)
    prefix_sum = [0 for i in range(n)]
    for i in range(n):
        if (s[i] == '1'):
            prefix_sum[i] = 1
    for i in range(1, n, 1):
        prefix_sum[i] += prefix_sum[i - 1]
    answer = 0
    for i in range(n):
        for j in range(i, n, 1):
            if (i - 1 >= 0):
                countOfOnes = prefix_sum[j] - prefix_sum[i - 1]
            else:
                countOfOnes = prefix_sum[j]
            length = j - i + 1
            if (countOfOnes > 0 and length % countOfOnes == 0):
                answer += 1
    return answer


if __name__ == '__main__':
    S = "1111100000"
    print(countOfSubstrings(S))

# Expected output:
25
# find the number of elements x such that x + k also exists in the array | function to return the count of element x such that x + k also lies in this array ; key in map will store elements and value will store the frequency of the elements ; find if i . first + k is present in this map or not ; if we find i . first or key + k in this map then we have to increase in answer the frequency of this element ; 
def count_element(N, K, arr):
    mp = dict()
    for i in range(N):
        mp[arr[i]] = mp .get(arr[i], 0) + 1
    answer = 0
    for i in mp:
        if i + K in mp:
            answer += mp[i]
    return answer


if __name__ == '__main__':
    arr = [3, 6, 2, 8, 7, 6, 5, 9]
    N = len(arr)
    K = 2
    print(count_element(N, K, arr))

# Expected output:
5
# find the size of largest group where groups are according to the xor of digits | function to find out xor of digit ; calculate xor digitwise ; return xor ; function to find the size of largest group ; hash map for counting frequency ; counting freq of each element ; find the maximum ; 
def digit_xor(x):
    xorr = 0
    while (x != 0):
        xorr ^= x % 10
        x = x // 10
    return xorr


def find_count(n):
    mpp = {}
    for i in range(1, n + 1):
        if digit_xor(i) in mpp:
            mpp[digit_xor(i)] += 1
        else:
            mpp[digit_xor(i)] = 1
    maxm = 0
    for x in mpp:
        if (mpp[x] > maxm):
            maxm = mpp[x]
    return maxm


N = 13
print(find_count(N))

# Expected output:
2
# count of largest sized groups while grouping according to product of digits | function to find out product of digit ; calculate product ; return the product of digits ; function to find the count ; hash map for counting frequency ; counting freq of each element ; find the maximum ; count the number of groups having size of equal to largest group . ; 
def digit_prod(x):
    prod = 1
    while (x):
        prod = prod * (x % 10)
        x = x // 10
    return prod


def find_count(n):
    mpp = {}
    for i in range(1, n + 1):
        x = digit_prod(i)
        if x in mpp:
            mpp[x] += 1
        else:
            mpp[x] = 1
    ans = 1
    maxm = 0
    for value in mpp .values():
        if (value > maxm):
            maxm = value
            ans = 1
        elif (value == maxm):
            ans = ans + 1
    return ans


N = 13
print(find_count(N))

# Expected output:
3
# count of subarrays having exactly k prime numbers | python3 program for the above approach ; a utility function to check if the number n is prime or not ; base cases ; check to skip middle five numbers in below loop ; if n is divisible by i & i + 2 then it is not prime ; function to find number of subarrays with sum exactly equal to k ; stl map to store number of subarrays starting from index zero having particular value of sum . ; to store the sum of element traverse so far ; add current element to currsum ; if currsum = k , then a new subarray is found ; if currsum > k then find the no . of subarrays with sum currsum - k and exclude those subarrays ; add currsum to count of different values of sum ; return the final result ; function to count the subarray with k primes ; update the array element ; if current element is prime then update the arr [ i ] to 1 ; else change arr [ i ] to 0 ; function call ; 

from math import sqrt


def isPrime(n):
    if (n <= 1):
        return False
    if (n <= 3):
        return True
    if (n % 2 == 0 or n % 3 == 0):
        return False
    for i in range(5, int(sqrt(n)) + 1, 6):
        if (n % i == 0 or n % (i + 2) == 0):
            return False
    return True


def findSubarraySum(arr, n, K):
    prevSum = {i: 0 for i in range(100)}
    res = 0
    currsum = 0
    for i in range(n):
        currsum += arr[i]
        if (currsum == K):
            res += 1
        if (currsum - K) in prevSum:
            res += (prevSum[currsum - K])
        prevSum[currsum] += 1
    return res


def countSubarray(arr, n, K):
    for i in range(n):
        if (isPrime(arr[i])):
            arr[i] = 1
        else:
            arr[i] = 0
    print(findSubarraySum(arr, n, K))


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

# Expected output:
4
# count the elements having frequency equals to its value | function to find the count ; hash map for counting frequency ; counting freq of each element ; check if value equals to frequency and increment the count ; 
def find_maxm(arr, n):
    mpp = {}
    for i in range(0, n):
        if arr[i] in mpp:
            mpp[arr[i]] = mpp[arr[i]] + 1
        else:
            mpp[arr[i]] = 1
    ans = 0
    for key in mpp:
        value = key
        freq = mpp[key]
        if value == freq:
            ans = ans + 1
    return ans


if __name__ == "__main__":
    arr = [3, 2, 2, 3, 4, 3]
    n = len(arr)
    print(find_maxm(arr, n))

# Expected output:
2
# find the number of permutations that satisfy the given condition in an array | function to calculate x ^ y recursively ; function to return the number of permutations that satisfy the given condition in an array ; if there is only one element then only one permutation is available ; sort the array for calculating the number of elements occurring twice ; if the maximum element is occurring twice , then the number of permutations satisfying the condition is 0 ; this variable will store the number of element occurring twice ; loop to check the number of elements occurring twice ; check if this element is occurring twice ; if this element is occurring twice then check if this number is occurring more than twice ; if element occurring thrice then no permutation will satisfy the given condition ; since we have checked the next element as well , then we can increment the loop variable ; 
def pow(x, y):
    if (y == 1):
        return x
    if (y == 0):
        return 1
    temp = pow(x, y // 2)
    temp *= temp
    if (y & 1):
        temp *= x
    return temp


def noOfPermutations(a, n):
    if (n == 1):
        return 1
    a .sort()
    if (a[n - 1] == a[n - 2]):
        return 0
    x = 0
    for i in range(n - 2):
        if (a[i] == a[i + 1]):
            if (a[i] == a[i + 2]):
                return 0
            x += 1
            i += 1
    return pow(2, n - 2 * x - 1)


if __name__ == "__main__":
    a = [1, 2, 2, 3, 4]
    n = len(a)
    num = noOfPermutations(a, n)
    print(num)

# Expected output:
4
# length of the smallest subarray that must be removed in order to maximise the gcd | function to find the length of the smallest subarray that must be removed in order to maximise the gcd ; store the maximum possible gcd of the resulting subarray ; two pointers initially pointing to the first and last element respectively ; moving the left pointer to the right if the elements are divisible by the maximum gcd ; moving the right pointer to the left if the elements are divisible by the maximum gcd ; return the length of the subarray ; 
def GetMinSubarrayLength(a, n):
    ans = max(a[0], a[n - 1])
    lo = 0
    hi = n - 1
    while (lo < n and a[lo] % ans == 0):
        lo += 1
    while (hi > lo and a[hi] % ans == 0):
        hi -= 1
    return (hi - lo + 1)


if __name__ == '__main__':
    arr = [4, 8, 2, 1, 4]
    N = len(arr)
    length = GetMinSubarrayLength(arr, N)
    print(length)

# Expected output:
2
# maximize the number of indices such that element is greater than element to its left | function to find the maximum pairs such that arr [ i + 1 ] > arr [ i ] ; to store the frequency of the element in arr [ ] ; store the frequency in map m ; to find the maximum frequency store in map m ; print the maximum number of possible pairs ; 
def countPairs(arr, N):
    M = dict .fromkeys(arr, 0)
    for i in range(N):
        M[arr[i]] += 1
    maxFreq = 0
    for it in M .values():
        maxFreq = max(maxFreq, it)
    print(N - maxFreq)


if __name__ == "__main__":
    arr = [1, 8, 5, 9, 8, 8, 7, 7, 5, 7, 7]
    N = len(arr)
    countPairs(arr, N)

# Expected output:
7