giulio98/xlcost-single-prompt huggingface dataset:
# maximize count of strings of length 3 that can be formed from n 1 s and m 0 s | function that counts the number of strings of length 3 that can be made with given m 0 s and n 1 s ; print the count of strings ; 
def number_of_strings(N, M):
    print(min(N, min(M, (N + M) // 3)))


if __name__ == '__main__':
    N = 4
    M = 19
    number_of_strings(N, M)

# Expected output:
4
# maximize count of subsets having product of smallest element and size of the subset at least x | function to return the maximum count of subsets possible which satisfy the above condition ; sort the array in descending order ; stores the count of subsets ; stores the size of the current subset ; check for the necessary conditions ; 
def maxSubset(arr, N, X):
    arr .sort(reverse=True)
    counter = 0
    sz = 0
    for i in range(N):
        sz += 1
        if (arr[i] * sz >= X):
            counter += 1
            sz = 0
    return counter


arr = [7, 11, 2, 9, 5]
N = len(arr)
X = 10
print(maxSubset(arr, N, X))

# Expected output:
2
# maximize modulus by replacing adjacent pairs with their modulus for any permutation of given array | python3 program to implement the above approach ; function to find the maximum value possible of the given expression from all permutations of the array ; stores the minimum value from the array ; return the answer ; 

import sys


def maximumModuloValue(A, n):
    mn = sys .maxsize
    for i in range(n):
        mn = min(A[i], mn)
    return mn


A = [7, 10, 12]
n = len(A)
print(maximumModuloValue(A, n))

# Expected output:
7
# final matrix after incrementing submatrices by k in range given by q queries | function to update the given query ; update top cell ; update bottom left cell ; update bottom right cell ; update top right cell ; function that updates the matrix mat [ ] [ ] by adding elements of aux [ ] [ ] ; compute the prefix sum of all columns ; compute the prefix sum of all rows ; get the final matrix by adding mat and aux matrix at each cell ; function that prints matrix mat [ ] ; traverse each row ; traverse each columns ; function that performs each query in the given matrix and print the updated matrix after each operation performed ; initialize all elements to 0 ; update auxiliary matrix by traversing each query ; update query ; compute the final answer ; print the updated matrix ; 
def updateQuery(from_x, from_y, to_x, to_y, k, aux):
    aux[from_x][from_y] += k
    if (to_x + 1 < 3):
        aux[to_x + 1][from_y] -= k
    if (to_x + 1 < 3 and to_y + 1 < 4):
        aux[to_x + 1][to_y + 1] += k
    if (to_y + 1 < 4):
        aux[from_x][to_y + 1] -= k
    return aux


def updatematrix(mat, aux):
    for i in range(3):
        for j in range(1, 4):
            aux[i][j] += aux[i][j - 1]
    for i in range(4):
        for j in range(1, 3):
            aux[j][i] += aux[j - 1][i]
    for i in range(3):
        for j in range(4):
            mat[i][j] += aux[i][j]
    return mat


def printmatrix(mat):
    for i in range(3):
        for j in range(4):
            print(mat[i][j], end=" ")
        print()


def matrixQuery(mat, Q, q):
    aux = [[0 for i in range(4)]for i in range(3)]
    for i in range(Q):
        updateQuery(q[i][0], q[i][1], q[i][2], q[i][3], q[i][4], aux)
    updatematrix(mat, aux)
    printmatrix(mat)


if __name__ == '__main__':
    mat = [[1, 0, 1, 2], [0, 2, 4, 1], [1, 2, 1, 0]]
    Q = 1
    q = [[0, 0, 1, 1, 2]]
    matrixQuery(mat, Q, q)

# Expected output:
3 2 1 2 
2 4 4 1 
1 2 1 0
# find second largest element in an array | function to print the second largest elements ; there should be atleast two elements ; sort the array ; start from second last element as the largest element is at last ; if the element is not equal to largest element ; 
def print2largest(arr, arr_size):
    if (arr_size < 2):
        return "Invalid input"
    arr .sort
    for i in range(arr_size - 2, -1, -1):
        if (arr[i] != arr[arr_size - 1]):
            return arr[i]
    return "There is no second largest element"


arr = [12, 35, 1, 10, 34, 1]
n = len(arr)
print(print2largest(arr, n))

# Expected output:
34
# find sum of all left leaves in a given binary tree | python3 program to find sum of all left leaves ; a binary tree node ; return the sum of left leaf nodes ; a queue of pairs to do bfs traversal and keep track if the node is a left or right child if boolean value is true then it is a left child . ; do bfs traversal ; if temp is a leaf node and left child of its parent ; if it is not leaf then push its children nodes into queue ; boolean value is true here because it is left child of its parent ; boolean value is false here because it is right child of its parent ; 

from collections import deque


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


def sumOfLeftLeaves(root):
    if (root is None):
        return 0
    q = deque()
    q .append([root, 0])
    sum = 0
    while (len(q) > 0):
        temp = q[0][0]
        is_left_child = q[0][1]
        q .popleft()
        if (not temp .left and not temp .right and is_left_child):
            sum = sum + temp .key
        if (temp .left):
            q .append([temp .left, 1])
        if (temp .right):
            q .append([temp .right, 0])
    return sum


if __name__ == '__main__':
    root = Node(20)
    root .left = Node(9)
    root .right = Node(49)
    root .right .left = Node(23)
    root .right .right = Node(52)
    root .right .right .left = Node(50)
    root .left .left = Node(5)
    root .left .right = Node(12)
    root .left .right .right = Node(12)
    print("Sum of left leaves is", sumOfLeftLeaves(root))

# Expected output:
Sum of left leaves is 78
# count of nested polygons that can be drawn by joining vertices internally | function that counts the nested polygons inside another polygons ; stores the count ; child polygons can only exists if parent polygon has sides > 5 ; get next nested polygon ; return the count ; 
def countNestedPolygons(sides):
    count = 0
    while (sides > 5):
        sides //= 2
        count += 1
    return count


N = 12
print(countNestedPolygons(N))

# Expected output:
2
# find second largest element in an array | function to print second largest elements ; there should be atleast two elements ; find the largest element ; find the second largest element ; 
def print2largest(arr, arr_size):
    if (arr_size < 2):
        print(" Invalid Input ")
        return
    largest = second = -2454635434
    for i in range(0, arr_size):
        largest = max(largest, arr[i])
    for i in range(0, arr_size):
        if (arr[i] != largest):
            second = max(second, arr[i])
    if (second == -2454635434):
        print("There is no second " + "largest element")
    else:
        print("The second largest " + "elementis", second)


if __name__ == '__main__':
    arr = [12, 35, 1, 10, 34, 1]
    n = len(arr)
    print2largest(arr, n)

# Expected output:
The second largest elementis 34
# find second largest element in an array | function to print the second largest elements ; there should be atleast two elements ; if current element is smaller than first then update both first and second ; if arr [ i ] is in between first and second then update second ; 
def print2largest(arr, arr_size):
    if (arr_size < 2):
        print(" Invalid Input ")
        return
    first = second = -2147483648
    for i in range(arr_size):
        if (arr[i] > first):
            second = first
            first = arr[i]
        elif (arr[i] > second and arr[i] != first):
            second = arr[i]
    if (second == -2147483648):
        print("There is no second largest element")
    else:
        print("The second largest element is", second)


arr = [12, 35, 1, 10, 34, 1]
n = len(arr)
print2largest(arr, n)

# Expected output:
The second largest element is 34
# queries to count characters having odd frequency in a range [ l , r ] | function to print the number of characters having odd frequencies for each query ; a function to construct the arr [ ] and prefix [ ] ; stores array length ; stores the unique powers of 2 associated to each character ; prefix array to store the xor values from array elements ; 
def queryResult(prefix, Q):
    l = Q[0]
    r = Q[1]
    if (l == 0):
        xorval = prefix[r]
        print(bin(xorval).count('1'))
    else:
        xorval = prefix[r] ^ prefix[l - 1]
        print(bin(xorval).count('1'))


def calculateCount(S, Q, m):
    n = len(S)
    arr = [0] * n
    for i in range(n):
        arr[i] = (1 << (ord(S[i]) - ord('a')))
    prefix = [0] * n
    x = 0
    for i in range(n):
        x ^= arr[i]
        prefix[i] = x
    for i in range(m):
        queryResult(prefix, Q[i])


if __name__ == '__main__':
    S = "geeksforgeeks"
    Q = [[2, 4], [0, 3], [0, 12]]
    calculateCount(S, Q, 3)

# Expected output:
3
2
3
# count of binary strings possible as per given conditions | function to generate maximum possible strings that can be generated ; maximum possible strings ; 
def countStrings(A, B, K):
    X = (A + B) // (K + 1)
    return (min(A, min(B, X)) * (K + 1))


N, M, K = 101, 231, 15
print(countStrings(N, M, K))

# Expected output:
320
# construct a matrix n x n with first n ^ 2 natural numbers for an input n | function to print the desired matrix ; iterate ove all [ 0 , n ] ; if is even ; if row number is even print the row in forward order ; if row number is odd print the row in reversed order ; 
def UniqueMatrix(N):
    element_value = 1
    i = 0
    while (i < N):
        if (i % 2 == 0):
            for f in range(element_value, element_value + N, 1):
                print(f, end=' ')
            element_value += N
        else:
            for k in range(element_value + N - 1, element_value - 1, -1):
                print(k, end=' ')
            element_value += N
        print()
        i = i + 1


N = 4
UniqueMatrix(N)

# Expected output:
1 2 3 4 
8 7 6 5 
9 10 11 12 
16 15 14 13
# maximum and minimum of an array using minimum number of comparisons | structure is used to return two values from minmax ( ) ; if there is only one element then return it as min and max both ; if there are more than one elements , then initialize min and max ; 

class pair:
    def __init__(self):
        self .min = 0
        self .max = 0


def getMinMax(arr: list, n: int) -> pair:
    minmax = pair()
    if n == 1:
        minmax .max = arr[0]
        minmax .min = arr[0]
        return minmax
    if arr[0] > arr[1]:
        minmax .max = arr[0]
        minmax .min = arr[1]
    else:
        minmax .max = arr[1]
        minmax .min = arr[0]
    for i in range(2, n):
        if arr[i] > minmax .max:
            minmax .max = arr[i]
        elif arr[i] < minmax .min:
            minmax .min = arr[i]
    return minmax


if __name__ == "__main__":
    arr = [1000, 11, 445, 1, 330, 3000]
    arr_size = 6
    minmax = getMinMax(arr, arr_size)
    print("Minimum element is", minmax .min)
    print("Maximum element is", minmax .max)

# Expected output:
Minimum element is 1
Maximum element is 3000
# find sum of all nodes of the given perfect binary tree | function to find sum of all of the nodes of given perfect binary tree ; no of leaf nodes ; list of vector to store nodes of all of the levels ; store the nodes of last level i . e . , the leaf nodes ; store nodes of rest of the level by moving in bottom - up manner ; loop to calculate values of parent nodes from the children nodes of lower level ; store the value of parent node as sum of children nodes ; traverse the list of vector and calculate the sum ; 
def SumNodes(l):
    leafNodeCount = pow(2, l - 1)
    vec = [[]for i in range(l)]
    for i in range(1, leafNodeCount + 1):
        vec[l - 1].append(i)
    for i in range(l - 2, -1, -1):
        k = 0
        while (k < len(vec[i + 1]) - 1):
            vec[i].append(vec[i + 1][k] + vec[i + 1][k + 1])
            k += 2
    Sum = 0
    for i in range(l):
        for j in range(len(vec[i])):
            Sum += vec[i][j]
    return Sum


if __name__ == '__main__':
    l = 3
    print(SumNodes(l))

# Expected output:
30
# maximum and minimum of an array using minimum number of comparisons | getminmax ( ) ; if array has even number of elements then initialize the first two elements as minimum and maximum ; set the starting index for loop ; if array has odd number of elements then initialize the first element as minimum and maximum ; set the starting index for loop ; in the while loop , pick elements in pair and compare the pair with max and min so far ; increment the index by 2 as two elements are processed in loop ; 
def getMinMax(arr):
    n = len(arr)
    if (n % 2 == 0):
        mx = max(arr[0], arr[1])
        mn = min(arr[0], arr[1])
        i = 2
    else:
        mx = mn = arr[0]
        i = 1
    while (i < n - 1):
        if arr[i] < arr[i + 1]:
            mx = max(mx, arr[i + 1])
            mn = min(mn, arr[i])
        else:
            mx = max(mx, arr[i])
            mn = min(mn, arr[i + 1])
        i += 2
    return (mx, mn)


if __name__ == '__main__':
    arr = [1000, 11, 445, 1, 330, 3000]
    mx, mn = getMinMax(arr)
    print("Minimum element is", mn)
    print("Maximum element is", mx)

# Expected output:
Minimum element is 1
Maximum element is 3000
# mo 's algorithm (query square root decomposition) | set 1 (introduction) | function that accepts array and list of queries and print sum of each query ; traverse through each query ; extract left and right indices ; compute sum of current query range ; print sum of current query range ; 
def printQuerySum(arr, Q):
    for q in Q:
        L, R = q
        s = 0
        for i in range(L, R + 1):
            s += arr[i]
        print("Sum of", q, "is", s)


arr = [1, 1, 2, 1, 3, 4, 5, 2, 8]
Q = [[0, 4], [1, 3], [2, 4]]
printQuerySum(arr, Q)

# Expected output:
Sum of [0, 4] is 8
Sum of [1, 3] is 4
Sum of [2, 4] is 6
# count of unique palindromic strings of length x from given string | function to count different palindromic string of length x from the given string s ; base case ; create the frequency array intitalise frequency array with 0 ; count the frequency in the string ; store frequency of the char ; check the frequency which is greater than zero ; no . of different char we can put at the position of the i and x - i ; iterator pointing to the last element of the set ; decrease the value of the char we put on the position i and n - i ; different no of char we can put at the position x / 2 ; return total no of different string ; 
def findways(s, x):
    if (x > len(s)):
        return 0
    n = len(s)
    freq = [0] * 26
    for i in range(n):
        freq[ord(s[i]) - ord('a')] += 1
    se = set()
    for i in range(26):
        if (freq[i] > 0):
            se .add(freq[i])
    ans = 1
    for i in range(x // 2):
        count = 0
        for u in se:
            if (u >= 2):
                count += 1
        if (count == 0):
            return 0
        else:
            ans *= count
        p = list(se)
        val = p[-1]
        p .pop(-1)
        se = set(p)
        if (val > 2):
            se .add(val - 2)
    if (x % 2 != 0):
        count = 0
        for u in se:
            if (u > 0):
                count += 1
        ans = ans * count
    return ans


if __name__ == '__main__':
    s = "aaa"
    x = 2
    print(findways(s, x))

# Expected output:
1
# min operations to reduce n to 1 by multiplying by a or dividing by b | function to check if it is possible to convert a number n to 1 by a minimum use of the two operations ; for the case b % a != 0 ; check if n equal to 1 ; check if n is not divisible by b ; initialize a variable c ; loop until n is divisible by b ; count number of divisions ; loop until n is divisible by c ; count number of operations ; check if n is reduced to 1 ; count steps ; return the total number of steps ; 
def FindIfPossible(n, a, b):
    if (b % a) != 0:
        if n == 1:
            return 0
        elif (n % b) != 0:
            return -1
        else:
            return int(n / b)
    c = b / a
    x = 0
    y = 0
    while (n % b == 0):
        n /= b
        x += 1
    while (n % c == 0):
        n /= c
        y += 1
    if n == 1:
        total_steps = x + 2 * y
        return total_steps
    else:
        return -1


n = 48
a = 3
b = 12
print(FindIfPossible(n, a, b))

# Expected output:
3
# find two numbers with sum n such that neither of them contains digit k | python3 implementation of the above approach ; count leading zeros ; it removes i characters starting from index 0 ; check each digit of the n ; if digit is k break it ; for odd numbers ; add d1 to a and d2 to b ; if the digit is not k , no need to break string d in a and 0 in b ; remove leading zeros ; return the answer a + b ; 
def removeLeadingZeros(Str):
    i = 0
    n = len(Str)
    while (Str[i] == '0' and i < n):
        i += 1
    Str = Str[i:]
    return Str


def findPairs(Sum, K):
    A = ""
    B = ""
    N = str(Sum)
    n = len(N)
    for i in range(n):
        D = int(N[i]) - int('0')
        if (D == K):
            D1 = D // 2
            D2 = (D // 2) + (D % 2)
            A = A + (str)(D1 + int('0'))
            B = B + (str)(D2 + int('0'))
        else:
            A = A + (str)(D + int('0'))
            B = B + '0'
    A = removeLeadingZeros(A)
    B = removeLeadingZeros(B)
    return A + B


N = 33673
K = 3
print(findPairs(N, K))

# Expected output:
1167122002
# minimum salary hike for each employee such that no employee feels unfair | python program to find the minimum hike of each employee such that no adjacent employee feels unfair ; as hikes are positive integers , keeping minimum value ; pass - 1 : compare with previous employee ; pass - 2 : compare with next employee ; 
def findMinimumHike(ratings, employees):
    hikes = [1 for i in range(employees)]
    for i in range(1, employees):
        if (ratings[i - 1] < ratings[i] and hikes[i - 1] >= hikes[i]):
            hikes[i] = hikes[i - 1] + 1
    for i in range(employees - 2, -1, -1):
        if (ratings[i] > ratings[i + 1] and hikes[i + 1] >= hikes[i]):
            hikes[i] = hikes[i + 1] + 1
    return hikes


data = [5, 3, 4, 2, 1, 6]
result = findMinimumHike(data, len(data))
print(result)
data = [1, 3, 5, 4]
result = findMinimumHike(data, len(data))
print(result)
data = [1, 4]
result = findMinimumHike(data, len(data))
print(result)

# Expected output:
[2, 1, 3, 2, 1, 2]
[1, 2, 3, 1]
[1, 2]
# find sum of all nodes of the given perfect binary tree | function to find sum of all of the nodes of given perfect binary tree ; function to find sum of all of the nodes of given perfect binary tree ; no of leaf nodes ; sum of nodes at last level ; sum of all nodes ; 

import math


def sumNodes(l):
    leafNodeCount = math .pow(2, l - 1)
    sumLastLevel = 0
    sumLastLevel = ((leafNodeCount * (leafNodeCount + 1)) / 2)
    sum = sumLastLevel * l
    return int(sum)


l = 3
print(sumNodes(l))

# Expected output:
30
# longest subsequence with different adjacent characters | dp table ; a recursive function to find the update the dp table ; if we reach end of the string ; if subproblem has been computed ; initialise variable to find the maximum length ; choose the current character ; omit the current character ; return the store answer to the current subproblem ; function to find the longest subsequence with different adjacent character ; length of the string s ; return the final ans after every recursive call ; 

dp = [[-1 for i in range(27)]for j in range(100005)]


def calculate(pos, prev, s):
    if (pos == len(s)):
        return 0
    if (dp[pos][prev] != -1):
        return dp[pos][prev]
    val = 0
    if (ord(s[pos]) - ord('a') + 1 != prev):
        val = max(val, 1 + calculate(pos + 1, ord(s[pos]) - ord('a') + 1, s))
    val = max(val, calculate(pos + 1, prev, s))
    dp[pos][prev] = val
    return dp[pos][prev]


def longestSubsequence(s):
    n = len(s)
    return calculate(0, 0, s)


if __name__ == '__main__':
    str = "ababa"
    print(longestSubsequence(str))

# Expected output:
5
# maximum profit by buying and selling a share at most k times | greedy approach | function to return the maximum profit ; find the farthest decreasing span of prices before prices rise ; find the farthest increasing span of prices before prices fall again ; check if the current buying price is greater than that of the previous transaction ; store the profit ; remove the previous transaction ; check if the current selling price is less than that of the previous transactions ; store the new profit ; remove the previous transaction ; add the new transactions ; finally store the profits of all the transactions ; add the highest k profits ; return the maximum profit ; 
def maxProfit(n, k, prices):
    ans = 0
    buy = 0
    sell = 0
    transaction = []
    profits = []
    while (sell < n):
        buy = sell
        while (buy < n - 1 and prices[buy] >= prices[buy + 1]):
            buy += 1
        sell = buy + 1
        while (sell < n and prices[sell] >= prices[sell - 1]):
            sell += 1
        while (len(transaction) !=
               0 and prices[buy] < prices[transaction[len(transaction) - 1][0]]):
            p = transaction[len(transaction) - 1]
            profits .append(prices[p[1] - 1] - prices[p[0]])
            transaction .remove(transaction[len(transaction) - 1])
        profits .sort(reverse=True)
        while (len(transaction) != 0 and prices[sell - 1] >
               prices[transaction[len(transaction) - 1][1] - 1]):
            p = transaction[len(transaction) - 1]
            profits .append(prices[p[1] - 1] - prices[buy])
            buy = p[0]
            transaction .remove(transaction[len(transaction) - 1])
        transaction .append([buy, sell])
    profits .sort(reverse=True)
    while (len(transaction) != 0):
        profits .append(prices[transaction[len(transaction) - 1]
                        [1] - 1] - prices[transaction[len(transaction) - 1][0]])
        transaction .remove(transaction[len(transaction) - 1])
    profits .sort(reverse=True)
    while (k != 0 and len(profits) != 0):
        ans += profits[0]
        profits .remove(profits[0])
        k -= 1
    return ans


if __name__ == '__main__':
    k = 3
    prices = [1, 12, 10, 7, 10, 13, 11, 10, 7, 6, 9]
    n = len(prices)
    print("Maximum profit is", maxProfit(n, k, prices))

# Expected output:
Maximum profit is 20
# find sum in range l to r in given sequence of integers | function to find the sum within the given range ; generating array from 
def findSum(L, R):
    arr = []
    i = 0
    x = 2
    k = 0
    while (i <= R):
        arr .insert(k, i + x)
        k += 1
        if (i + 1 <= R):
            arr .insert(k, i + 1 + x)
        k += 1
        x *= -1
        i += 2
    sum = 0
    for i in range(L, R + 1):
        sum += arr[i]
    return sum


L = 0
R = 5
print(findSum(L, R))

# Expected output:
19
# count of pairs from arrays a and b such that element in a is greater than element in b at that index | python3 program to find the maximum count of values that follow the given condition ; function to find the maximum count of values that follow the given condition ; initializing the max - heap for the array a [ ] ; adding the values of a [ ] into max heap ; adding the values of b [ ] into max heap ; counter variable ; loop to iterate through the heap ; comparing the values at the top . if the value of heap a [ ] is greater , then counter is incremented ; 

import heapq


def check(A, B, N):
    pq1 = []
    pq2 = []
    for i in range(N):
        heapq .heappush(pq1, -A[i])
    for i in range(N):
        heapq .heappush(pq2, -B[i])
    c = 0
    for i in range(N):
        if -pq1[0] > -pq2[0]:
            c += 1
            heapq .heappop(pq1)
            heapq .heappop(pq2)
        else:
            if len(pq2) == 0:
                break
            heapq .heappop(pq2)
    return (c)


A = [10, 3, 7, 5, 8]
B = [8, 6, 2, 5, 9]
N = len(A)
print(check(A, B, N))

# Expected output:
4