giulio98/xlcost-single-prompt huggingface dataset:
# count distinct regular bracket sequences which are not n periodic | function that finds the value of binomial coefficient c ( n , k ) ; since c ( n , k ) = c ( n , n - k ) ; calculate the value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; return the c ( n , k ) ; binomial coefficient based function to find nth catalan number in o ( n ) time ; calculate value of 2 ncn ; return c ( 2 n , n ) / ( n + 1 ) ; function to find possible ways to put balanced parenthesis in an expression of length n ; if n is odd , not possible to create any valid parentheses ; otherwise return n / 2 th catalan number ; difference between counting ways of 2 * n and n is the result ; 
def binomialCoeff(n, k):
    res = 1
    if (k > n - k):
        k = n - k
    for i in range(k):
        res = res * (n - i)
        res = res // (i + 1)
    return res


def catalan(n):
    c = binomialCoeff(2 * n, n)
    return c // (n + 1)


def findWays(n):
    if ((n & 1) == 1):
        return 0
    return catalan(n // 2)


def countNonNPeriodic(N):
    print(findWays(2 * N) - findWays(N))


N = 4
countNonNPeriodic(N)

# Expected output:
12
# check if two elements of a matrix are on the same diagonal or not | function to check if two integers are on the same diagonal of the matrix ; storing indexes of y in p , q ; condition to check if the both the elements are in same diagonal of a matrix ; 
def checkSameDiag(x, y):
    for i in range(m):
        for j in range(n):
            if li[i][j] == x:
                I, J = i, j
            if li[i][j] == y:
                P, Q = i, j
    if P - Q == I - J or P + Q == I + J:
        print("YES")
    else:
        print("NO")


if __name__ == "__main__":
    m, n = 6, 5
    li = [[32, 94, 99, 26, 82], [51, 69, 52, 63, 17], [90, 36, 88, 55, 33], [
        93, 42, 73, 39, 28], [81, 31, 83, 53, 10], [12, 29, 85, 80, 87]]
    x, y = 42, 80
    checkSameDiag(x, y)

# Expected output:
YES
# count of decrement operations required to obtain k in n steps | function to check whether m number of steps of type 1 are valid or not ; if m and n are the count of operations of type 1 and type 2 respectively , then n - m operations are performed ; find the value of s after step 2 ; if m steps of type 1 is valid ; function to find the number of operations of type 1 required ; iterate over the range ; find the value of mid ; check if m steps of type 1 are valid or not ; if mid is the valid number of steps ; if no valid number of steps exist ; 
def isValid(n, m, k):
    step2 = n - m
    cnt = (step2 * (step2 + 1)) // 2
    if (cnt - m == k):
        return 0
    if (cnt - m > k):
        return 1
    return -1


def countOfOperations(n, k):
    start = 0
    end = n
    ok = 1
    while (start <= end):
        mid = (start + end) // 2
        temp = isValid(n, mid, k)
        if (temp == 0):
            ok = 0
            print(mid)
            break
        elif (temp == 1):
            start = mid + 1
        else:
            end = mid - 1
    if (ok):
        print("-1")


N = 5
K = 4
countOfOperations(N, K)

# Expected output:
2
# count prime numbers that can be expressed as sum of consecutive prime numbers | function to check if a number is prime or not ; base case ; iterate till [ 5 , sqrt ( n ) ] to detect primality of numbers ; if n is divisible by i or i + 2 ; return 1 if n is prime ; function to count the prime numbers which can be expressed as sum of consecutive prime numbers ; initialize count as 0 ; stores prime numbers ; if i is prime ; initialize the sum ; find all required primes upto n ; add it to the sum ; return the final count ; 
def isprm(n):
    if (n <= 1):
        return 0
    if (n <= 3):
        return 1
    if (n % 2 == 0 or n % 3 == 0):
        return 0
    i = 5
    while (i * i <= n):
        if (n % i == 0 or n % (i + 2) == 0):
            return 0
        i = i + 6
    return 1


def countprime(n):
    count = 0
    primevector = []
    for i in range(2, n + 1):
        if (isprm(i) == 1):
            primevector .append(i)
    sum = primevector[0]
    for i in range(1, len(primevector)):
        sum += primevector[i]
        if (sum > n):
            break
        if (isprm(sum) == 1):
            count += 1
    return count


N = 45
print(countprime(N))

# Expected output:
3
# find a subarray of size k whose sum is a perfect square | python3 program for the above approach ; function to check if a given number is a perfect square or not ; find square root of n ; check if the square root is an integer or not ; function to print the subarray whose sum is a perfect square ; sum of first k elements ; if the first k elements have a sum as perfect square ; iterate through the array ; if sum is perfect square ; if subarray not found ; 

from math import sqrt, ceil, floor


def isPerfectSquare(n):
    sr = sqrt(n)
    return ((sr - floor(sr)) == 0)


def SubarrayHavingPerfectSquare(arr, k):
    ans = [0, 0]
    sum = 0
    i = 0
    while i < k:
        sum += arr[i]
        i += 1
    found = False
    if (isPerfectSquare(sum)):
        ans[0] = 0
        ans[1] = i - 1
    else:
        for j in range(i, len(arr)):
            sum = sum + arr[j] - arr[j - k]
            if (isPerfectSquare(sum)):
                found = True
                ans[0] = j - k + 1
                ans[1] = j
        for k in range(ans[0], ans[1] + 1):
            print(arr[k], end=" ")
    if (found == False):
        print("-1")


if __name__ == '__main__':
    arr = [20, 34, 51, 10, 99, 87, 23, 45]
    K = 3
    SubarrayHavingPerfectSquare(arr, K)

# Expected output:
10 99 87
# check if any permutation of a number without any leading zeros is a power of 2 or not | python3 program for the above approach ; function to update the frequency array such that freq [ i ] stores the frequency of digit i to n ; while there are digits left to process ; update the frequency of the current digit ; remove the last digit ; function that returns true if a and b are anagrams of each other ; to store the frequencies of the digits in a and b ; update the frequency of the digits in a ; update the frequency of the digits in b ; match the frequencies of the common digits ; if frequency differs for any digit then the numbers are not anagrams of each other ; function to check if any permutation of a number is a power of 2 or not ; iterate over all possible perfect power of 2 ; print that number ; 

TEN = 10


def updateFreq(n, freq):
    while (n):
        digit = n % TEN
        freq[digit] += 1
        n //= TEN


def areAnagrams(a, b):
    freqA = [0] * (TEN)
    freqB = [0] * (TEN)
    updateFreq(a, freqA)
    updateFreq(b, freqB)
    for i in range(TEN):
        if (freqA[i] != freqB[i]):
            return False
    return True


def isPowerOf2(N):
    for i in range(32):
        if (areAnagrams(1 << i, N)):
            print(1 << i)
            return True
    return False


N = 46
if (isPowerOf2(N) == 0):
    print("No")

# Expected output:
64
# count number of triangles possible with length of sides not exceeding n | function to count total number of right angled triangle ; initialise count with 0 ; run three nested loops and check all combinations of sides ; condition for right angled triangle ; increment count ; 
def right_angled(n):
    count = 0
    for z in range(1, n + 1):
        for y in range(1, z + 1):
            for x in range(1, y + 1):
                if ((x * x) + (y * y) == (z * z)):
                    count += 1
    return count


n = 5
print(right_angled(n))

# Expected output:
1
# check if the given two matrices are mirror images of one another | function to check whether the two matrices are mirror of each other ; initialising row and column of second matrix ; iterating over the matrices ; check row of first matrix with reversed row of second matrix ; if the element is not equal ; increment column ; reset column to 0 for new row ; increment row ; 
def mirrorMatrix(mat1, mat2, N):
    row = 0
    col = 0
    isMirrorImage = True
    for i in range(N):
        for j in range(N - 1, -1, -1):
            if (mat2[row][col] != mat1[i][j]):
                isMirrorImage = False
            col += 1
        col = 0
        row += 1
    if (isMirrorImage):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    N = 4
    mat1 = [[1, 2, 3, 4], [0, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
    mat2 = [[4, 3, 2, 1], [8, 7, 6, 0], [12, 11, 10, 9], [16, 15, 14, 13]]
    mirrorMatrix(mat1, mat2, N)

# Expected output:
Yes
# calculate number of nodes between two vertices in an acyclic graph by dfs method | function to return the count of nodes in the path from source to destination ; mark the node visited ; if dest is reached ; traverse all adjacent nodes ; if not already visited ; if there is path , then include the current node ; return 0 if there is no path between src and dest through the current node ; function to return the count of nodes between two given vertices of the acyclic graph ; initialize an adjacency list ; populate the edges in the list ; mark all the nodes as not visited ; count nodes in the path from src to dest ; return the nodes between src and dest ; 
def dfs(src, dest, vis, adj):
    vis[src] = 1
    if (src == dest):
        return 1
    for u in adj[src]:
        if not vis[u]:
            temp = dfs(u, dest, vis, adj)
            if (temp != 0):
                return temp + 1
    return 0


def countNodes(V, E, src, dest, edges):
    adj = [[]for i in range(V + 1)]
    for i in range(E):
        adj[edges[i][0]].append(edges[i][1])
        adj[edges[i][1]].append(edges[i][0])
    vis = [0] * (V + 1)
    count = dfs(src, dest, vis, adj)
    return count - 2


if __name__ == '__main__':
    V = 8
    E = 7
    src = 5
    dest = 2
    edges = [[1, 4], [4, 5], [4, 2], [2, 6], [6, 3], [2, 7], [3, 8]]
    print(countNodes(V, E, src, dest, edges))

# Expected output:
1
# check if all array elements are pairwise co | function to calculate gcd ; function to calculate lcm ; function to check if aelements in the array are pairwise coprime ; initialize variables ; iterate over the array ; calculate product of array elements ; calculate lcm of array elements ; if the product of array elements is equal to lcm of the array ; 
def GCD(a, b):
    if (a == 0):
        return b
    return GCD(b % a, a)


def LCM(a, b):
    return (a * b) // GCD(a, b)


def checkPairwiseCoPrime(A, n):
    prod = 1
    lcm = 1
    for i in range(n):
        prod *= A[i]
        lcm = LCM(A[i], lcm)
    if (prod == lcm):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    A = [2, 3, 5]
    n = len(A)
    checkPairwiseCoPrime(A, n)

# Expected output:
Yes
# partition a set into two non | python3 program for above approach ; function to return the maximum difference between the subset sums ; stores the total sum of the array ; checks for positive and negative elements ; stores the minimum element from the given array ; traverse the array ; calculate total sum ; mark positive element present in the set ; mark negative element present in the set ; find the minimum element of the set ; if the array contains both positive and negative elements ; otherwise ; 

import sys


def maxDiffSubsets(arr):
    totalSum = 0
    pos = False
    neg = False
    min = sys .maxsize
    for i in range(len(arr)):
        totalSum += abs(arr[i])
        if (arr[i] > 0):
            pos = True
        if (arr[i] < 0):
            neg = True
        if (arr[i] < min):
            min = arr[i]
    if (pos and neg):
        return totalSum
    else:
        return totalSum - 2 * min


if __name__ == '__main__':
    S = [1, 2, 1]
    N = len(S)
    if (N < 2):
        print("Not Possible")
    else:
        print(maxDiffSubsets(S))

# Expected output:
2
# split array into two subarrays such that difference of their sum is minimum | python3 program for the above approach ; function to return minimum difference between two subarray sums ; to store prefix sums ; generate prefix sum array ; to store suffix sums ; generate suffix sum array ; stores the minimum difference ; traverse the given array ; calculate the difference ; update mindiff ; return mindiff ; 

import sys


def minDiffSubArray(arr, n):
    prefix_sum = [0] * n
    prefix_sum[0] = arr[0]
    for i in range(1, n):
        prefix_sum[i] = (prefix_sum[i - 1] + arr[i])
    suffix_sum = [0] * n
    suffix_sum[n - 1] = arr[n - 1]
    for i in range(n - 2, -1, -1):
        suffix_sum[i] = (suffix_sum[i + 1] + arr[i])
    minDiff = sys .maxsize
    for i in range(n - 1):
        diff = abs(prefix_sum[i] - suffix_sum[i + 1])
        if (diff < minDiff):
            minDiff = diff
    return minDiff


if __name__ == '__main__':
    arr = [7, 9, 5, 10]
    n = len(arr)
    print(minDiffSubArray(arr, n))

# Expected output:
1
# count of days remaining for the next day with higher temperature | function to determine how many days required to wait for the next warmer temperature ; to store the answer ; traverse all the temperatures ; check if current index is the next warmer temperature of any previous indexes ; pop the element ; push the current index ; print waiting days ; 
def dailyTemperatures(T):
    n = len(T)
    daysOfWait = [-1] * n
    s = []
    for i in range(n):
        while (len(s) != 0 and T[s[-1]] < T[i]):
            daysOfWait[s[-1]] = i - s[-1]
            s .pop(-1)
        s .append(i)
    for i in range(n):
        print(daysOfWait[i], end=" ")


arr = [73, 74, 75, 71, 69, 72, 76, 73]
dailyTemperatures(arr)

# Expected output:
1 1 4 2 1 1 -1 -1
# find node u containing all nodes from a set v at atmost distance 1 from the path from root to u | to store the time ; function to perform dfs to store times , distance and parent of each node ; update the distance of node u ; update parent of node u ; increment time timet ; discovery time of node u ; traverse the adjacency list of current node and recursively call dfs for each vertex ; if current node adj [ u ] [ i ] is unvisited ; update the finishing time ; function to add edges between nodes u and v ; function to find the node u such that path from root to u contains nodes in v [ ] ; initialise vis , dis , parent , pretime , and posttime ; store adjacency list ; create adjacency list ; perform dfs traversal ; stores the distance of deepest vertex 'u ; update the deepest node by traversing the qu [ ] ; find deepest vertex ; replace each vertex with it 's  corresponding parent except  the root vertex ; checks if the ancestor with respect to deepest vertex u ; update ans ; prthe result ; 

timeT = 0


def dfs(u, p, dis,
        vis,
        distance,
        parent,
        preTime,
        postTime,
        Adj):

    global timeT
    distance[u] = dis
    parent[u] = p
    vis[u] = 1
    timeT += 1
    preTime[u] = timeT
    for i in range(len(Adj[u])):
        if (vis[Adj[u][i]] == 0):

            dfs(Adj[u][i], u, dis + 1,
                vis, distance, parent,
                preTime, postTime, Adj)

    timeT += 1
    postTime[u] = timeT


def addEdge(Adj, u, v):

    Adj[u].append(v)
    Adj[v].append(u)


def findNodeU(N, V, Vertices, Edges):
    vis = [0 for i in range(N + 1)]
    distance = [0 for i in range(N + 1)]
    parent = [0 for i in range(N + 1)]
    preTime = [0 for i in range(N + 1)]
    postTime = [0 for i in range(N + 1)]
    Adj = [[] for i in range(N + 1)]

    u = 0
    v = 0
    for i in range(N - 1):

        addEdge(Adj, Edges[i][0],
                Edges[i][1])
    dfs(1, 0, 0, vis, distance, parent,
        preTime, postTime, Adj)

    maximumDistance = 0
    maximumDistance = 0
    for k in range(V):
        if (maximumDistance < distance[Vertices[k]]):

            maximumDistance = distance[Vertices[k]]
            u = Vertices[k]
        if (parent[Vertices[k]] != 0):
            Vertices[k] = parent[Vertices[k]]

    ans = True

    flag = False

    for k in range(V):
        if (preTime[Vertices[k]] <= preTime[u]
                and postTime[Vertices[k]]
                >= postTime[u]):
            flag = True
        else:
            flag = False
        ans = ans & flag
    if (ans):
        print(u)
    else:
        print('No')


if __name__ == '__main__':
    N = 10

    V = 5
    Vertices = [4, 3, 8, 9, 10]
    Edges = [[1, 2], [1, 3],
             [1, 4], [2, 5],
             [2, 6], [3, 7],
             [7, 8], [7, 9],
             [9, 10]]
    findNodeU(N, V, Vertices, Edges)

# Expected output:
10
# check if an array contains only one distinct element | function to find if the array contains only one distinct element ; create a set ; compare and print the result ; 
def uniqueElement(arr, n):
    s = set(arr)
    if (len(s) == 1):
        print('YES')
    else:
        print('NO')


if __name__ == '__main__':
    arr = [9, 9, 9, 9, 9, 9, 9]
    n = len(arr)
    uniqueElement(arr, n)

# Expected output:
YES
# maximum cost of splitting given binary tree into two halves | to store the results and sum of all nodes in the array ; to create adjacency list ; function to add edges into the adjacency list ; recursive function that calculate the value of the cost of splitting the tree recursively ; fetch the child of node - r ; neglect if cur node is parent ; add all values of nodes which are decendents of r ; the two trees formed are rooted at ' r ' with its decendents ; check and replace if current product t1 * t2 is large ; function to find the maximum cost after splitting the tree in 2 halves ; find sum of values in all nodes ; traverse edges to create adjacency list ; function call ; 

ans = 0
allsum = 0
edges = [[]for i in range(100001)]


def addedge(a, b):
    global edges
    edges[a].append(b)
    edges[b].append(a)


def findCost(r, p, arr):
    global edges
    global ans
    global allsum
    i = 0
    for i in range(len(edges[r])):
        cur = edges[r][i]
        if (cur == p):
            continue
        findCost(cur, r, arr)
        arr[r] += arr[cur]
    t1 = arr[r]
    t2 = allsum - t1
    if (t1 * t2 > ans):
        ans = t1 * t2


def maximumCost(r, p, N, M, arr, Edges):
    global allsum
    for i in range(N):
        allsum += arr[i]
    for i in range(M):
        addedge(Edges[i][0], Edges[i][1])
    findCost(r, p, arr)


if __name__ == '__main__':
    N = 6
    arr = [13, 8, 7, 4, 5, 9]
    M = 5
    Edges = [[0, 1], [1, 2], [1, 4], [3, 4], [4, 5]]
    maximumCost(1, -1, N, M, arr, Edges)
    print(ans)

# Expected output:
504
# diameters for each node of tree after connecting it with given disconnected component | python3 program to implement the above approach ; keeps track of the farthest end of the diameter ; keeps track of the length of the diameter ; stores the nodes which are at ends of the diameter ; perform dfs on the 

from collections import defaultdict
X = 1
diameter = 0
mp = defaultdict(lambda: 0)


def dfs(current_node, prev_node, len, add_to_map, adj):
    global diameter, X
    if len > diameter:
        diameter = len
        X = current_node
    if add_to_map and len == diameter:
        mp[current_node] = 1
    for it in adj[current_node]:
        if it != prev_node:
            dfs(it, current_node, len + 1, add_to_map, adj)


def dfsUtility(adj):
    dfs(1, -1, 0, 0, adj)
    farthest_node = X
    dfs(farthest_node, -1, 0, 0, adj)
    dfs(farthest_node, -1, 0, 1, adj)
    dfs(X, -1, 0, 1, adj)


def printDiameters(adj):
    global diameter
    dfsUtility(adj)
    for i in range(1, 6 + 1):
        if mp[i] == 1:
            print(diameter + 1, end=", ")
        else:
            print(diameter, end=", ")


adj = []
for i in range(7):
    adj .append([])
adj[1].append(2)
adj[2].append(1)
adj[1].append(3)
adj[3].append(1)
adj[2].append(4)
adj[4].append(2)
adj[2].append(5)
adj[5].append(2)
adj[2].append(6)
adj[6].append(2)
printDiameters(adj)

# Expected output:
3, 3, 4, 4, 4, 4,
# count of replacements required to make the sum of all pairs of given type from the array equal | python3 program to implement the above approach ; function to find the minimum replacements required ; stores the maximum and minimum values for every pair of the form arr [ i ] , arr [ n - i - 1 ] ; map for storing frequencies of every sum formed by pairs ; minimum element in the pair ; maximum element in the pair ; incrementing the frequency of sum encountered ; insert minimum and maximum values ; sorting the vectors ; iterate over all possible values of x ; count of pairs for which x > x + k ; count of pairs for which x < mn + 1 ; count of pairs requiring 2 replacements ; count of pairs requiring no replacements ; count of pairs requiring 1 replacement ; update the answer ; return the answer ; 

inf = 10 ** 18


def firstOccurance(numbers, length, searchnum):
    answer = -1
    start = 0
    end = length - 1
    while start <= end:
        middle = (start + end) // 2
        if numbers[middle] == searchnum:
            answer = middle
            end = middle - 1
        elif numbers[middle] > searchnum:
            end = middle - 1
        else:
            start = middle + 1
    return answer


def minimumReplacement(arr, N, K):
    ans = inf
    max_values = []
    min_values = []
    sum_equal_to_x = dict()
    for i in range(N // 2):
        mn = min(arr[i], arr[N - i - 1])
        mx = max(arr[i], arr[N - i - 1])
        if (arr[i] + arr[N - i - 1]not in sum_equal_to_x):
            sum_equal_to_x[arr[i] + arr[N - i - 1]] = 0
        sum_equal_to_x[arr[i] + arr[N - i - 1]] += 1
        min_values .append(mn)
        max_values .append(mx)
    max_values .sort()
    min_values .sort()
    for x in range(2, 2 * K + 1):
        mp1 = firstOccurance(max_values, len(max_values), x - K)
        mp2 = firstOccurance(min_values, len(min_values), x)
        rep2 = mp1 + (N // 2 - mp2)
        if x in sum_equal_to_x:
            rep0 = sum_equal_to_x[x]
        else:
            rep0 = 0
        rep1 = (N // 2 - rep2 - rep0)
        ans = min(ans, rep2 * 2 + rep1)
    return ans


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

# Expected output:
1
# count of ways to obtain given sum from the given array elements | function to call dfs to calculate the number of ways ; if target + sum is odd or s exceeds sum ; no sultion exists ; return the answer ; 
def knapSack(nums, S):
    sum = 0
    for i in range(len(nums)):
        sum += nums[i]
    if (sum < S or -sum > -S or (S + sum) % 2 == 1):
        return 0
    dp = [0] * (((S + sum) // 2) + 1)
    dp[0] = 1
    for j in range(len(nums)):
        for i in range(len(dp) - 1, nums[j] - 1, -1):
            dp[i] += dp[i - nums[j]]
    return dp[len(dp) - 1]


if __name__ == '__main__':
    S = 3
    arr = [1, 2, 3, 4, 5]
    answer = knapSack(arr, S)
    print(answer)

# Expected output:
3
# maximum distance between two elements whose absolute difference is k | function that find maximum distance between two elements whose absolute difference is k ; to store the first index ; traverse elements and find maximum distance between 2 elements whose absolute difference is k ; if this is first occurrence of element then insert its index in map ; if next element present in map then update max distance ; if previous element present in map then update max distance ; return the answer ; given array arr [ ] ; 
def maxDistance(arr, K):
    map = {}
    maxDist = 0
    for i in range(len(arr)):
        if not arr[i] in map:
            map[arr[i]] = i
        if arr[i] + K in map:
            maxDist = max(maxDist, i - map[arr[i] + K])
        if arr[i] - K in map:
            maxDist = max(maxDist, i - map[arr[i] - K])
    if maxDist == 0:
        return -1
    else:
        return maxDist


arr = [11, 2, 3, 8, 5, 2]
K = 2
print(maxDistance(arr, K))

# Expected output:
2
# count of ordered pairs ( x , y ) satisfying the equation 1 / x + 1 / y = 1 / n | function to find number of ordered positive integer pairs ( x , y ) such that they satisfy the equation ; initialize answer variable ; iterate over all possible values of y ; for valid x and y , ( n * n ) % ( y - n ) has to be 0 ; increment count of ordered pairs ; print the answer ; 
def solve(n):
    ans = 0
    y = n + 1
    while (y <= n * n + n):
        if ((n * n) % (y - n) == 0):
            ans += 1
        y += 1
    print(ans)


n = 5
solve(n)

# Expected output:
3