giulio98/xlcost-single-prompt huggingface dataset:
# spanning tree with maximum degree ( using kruskal 's algorithm) | python3 implementation of the approach ; par and rank will store the parent and rank of particular node in the union find algorithm ; find function of union find algorithm ; union function of union find algorithm ; function to find the required spanning tree ; initialising parent of a node by itself ; variable to store the node with maximum degree ; finding the node with maximum degree ; union of all edges incident on vertex with maximum degree ; carrying out normal kruskal algorithm ; 

from typing import List
par = []
rnk = []


def find(x: int) -> int:
    global par
    if (par[x] != x):
        par[x] = find(par[x])
    return par[x]


def Union(u: int, v: int) -> None:
    global par, rnk
    x = find(u)
    y = find(v)
    if (x == y):
        return
    if (rnk[x] > rnk[y]):
        par[y] = x
    elif (rnk[x] < rnk[y]):
        par[x] = y
    else:
        par[x] = y
        rnk[y] += 1


def findSpanningTree(deg: List[int], n: int, m: int,
                     g: List[List[int]]) -> None:
    global rnk, par
    par = [i for i in range(n + 1)]
    rnk = [0] * (n + 1)
    max = 1
    for i in range(2, n + 1):
        if (deg[i] > deg[max]):
            max = i
    for v in g[max]:
        print("{} {}".format(max, v))
        Union(max, v)
    for u in range(1, n + 1):
        for v in g[u]:
            x = find(u)
            y = find(v)
            if (x == y):
                continue
            Union(x, y)
            print("{} {}".format(u, v))


if __name__ == "__main__":
    n = 5
    m = 5
    g = [[]for _ in range(n + 1)]
    deg = [0] * (n + 1)
    g[1].append(2)
    g[2].append(1)
    deg[1] += 1
    deg[2] += 1
    g[1].append(5)
    g[5].append(1)
    deg[1] += 1
    deg[5] += 1
    g[2].append(3)
    g[3].append(2)
    deg[2] += 1
    deg[3] += 1
    g[5].append(3)
    g[3].append(5)
    deg[3] += 1
    deg[5] += 1
    g[3].append(4)
    g[4].append(3)
    deg[3] += 1
    deg[4] += 1
    findSpanningTree(deg, n, m, g)

# Expected output:
3 2
3 5
3 4
1 2
# given count of digits 1 , 2 , 3 , 4 , find the maximum sum possible | function to find the maximum possible sum ; to store required sum ; number of 234 's can be formed ; sum obtained with 234 s ; remaining 2 's ; sum obtained with 12 s ; return the required sum ; 
def Maxsum(c1, c2, c3, c4):
    sum = 0
    two34 = min(c2, min(c3, c4))
    sum = two34 * 234
    c2 -= two34
    sum += min(c2, c1) * 12
    return sum


c1 = 5
c2 = 2
c3 = 3
c4 = 4
print(Maxsum(c1, c2, c3, c4))

# Expected output:
468
# count of pairs from 1 to a and 1 to b whose sum is divisible by n | function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; pairs from 1 to n * ( a / n ) and 1 to n * ( b / n ) ; pairs from 1 to n * ( a / n ) and n * ( b / n ) to b ; pairs from n * ( a / n ) to a and 1 to n * ( b / n ) ; pairs from n * ( a / n ) to a and n * ( b / n ) to b ; return answer ; 
def findCountOfPairs(a, b, n):
    ans = 0
    ans += n * int(a / n) * int(b / n)
    ans += int(a / n) * (b % n)
    ans += (a % n) * int(b / n)
    ans += int(((a % n) + (b % n)) / n)
    return ans


if __name__ == '__main__':
    a = 5
    b = 13
    n = 3
    print(findCountOfPairs(a, b, n))

# Expected output:
22
# generate array with minimum sum which can be deleted in p steps | function to find the required array ; calculating minimum possible sum ; array ; place first p natural elements ; fill rest of the elements with 1 ; 
def findArray(N, P):
    ans = (P * (P + 1)) // 2 + (N - P)
    arr = [0] * (N + 1)
    for i in range(1, P + 1):
        arr[i] = i
    for i in range(P + 1, N + 1):
        arr[i] = 1
    print("The Minimum Possible Sum is: ", ans)
    print("The Array Elements are: ")
    for i in range(1, N + 1):
        print(arr[i], end=" ")


N = 5
P = 3
findArray(N, P)

# Expected output:
The Minimum Possible Sum is:  8
The Array Elements are: 
1 2 3 1 1
# find intersection of all intervals | function to print the intersection ; first interval ; check rest of the intervals and find the intersection ; if no intersection exists ; else update the intersection ; 
def findIntersection(intervals, N):
    l = intervals[0][0]
    r = intervals[0][1]
    for i in range(1, N):
        if (intervals[i][0] > r or intervals[i][1] < l):
            print(-1)
        else:
            l = max(l, intervals[i][0])
            r = min(r, intervals[i][1])
    print("[", l, ", ", r, "]")


intervals = [[1, 6], [2, 8], [3, 10], [5, 8]]
N = len(intervals)
findIntersection(intervals, N)

# Expected output:
[ 5 ,  6 ]
# maximum size of sub | function that compares a and b ; function to return length of longest subarray that satisfies one of the given conditions ; 
def cmp(a, b):
    return (a > b) - (a < b)


def maxSubarraySize(arr):
    N = len(arr)
    ans = 1
    anchor = 0
    for i in range(1, N):
        c = cmp(arr[i - 1], arr[i])
        if c == 0:
            anchor = i
        elif i == N - 1 or c * cmp(arr[i], arr[i + 1]) != -1:
            ans = max(ans, i - anchor + 1)
            anchor = i
    return ans


arr = [9, 4, 2, 10, 7, 8, 8, 1, 9]
print(maxSubarraySize(arr))

# Expected output:
5
# maximum count of sub | function to return the count of the required sub - strings ; iterate over all characters ; count with current character ; if the substring has a length k then increment count with current character ; update max count ; 
def maxSubStrings(s, k):
    maxSubStr = 0
    n = len(s)
    for c in range(27):
        ch = chr(ord('a') + c)
        curr = 0
        for i in range(n - k):
            if (s[i] != ch):
                continue
            cnt = 0
            while (i < n and s[i] == ch and cnt != k):
                i += 1
                cnt += 1
            i -= 1
            if (cnt == k):
                curr += 1
        maxSubStr = max(maxSubStr, curr)
    return maxSubStr


if __name__ == '__main__':
    s = "aaacaabbaa"
    k = 2
    print(maxSubStrings(s, k))

# Expected output:
3
# count valid pairs in the array satisfying given conditions | function to return total valid pairs ; initialize count of all the elements ; frequency count of all the elements ; add total valid pairs ; exclude pairs made with a single element i . e . ( x , x ) ; 
def ValidPairs(arr):
    count = [0] * 121
    for ele in arr:
        count[ele] += 1
    ans = 0
    for eleX, countX in enumerate(count):
        for eleY, countY in enumerate(count):
            if eleX < eleY:
                continue
            if (abs(eleX - eleY) % 2 == 1):
                continue
            ans += countX * countY
            if eleX == eleY:
                ans -= countX
    return ans


arr = [16, 17, 18]
print(ValidPairs(arr))

# Expected output:
1
# distribution of candies according to ages of students | function to check the validity of distribution ; stroring the max age of all students + 1 ; stroring the max candy + 1 ; creating the frequency array of the age of students ; creating the frequency array of the packets of candies ; pointer to tell whether we have reached the end of candy frequency array ; flag to tell if distribution is possible or not ; flag to tell if we can choose some candy packets for the students with age j ; if the quantity of packets is greater than or equal to the number of students of age j , then we can choose these packets for the students ; start searching from k + 1 in next operation ; if we cannot choose any packets then the answer is no ; 
def check_distribution(n, k, age, candy):
    mxage = max(age) + 1
    mxcandy = max(candy) + 1
    fr1 = [0] * mxage
    fr2 = [0] * mxcandy
    for j in range(n):
        fr1[age[j]] += 1
    for j in range(k):
        fr2[candy[j]] += 1
    k = 0
    Tf = True
    for j in range(mxage):
        if (fr1[j] == 0):
            continue
        flag = False
        while (k < mxcandy):
            if (fr1[j] <= fr2[k]):
                flag = True
                break
            k += 1
        k = k + 1
        if (flag == False):
            Tf = False
            break
    if (Tf):
        print("YES")
    else:
        print("NO")


age = [5, 15, 10]
candy = [2, 2, 2, 3, 3, 4]
n = len(age)
k = len(candy)
check_distribution(n, k, age, candy)

# Expected output:
YES
# minimum number of 1 's to be replaced in a binary array | function to find minimum number of 1 ' s ▁ to ▁ be ▁ replaced ▁ to ▁ 0' s ; return final answer ; 
def minChanges(A, n):
    cnt = 0
    for i in range(n - 2):
        if ((i - 1 >= 0) and A[i - 1] == 1 and A[i + 1] == 1 and A[i] == 0):
            A[i + 1] = 0
            cnt = cnt + 1
    return cnt


A = [1, 1, 0, 1, 1, 0, 1, 0, 1, 0]
n = len(A)
print(minChanges(A, n))

# Expected output:
2
# number of closing brackets needed to complete a regular bracket sequence | function to find number of closing brackets and complete a regular bracket sequence ; finding the length of sequence ; counting opening brackets ; counting closing brackets ; checking if at any position the number of closing bracket is more then answer is impossible ; if possible , print ' s ' and required closing brackets . ; 
def completeSequence(s):
    n = len(s)
    open = 0
    close = 0
    for i in range(n):
        if (s[i] == '('):
            open += 1
        else:
            close += 1
        if (close > open):
            print("IMPOSSIBLE")
            return
    print(s, end="")
    for i in range(open - close):
        print(")", end="")


if __name__ == "__main__":
    s = "(()(()("
    completeSequence(s)

# Expected output:
(()(()()))
# lexicographically smallest permutation with no digits at original index | function to print the smallest permutation ; when n is even ; when n is odd ; handling last 3 digit ; add eol and print result ; 
def smallestPermute(n):
    res = [""] * (n + 1)
    if (n % 2 == 0):
        for i in range(n):
            if (i % 2 == 0):
                res[i] = chr(48 + i + 2)
            else:
                res[i] = chr(48 + i)
    else:
        for i in range(n - 2):
            if (i % 2 == 0):
                res[i] = chr(48 + i + 2)
            else:
                res[i] = chr(48 + i)
        res[n - 1] = chr(48 + n - 2)
        res[n - 2] = chr(48 + n)
        res[n - 3] = chr(48 + n - 1)
    res = ''.join(res)
    return res


if __name__ == "__main__":
    n = 7
    print(smallestPermute(n))

# Expected output:
2143675
# minimum array insertions required to make consecutive difference <= k | python3 implementation of above approach ; function to return minimum number of insertions required ; initialize insertions to 0 ; return total insertions ; 

import math


def minInsertions(H, n, K):
    inser = 0
    for i in range(1, n):
        diff = abs(H[i] - H[i - 1])
        if (diff <= K):
            continue
        else:
            inser += math .ceil(diff / K) - 1
    return inser


H = [2, 4, 8, 16]
K = 3
n = len(H)
print(minInsertions(H, n, K))

# Expected output:
3
# minimum number of operations required to reduce n to 1 | function that returns the minimum number of operations to be performed to reduce the number to 1 ; to stores the total number of operations to be performed ; if n is divisible by 3 then reduce it to n / 3 ; if n modulo 3 is 1 decrement it by 1 ; if n modulo 3 is 2 then increment it by 1 ; update the counter ; 
def count_minimum_operations(n):
    count = 0
    while (n > 1):
        if (n % 3 == 0):
            n //= 3
        elif (n % 3 == 1):
            n -= 1
        else:
            if (n == 2):
                n -= 1
            else:
                n += 1
        count += 1
    return count


if __name__ == "__main__":
    n = 4
    ans = count_minimum_operations(n)
    print(ans)

# Expected output:
2
# minimum number of operations required to reduce n to 1 | function that returns the minimum number of operations to be performed to reduce the number to 1 ; base cases ; 
def count_minimum_operations(n):
    if (n == 2):
        return 1
    elif (n == 1):
        return 0
    if (n % 3 == 0):
        return 1 + count_minimum_operations(n / 3)
    elif (n % 3 == 1):
        return 1 + count_minimum_operations(n - 1)
    else:
        return 1 + count_minimum_operations(n + 1)


n = 4
ans = count_minimum_operations(n)
print(ans)

# Expected output:
2
# maximize the sum of array by multiplying prefix of array with | python implementation of the approach ; to store sum ; to store ending indices of the chosen prefix arrays ; adding the absolute value of a [ i ] ; if i == 0 then there is no index to be flipped in ( i - 1 ) position ; print the maximised sum ; print the ending indices of the chosen prefix arrays ; 
def maxSum(arr, n):
    s = 0
    l = []
    for i in range(len(a)):
        s += abs(a[i])
        if (a[i] >= 0):
            continue
        if (i == 0):
            l .append(i + 1)
        else:
            l .append(i + 1)
            l .append(i)
    print(s)
    print(*l)


n = 4
a = [1, -2, -3, 4]
maxSum(a, n)

# Expected output:
10
2 1 3 2
# find the longest common prefix between two strings after performing swaps on second string | python program to find the longest common prefix between two strings after performing swaps on the second string ; a = len ( x ) length of x b = len ( y ) length of y ; creating frequency array of characters of y ; storing the length of longest common prefix ; checking if the frequency of the character at position i in x in b is greater than zero or not if zero we increase the prefix count by 1 ; 
def LengthLCP(x, y):
    fr = [0] * 26
    a = len(x)
    b = len(y)
    for i in range(b):
        fr[ord(y[i]) - 97] += 1
    c = 0
    for i in range(a):
        if (fr[ord(x[i]) - 97] > 0):
            c += 1
            fr[ord(x[i]) - 97] -= 1
        else:
            break
    print(c)


x, y = "here", "there"
LengthLCP(x, y)

# Expected output:
4
# all possible co | function to count possible pairs ; total count of numbers in range ; printing count of pairs ; 
def CountPair(L, R):
    x = (R - L + 1)
    print(x // 2)


if __name__ == '__main__':
    L, R = 1, 8
    CountPair(L, R)

# Expected output:
4
# problems not solved at the end of nth day | function to find problems not solved at the end of nth day ; 
def problemsLeft(K, P, N):
    if (K <= P):
        return 0
    else:
        return ((K - P) * N)


K, P, N = 4, 1, 10
print(problemsLeft(K, P, N))

# Expected output:
30
# kruskal 's algorithm (simple implementation for adjacency matrix) | find set of vertex i ; does union of i and j . it returns false if i and j are already in same set . ; finds mst using kruskal 's algorithm ; 
def find(i):
    while parent[i] != i:
        i = parent[i]
    return i


def union(i, j):
    a = find(i)
    b = find(j)
    parent[a] = b


def kruskalMST(cost):
    mincost = 0
    for i in range(V):
        parent[i] = i
    edge_count = 0
    while edge_count < V - 1:
        min = INF
        a = -1
        b = -1
        for i in range(V):
            for j in range(V):
                if find(i) != find(j) and cost[i][j] < min:
                    min = cost[i][j]
                    a = i
                    b = j
        union(a, b)
        print('Edge {}:({}, {}) cost:{}'.format(edge_count, a, b, min))
        edge_count += 1
        mincost += min
    print("Minimum cost= {}".format(mincost))


V = 5
parent = [i for i in range(V)]
INF = float('inf')
cost = [[INF, 2, INF, 6, INF], [2, INF, 3, 8, 5], [
    INF, 3, INF, INF, 7], [6, 8, INF, INF, 9], [INF, 5, 7, 9, INF]]
kruskalMST(cost)

# Expected output:
Edge 0:(0, 1) cost:2
Edge 1:(1, 2) cost:3
Edge 2:(1, 4) cost:5
Edge 3:(0, 3) cost:6
Minimum cost= 16
# number of chocolates left after k iterations | function to find the chocolates left ; 
def results(n, k):
    return round(pow(n, (1.0 / pow(2, k))))


k = 3
n = 100000000
print("Chocolates left after"),
print(k),
print("iterations are"),
print(int(results(n, k)))

# Expected output:
Chocolates left after
3
iterations are
10
# subarray whose absolute sum is closest to k | python code to find sub - array whose sum shows the minimum deviation ; starting index , ending index , deviation ; iterate i and j to get all subarrays ; found sub - array with less sum ; exactly same sum ; 
def getSubArray(arr, n, K):
    i = -1
    j = -1
    currSum = 0
    result = [i, j, abs(K - abs(currSum))]
    for i in range(0, n):
        currSum = 0
        for j in range(i, n):
            currSum += arr[j]
            currDev = abs(K - abs(currSum))
            if (currDev < result[2]):
                result = [i, j, currDev]
            if (currDev == 0):
                return result
    return result


def main():
    arr = [15, -3, 5, 2, 7, 6, 34, -6]
    n = len(arr)
    K = 50
    [i, j, minDev] = getSubArray(arr, n, K)
    if (i == -1):
        print("The empty array shows minimum Deviation")
        return 0
    for i in range(i, j + 1):
        print(arr[i],)


main()

# Expected output:
-3
5
2
7
6
34
# longest subsequence whose average is less than k | python3 program to perform q queries to find longest subsequence whose average is less than k ; function to print the length for evey query ; sort array of n elements ; array to store average from left ; sort array of average ; number of queries ; print answer to every query using binary search ; 

import bisect


def longestSubsequence(a, n, q, m):
    a .sort()
    Sum = 0
    b = [None] * n
    for i in range(0, n):
        Sum += a[i]
        av = Sum // (i + 1)
        b[i] = av + 1
    b .sort()
    for i in range(0, m):
        k = q[i]
        longest = bisect .bisect_right(b, k)
        print("Answer to Query", i + 1, ":", longest)


if __name__ == "__main__":
    a = [1, 3, 2, 5, 4]
    n = len(a)
    q = [4, 2, 1, 5]
    m = len(q)
    longestSubsequence(a, n, q, m)

# Expected output:
Answer to Query 1 : 5
Answer to Query 2 : 2
Answer to Query 3 : 0
Answer to Query 4 : 5
# make array elements equal in minimum steps | returns the minimum steps required to make an array of n elements equal , where the first array element equals m ; corner case 1 : when n = 1 ; corner case 2 : when n = 2 ; 
def steps(N, M):
    if (N == 1):
        return 0
    elif (N == 2):
        return M
    return 2 * M + (N - 3)


N = 4
M = 4
print(steps(N, M))

# Expected output:
9
# minimum increment / decrement to make array non | python3 code to count the change required to convert the array into non - increasing array ; min heap ; here in the loop we will check that whether the upcoming element of array is less than top of priority queue . if yes then we calculate the difference . after that we will remove that element and push the current element in queue . and the sum is incremented by the value of difference ; 

from queue import PriorityQueue


def DecreasingArray(a, n):
    ss, dif = (0, 0)
    pq = PriorityQueue()
    for i in range(n):
        tmp = 0
        if not pq .empty():
            tmp = pq .get()
            pq .put(tmp)
        if not pq .empty() and tmp < a[i]:
            dif = a[i] - tmp
            ss += dif
            pq .get()
        pq .put(a[i])
    return ss


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

# Expected output:
1
# schedule jobs so that each server gets equal load | function to find new array a ; find sum s of both arrays a and b . ; single element case . ; this checks whether sum s can be divided equally between all array elements . i . e . whether all elements can take equal value or not . ; compute possible value of new array elements . ; possibility 1 ; ensuring that all elements of array b are used . ; if a ( i ) already updated to x move to next element in array a . ; possibility 2 ; possibility 3 ; possibility 4 ; if a ( i ) can not be made equal to x even after adding all possible elements from b ( i ) then print - 1. ; check whether all elements of b are used . ; return the new array element value . ; 
def solve(a, b, n):
    s = 0
    for i in range(0, n):
        s += a[i] + b[i]
    if n == 1:
        return a[0] + b[0]
    if s % n != 0:
        return -1
    x = s // n
    for i in range(0, n):
        if a[i] > x:
            return -1
        if i > 0:
            a[i] += b[i - 1]
            b[i - 1] = 0
        if a[i] == x:
            continue
        y = a[i] + b[i]
        if i + 1 < n:
            y += b[i + 1]
        if y == x:
            a[i] = y
            b[i] = 0
            if i + 1 < n:
                b[i + 1] = 0
            continue
        if a[i] + b[i] == x:
            a[i] += b[i]
            b[i] = 0
            continue
        if i + 1 < n and a[i] + b[i + 1] == x:
            a[i] += b[i + 1]
            b[i + 1] = 0
            continue
        return -1
    for i in range(0, n):
        if b[i] != 0:
            return -1
    return x


if __name__ == "__main__":
    a = [6, 14, 21, 1]
    b = [15, 7, 10, 10]
    n = len(a)
    print(solve(a, b, n))

# Expected output:
21
# check if it is possible to survive on island | function to find the minimum days ; if we can not buy at least a week supply of food during the first week or we can not buy a day supply of food on the first day then we can 't survive. ; if we can survive then we can buy ceil ( a / n ) times where a is total units of food required . ; 
def survival(S, N, M):
    if (((N * 6) < (M * 7) and S > 6) or M > N):
        print("No")
    else:
        days = (M * S) / N
        if (((M * S) % N) != 0):
            days += 1
        print("Yes "),
        print(days)


S = 10
N = 16
M = 2
survival(S, N, M)

# Expected output:
Yes 
2.25
# lexicographically largest subsequence such that every character occurs at least k times | find lexicographically largest subsequence of s [ 0. . n - 1 ] such that every character appears at least k times . the result is filled in t [ ] ; starting from largest charter ' z ' to 'a ; counting the frequency of the character ; if frequency is greater than k ; from the last point we leave ; check if string contain ch ; if yes , append to output string ; update the last point . ; 
def subsequence(s, t, n, k):
    last = 0
    cnt = 0
    new_last = 0
    size = 0
    string = 'zyxwvutsrqponmlkjihgfedcba'

    for ch in string:
        cnt = 0
        for i in range(last, n):
            if s[i] == ch:
                cnt += 1
        if cnt >= k:
            for i in range(last, n):
                if s[i] == ch:
                    t[size] = ch
                    new_last = i
                    size += 1
            last = new_last


if __name__ == "__main__":
    s = ['b', 'a', 'n', 'a', 'n', 'a']
    n = len(s)
    k = 2
    t = [''] * n
    subsequence(s, t, n - 1, k)
    t = ''.join(t)
    print(t)

# Expected output:
nn
# largest permutation after at most k swaps | function to find the largest permutation after k swaps ; storing the elements and their index in map ; if number of swaps allowed are equal to number of elements then the resulting permutation will be descending order of given permutation . ; if j is not at it 's best index ; change the index of the element which was at position 0. swap the element basically . ; decrement number of swaps ; 
def bestpermutation(arr, k, n):
    h = {}
    for i in range(n):
        h[arr[i]] = i
    if (n <= k):
        arr .sort()
        arr .reverse()
    else:
        for j in range(n, 0, -1):
            if (k > 0):
                initial_index = h[j]
                best_index = n - j
                if (initial_index != best_index):
                    h[j] = best_index
                    element = arr[best_index]
                    h[element] = initial_index
                    arr[best_index], arr[initial_index] = (
                        arr[initial_index], arr[best_index])
                    k -= 1


arr = [3, 1, 4, 2, 5]
k = 10
n = len(arr)
bestpermutation(arr, k, n)
print("Largest possible permutation after", k, "swaps is", end=" ")
for i in range(n):
    print(arr[i], end=" ")

# Expected output:
Largest possible permutation after 10 swaps is 5 4 3 2 1