giulio98/xlcost-single-prompt huggingface dataset:
# minimum number of edges that need to be added to form a triangle | function to return the minimum number of edges that need to be added to the given graph such that it contains at least one triangle ; adj is the adjacency matrix such that adj [ i ] [ j ] = 1 when there is an edge between i and j ; as the graph is undirected so there will be an edge between ( i , j ) and ( j , i ) ; to store the required count of edges ; for every possible vertex triplet ; if the vertices form a triangle ; if no edges are present ; if only 1 edge is required ; two edges are required ; 
def minEdges(v, n):
    adj = dict .fromkeys(range(n + 1))
    for i in range(n + 1):
        adj[i] = [0] * (n + 1)
    for i in range(len(v)):
        adj[v[i][0]][v[i][1]] = 1
        adj[v[i][1]][v[i][0]] = 1
    edgesNeeded = 3
    for i in range(1, n + 1):
        for j in range(i + 1, n + 1):
            for k in range(j + 1, n + 1):
                if (adj[i][j] and adj[j][k] and adj[k][i]):
                    return 0
                if (not (adj[i][j] or adj[j][k] or adj[k][i])):
                    edgesNeeded = min(edgesNeeded, 3)
                else:
                    if ((adj[i][j] and adj[j][k]) or (
                            adj[j][k] and adj[k][i]) or (adj[k][i] and adj[i][j])):
                        edgesNeeded = 1
                    else:
                        edgesNeeded = min(edgesNeeded, 2)
    return edgesNeeded


if __name__ == "__main__":
    n = 3
    v = [[1, 2], [1, 3]]
    print(minEdges(v, n))

# Expected output:
1
# length of the longest subsequence such that xor of adjacent elements is non | function to find the length of the longest subsequence such that the xor of adjacent elements in the subsequence must be non - decreasing ; computing xor of all the pairs of elements and store them along with the pair ( i , j ) ; sort all possible xor values ; initialize the dp array ; calculating the dp array for each possible position and calculating the max length that ends at a particular index ; taking maximum of all position ; 
def LongestXorSubsequence(arr, n):
    v = []
    for i in range(0, n):
        for j in range(i + 1, n):
            v .append([(arr[i] ^ arr[j]), (i, j)])
    v .sort()
    dp = [1 for x in range(88)]
    for a, b in v:
        dp[b[1]] = max(dp[b[1]], 1 + dp[b[0]])
    ans = 1
    for i in range(0, n):
        ans = max(ans, dp[i])
    return ans


arr = [2, 12, 6, 7, 13, 14, 8, 6]
n = len(arr)
print(LongestXorSubsequence(arr, n))

# Expected output:
5
# delete edge to minimize subtree sum difference | dfs method to traverse through edges , calculating subtree sum at each node and updating the difference between subtrees ; loop for all neighbors except parent and aggregate sum over all subtrees ; store sum in current node 's  subtree index ; at one side subtree sum is ' sum ' and other side subtree sum is ' totalsum ▁ - ▁ sum ' so their difference will be totalsum - 2 * sum , by which we 'll update res ; method returns minimum subtree sum difference ; calculating total sum of tree and initializing subtree sum 's  by vertex values ; filling edge data structure ; calling dfs method at node 0 , with parent as - 1 ; 
def dfs(u, parent, totalSum, edge, subtree, res):
    Sum = subtree[u]
    for i in range(len(edge[u])):
        v = edge[u][i]
        if (v != parent):
            dfs(v, u, totalSum, edge, subtree, res)
            Sum += subtree[v]
    subtree[u] = Sum
    if (u != 0 and abs(totalSum - 2 * Sum) < res[0]):
        res[0] = abs(totalSum - 2 * Sum)


def getMinSubtreeSumDifference(vertex, edges, N):
    totalSum = 0
    subtree = [None] * N
    for i in range(N):
        subtree[i] = vertex[i]
        totalSum += vertex[i]
    edge = [[]for i in range(N)]
    for i in range(N - 1):
        edge[edges[i][0]].append(edges[i][1])
        edge[edges[i][1]].append(edges[i][0])
    res = [999999999999]
    dfs(0, -1, totalSum, edge, subtree, res)
    return res[0]


if __name__ == '__main__':
    vertex = [4, 2, 1, 6, 3, 5, 2]
    edges = [[0, 1], [0, 2], [0, 3], [2, 4], [2, 5], [3, 6]]
    N = len(vertex)
    print(getMinSubtreeSumDifference(vertex, edges, N))

# Expected output:
5
# minimum operations required to make every element greater than or equal to k | function to calculate gcd of two numbers ; function to get minimum operation needed ; the priority queue holds a minimum element in the top position ; push value one by one from the given array ; store count of minimum operation needed ; all elements are now >= k ; it is impossible to make as there are no sufficient elements available ; take two smallest elements and replace them by their lcm first smallest element ; second smallest element ; increment the count ; 
def gcd(a, b):

    if (a == 0):
        return b
    return gcd(b % a, a)


def FindMinOperation(a, n, k):

    Q = []
    for i in range(0, n):
        Q.append(a[i])
    Q.sort()
    ans = 0
    while (True):
        if (Q[0] >= k):
            break
        if (len(Q) < 2):
            return -1
        x = Q[0]
        Q.pop(0)
        y = Q[0]
        Q.pop(0)
        z = (x * y) // gcd(x, y)
        Q.append(z)
        Q.sort()
        ans += 1

    return ans


a = [3, 5, 7, 6, 8]
k = 8
n = len(a)

print(FindMinOperation(a, n, k))

# Expected output:
2
# find the lexicographically smallest string which satisfies the given condition | function to return the required string ; first character will always be 'a ; to store the resultant string ; since length of the string should be greater than 0 and first element of array should be 1 ; check one by one all element of given prefix array ; if the difference between any two consecutive elements of the prefix array is greater than 1 then there will be no such string possible that satisfies the given array . also , string cannot have more than 26 distinct characters ; if difference is 0 then the ( i + 1 ) th character will be same as the ith character ; if difference is 1 then the ( i + 1 ) th character will be different from the ith character ; return the resultant string ; 
def smallestString(N, A):

    ch = 'a'
    S = ""
    if (N < 1 or A[0] != 1):
        S = "-1"
        return S
    S += str(ch)
    ch = chr(ord(ch) + 1)
    for i in range(1, N):
        diff = A[i] - A[i - 1]
        if (diff > 1 or diff < 0 or A[i] > 26):
            S = "-1"
            return S
        elif (diff == 0):
            S += 'a'
        else:
            S += ch
            ch = chr(ord(ch) + 1)
    return S


arr = [1, 1, 2, 3, 3]
n = len(arr)
print(smallestString(n, arr))

# Expected output:
aabca
# count of alphabets whose ascii values can be formed with the digits of n | python3 implementation of the approach ; function that returns true if num can be formed with the digits in digits [ ] array ; copy of the digits array ; get last digit ; if digit array doesn 't contain  current digit ; one occurrence is used ; remove the last digit ; function to return the count of required alphabets ; to store the occurrences of digits ( 0 - 9 ) ; get last digit ; update the occurrence of the digit ; remove the last digit ; if any lowercase character can be picked from the current digits ; if any uppercase character can be picked from the current digits ; return the required count of alphabets ; 

import math


def canBePicked(digits, num):
    copyDigits = []
    for i in range(len(digits)):
        copyDigits .append(digits[i])
    while (num > 0):
        digit = num % 10
        if (copyDigits[digit] == 0):
            return False
        else:
            copyDigits[digit] -= 1
        num = math .floor(num / 10)
    return True


def countAlphabets(n):
    count = 0
    digits = [0] * 10
    while (n > 0):
        digit = n % 10
        digits[digit] += 1
        n = math .floor(n / 10)
    for i in range(ord('a'), ord('z') + 1):
        if (canBePicked(digits, i)):
            count += 1
    for i in range(ord('A'), ord('Z') + 1):
        if (canBePicked(digits, i)):
            count += 1
    return count


n = 1623455078
print(countAlphabets(n))

# Expected output:
27
# largest number less than x having at most k set bits | function to return the greatest number <= x having at most k set bits . ; remove rightmost set bits one by one until we count becomes k ; return the required number ; 
def greatestKBits(X, K):
    set_bit_count = bin(X).count('1')
    if (set_bit_count <= K):
        return X
    diff = set_bit_count - K
    for i in range(0, diff, 1):
        X &= (X - 1)
    return X


if __name__ == '__main__':
    X = 21
    K = 2
    print(greatestKBits(X, K))

# Expected output:
20
# find the minimum number of moves needed to move from one cell of matrix to another | python3 program to find the minimum numbers of moves needed to move from source to destination . ; add edge to graph ; level bfs function to find minimum path from source to sink ; base case ; make initial distance of all vertex - 1 from source ; create a queue for bfs ; mark the source node level [ s ] = '0 ; it will be used to get all adjacent vertices of a vertex ; dequeue a vertex from queue ; get all adjacent vertices of the dequeued vertex s . if a adjacent has not been visited ( level [ i ] < '0' ) , then update level [ i ] = = parent_level [ s ] + 1 and enqueue it ; else , continue to do bfs ; return minimum moves from source to sink ; returns minimum numbers of moves from a source ( a cell with value 1 ) to a destination ( a cell with value 2 ) ;  ; create graph with n * n node each cell consider as node number of current vertex ; connect all 4 adjacent cell to current cell ; source index ; destination index ; find minimum moves ; 

class Graph:
    def __init__(self, V):
        self .V = V
        self .adj = [[]for i in range(V)]

    def addEdge(self, s, d):
        self .adj[s].append(d)
        self .adj[d].append(s)

    def BFS(self, s, d):
        if (s == d):
            return 0
        level = [-1] * self .V
        queue = []
        level[s] = 0
        queue .append(s)
        while (len(queue) != 0):
            s = queue .pop()
            i = 0
            while i < len(self .adj[s]):
                if (level[self .adj[s][i]] <
                        0 or level[self .adj[s][i]] > level[s] + 1):
                    level[self .adj[s][i]] = level[s] + 1
                    queue .append(self .adj[s][i])
                i += 1
        return level[d]


def isSafe(i, j, M):
    global N
    if ((i < 0 or i >= N) or (j < 0 or j >= N) or M[i][j] == 0):
        return False
    return True


def MinimumPath(M):
    global N
    s, d = None, None
    V = N * N + 2
    g = Graph(V)
    k = 1
    for i in range(N):
        for j in range(N):
            if (M[i][j] != 0):
                if (isSafe(i, j + 1, M)):
                    g .addEdge(k, k + 1)
                if (isSafe(i, j - 1, M)):
                    g .addEdge(k, k - 1)
                if (j < N - 1 and isSafe(i + 1, j, M)):
                    g .addEdge(k, k + N)
                if (i > 0 and isSafe(i - 1, j, M)):
                    g .addEdge(k, k - N)
            if (M[i][j] == 1):
                s = k
            if (M[i][j] == 2):
                d = k
            k += 1
    return g .BFS(s, d)


N = 4
M = [[3, 3, 1, 0], [3, 0, 3, 3], [2, 3, 0, 3], [0, 3, 3, 3]]
print(MinimumPath(M))

# Expected output:
4
# find two numbers whose sum and gcd are given | python 3 program to find two numbers whose sum and gcd is given ; function to find two numbers whose sum and gcd is given ; sum != gcd checks that both the numbers are positive or not ; 

from math import gcd as __gcd


def findTwoNumbers(sum, gcd):
    if (__gcd(gcd, sum - gcd) == gcd and sum != gcd):
        print("a =", min(gcd, sum - gcd), ", b =", sum - min(gcd, sum - gcd))
    else:
        print(-1)


if __name__ == '__main__':
    sum = 8
    gcd = 2
    findTwoNumbers(sum, gcd)

# Expected output:
a = 2 , b = 6
# find maximum distance between any city and station | function to calculate the maximum distance between any city and its nearest station ; 
def findMaxDistance(numOfCities, station):
    hasStation = [False] * numOfCities
    for city in station:
        hasStation[city] = True
    dist, maxDist = 0, min(station)
    for city in range(numOfCities):
        if hasStation[city]:
            maxDist = max((dist + 1) // 2, maxDist)
            dist = 0
        else:
            dist += 1
    return max(maxDist, dist)


numOfCities = 6
station = [3, 1]
print("Max Distance:", findMaxDistance(numOfCities, station))

# Expected output:
Max Distance: 2
# split the number into n parts such that difference between the smallest and the largest part is minimum | function that prints the required sequence ; if we cannot split the number into exactly ' n ' parts ; if x % n == 0 then the minimum difference is 0 and all numbers are x / n ; upto n - ( x % n ) the values will be x / n after that the values will be x / n + 1 ; 
def split(x, n):
    if (x < n):
        print(-1)
    elif (x % n == 0):
        for i in range(n):
            print(x // n, end=" ")
    else:
        zp = n - (x % n)
        pp = x // n
        for i in range(n):
            if (i >= zp):
                print(pp + 1, end=" ")
            else:
                print(pp, end=" ")


x = 5
n = 3
split(x, n)

# Expected output:
1 2 2
# minimum time to reach a point with + t and | returns the minimum time required to reach 'x ; stores the minimum time ; increment ' t ' by 1 ; update the sum ; 
def cal_minimum_time(X):
    t = 0
    sum = 0
    while (sum < X):
        t = t+1
        sum = sum+t
    return t


if __name__ == '__main__':
    n = 6
    ans = cal_minimum_time(n)
    print("The minimum time required is :", ans)

# Expected output:
The minimum time required is : 3
# sum of minimum difference between consecutive elements of an array | utility pair ; function to find minimum sum of difference of consecutive element ; ul to store upper limit ll to store lower limit ; storethe lower range in ll and upper range in ul ; 

class pair:
    first = 0
    second = 0

    def __init__(self, a, b):
        self .first = a
        self .second = b


def solve(v, n):
    ans = 0
    ul = 0
    ll = 0
    ll = v[0].first
    ul = v[0].second
    ans = 0
    for i in range(1, n):
        if (v[i].first <= ul and v[i].first >= ll) or (
                v[i].second >= ll and v[i].second <= ul):
            if v[i].first > ll:
                ll = v[i].first
            if v[i].second < ul:
                ul = v[i].second
        elif v[i].first > ul:
            ans += abs(ul - v[i].first)
            ul = v[i].first
            ll = v[i].first
        elif v[i].second < ll:
            ans += abs(ll - v[i].second)
            ul = v[i].second
            ll = v[i].second
    return ans


v = [pair(1, 3), pair(2, 5), pair(6, 8), pair(1, 2), pair(2, 3)]
n = len(v)
print(solve(v, n))

# Expected output:
7
# find the largest cube formed by deleting minimum digits from a number | python3 code to implement maximum perfect cube formed after deleting minimum digits ; returns vector of pre processed perfect cubes ; convert the cube to string and push into preprocessedcubes vector ; utility function for findlargestcube ( ) . returns the largest cube number that can be formed ; reverse the preprocessed cubes so that we have the largest cube in the beginning of the vector ; iterate over all cubes ; check if the current digit of the cube matches with that of the number num ; if control reaches here , the its not possible to form a perfect cube ; wrapper for findlargestcubeutil ( ) ; pre process perfect cubes ; convert number n to string ; 

import math as mt


def preProcess(n):
    preProcessedCubes = list()
    for i in range(1, mt .ceil(n ** (1. / 3.))):
        iThCube = i ** 3
        cubeString = str(iThCube)
        preProcessedCubes .append(cubeString)
    return preProcessedCubes


def findLargestCubeUtil(num, preProcessedCubes):
    preProcessedCubes = preProcessedCubes[::-1]
    totalCubes = len(preProcessedCubes)
    for i in range(totalCubes):
        currCube = preProcessedCubes[i]
        digitsInCube = len(currCube)
        index = 0
        digitsInNumber = len(num)
        for j in range(digitsInNumber):
            if (num[j] == currCube[index]):
                index += 1
            if (digitsInCube == index):
                return currCube
    return "Not Possible"


def findLargestCube(n):
    preProcessedCubes = preProcess(n)
    num = str(n)
    ans = findLargestCubeUtil(num, preProcessedCubes)
    print("Largest Cube that can be formed from", n, "is", ans)


n = 4125
findLargestCube(n)
n = 876
findLargestCube(n)

# Expected output:
Largest Cube that can be formed from 4125 is 125
Largest Cube that can be formed from 876 is 8
# water connection problem | number of houses and number of pipes ; array rd stores the ending vertex of pipe ; array wd stores the value of diameters between two pipes ; array cd stores the starting end of pipe ; list a , b , c are used to store the final output ; function performing calculations . ; if a pipe has no ending vertex but has starting vertex i . e is an outgoing pipe then we need to start dfs with this vertex . ; we put the details of component in final output array ; 

n = 0
p = 0
rd = [0] * 1100
wt = [0] * 1100
cd = [0] * 1100
a = []
b = []
c = []
ans = 0


def dfs(w):
    global ans
    if (cd[w] == 0):
        return w
    if (wt[w] < ans):
        ans = wt[w]
    return dfs(cd[w])


def solve(arr):
    global ans
    i = 0
    while (i < p):
        q = arr[i][0]
        h = arr[i][1]
        t = arr[i][2]
        cd[q] = h
        wt[q] = t
        rd[h] = q
        i += 1
    a = []
    b = []
    c = []
    for j in range(1, n + 1):
        if (rd[j] == 0 and cd[j]):
            ans = 1000000000
            w = dfs(j)
            a .append(j)
            b .append(w)
            c .append(ans)
    print(len(a))
    for j in range(len(a)):
        print(a[j], b[j], c[j])


n = 9
p = 6
arr = [[7, 4, 98], [5, 9, 72], [4, 6, 10], [2, 8, 22], [9, 7, 17], [3, 1, 66]]
solve(arr)

# Expected output:
3
2 8 22
3 1 66
5 6 10
# print a closest string that does not contain adjacent duplicates | function to print simple string ; if any two adjacent characters are equal ; initialize it to ' a ' ; traverse the loop until it is different from the left and right letter . ; 
def noAdjacentDup(s):
    n = len(s)
    for i in range(1, n):
        if (s[i] == s[i - 1]):
            s[i] = "a"
            while (s[i] == s[i - 1] or (i + 1 < n and s[i] == s[i + 1])):
                s[i] += 1
            i += 1
    return s


s = list("geeksforgeeks")
print("".join(noAdjacentDup(s)))

# Expected output:
geaksforgeaks
# array element moved by k using single moves | python3 code to find winner of game ; if the number of steps is more then n - 1 ; initially the best is 0 and no of wins is 0. ; traverse through all the numbers ; if the value of array is more then that of previous best ; best is replaced by a [ i ] ; if not the first index ; no of wins is 1 now ; if any position has more then k wins then return ; maximum element will be winner because we move smaller element at end and repeat the process . ; 
def winner(a, n, k):
    if k >= n - 1:
        return n
    best = 0
    times = 0
    for i in range(n):
        if a[i] > best:
            best = a[i]
            if i:
                times = 1
        else:
            if times >= k:
                return best
    return best


a = [2, 1, 3, 4, 5]
n = len(a)
k = 2
print(winner(a, n, k))

# Expected output:
5
# paper cut into minimum number of squares | returns min number of squares needed ; swap if a is small size side . ; iterate until small size side is greater then 0 ; update result ; 
def minimumSquare(a, b):
    result = 0
    rem = 0
    if (a < b):
        a, b = b, a
    while (b > 0):
        result += int(a / b)
        rem = int(a % b)
        a = b
        b = rem
    return result


n = 13
m = 29
print(minimumSquare(n, m))

# Expected output:
9
# count of non decreasing arrays with ith element in range [ a [ i ] , b [ i ] ] | function to count the total number of possible valid arrays ; make a 2d dp table ; make a 2d prefix sum table ;  ; base case ; initialize the prefix values ; iterate over the range and update the dp table accordingly ; add the dp values to the prefix sum ; update the prefix sum table ; find the result count of arrays formed ; return the total count of arrays ; 
def totalValidArrays(a, b, N):
    dp = [[0 for _ in range(b[N - 1] + 1)]for _ in range(N + 1)]
    pref = [[0 for _ in range(b[N - 1] + 1)]for _ in range(N + 1)]
    dp[0][0] = 1
    for i in range(0, b[N - 1] + 1):
        pref[0][i] = 1
    for i in range(1, N + 1):
        for j in range(a[i - 1], b[i - 1]+1):
            dp[i][j] += pref[i - 1][j]
            pref[i][j] += dp[i][j]
        for j in range(0, b[N - 1] + 1):
            if (j > 0):
                pref[i][j] += pref[i][j - 1]
    ans = 0
    for i in range(a[N - 1], b[N - 1]+1):
        ans += dp[N][i]
    return ans


if __name__ == "__main__":
    A = [1, 1]
    B = [2, 3]
    N = len(A)
    print(totalValidArrays(A, B, N))

# Expected output:
5
# count of integers in range [ l , r ] having even frequency of each digit | stores the upper limit of the range ; stores the overlapping states ; recursive function to calculate the count of valid integers in the range [ 1 , s ] using memoization ; base case ; if current integer has even count of digits and is not repeated ; if current state is already considered ; stores the maximum valid digit at the current index ; stores the count of valid integers ; if the current digit is not the most significant digit , i . e , the integer is already started ; iterate through all valid digits ; recursive call for ith digit at the current index ; recursive call for integers having leading zeroes in the beginning ; iterate through all valid digits as most significant digits ; recursive call for ith digit at the current index ; return answer ; function to calculate valid number in the range [ 1 , x ] ; initialize dp array with - 1 ; store the range in form of string ; return count ; function to find the count of integers in the range [ l , r ] such that the frequency of each digit is even ; 

s = ""
dp = [[[[0 for _ in range(2)]for _ in range(2)]
       for _ in range(10)]for _ in range(1024)]


def calcCnt(mask, sz, smaller, started):
    if (sz == len(s)):
        return (mask == 0 and started)
    if (dp[mask][sz][smaller][started] != -1):
        return dp[mask][sz][smaller][started]
    mx = 9
    if (not smaller):
        mx = ord(s[sz]) - ord('0')
    ans = 0
    if (started):
        for i in range(0, mx + 1):
            ans += calcCnt(mask ^ (1 << i), sz + 1,
                           smaller or (i < ord(s[sz]) - ord('0')), 1)
    else:
        ans = calcCnt(mask, sz + 1, 1, 0)
        for i in range(1, mx + 1):
            ans += calcCnt(mask ^ (1 << i), sz + 1,
                           smaller or (i < ord(s[sz]) - ord('0')), 1)
    dp[mask][sz][smaller][started] = ans
    return dp[mask][sz][smaller][started]


def countInt(x):
    global dp
    dp = [[[[-1 for _ in range(2)]for _ in range(2)]
           for _ in range(10)]for _ in range(1024)]
    global s
    s = str(x)
    return calcCnt(0, 0, 0, 0)


def countIntInRange(L, R):
    return countInt(R) - countInt(L - 1)


if __name__ == "__main__":
    L = 32
    R = 1010
    print(countIntInRange(L, R))

# Expected output:
9