giulio98/xlcost-single-prompt huggingface dataset:
# minimum cells required to reach destination with jumps equal to cell values | python3 implementation to count minimum cells required to be covered to reach destination ; function to count minimum cells required to be covered to reach destination ; to store min cells required to be covered to reach a particular cell ; base case ; building up the dp [ ] [ ] matrix ; dp [ i ] [ j ] != max denotes that cell ( i , j ) can be reached from cell ( 0 , 0 ) and the other half of the condition finds the cell on the right that can be reached from ( i , j ) ; the other half of the condition finds the cell right below that can be reached from ( i , j ) ; it true then cell ( m - 1 , n - 1 ) can be reached from cell ( 0 , 0 ) and returns the minimum number of cells covered ; cell ( m - 1 , n - 1 ) cannot be reached from cell ( 0 , 0 ) ; 

SIZE = 100
MAX = 10000000


def minCells(mat, m, n):
    dp = [[MAX for i in range(n)]for i in range(m)]
    dp[0][0] = 1
    for i in range(m):
        for j in range(n):
            if (dp[i][j] != MAX and (j + mat[i][j]) <
                    n and (dp[i][j] + 1) < dp[i][j + mat[i][j]]):
                dp[i][j + mat[i][j]] = dp[i][j] + 1
            if (dp[i][j] != MAX and (i + mat[i][j]) <
                    m and (dp[i][j] + 1) < dp[i + mat[i][j]][j]):
                dp[i + mat[i][j]][j] = dp[i][j] + 1
    if (dp[m - 1][n - 1] != MAX):
        return dp[m - 1][n - 1]
    return -1


mat = [[2, 3, 2, 1, 4], [3, 2, 5, 8, 2], [1, 1, 2, 2, 1]]
m = 3
n = 5
print("Minimum number of cells = ", minCells(mat, m, n))

# Expected output:
Minimum number of cells =  4
# find longest bitonic sequence such that increasing and decreasing parts are from two different arrays | python3 to find largest bitonic sequence such that ; utility binary search ; function to find lis in reverse form ; len = 1 it will always poto empty location ; new smallest value ; arr [ i ] wants to extend largest subsequence ; arr [ i ] wants to be a potential candidate of future subsequence it will replace ceil value in tailindices ; put lis into vector ; function for finding longest bitonic seq ; find lis of array 1 in reverse form ; reverse res to get lis of first array ; reverse array2 and find its lis ; print result ; 

res = []


def GetCeilIndex(arr, T, l, r, key):
    while (r - l > 1):
        m = l + (r - l) // 2
        if (arr[T[m]] >= key):
            r = m
        else:
            l = m
    return r


def LIS(arr, n):
    tailIndices = [0]*(n)
    prevIndices = [-1]*(n)
    leN = 1
    for i in range(1, n):
        if (arr[i] < arr[tailIndices[0]]):
            tailIndices[0] = i
        elif (arr[i] > arr[tailIndices[leN - 1]]):
            prevIndices[i] = tailIndices[leN - 1]
            tailIndices[leN] = i
            leN += 1
        else:
            pos = GetCeilIndex(arr, tailIndices, -1, leN - 1, arr[i])
            prevIndices[i] = tailIndices[pos - 1]
            tailIndices[pos] = i
    i = tailIndices[leN - 1]
    while (i >= 0):
        res .append(arr[i])
        i = prevIndices[i]


def longestBitonic(arr1, n1, arr2, n2):
    global res
    LIS(arr1, n1)
    res = res[::-1]
    arr2 = arr2[::-1]
    LIS(arr2, n2)
    for i in res:
        print(i, end=" ")


arr1 = [1, 2, 4, 3, 2]
arr2 = [8, 6, 4, 7, 8, 9]
n1 = len(arr1)
n2 = len(arr2)
longestBitonic(arr1, n1, arr2, n2)

# Expected output:
1 2 3 8 6 4
# maximize the binary matrix by filpping submatrix once | python 3 program to find maximum number of ones after one flipping in binary matrix ; return number of ones in square submatrix of size k x k starting from ( x , y ) ; return maximum number of 1 s after flipping a submatrix ; precomputing the number of 1 s ; finding the maximum number of 1 s after flipping ; 

R = 3
C = 3


def cal(ones, x, y, k):
    return (ones[x + k - 1][y + k - 1] - ones[x - 1][y + k - 1] -
            ones[x + k - 1][y - 1] + ones[x - 1][y - 1])


def sol(mat):
    ans = 0
    ones = [[0 for i in range(C + 1)]for i in range(R + 1)]
    for i in range(1, R + 1, 1):
        for j in range(1, C + 1, 1):
            ones[i][j] = (ones[i - 1][j] + ones[i][j - 1] -
                          ones[i - 1][j - 1] + (mat[i - 1][j - 1] == 1))
    for k in range(1, min(R, C) + 1, 1):
        for i in range(1, R - k + 2, 1):
            for j in range(1, C - k + 2, 1):
                ans = max(ans, (ones[R][C] + k * k - 2 * cal(ones, i, j, k)))
    return ans


if __name__ == '__main__':
    mat = [[0, 0, 1], [0, 0, 1], [1, 0, 1]]
    print(sol(mat))

# Expected output:
8
# minimum steps to minimize n as per given condition | a tabulation based solution in python3 ; 
def getMinSteps(n):
    table = [0] * (n + 1)
    for i in range(n + 1):
        table[i] = n - i
    for i in range(n, 0, -1):
        if (not (i % 2)):
            table[i // 2] = min(table[i] + 1, table[i // 2])
        if (not (i % 3)):
            table[i // 3] = min(table[i] + 1, table[i // 3])
    return table[1]


if __name__ == "__main__":
    n = 14
    print(getMinSteps(n))

# Expected output:
5
# Maximum points collected by two persons allowed to meet once | Python program to find maximum points that can be collected by two persons in a matrix . ; To store points collected by Person P1 when he / she begins journy from start and from end . ; To store points collected by Person P2 when he / she begins journey from start and from end . ; Table for P1 's journey from  start to meeting cell ; Table for P1 's journey from  end to meet cell ; Table for P2 's journey from start to meeting cell ; Table for P2 's journey from end to meeting cell ; Now iterate over all meeting positions ( i , j ) ;

M = 3
N = 3


def findMaxPoints(A):
    P1S = [[0 for i in range(N + 2)]for j in range(M + 2)]
    P1E = [[0 for i in range(N + 2)]for j in range(M + 2)]
    P2S = [[0 for i in range(N + 2)]for j in range(M + 2)]
    P2E = [[0 for i in range(N + 2)]for j in range(M + 2)]
    for i in range(1, N + 1):
        for j in range(1, M + 1):
            P1S[i][j] = max(P1S[i - 1][j], P1S[i][j - 1]) + A[i - 1][j - 1]
    for i in range(N, 0, -1):
        for j in range(M, 0, -1):
            P1E[i][j] = max(P1E[i + 1][j], P1E[i][j + 1]) + A[i - 1][j - 1]
    for i in range(N, 0, -1):
        for j in range(1, M + 1):
            P2S[i][j] = max(P2S[i + 1][j], P2S[i][j - 1]) + A[i - 1][j - 1]
    for i in range(1, N + 1):
        for j in range(M, 0, -1):
            P2E[i][j] = max(P2E[i - 1][j], P2E[i][j + 1]) + A[i - 1][j - 1]
    ans = 0
    for i in range(2, N):
        for j in range(2, M):
            op1 = P1S[i][j - 1] + P1E[i][j + 1] + P2S[i + 1][j] + P2E[i - 1][j]
            op2 = P1S[i - 1][j] + P1E[i + 1][j] + P2S[i][j - 1] + P2E[i][j + 1]
            ans = max(ans, max(op1, op2))
    return ans


A = [[100, 100, 100], [100, 1, 100], [100, 100, 100]]
print("Max Points : ", findMaxPoints(A))

# Expected output:
Max Points :  800
# longest subsequence such that difference between adjacents is one | function to find the length of longest subsequence ; initialize the dp [ ] array with 1 as a single element will be of 1 length ; start traversing the given array ; compare with all the previous elements ; if the element is consecutive then consider this subsequence and update dp [ i ] if required . ; longest length will be the maximum value of dp array . ; 
def longestSubseqWithDiffOne(arr, n):
    dp = [1 for i in range(n)]
    for i in range(n):
        for j in range(i):
            if ((arr[i] == arr[j] + 1) or (arr[i] == arr[j] - 1)):
                dp[i] = max(dp[i], dp[j] + 1)
    result = 1
    for i in range(n):
        if (result < dp[i]):
            result = dp[i]
    return result


arr = [1, 2, 3, 4, 5, 3, 2]
n = len(arr)
print(longestSubseqWithDiffOne(arr, n))

# Expected output:
6
# non | a dynamic programming based function to find nth catalan number ; table to store results of subproblems ; fill entries in catalan [ ] using recursive formula ; return last entry ; returns count of ways to connect n points on a circle such that no two connecting lines cross each other and every point is connected with one other point . ; throw error if n is odd ; else return n / 2 'th catalan number ; 
def catalanDP(n):
    catalan = [1 for i in range(n + 1)]
    for i in range(2, n + 1):
        catalan[i] = 0
        for j in range(i):
            catalan[i] += (catalan[j] * catalan[i - j - 1])
    return catalan[n]


def countWays(n):
    if (n & 1):
        print("Invalid")
        return 0
    return catalanDP(n // 2)


print(countWays(6))

# Expected output:
5
# ways to arrange balls such that adjacent balls are of different types | python3 program to count number of ways to arrange three types of balls such that no two balls of same color are adjacent to each other ; table to store to store results of subproblems ; returns count of arrangements where last placed ball is ' last ' . ' last ' is 0 for ' p ' , 1 for ' q ' and 2 for 'r ; if number of balls of any color becomes less than 0 the number of ways arrangements is 0. ; if last ball required is of type p and the number of balls of p type is 1 while number of balls of other color is 0 the number of ways is 1. ; same case as above for ' q ' and 'r ; if this subproblem is already evaluated ; if last ball required is p and the number of ways is the sum of number of ways to form sequence with ' p - 1' p balls , q q balls and r r balls ending with q and r . ; same as above case for ' q ' and 'r ; ( last == 2 ) ; returns count of required arrangements ; three cases arise : last required balls is type p last required balls is type q last required balls is type r ; 

MAX = 100
dp = [[[[-1] * 4 for i in range(MAX)]
       for j in range(MAX)]
      for k in range(MAX)]


def countWays(p, q, r, last):
    if (p < 0 or q < 0 or r < 0):
        return 0
    if (p == 1 and q == 0 and
            r == 0 and last == 0):
        return 1
    if (p == 0 and q == 1 and
            r == 0 and last == 1):
        return 1
    if (p == 0 and q == 0 and
            r == 1 and last == 2):
        return 1

    if (dp[p][q][r][last] != -1):
        return dp[p][q][r][last]
    if (last == 0):
        dp[p][q][r][last] = (countWays(p - 1, q, r, 1) +
                             countWays(p - 1, q, r, 2))
    elif (last == 1):
        dp[p][q][r][last] = (countWays(p, q - 1, r, 0) +
                             countWays(p, q - 1, r, 2))
    else:
        dp[p][q][r][last] = (countWays(p, q, r - 1, 0) +
                             countWays(p, q, r - 1, 1))

    return dp[p][q][r][last]


def countUtil(p, q, r):
    return (countWays(p, q, r, 0) +
            countWays(p, q, r, 1) +
            countWays(p, q, r, 2))


p, q, r = 1, 1, 1
print(countUtil(p, q, r))

# Expected output:
6
# count derangements ( permutation such that no element appears in its original position ) | function to count derangements ; base cases ; countder ( n ) = ( n - 1 ) [ countder ( n - 1 ) + der ( n - 2 ) ] ; 
def countDer(n):
    if (n == 1):
        return 0
    if (n == 2):
        return 1
    return (n - 1) * (countDer(n - 1) + countDer(n - 2))


n = 4
print("Count of Derangements is ", countDer(n))

# Expected output:
Count of Derangements is  9
# count derangements ( permutation such that no element appears in its original position ) | function to count derangements ; create an array to store counts for subproblems ; base cases ; fill der [ 0. . n ] in bottom up manner using above recursive formula ; return result for n ; 
def countDer(n):
    der = [0 for i in range(n + 1)]
    der[1] = 0
    der[2] = 1
    for i in range(3, n + 1):
        der[i] = (i - 1) * (der[i - 1] + der[i - 2])
    return der[n]


n = 4
print("Count of Derangements is ", countDer(n))

# Expected output:
Count of Derangements is  9
# find number of solutions of a linear equation of n variables | returns count of solutions for given rhs and coefficients coeff [ 0. . . n - 1 ] ; create and initialize a table to store results of subproblems ; fill table in bottom up manner ; 
def countSol(coeff, n, rhs):
    dp = [0 for i in range(rhs + 1)]
    dp[0] = 1
    for i in range(n):
        for j in range(coeff[i], rhs + 1):
            dp[j] += dp[j - coeff[i]]
    return dp[rhs]


coeff = [2, 2, 5]
rhs = 4
n = len(coeff)
print(countSol(coeff, n, rhs))

# Expected output:
3
# maximum product cutting | dp | the main function that returns the max possible product ; n equals to 2 or 3 must be handled explicitly ; keep removing parts of size 3 while n is greater than 4 ; keep multiplying 3 to res ; the last part multiplied by previous parts ; 
def maxProd(n):
    if (n == 2 or n == 3):
        return (n - 1)
    res = 1
    while (n > 4):
        n -= 3
        res *= 3
    return (n * res)


print("Maximum Product is ", maxProd(10))

# Expected output:
Maximum Product is  36
# dice throw | dp | the main function that returns number of ways to get sum ' x ' with ' n ' dice and ' m ' with m faces . ; create a table to store results of subproblems . one extra row and column are used for simpilicity ( number of dice is directly used as row index and sum is directly used as column index ) . the entries in 0 th row and 0 th column are never used . ; table entries for only one dice ; fill rest of the entries in table using recursive relation i : number of dice , j : sum ; return value ; 
def findWays(m, n, x):
    table = [[0] * (x + 1)for i in range(n + 1)]
    for j in range(1, min(m + 1, x + 1)):
        table[1][j] = 1
    for i in range(2, n + 1):
        for j in range(1, x + 1):
            for k in range(1, min(m + 1, j)):
                table[i][j] += table[i - 1][j - k]
    return table[-1][-1]


print(findWays(4, 2, 1))
print(findWays(2, 2, 3))
print(findWays(6, 3, 8))
print(findWays(4, 2, 5))
print(findWays(4, 3, 5))

# Expected output:
0
2
21
4
6
# dice throw | dp | * count ways * * @ param f * @ param d * @ param s * @ return ; create a table to store results of subproblems . one extra row and column are used for simpilicity ( number of dice is directly used as row index and sum is directly used as column index ) . the entries in 0 th row and 0 th column are never used . ; table entries for no dices if you do not have any data , then the value must be 0 , so the result is 1 ; iterate over dices ; iterate over sum ; the result is obtained in two ways , pin the current dice and spending 1 of the value , so we have mem [ i - 1 ] [ j - 1 ] remaining combinations , to find the remaining combinations we would have to pin the values ? ? above 1 then we use mem [ i ] [ j - 1 ] to sum all combinations that pin the remaining j - 1 's. but there is a way, when "j-f-1> = 0" we would be adding  extra combinations, so we remove the combinations that only pin the extrapolated dice face and  subtract the extrapolated combinations. ; 
def findWays(f, d, s):
    mem = [[0 for i in range(s + 1)]for j in range(d + 1)]
    mem[0][0] = 1
    for i in range(1, d + 1):
        for j in range(1, s + 1):
            mem[i][j] = mem[i][j - 1] + mem[i - 1][j - 1]
            if j - f - 1 >= 0:
                mem[i][j] -= mem[i - 1][j - f - 1]
    return mem[d][s]


print(findWays(4, 2, 1))
print(findWays(2, 2, 3))
print(findWays(6, 3, 8))
print(findWays(4, 2, 5))
print(findWays(4, 3, 5))

# Expected output:
0
2
21
4
6
# minimum insertions to form a palindrome | dp | a naive recursive program to find minimum number insertions needed to make a string palindrome ; recursive function to find minimum number of insertions ; base cases ; check if the first and last characters are same . on the basis of the comparison result , decide which subrpoblem ( s ) to call ; 

import sys


def findMinInsertions(str, l, h):
    if (l > h):
        return sys .maxsize
    if (l == h):
        return 0
    if (l == h - 1):
        return 0 if (str[l] == str[h])else 1
    if (str[l] == str[h]):
        return findMinInsertions(str, l + 1, h - 1)
    else:
        return (min(findMinInsertions(str, l, h - 1),
                findMinInsertions(str, l + 1, h)) + 1)


if __name__ == "__main__":
    str = "geeks"
    print(findMinInsertions(str, 0, len(str) - 1))

# Expected output:
3
# longest palindromic subsequence | dp | a utility function to get max of two egers ; returns the length of the longest palindromic subsequence in seq ; base case 1 : if there is only 1 character ; base case 2 : if there are only 2 characters and both are same ; if the first and last characters match ; if the first and last characters do not match ; 
def max(x, y):
    if (x > y):
        return x
    return y


def lps(seq, i, j):
    if (i == j):
        return 1
    if (seq[i] == seq[j] and i + 1 == j):
        return 2
    if (seq[i] == seq[j]):
        return lps(seq, i + 1, j - 1) + 2
    return max(lps(seq, i, j - 1), lps(seq, i + 1, j))


if __name__ == '__main__':
    seq = "GEEKSFORGEEKS"
    n = len(seq)
    print("The length of the LPS is", lps(seq, 0, n - 1))

# Expected output:
The length of the LPS is 5
# count occurrences of a string that can be constructed from another given string | python3 implementation of the above approach ; function to find the count ; initialize hash for both strings ; hash the frequency of letters of str1 ; hash the frequency of letters of str2 ; find the count of str2 constructed from str1 ; return answer ; 

import sys


def findCount(str1, str2):
    len1 = len(str1)
    len2 = len(str2)
    ans = sys .maxsize
    hash1 = [0] * 26
    hash2 = [0] * 26
    for i in range(0, len1):
        hash1[ord(str1[i]) - 97] = hash1[ord(str1[i]) - 97] + 1
    for i in range(0, len2):
        hash2[ord(str2[i]) - 97] = hash2[ord(str2[i]) - 97] + 1
    for i in range(0, 26):
        if (hash2[i] != 0):
            ans = min(ans, hash1[i] // hash2[i])
    return ans


str1 = "geeksclassesatnoida"
str2 = "sea"
print(findCount(str1, str2))

# Expected output:
3
# check if a string is the typed name of the given name | check if the character is vowel or not ; returns true if ' typed ' is a typed name given str ; traverse through all characters of str ; if current characters do not match ; if not vowel , simply move ahead in both ; count occurrences of current vowel in str ; count occurrence of current vowel in typed ; 
def isVowel(c):
    vowel = "aeiou"
    for i in range(len(vowel)):
        if (vowel[i] == c):
            return True
    return False


def printRLE(str, typed):
    n = len(str)
    m = len(typed)
    j = 0
    for i in range(n):
        if str[i] != typed[j]:
            return False
        if isVowel(str[i]) == False:
            j = j + 1
            continue
        count1 = 1
        while (i < n - 1 and (str[i] == str[i + 1])):
            count1 = count1 + 1
            i = i + 1
        count2 = 1
        while (j < m - 1 and typed[j] == str[i]):
            count2 = count2 + 1
            j = j + 1
        if count1 > count2:
            return False
    return True


name = "alex"
typed = "aaalaeex"
if (printRLE(name, typed)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# program to replace a word with asterisks in a sentence | function takes two parameter ; break down sentence by ' ▁ ' spaces and store each individual word in a different list ; a new string to store the result ; creating the censor which is an asterisks " * " text of the length of censor word ; count variable to access our word_list ; iterating through our list of extracted words ; changing the censored word to created asterisks censor ; join the words ; 
def censor(text, word):
    word_list = text .split()
    result = ''
    stars = '*' * len(word)
    count = 0
    index = 0
    for i in word_list:
        if i == word:
            word_list[index] = stars
        index += 1
    result = ' '.join(word_list)
    return result


if __name__ == '__main__':
    extract = "GeeksforGeeks is a computer science portal for geeks.\\STRNEWLINETABSYMBOLTABSYMBOLTABSYMBOLI am pursuing my major in computer science. "
    cen = "computer"
    print(censor(extract, cen))

# Expected output:
GeeksforGeeks is a ******** science portal for geeks.\STRNEWLINETABSYMBOLTABSYMBOLTABSYMBOLI am pursuing my major in ******** science.
# longest substring containing '1' | function to find length of longest substring containing '1 ; count the number of contiguous 1 's ; 
def maxlength(s):
    n = len(s)
    ans = 0
    for i in range(n):
        if (s[i] == '1'):
            count = 1
            j = i + 1
            while (j <= n - 1 and s[j] == '1'):
                count += 1
                j += 1
            ans = max(ans, count)
    return ans


s = "11101110"
print(maxlength(s))

# Expected output:
3
# generate all possible strings formed by replacing letters with given respective symbols | function to generate all possible string by replacing the characters with mapped symbols ; base case ; function call with the p - th character not replaced ; replace the p - th character ; function call with the p - th character replaced ; 
def generateLetters(S, P, M):
    if (P == len(S)):
        print(S)
        return
    generateLetters(S, P + 1, M)
    S = S .replace(S[P], M[S[P]])
    generateLetters(S, P + 1, M)


S = "aBc"
M = {}
M['a'] = '$'
M['B'] = '#'
M['c'] = '^'
M['d'] = '&'
M['1'] = '*'
M['2'] = '!'
M['E'] = '@'
generateLetters(S, 0, M)

# Expected output:
aBc
aB^
a#c
a#^
$Bc
$B^
$#c
$#^
# minimize swaps of pairs of characters required such that no two adjacent characters in the string are same | python3 program for the above approach ; function to check if s contains any pair of adjacent characters that are same ; traverse the string s ; if current pair of adjacent characters are the same ; return true ; utility function to find the minimum number of swaps of pair of characters required to make all pairs of adjacent characters different ; check if the required string is formed already ; traverse the string s ; swap the characters at i and j position ; swap for backtracking step ; function to find the minimum number of swaps of pair of characters required to make all pairs of adjacent characters different ; stores the resultant minimum number of swaps required ; function call to find the minimum swaps required ; prvar the result ; 

import sys
ansSwaps = 0


def check(S):
    for i in range(1, len(S)):
        if (S[i - 1] == S[i]):
            return False
    return True


def minimumSwaps(S, swaps, idx):
    global ansSwaps
    if (check(S)):
        ansSwaps = 1 + min(ansSwaps, swaps)
    for i in range(idx, len(S)):
        for j in range(i + 1, len(S)):
            swap(S, i, j)
            minimumSwaps(S, swaps + 1, i + 1)
            S = swap(S, i, j)


def swap(arr, i, j):
    temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
    return arr


def findMinimumSwaps(S):
    global ansSwaps
    ansSwaps = sys .maxsize
    minimumSwaps(S, 0, 0)
    if (ansSwaps == sys .maxsize):
        print("-1")
    else:
        print(ansSwaps)


S = "ABAACD"
findMinimumSwaps(S .split())

# Expected output:
1