giulio98/xlcost-single-prompt huggingface dataset:
# maximum of all distances to the nearest 1 cell from any 0 cell in a binary matrix | function to find the maximum distance ; set up top row and left column ; pass one : top left to bottom right ; check if there was no " one " cell ; set up top row and left column ; past two : bottom right to top left ; 
def maxDistance(grid):
    if (len(grid) == 0):
        return -1
    N = len(grid)
    INF = 1000000
    if grid[0][0] == 1:
        grid[0][0] = 0
    else:
        grid[0][0] = INF
    for i in range(1, N):
        if grid[0][i] == 1:
            grid[0][i] = 0
        else:
            grid[0][i] = grid[0][i - 1] + 1
    for i in range(1, N):
        if grid[i][0] == 1:
            grid[i][0] = 0
        else:
            grid[i][0] = grid[i - 1][0] + 1
    for i in range(1, N):
        for j in range(1, N):
            if grid[i][j] == 1:
                grid[i][j] = 0
            else:
                grid[i][j] = min(grid[i - 1][j], grid[i][j - 1] + 1)
    if (grid[N - 1][N - 1] >= INF):
        return -1
    maxi = grid[N - 1][N - 1]
    for i in range(N - 2, -1, -1):
        grid[N - 1][i] = min(grid[N - 1][i], grid[N - 1][i + 1] + 1)
        maxi = max(grid[N - 1][i], maxi)
    for i in range(N - 2, -1, -1):
        grid[i][N - 1] = min(grid[i][N - 1], grid[i + 1][N - 1] + 1)
        maxi = max(grid[i][N - 1], maxi + 1)
    for i in range(N - 2, -1, -1):
        for j in range(N - 2, -1, -1):
            grid[i][j] = min(grid[i][j], min(
                grid[i + 1][j] + 1, grid[i][j + 1] + 1))
            maxi = max(grid[i][j], maxi)
    if maxi == 0:
        return -1
    else:
        return maxi


arr = [[0, 0, 1], [0, 0, 0], [0, 0, 0]]
print(maxDistance(arr))

# Expected output:
4
# minimize total cost without repeating same task in two consecutive iterations | function to return the minimum cost for n iterations ; construct the dp table ; 1 st row of dp table will be equal to the 1 st of cost matrix ; iterate through all the rows ; to iterate through the columns of current row ; initialize val as infinity ; to iterate through the columns of previous row ; fill the dp matrix ; returning the minimum value ; 
def findCost(cost_mat, N, M):
    dp = [[0] * M for _ in range(M)]
    dp[0] = cost_mat[0]
    for row in range(1, N):
        for curr_col in range(M):
            val = 999999999
            for prev_col in range(M):
                if curr_col != prev_col:
                    val = min(val, dp[row - 1][prev_col])
            dp[row][curr_col] = val + cost_mat[row][curr_col]
    return min(dp[-1])


if __name__ == "__main__":
    N = 4
    M = 4
    cost_mat = [[4, 5, 3, 2], [6, 2, 8, 1], [6, 2, 2, 1], [0, 5, 5, 1]]
    print(findCost(cost_mat, N, M))

# Expected output:
5
# split the given string into primes : digit dp | function to precompute all the primes upto 1000000 and store it in a set using sieve of eratosthenes ; here str ( ) is used for converting int to string ; a function to find the minimum number of segments the given string can be divided such that every segment is a prime ; declare a splitdp [ ] array and initialize to - 1 ; call sieve function to store primes in primes array ; build the dp table in a bottom - up manner ; if the prefix is prime then the prefix will be found in the prime set ; if the given prefix can be split into primes then for the remaining string from i to j check if prime . if yes calculate the minimum split till j ; to check if the substring from i to j is a prime number or not ; if it is a prime , then update the dp array ; return the minimum number of splits for the entire string ; 
def getPrimesFromSeive(primes):
    prime = [True] * (1000001)
    prime[0], prime[1] = False, False
    i = 2
    while (i * i <= 1000000):
        if (prime[i]):
            for j in range(i * i, 1000001, i):
                prime[j] = False
        i += 1
    for i in range(2, 1000001):
        if (prime[i]):
            primes .append(str(i))


def splitIntoPrimes(number):
    numLen = len(number)
    splitDP = [-1] * (numLen + 1)
    primes = []
    getPrimesFromSeive(primes)
    for i in range(1, numLen + 1):
        if (i <= 6 and (number[0:i] in primes)):
            splitDP[i] = 1
        if (splitDP[i] != -1):
            j = 1
            while (j <= 6 and (i + j <= numLen)):
                if (number[i:i + j] in primes):
                    if (splitDP[i + j] == -1):
                        splitDP[i + j] = 1 + splitDP[i]
                    else:
                        splitDP[i + j] = min(splitDP[i + j], 1 + splitDP[i])
                j += 1
    return splitDP[numLen]


print(splitIntoPrimes("13499315"))
print(splitIntoPrimes("43"))

# Expected output:
3
1
# number of ways to convert a character x to a string y | python3 implementation of the approach ; function to find the modular - inverse ; while power > 1 ; updating s and a ; updating power ; return the final answer ; function to return the count of ways ; to store the final answer ; to store pre - computed factorials ; computing factorials ; loop to find the occurrences of x and update the ans ; multiplying the answer by ( n - 1 ) ! ; return the final answer ; 

MOD = 1000000007


def modInv(a, p=MOD - 2):
    s = 1
    while (p != 1):
        if (p % 2):
            s = (s * a) % MOD
        a = (a * a) % MOD
        p //= 2
    return (a * s) % MOD


def findCnt(x, y):
    ans = 0
    fact = [1] * (len(y) + 1)
    for i in range(1, len(y)):
        fact[i] = (fact[i - 1] * i) % MOD
    for i in range(len(y)):
        if (y[i] == x):
            ans += (modInv(fact[i]) * modInv(fact[len(y) - i - 1])) % MOD
            ans %= MOD
    ans *= fact[(len(y) - 1)]
    ans %= MOD
    return ans


if __name__ == "__main__":
    x = 'a'
    y = "xxayy"
    print(findCnt(x, y))

# Expected output:
6
# find the largest divisor subset in the array | function to find the required subsequence ; sort the array ; keep a count of the length of the subsequence and the previous element set the initial values ; maximum length of the subsequence and the last element ; run a loop for every element ; check for all the divisors ; if the element is a divisor and the length of subsequence will increase by adding j as previous element of i ; increase the count ; update the max count ; get the last index of the subsequence ; print the element ; move the index to the previous element ; 
def findSubSeq(arr, n):
    arr .sort()
    count = [1] * n
    prev = [-1] * n
    max = 0
    maxprev = -1
    for i in range(n):
        for j in range(i - 1, -1, -1):
            if (arr[i] % arr[j] == 0 and count[j] + 1 > count[i]):
                count[i] = count[j] + 1
                prev[i] = j
        if (max < count[i]):
            max = count[i]
            maxprev = i
    i = maxprev
    while (i >= 0):
        if (arr[i] != -1):
            print(arr[i], end=" ")
        i = prev[i]


if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5]
    n = len(arr)
    findSubSeq(arr, n)

# Expected output:
4 2 1
# minimum number of integers required such that each segment contains at least one of them | function to compute minimum number of points which cover all segments ; sort the list of tuples by their second element . ; to store the solution ; iterate over all the segments ; get the start point of next segment ; loop over all those segments whose start point is less than the end point of current segment ; print the possibles values of m ; 
def minPoints(points):
    points .sort(key=lambda x: x[1])
    coordinates = []
    i = 0
    while i < n:
        seg = points[i][1]
        coordinates .append(seg)
        p = i + 1
        if p >= n:
            break
        arrived = points[p][0]
        while seg >= arrived:
            p += 1
            if p >= n:
                break
            arrived = points[p][0]
        i = p
    for point in coordinates:
        print(point, end=" ")


n = 4
start = [4, 1, 2, 5]
end = [7, 3, 5, 6]
points = []
for i in range(n):
    tu = (start[i], end[i])
    points .append(tu)
minPoints(points)

# Expected output:
3 6
# optimally accommodate 0 s and 1 s from a binary string into k buckets | python3 implementation of the approach ; function to find the minimum required sum using dynamic programming ; dp [ i ] [ j ] = minimum val of accommodation till j 'th index of the string  using i+1 number of buckets.  final ans will be in dp[n-1][k-1]  initialise dp with all states as 0 ; corner cases ; filling first row , if only 1 bucket then simple count number of zeros and ones and do the multiplication ; if k = 0 then this arrangement is not possible ; if no arrangement is possible then our answer will remain int_max so return - 1 ; 

import sys


def solve(Str, K):
    n = len(Str)
    dp = [[0 for i in range(n)]for j in range(K)]
    if (n < K):
        return -1
    elif (n == K):
        return 0
    zeroes = 0
    ones = 0
    for i in range(n):
        if (Str[i] == '0'):
            zeroes += 1
        else:
            ones += 1
        dp[0][i] = ones * zeroes
    for s in range(1, K):
        for i in range(n):
            dp[s][i] = sys .maxsize
            ones = 0
            zeroes = 0
            for k in range(i, -1, -1):
                if (Str[k] == '0'):
                    zeroes += 1
                else:
                    ones += 1
                temp = 0
                if (k - 1 >= 0):
                    temp = ones * zeroes + dp[s - 1][k - 1]
                else:
                    temp = sys .maxsize
                dp[s][i] = min(dp[s][i], temp)
    if (dp[K - 1][n - 1] == sys .maxsize):
        return -1
    else:
        return dp[K - 1][n - 1]


S = "0101"
K = 2
print(solve(S, K))

# Expected output:
2
# largest subset of rectangles such that no rectangle fit in any other rectangle | recursive function to get the largest subset ; base case when it exceeds ; if the state has been visited previously ; initialize ; no elements in subset yet ; first state which includes current index ; second state which does not include current index ; if the rectangle fits in , then do not include the current index in subset ; first state which includes current index ; second state which does not include current index ; function to get the largest subset ; sort the array ; get the answer ; 
def findLongest(a, n, present, previous):
    if present == n:
        return 0
    elif previous != -1:
        if dp[present][previous] != -1:
            return dp[present][previous]
    ans = 0
    if previous == -1:
        ans = 1 + findLongest(a, n, present + 1, present)
        ans = max(ans, findLongest(a, n, present + 1, previous))
    else:
        h1 = a[previous][0]
        h2 = a[present][0]
        w1 = a[previous][1]
        w2 = a[present][1]
        if h1 <= h2 and w1 <= w2:
            ans = max(ans, findLongest(a, n, present + 1, previous))
        else:
            ans = 1 + findLongest(a, n, present + 1, present)
            ans = max(ans, findLongest(a, n, present + 1, previous))
    dp[present][previous] = ans
    return ans


def getLongest(a, n):
    a .sort()
    ans = findLongest(a, n, 0, -1)
    return ans


if __name__ == "__main__":
    a = [[1, 5], [2, 4], [1, 1], [3, 3]]
    N = 10
    dp = [[-1 for i in range(N)]for j in range(N)]
    n = len(a)
    print(getLongest(a, n))

# Expected output:
3
# number of ways to partition a string into two balanced subsequences | for maximum length of input string ; declaring the dp table ; function to calculate the number of valid assignments ; return 1 if both subsequences are balanced ; increment the count if it is an opening bracket ; decrement the count if it a closing bracket ; 

MAX = 10
F = [[[-1 for i in range(MAX)]for j in range(MAX)]for k in range(MAX)]


def noOfAssignments(S, n, i, c_x, c_y):
    if F[i][c_x][c_y] != -1:
        return F[i][c_x][c_y]
    if i == n:
        F[i][c_x][c_y] = not c_x and not c_y
        return F[i][c_x][c_y]
    if S[i] == '(':
        F[i][c_x][c_y] = noOfAssignments(
            S, n, i + 1, c_x + 1, c_y) + noOfAssignments(S, n, i + 1, c_x, c_y + 1)
        return F[i][c_x][c_y]
    F[i][c_x][c_y] = 0
    if c_x:
        F[i][c_x][c_y] += noOfAssignments(S, n, i + 1, c_x - 1, c_y)
    if c_y:
        F[i][c_x][c_y] += noOfAssignments(S, n, i + 1, c_x, c_y - 1)
    return F[i][c_x][c_y]


if __name__ == "__main__":
    S = "(())"
    n = len(S)
    print(noOfAssignments(S, n, 0, 0, 0))

# Expected output:
6
# gould 's sequence | utility function to count odd numbers in ith row of pascals 's triangle ; initialize count as zero ; return 2 ^ count ; function to generate gould 's sequence ; loop to generate gould 's  sequence up to n ; 
def countOddNumber(row_num):
    count = 0
    while row_num != 0:
        count += row_num & 1
        row_num >>= 1
    return (1 << count)


def gouldSequence(n):
    for row_num in range(0, n):
        print(countOddNumber(row_num), end=" ")


if __name__ == "__main__":
    n = 16
    gouldSequence(n)

# Expected output:
1 2 2 4 2 4 4 8 2 4 4 8 4 8 8 16
# count numbers ( smaller than or equal to n ) with given digit sum | n can be max 10 ^ 18 and hence digitsum will be 162 maximum . ; if sum_so_far equals to given sum then return 1 else 0 ; our constructed number should not become greater than n . ; if tight is true then it will also be true for ( i + 1 ) digit . ; 
def solve(i, tight, sum_so_far, Sum, number, length):
    if i == length:
        if sum_so_far == Sum:
            return 1
        else:
            return 0
    ans = dp[i][tight][sum_so_far]
    if ans != -1:
        return ans
    ans = 0
    for currdigit in range(0, 10):
        currdigitstr = str(currdigit)
        if not tight and currdigitstr > number[i]:
            break
        ntight = tight or currdigitstr < number[i]
        nsum_so_far = sum_so_far + currdigit
        ans += solve(i + 1, ntight, nsum_so_far, Sum, number, length)
    return ans


if __name__ == "__main__":
    count, Sum = 0, 4
    number = "100"
    dp = [[[-1 for i in range(162)]for j in range(2)]for k in range(18)]
    print(solve(0, 0, 0, Sum, number, len(number)))

# Expected output:
5
# longest dividing subsequence | lds ( ) returns the length of the longest dividing subsequence in arr [ ] of size n ; compute optimized lds values in bottom up manner ; return maximum value in lds [ ] ; 
def lds(arr, n):
    lds = [0 for i in range(n)]
    lds[0] = 1
    for i in range(n):
        lds[i] = 1
        for j in range(i):
            if (lds[j] != 0 and arr[i] % arr[j] == 0):
                lds[i] = max(lds[i], lds[j] + 1)
    return max(lds)


arr = [2, 11, 16, 12, 36, 60, 71, 17, 29, 144, 288, 129, 432, 993]
print("Length of lds is", lds(arr, len(arr)))

# Expected output:
Length of lds is 5
# memoization ( 1d , 2d and 3d ) | returns length of lcs for x [ 0. . m - 1 ] , y [ 0. . n - 1 ] memoization applied in recursive solution ; base case ; if the same state has already been computed ; if equal , then we store the value of the function call ; store it in arr to avoid further repetitive work in future function calls ; store it in arr to avoid further repetitive work in future function calls ; 
def lcs(X, Y, Z, m, n, o):
    global arr
    if (m == 0 or n == 0 or o == 0):
        return 0
    if (arr[m - 1][n - 1][o - 1] != -1):
        return arr[m - 1][n - 1][o - 1]
    if (X[m - 1] == Y[n - 1] and Y[n - 1] == Z[o - 1]):
        arr[m - 1][n - 1][o - 1] = 1 + lcs(X, Y, Z, m - 1, n - 1, o - 1)
        return arr[m - 1][n - 1][o - 1]
    else:
        arr[m -
            1][n -
               1][o -
                  1] = max(lcs(X, Y, Z, m, n -
                               1, o), max(lcs(X, Y, Z, m -
                                              1, n, o), lcs(X, Y, Z, m, n, o -
                                                            1)))
        return arr[m - 1][n - 1][o - 1]


arr = [[[0 for k in range(100)]for j in range(100)]for i in range(100)]
for i in range(100):
    for j in range(100):
        for k in range(100):
            arr[i][j][k] = -1
X = "geeks"
Y = "geeksfor"
Z = "geeksforgeeks"
m = len(X)
n = len(Y)
o = len(Z)
print("Length of LCS is ", lcs(X, Y, Z, m, n, o))

# Expected output:
Length of LCS is  5
# find the probability of reaching all points after n moves from point n | function to calculate the probabilities ; array where row represent the pass and the column represents the points on the line ; initially the person can reach left or right with one move ; calculate probabilities for n - 1 moves ; when the person moves from ith index in right direction when i moves has been done ; when the person moves from ith index in left direction when i moves has been done ; print the arr ; 
def printProbabilities(n, left):
    right = 1 - left
    arr = [[0 for j in range(2 * n + 1)]for i in range(n + 1)]
    arr[1][n + 1] = right
    arr[1][n - 1] = left
    for i in range(2, n + 1):
        for j in range(1, 2 * n + 1):
            arr[i][j] += (arr[i - 1][j - 1] * right)
        for j in range(2 * n - 1, -1, -1):
            arr[i][j] += (arr[i - 1][j + 1] * left)
    for i in range(2 * n + 1):
        print("{:5.4f} ".format(arr[n][i]), end=' ')


if __name__ == "__main__":
    n = 2
    left = 0.5
    printProbabilities(n, left)

# Expected output:
0.2500  0.0000  0.5000  0.0000  0.2500
# check if it is possible to reach a number by making jumps of two given length | python3 implementation of the approach ; function to perform bfs traversal to find minimum number of step needed to reach x from k ; calculate gcd of d1 and d2 ; if position is not reachable return - 1 ; queue for bfs ; hash table for marking visited positions ; we need 0 steps to reach k ; mark starting position as visited ; stp is the number of steps to reach position s ; if position not visited add to queue and mark visited ; 

from math import gcd as __gcd
from collections import deque as queue


def minStepsNeeded(k, d1, d2, x):
    gcd = __gcd(d1, d2)
    if ((k - x) % gcd != 0):
        return -1
    q = queue()
    visited = dict()
    q .appendleft([k, 0])
    visited[k] = 1
    while (len(q) > 0):
        sr = q .pop()
        s, stp = sr[0], sr[1]
        if (s == x):
            return stp
        if (s + d1 not in visited):
            q .appendleft([(s + d1), stp + 1])
            visited[(s + d1)] = 1
        if (s + d2 not in visited):
            q .appendleft([(s + d2), stp + 1])
            visited[(s + d2)] = 1
        if (s - d1 not in visited):
            q .appendleft([(s - d1), stp + 1])
            visited[(s - d1)] = 1
        if (s - d2 not in visited):
            q .appendleft([(s - d2), stp + 1])
            visited[(s - d2)] = 1


k = 10
d1 = 4
d2 = 6
x = 8
print(minStepsNeeded(k, d1, d2, x))

# Expected output:
2
# tiling with dominoes | python 3 program to find no . of ways to fill a 3 xn board with 2 x1 dominoes . ; 
def countWays(n):
    A = [0] * (n + 1)
    B = [0] * (n + 1)
    A[0] = 1
    A[1] = 0
    B[0] = 0
    B[1] = 1
    for i in range(2, n + 1):
        A[i] = A[i - 2] + 2 * B[i - 1]
        B[i] = A[i - 1] + B[i - 2]
    return A[n]


n = 8
print(countWays(n))

# Expected output:
153
# connect nodes at same level | a binary tree node ; sets the nextright of root and calls connectrecur ( ) for other nodes ; set the nextright for root ; set the next right for rest of the nodes ( other than root ) ; set next right of all descendents of p . assumption : p is a compete binary tree ; base case ; set the nextright pointer for p 's   left child  ; set the nextright pointer for p 's right  child p.nextright will be none if p is   the right most child at its level  ; set nextright for other nodes in pre order fashion ; 

class newnode:
    def __init__(self, data):
        self .data = data
        self .left = self .right = self .nextRight = None


def connect(p):
    p .nextRight = None
    connectRecur(p)


def connectRecur(p):
    if (not p):
        return
    if (p .left):
        p .left .nextRight = p .right
    if (p .right):
        if p .nextRight:
            p .right .nextRight = p .nextRight .left
        else:
            p .right .nextRight = None
    connectRecur(p .left)
    connectRecur(p .right)


if __name__ == '__main__':
    root = newnode(10)
    root .left = newnode(8)
    root .right = newnode(2)
    root .left .left = newnode(3)
    connect(root)
    print(
        "Following are populated nextRight",
        "pointers in the tree (-1 is printed",
        "if there is no nextRight)")
    print("nextRight of", root .data, "is ", end="")
    if root .nextRight:
        print(root .nextRight .data)
    else:
        print(-1)
    print("nextRight of", root .left .data, "is ", end="")
    if root .left .nextRight:
        print(root .left .nextRight .data)
    else:
        print(-1)
    print("nextRight of", root .right .data, "is ", end="")
    if root .right .nextRight:
        print(root .right .nextRight .data)
    else:
        print(-1)
    print("nextRight of", root .left .left .data, "is ", end="")
    if root .left .left .nextRight:
        print(root .left .left .nextRight .data)
    else:
        print(-1)

# Expected output:
Following are populated nextRight pointers in the tree (-1 is printed if there is no nextRight)
nextRight of 10 is -1
nextRight of 8 is 2
nextRight of 2 is -1
nextRight of 3 is -1
# counting pairs when a person can form pair with at most one | number of ways in which participant can take part . ; base condition ; a participant can choose to consider ( 1 ) remains single . number of people reduce to ( x - 1 ) ( 2 ) pairs with one of the ( x - 1 ) others . for every pairing , number of people reduce to ( x - 2 ) . ; 
def numberOfWays(x):
    if x == 0 or x == 1:
        return 1
    else:
        return (numberOfWays(x - 1) + (x - 1) * numberOfWays(x - 2))


x = 3
print(numberOfWays(x))

# Expected output:
4
# counting pairs when a person can form pair with at most one | python program to find number of ways in which participant can take part . ; 
def numberOfWays(x):
    dp = []
    dp .append(1)
    dp .append(1)
    for i in range(2, x + 1):
        dp .append(dp[i - 1] + (i - 1) * dp[i - 2])
    return (dp[x])


x = 3
print(numberOfWays(x))

# Expected output:
4
# number of ways to arrange n items under given constraints | python3 program to find number of ways to arrange items under given constraint ; method returns number of ways with which items can be arranged ; calculate value of binomial coefficient in bottom up manner ; base cases ; calculate value using previously stored values ; declare dp array to store result up to ith colored item ; variable to keep track of count of items considered till now ; loop over all different colors ; populate next value using current value and stated relation ; return value stored at last index ; 

import numpy as np


def waysToArrange(N, K, k):
    C = np .zeros((N + 1, N + 1))
    for i in range(N + 1):
        for j in range(i + 1):
            if (j == 0 or j == i):
                C[i][j] = 1
            else:
                C[i][j] = (C[i - 1][j - 1] + C[i - 1][j])
    dp = np .zeros((K + 1))
    count = 0
    dp[0] = 1
    for i in range(K):
        dp[i + 1] = (dp[i] * C[count + k[i] - 1][k[i] - 1])
        count += k[i]
    return dp[K]


if __name__ == "__main__":
    N = 4
    k = [2, 2]
    K = len(k)
    print(int(waysToArrange(N, K, k)))

# Expected output:
3