giulio98/xlcost-single-prompt huggingface dataset:
# maximize count of distinct profits possible by n transactions | function to count distinct profits possible ; stores the minimum total profit ; stores the maximum total profit ; return count of distinct profits ; 
def numberOfWays(N, X, Y):
    S1 = (N - 1) * X + Y
    S2 = (N - 1) * Y + X
    return (S2 - S1 + 1)


if __name__ == '__main__':
    N = 3
    X = 13
    Y = 15
    print(numberOfWays(N, X, Y))

# Expected output:
3
# minimum number of operations required to make a permutation of first n natural numbers equal | function to find the minimum number of operations required to make all array elements equal ; store the count of operations required ; increment by k - 1 , as the last element will be used again for the next k consecutive elements ; increment count by 1 ; return the result ; 
def MinimumOperations(A, N, K):
    Count = 0
    i = 0
    while (i < N - 1):
        i = i + K - 1
        Count += 1
    return Count


if __name__ == '__main__':
    A = [5, 4, 3, 1, 2]
    K = 3
    N = len(A)
    print(MinimumOperations(A, N, K))

# Expected output:
2
# consecutive prime numbers greater than equal to given number . | python 3 program for the above approach function to check prime . ; function to check prime . ; it means it is not a prime ; no factor other than 1 therefore prime number ; function to find out the required consecutive primes . ; finding first prime just less than sqrt ( n ) . ; finding prime just greater than sqrt ( n ) . ; product of both prime is greater than n then print it ; finding prime greater than second ; 

from math import sqrt


def is_prime(n):
    if (n == 1):
        return False
    for i in range(2, int(sqrt(n)) + 1, 1):
        if (n % i == 0):
            return False
    return True


def consecutive_primes(n):
    first = -1
    second = -1
    i = int(sqrt(n))
    while (i >= 2):
        if (is_prime(i)):
            first = i
            break
        i -= 1
    for i in range(int(sqrt(n)) + 1, n // 2 + 1, 1):
        if (is_prime(i)):
            second = i
            break
    if (first * second >= n):
        print(first, second)
    else:
        for i in range(second + 1, n + 1, 1):
            if (is_prime(i)):
                print(second, i)
                return


if __name__ == '__main__':
    n = 14
    consecutive_primes(n)

# Expected output:
3 5
# reorder characters of a string to valid english representations of digits | python program to implement the above approach ; function to construct the original set of digits from the string in ascending order ; store the unique characters corresponding to word and number ; store the required result ; store the frequency of each character of s ; traverse the unique characters ; store the count of k [ i ] in s ; traverse the corresponding word ; decrement the frequency of characters by x ; append the digit x times to ans ; sort the digits in ascending order ; 

from collections import Counter


def construct_digits(s):
    k = ["z", "w", "u", "x", "g", "h", "o", "f", "v", "i"]
    l = [
        "zero",
        "two",
        "four",
        "six",
        "eight",
        "three",
        "one",
        "five",
        "seven",
        "nine"]
    c = [0, 2, 4, 6, 8, 3, 1, 5, 7, 9]
    ans = []
    d = Counter(s)
    for i in range(len(k)):
        x = d .get(k[i], 0)
        for j in range(len(l[i])):
            d[l[i][j]] -= x
        ans .append(str(c[i]) * x)
    ans .sort()
    return "".join(ans)


s = "fviefuro"
print(construct_digits(s))

# Expected output:
45
# minimum decrements required to make all pairs of adjacent matrix elements distinct | function to count minimum number of operations required ; case 1 : ; case 2 : ; print the minimum number of operations required ; the 

n = 3
m = 3


def countDecrements(arr):
    count_1 = 0
    count_2 = 0
    for i in range(n):
        for j in range(m):
            if ((i + j) % 2 == arr[i][j] % 2):
                count_1 += 1
            if (1 - (i + j) % 2 == arr[i][j] % 2):
                count_2 += 1
    print(min(count_1, count_2))


arr = [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
countDecrements(arr)

# Expected output:
3
# check if x can be converted to y by converting to 3 * ( x / 2 ) or x | function to check if x can be made equal to y by converting x to ( 3 * x / 2 ) or ( x - 1 ) ; conditions for possible conversion ; otherwise , conversion is not possible ; 
def check(X, Y):
    if (X > 3):
        print("Yes")
    elif (X == 1 and Y == 1):
        print("Yes")
    elif (X == 2 and Y <= 3):
        print("Yes")
    elif (X == 3 and Y <= 3):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    X = 6
    Y = 8
    check(X, Y)

# Expected output:
Yes
# count distinct sum of pairs possible from a given range | function to count distinct sum of pairs possible from the range [ l , r ] ; return the count of distinct sum of pairs ; 
def distIntegers(L, R):
    return 2 * R - 2 * L + 1


if __name__ == '__main__':
    L, R = 3, 8
    print(distIntegers(L, R))

# Expected output:
11
# count subarrays having even bitwise xor | function to count subarrays having even bitwise xor ; store the required result ; stores count of subarrays with even and odd xor values ; stores bitwise xor of current subarray ; traverse the array ; update current xor ; if xor is even ; update ans ; increment count of subarrays with even xor ; otherwise , increment count of subarrays with odd xor ; print the result ; 
def evenXorSubarray(arr, n):
    ans = 0
    freq = [0] * n
    XOR = 0
    for i in range(n):
        XOR = XOR ^ arr[i]
        if (XOR % 2 == 0):
            ans += freq[0] + 1
            freq[0] += 1
        else:
            ans += freq[1]
            freq[1] += 1
    print(ans)


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

# Expected output:
4
# count occurrences of an element in a matrix of size n * n generated such that each element is equal to product of its indices | python3 program for the above approach ; function to count the occurrences of x in the generated square matrix ; stores the required result ; iterate upto square root of x ; check if i divides x ; store the quotient obtained on dividing x by i ; if both the numbers fall in the range , update count ; return the result ; 

from math import sqrt


def countOccurrences(N, X):
    count = 0
    for i in range(1, int(sqrt(X)) + 1):
        if X % i == 0:
            a = i
            b = X // i
            if a <= N and b <= N:
                if a == b:
                    count += 1
                else:
                    count += 2
    return count


if __name__ == '__main__':
    N = 7
    X = 12
    print(countOccurrences(N, X))

# Expected output:
4
# maximize array product by changing any array element arr [ i ] to ( | function to find array with maximum product by changing array elements to ( - 1 ) arr [ i ] - 1 ; traverse the array ; applying the operation on all the positive elements ; stores maximum element in array ; stores index of maximum element ; check if current element is greater than the maximum element ; find index of the maximum element ; perform the operation on the maximum element ; prthe elements of the array ; 
def findArrayWithMaxProduct(arr, N):
    for i in range(N):
        if (arr[i] >= 0):
            arr[i] = -arr[i] - 1
    if (N % 2 == 1):
        max_element = -1
        index = -1
        for i in range(N):
            if (abs(arr[i]) > max_element):
                max_element = abs(arr[i])
                index = i
        arr[index] = -arr[index] - 1
    for i in arr:
        print(i, end=" ")


if __name__ == '__main__':
    arr = [-3, 0, 1]
    N = len(arr)
    findArrayWithMaxProduct(arr, N)

# Expected output:
2 -1 -2
# lexicographically smallest permutation of first n natural numbers having k perfect indices | function to print the lexicographically smallest permutation with k perfect indices ; iterator to traverse the array ; traverse first k array indices ; traverse remaining indices ; 
def findPerfectIndex(N, K):
    i = 0
    for i in range(K):
        print((N - K + 1) + i, end=" ")
    for i in range(3, N):
        print(i - K + 1, end=" ")


N = 10
K = 3
findPerfectIndex(N, K)

# Expected output:
8 9 10 1 2 3 4 5 6 7
# count pairs having distinct sum from a given range | function to count pairs made up of elements from the range [ l , r ] having distinct sum ; stores the least sum which can be formed by the pairs ; stores the highest sum which can be formed by the pairs ; stores the count of pairs having distinct sum ; print the count of pairs ; 
def countPairs(L, R):
    firstNum = 2 * L
    lastNum = 2 * R
    Cntpairs = lastNum - firstNum + 1
    print(Cntpairs)


if __name__ == '__main__':
    L, R = 2, 3
    countPairs(L, R)

# Expected output:
3
# count pairs from an array whose bitwise or is greater than bitwise and | python 3 program for the above approach ; function to count the number of pairs ( i , j ) their bitwise or is greater than bitwise and ; total number of pairs possible from the array ; stores frequency of each array element ; traverse the array a [ ] ; increment ump [ a [ i ] ] by 1 ; traverse the hashmap ump ; subtract those pairs ( i , j ) from count which has the same element on index i and j ( i < j ) ; print the result ; 

from collections import defaultdict


def countPairs(A, n):
    count = (n * (n - 1)) // 2
    ump = defaultdict(int)
    for i in range(n):
        ump[A[i]] += 1
    for it in ump .keys():
        c = ump[it]
        count = count - (c * (c - 1)) // 2
    print(count)


if __name__ == "__main__":
    A = [1, 4, 7]
    N = len(A)
    countPairs(A, N)

# Expected output:
3
# construct a k | function to construct binary string according to the given conditions ; initialize with 1 ; traverse the array ; to check if the i - th eger needs to be considered or not ; print the binary string for i in range ( 1 , k ) : print ( bit [ i ] ) ; given array ; size of the array ; 
def constructBinaryString(arr, N, K):
    bit = 1
    for i in range(0, N):
        bit |= bit << arr[i]
    bit = bin(bit).replace("0b", "")
    print(bit[1:K + 1])


arr = [1, 6, 1]
N = len(arr)
K = 8
constructBinaryString(arr, N, K)

# Expected output:
11000111
# check if a rook can reach the given destination in a single move | function to check if it is possible to reach destination in a single move by a rook ; 
def check(current_row, current_col, destination_row, destination_col):
    if (current_row == destination_row):
        return ("POSSIBLE")
    elif (current_col == destination_col):
        return ("POSSIBLE")
    else:
        return ("NOT POSSIBLE")


current_row = 8
current_col = 8
destination_row = 8
destination_col = 4
output = check(current_row, current_col, destination_row, destination_col)
print(output)

# Expected output:
POSSIBLE
# append x digits to the end of n to make it divisible by m | base case ; if n is divisible by m ; global variable to store result ; iterate over the range [ 0 , 9 ] ; if n is divisible by m upon appending x digits ; 

res = -1


def isDiv(N, X, M):
    if (X == 0):
        if (N % M == 0):
            global res
            res = N
            return True

        return False
    for i in range(10):
        if (isDiv(N*10+i, X-1, M)):
            return True


if __name__ == "__main__":
    N, M, X = 4, 50, 2
    if (isDiv(N, X, M)):
        print(res)
    else:
        print("-1")

# Expected output:
400
# minimum increments to modify array such that value of any array element can be splitted to make all remaining elements equal | function to count minimum moves ; stores sum of given array ; stores maximum array element ; base case ; if n is 2 , the answer will always be 0 ; traverse the array ; calculate sum of the array ; finding maximum element ; calculate ceil ( sum / n - 1 ) ; if k is smaller than maxelement ; final sum - original sum ; print the minimum number of increments required ; 
def minimumMoves(arr, N):
    sum = 0
    maxelement = -1
    if (N == 2):
        print(0, end="")
    for i in range(N):
        sum += arr[i]
        maxelement = max(maxelement, arr[i])
    K = (sum + N - 2) // (N - 1)
    K = max(maxelement, K)
    ans = K * (N - 1) - sum
    print(ans)


if __name__ == '__main__':
    arr = [2, 3, 7]
    N = 3
    minimumMoves(arr, N)

# Expected output:
2
# generate an array with product of all subarrays of length exceeding one divisible by k | function to check if the required array can be generated or not ; to check if divisor exists ; to store divisiors of k ; check if k is prime or not ; if array can be generated ; print d1 and d2 alternatively ; no such array can be generated ; 
def array_divisbleby_k(N, K):
    flag = False
    d1, d2 = 0, 0
    for i in range(2, int(K ** (1 / 2)) + 1):
        if (K % i == 0):
            flag = True
            d1 = i
            d2 = K // i
            break
    if (flag):
        for i in range(N):
            if (i % 2 == 1):
                print(d2, end=" ")
            else:
                print(d1, end=" ")
    else:
        print(-1)


if __name__ == "__main__":
    N = 5
    K = 21
    array_divisbleby_k(N, K)

# Expected output:
3 7 3 7 3
# minimum characters to be replaced to make a string concatenation of a k | python3 program for the above approach ; function to add an edge to graph ; function to perform dfs traversal on the graph recursively from a given vertex u ; visit the current vertex ; total number of nodes in this component ; increment the frequency of u ; function for finding the minimum number changes required in given string ; form the edges according to the given conditions ; find minimum number of operations ; frequency array for finding the most frequent character ; frequency array for finding the most frequent character ; finding most frequent character ; change rest of the characters to most frequent one ; print total number of changes ; 

import sys
sys .setrecursionlimit(1500)


def addEdge(u, v):
    global adj
    adj[u].append(v)
    adj[v].append(u)


def DFS(u, fre, S):
    global visited, adj, cnt
    visited[u] = 1
    cnt += 1
    fre[ord(S[u]) - ord('a')] += 1
    for i in adj[u]:
        if (visited[i] == 0):
            DFS(i, fre, S)


def minimumOperations(S, m):
    global adj, visited, cnt
    total, N = 0, len(S)
    for i in range(N):
        addEdge(i, N - i - 1)
        addEdge(N - i - 1, i)
    for i in range(N - m):
        addEdge(i, i + m)
        addEdge(i + m, i)
    for i in range(N):
        if (not visited[i]):
            fre = [0] * 26
            cnt, maxx = 0, -1
            DFS(i, fre, S)
            for j in range(26):
                maxx = max(maxx, fre[j])
            total += cnt - maxx
    print(total)


if __name__ == '__main__':
    adj = [[]for i in range(101)]
    visited, cnt = [0 for i in range(101)], 0
    S = "abaaba"
    K = 2
    minimumOperations(S, K)

# Expected output:
2
# replace specified matrix elements such that no two adjacent elements are equal | function to display the valid matrix ; traverse the matrix ; if the current cell is a free space and is even - indexed ; if the current cell is a free space and is odd - indexed ; print the matrix ; given n and m ; 
def Print(arr, n, m):
    for i in range(n):
        for j in range(m):
            a = arr[i][j]
            if ((i + j) % 2 == 0 and a == 'F'):
                arr[i][j] = '1'
            elif (a == 'F'):
                arr[i][j] = '2'
    for i in range(n):
        for j in range(m):
            print(arr[i][j], end="")
        print()


n, m = 4, 4
arr = [['F', 'F', 'F', 'F'], ['F', 'O', 'F', 'F'],
       ['F', 'F', 'O', 'F'], ['F', 'F', 'F', 'F']]
Print(arr, n, m)

# Expected output:
1212
2O21
12O2
2121
# lexicographically smallest string formed by removing duplicates | function that finds lexicographically smallest after removing the duplicates from the given string ; stores the frequency of characters ; mark visited characters ; stores count of each character ; stores the resultant string ; decrease the count of current character ; if character is not already in answer ; last character > s [ i ] and its count > 0 ; mark letter unvisited ; add s [ i ] in res and mark it visited ; return the resultant string ; 
def removeDuplicateLetters(s):
    cnt = [0] * 26
    vis = [0] * 26
    n = len(s)
    for i in s:
        cnt[ord(i) - ord('a')] += 1
    res = []
    for i in range(n):
        cnt[ord(s[i]) - ord('a')] -= 1
        if (not vis[ord(s[i]) - ord('a')]):
            while (len(res) > 0 and res[-1] > s[i]
                   and cnt[ord(res[-1]) - ord('a')] > 0):
                vis[ord(res[-1]) - ord('a')] = 0
                del res[-1]
            res += s[i]
            vis[ord(s[i]) - ord('a')] = 1
    return "".join(res)


if __name__ == '__main__':
    S = "acbc"
    print(removeDuplicateLetters(S))

# Expected output:
abc
# number of pairs whose product is a power of 2 | function to count pairs having product equal to a power of 2 ; stores count of array elements which are power of 2 ; if array element contains only one set bit ; increase count of powers of 2 ; count required number of pairs ; print the required number of pairs ; 
def countPairs(arr, N):
    countPowerof2 = 0
    for i in range(N):
        if (bin(arr[i]).count('1') == 1):
            countPowerof2 += 1
    desiredPairs = (countPowerof2 * (countPowerof2 - 1)) // 2
    print(desiredPairs)


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

# Expected output:
3
# maximum possible sum of squares of stack elements satisfying the given properties | function to find the maximum sum of squares of stack elements ; stores the sum ofsquares of stack elements ; check if sum is valid ; initialize all stack elements with 1 ; stores the count the number of stack elements not equal to 1 ; add the sum of squares of stack elements not equal to 1 ; add 1 * 1 to res as the remaining stack elements are 1 ; print the result ; 
def maxSumOfSquares(N, S):
    res = 0
    if (S < N or S > 9 * N):
        cout << -1
        return
    S = S - N
    c = 0
    while (S > 0):
        c += 1
        if (S // 8 > 0):
            res += 9 * 9
            S -= 8
        else:
            res += (S + 1) * (S + 1)
            break
    res = res + (N - c)
    print(res)


if __name__ == '__main__':
    N = 3
    S = 12
    maxSumOfSquares(N, S)

# Expected output:
86
# unset least significant k bits of a given number | function to return the value after unsetting k lsbs ; create a mask ; bitwise and operation with the number and the mask ; 
def clearLastBit(N, K):
    mask = (-1 << K + 1)
    N = N & mask
    return N


N = 730
K = 3
print(clearLastBit(N, K))

# Expected output:
720
# check if quantities of 3 distinct colors can be converted to a single color by given merge | function to check whether it is possible to do the operation or not ; calculate modulo 3 of all the colors ; check for any equal pair ; otherwise ; 
def isPossible(r, b, g):
    r = r % 3
    b = b % 3
    g = g % 3
    if (r == b or b == g or g == r):
        return True
    else:
        return False


R = 1
B = 3
G = 6
if (isPossible(R, B, G)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# minimize steps required to make all array elements same by adding 1 , 2 or 5 | function to calculate the minimum number of steps ; count stores number of operations required to make all elements equal to minimum value ; remark , the array should remain unchanged for further calculations with different minimum ; storing the current value of arr [ i ] in val ; finds how much extra amount is to be removed ; subtract the maximum number of 5 and stores remaining ; subtract the maximum number of 2 and stores remaining ; restores the actual value of arr [ i ] ; return the count ; function to find the minimum number of steps to make array elements same ; sort the array in descending order ; stores the minimum array element ; stores the operations required to make array elements equal to minimum ; stores the operations required to make array elements equal to minimum - 1 ; stores the operations required to make array elements equal to minimum - 2 ; return minimum of the three counts ; 
def calculate_steps(arr, n, minimum):
    count = 0
    for i in range(n):
        val = arr[i]
        if (arr[i] > minimum):
            arr[i] = arr[i] - minimum
            count += arr[i] // 5
            arr[i] = arr[i] % 5
            count += arr[i] // 2
            arr[i] = arr[i] % 2
            if (arr[i]):
                count += 1
        arr[i] = val
    return count


def solve(arr, n):
    arr = sorted(arr)
    arr = arr[::-1]
    minimum = arr[n - 1]
    count1 = 0
    count2 = 0
    count3 = 0
    count1 = calculate_steps(arr, n, minimum)
    count2 = calculate_steps(arr, n, minimum - 1)
    count3 = calculate_steps(arr, n, minimum - 2)
    return min(count1, min(count2, count3))


if __name__ == '__main__':
    arr = [3, 6, 6]
    N = len(arr)
    print(solve(arr, N))

# Expected output:
3
# largest palindromic string possible from given strings by rearranging the characters | python3 program for the above approach ; function to find largest palindrome possible from s and p after rearranging characters to make palindromic string t ; using unordered_map to store frequency of elements mapt will have freq of elements of t ; size of both the strings ; take all character in mapt which occur even number of times in respective strings & simultaneously update number of characters left in map ; check if a unique character is present in both string s and p ; making string t in two halves half1 - first half half2 - second half ; reverse the half2 to attach with half1 to make palindrome ; if same unique element is present in both s and p , then taking that only which is already taken through mapt ; if same unique element is not present in s and p , then take characters that make string t lexicographically smallest ; if no unique element is present in both string s and p ; 

from collections import defaultdict


def mergePalindromes(S, P):
    mapS = defaultdict(lambda: 0)
    mapP = defaultdict(lambda: 0)
    mapT = defaultdict(lambda: 0)
    n = len(S)
    m = len(P)
    for i in range(n):
        mapS[ord(S[i])] += 1
    for i in range(m):
        mapP[ord(P[i])] += 1
    for i in range(ord('a'), ord('z') + 1):
        if (mapS[i] % 2 == 0):
            mapT[i] += mapS[i]
            mapS[i] = 0
        else:
            mapT[i] += mapS[i] - 1
            mapS[i] = 1
        if (mapP[i] % 2 == 0):
            mapT[i] += mapP[i]
            mapP[i] = 0
        else:
            mapT[i] += mapP[i] - 1
            mapP[i] = 1
    check = 0
    for i in range(ord('a'), ord('z') + 1):
        if (mapS[i] > 0 and mapP[i] > 0):
            mapT[i] += 2
            check = 1
            break
    half1, half2 = "", ""
    for i in range(ord('a'), ord('z') + 1):
        j = 0
        while ((2 * j) < mapT[i]):
            half1 += chr(i)
            half2 += chr(i)
            j += 1
    half2 = half2[::-1]
    if (check):
        return half1 + half2
    for i in range(ord('a'), ord('z') + 1):
        if (mapS[i] > 0 or mapP[i] > 0):
            half1 += chr(i)
            return half1 + half2
    return half1 + half2


S = "aeabb"
P = "dfedf"
print(mergePalindromes(S, P))

# Expected output:
abdeffedba
# count of subarrays having sum equal to its length | python3 program for the above approach ; function that counts the subarrays with sum of its elements as its length ; decrementing all the elements of the array by 1 ; making prefix sum array ; declare map to store count of elements upto current element ; to count all the subarrays whose prefix sum is 0 ; iterate the array ; increment answer by count of current element of prefix array ; return the answer ; 

from collections import defaultdict


def countOfSubarray(arr, N):
    for i in range(N):
        arr[i] -= 1
    pref = [0] * N
    pref[0] = arr[0]
    for i in range(1, N):
        pref[i] = pref[i - 1] + arr[i]
    mp = defaultdict(lambda: 0)
    answer = 0
    mp[0] += 1
    for i in range(N):
        answer += mp[pref[i]]
        mp[pref[i]] += 1
    return answer


arr = [1, 1, 0]
N = len(arr)
print(countOfSubarray(arr, N))

# Expected output:
3