giulio98/xlcost-single-prompt huggingface dataset:
# shortest uncommon subsequence | a simple recursive python program to find shortest uncommon subsequence . ; a recursive function to find the length of shortest uncommon subsequence ; s string is empty ; t string is empty ; loop to search for current character ; char not found in t ; return minimum of following two not including current char in answer including current char ; 

MAX = 1005


def shortestSeq(S, T, m, n):
    if m == 0:
        return MAX
    if (n <= 0):
        return 1
    for k in range(n):
        if (T[k] == S[0]):
            break
    if (k == n):
        return 1
    return min(shortestSeq(S[1:], T, m - 1, n), 1 +
               shortestSeq((S[1:]), T[k + 1:], m - 1, n - k - 1))


S = "babab"
T = "babba"
m = len(S)
n = len(T)
ans = shortestSeq(S, T, m, n)
if (ans >= MAX):
    ans = -1
print("Length of shortest subsequence is:", ans)

# Expected output:
Length of shortest subsequence is: 3
# shortest uncommon subsequence | a dynamic programming based python program to find shortest uncommon subsequence . ; returns length of shortest common subsequence ; declaring 2d array of m + 1 rows and n + 1 columns dynamically ; t string is empty ; s string is empty ; char not present in t ; 

MAX = 1005


def shortestSeq(S: list, T: list):
    m = len(S)
    n = len(T)
    dp = [[0 for i in range(n + 1)]for j in range(m + 1)]
    for i in range(m + 1):
        dp[i][0] = 1
    for i in range(n + 1):
        dp[0][i] = MAX
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            ch = S[i - 1]
            k = j - 1
            while k >= 0:
                if T[k] == ch:
                    break
                k -= 1
            if k == -1:
                dp[i][j] = 1
            else:
                dp[i][j] = min(dp[i - 1][j], dp[i - 1][k] + 1)
    ans = dp[m][n]
    if ans >= MAX:
        ans = -1
    return ans


if __name__ == "__main__":
    S = "babab"
    T = "babba"
    print("Length of shortest subsequence is:", shortestSeq(S, T))

# Expected output:
Length of shortest subsequence is: 3
# count number of ways to jump to reach end | function to count ways to jump to reach end for each array element ; count_jump [ i ] store number of ways arr [ i ] can reach to the end ; last element does not require to jump . count ways to jump for remaining elements ; if the element can directly jump to the end ; add the count of all the elements that can reach to end and arr [ i ] can reach to them ; if element can reach to end then add its count to count_jump [ i ] ; if arr [ i ] cannot reach to the end ; print count_jump for each array element ; 
def countWaysToJump(arr, n):
    count_jump = [0 for i in range(n)]
    for i in range(n - 2, -1, -1):
        if (arr[i] >= n - i - 1):
            count_jump[i] += 1
        j = i + 1
        while (j < n - 1 and j <= arr[i] + i):
            if (count_jump[j] != -1):
                count_jump[i] += count_jump[j]
            j += 1
        if (count_jump[i] == 0):
            count_jump[i] = -1
    for i in range(n):
        print(count_jump[i], end=" ")


arr = [1, 3, 5, 8, 9, 1, 0, 7, 6, 8, 9]
n = len(arr)
countWaysToJump(arr, n)

# Expected output:
52 52 28 16 8 -1 -1 4 2 1 0
# minimum steps to delete a string after repeated deletion of palindrome substrings | method returns minimum step for deleting the string , where in one step a palindrome is removed ; declare dp array and initialize it with 0 s ; loop for substring length we are considering ; loop with two variables i and j , denoting starting and ending of substrings ; if substring length is 1 , then 1 step will be needed ; delete the ith char individually and assign result for subproblem ( i + 1 , j ) ; if current and next char are same , choose min from current and subproblem ( i + 2 , j ) ; loop over all right characters and suppose kth char is same as ith character then choose minimum from current and two substring after ignoring ith and kth char ; uncomment below snippet to print actual dp tablex for ( int i = 0 ; i < n ; i ++ , cout << endl ) for ( int j = 0 ; j < n ; j ++ ) cout << dp [ i ] [ j ] << " ▁ " ; ; 
def minStepToDeleteString(str):
    N = len(str)
    dp = [[0 for x in range(N + 1)]for y in range(N + 1)]
    for l in range(1, N + 1):
        i = 0
        j = l - 1
        while j < N:
            if (l == 1):
                dp[i][j] = 1
            else:
                dp[i][j] = 1 + dp[i + 1][j]
                if (str[i] == str[i + 1]):
                    dp[i][j] = min(1 + dp[i + 2][j], dp[i][j])
                for K in range(i + 2, j + 1):
                    if (str[i] == str[K]):
                        dp[i][j] = min(dp[i + 1][K - 1] +
                                       dp[K + 1][j], dp[i][j])
            i += 1
            j += 1
    return dp[0][N - 1]


if __name__ == "__main__":
    str = "2553432"
    print(minStepToDeleteString(str))

# Expected output:
2
# clustering / partitioning an array such that sum of square differences is minimum | initialize answer as infinite . ; function to generate all possible answers . and compute minimum of all costs . i -- > is index of previous partition par -- > is current number of partitions a [ ] and n -- > input array and its size current_ans -- > cost of partitions made so far . ; if number of partitions is more than k ; if we have mad k partitions and have reached last element ; 1 ) partition array at different points 2 ) for every point , increase count of partitions , " par " by 1. 3 ) before recursive call , add cost of the partition to current_ans ; 

inf = 1000000000
ans = inf


def solve(i, par, a, n, k, current_ans):
    if (par > k):
        return 0
    global ans
    if (par == k and i == n - 1):
        ans = min(ans, current_ans)
        return 0
    for j in range(i + 1, n):
        solve(j, par + 1, a, n, k, current_ans +
              (a[j] - a[i + 1]) * (a[j] - a[i + 1]))


k = 2
a = [1, 5, 8, 10]
n = len(a)
solve(-1, 0, a, n, k, 0)
print(ans)

# Expected output:
20
# minimum steps to minimize n as per given condition | function to calculate min steps ; base case ; store temp value for n as min ( f ( n - 1 ) , f ( n2 ) , f ( n3 ) ) + 1 ; store memo [ n ] and return ; this function mainly initializes memo [ ] and calls getminsteps ( n , memo ) ; initialize memoized array ; 
def getMinSteps(n, memo):
    if (n == 1):
        return 0
    if (memo[n] != -1):
        return memo[n]
    res = getMinSteps(n - 1, memo)
    if (n % 2 == 0):
        res = min(res, getMinSteps(n // 2, memo))
    if (n % 3 == 0):
        res = min(res, getMinSteps(n // 3, memo))
    memo[n] = 1 + res
    return memo[n]


def getsMinSteps(n):
    memo = [0 for i in range(n + 1)]
    for i in range(n + 1):
        memo[i] = -1
    return getMinSteps(n, memo)


n = 10
print(getsMinSteps(n))

# Expected output:
3
# count of arrays in which all adjacent elements are such that one of them divide the another | python3 program to count the number of arrays of size n such that every element is in range [ 1 , m ] and adjacent are divisible ; for storing factors . ; for storing multiples . ; calculating the factors and multiples of elements [ 1. . . m ] . ; initialising for size 1 array for each i <= m . ; calculating the number of array possible of size i and starting with j . ; for all previous possible values . adding number of factors . ; adding number of multiple . ; calculating the total count of array which start from [ 1. . . m ] . ; 

MAX = 1000


def numofArray(n, m):
    dp = [[0 for i in range(MAX)]for j in range(MAX)]
    di = [[]for i in range(MAX)]
    mu = [[]for i in range(MAX)]
    for i in range(1, m + 1):
        for j in range(2 * i, m + 1, i):
            di[j].append(i)
            mu[i].append(j)
        di[i].append(i)
    for i in range(1, m + 1):
        dp[1][i] = 1
    for i in range(2, n + 1):
        for j in range(1, m + 1):
            dp[i][j] = 0
            for x in di[j]:
                dp[i][j] += dp[i - 1][x]
            for x in mu[j]:
                dp[i][j] += dp[i - 1][x]
    ans = 0
    for i in range(1, m + 1):
        ans += dp[n][i]
        di[i].clear()
        mu[i].clear()
    return ans


if __name__ == "__main__":
    n = m = 3
    print(numofArray(n, m))

# Expected output:
17
# temple offerings | python3 program to find temple offerings required ; to store count of increasing order temples on left and right ( including current temple ) ; returns count of minimum offerings for n temples of given heights . ; initialize counts for all temples ; values corner temples ; filling left and right values using same values of previous ( or next ; computing max of left and right for all temples and returing sum ; 

from typing import List


class Temple:
    def __init__(self, l: int, r: int):
        self .L = l
        self .R = r


def offeringNumber(n: int, templeHeight: List[int]) -> int:
    chainSize = [0] * n
    for i in range(n):
        chainSize[i] = Temple(-1, -1)
    chainSize[0].L = 1
    chainSize[-1].R = 1
    for i in range(1, n):
        if templeHeight[i - 1] < templeHeight[i]:
            chainSize[i].L = chainSize[i - 1].L + 1
        else:
            chainSize[i].L = 1
    for i in range(n - 2, -1, -1):
        if templeHeight[i + 1] < templeHeight[i]:
            chainSize[i].R = chainSize[i + 1].R + 1
        else:
            chainSize[i].R = 1
    sm = 0
    for i in range(n):
        sm += max(chainSize[i].L, chainSize[i].R)
    return sm


if __name__ == '__main__':
    arr1 = [1, 2, 2]
    print(offeringNumber(3, arr1))
    arr2 = [1, 4, 3, 6, 2, 1]
    print(offeringNumber(6, arr2))

# Expected output:
4
10
# smallest length string with repeated replacement of two distinct adjacent | returns smallest possible length with given operation allowed . ; counint occurrences of three different characters ' a ' , ' b ' and ' c ' in str ; if all characters are same . ; if all characters are present even number of times or all are present odd number of times . ; answer is 1 for all other cases . ; 
def stringReduction(str):
    n = len(str)
    count = [0] * 3
    for i in range(n):
        count[ord(str[i]) - ord('a')] += 1
    if (count[0] == n or count[1] == n or count[2] == n):
        return n
    if ((count[0] % 2) == (count[1] % 2) and (count[1] % 2) == (count[2] % 2)):
        return 2
    return 1


if __name__ == "__main__":
    str = "abcbbaacb"
    print(stringReduction(str))

# Expected output:
1
# largest sum zigzag sequence in a matrix | memoization based python3 program to find the largest sum zigzag sequence ; returns largest sum of a zigzag sequence starting from ( i , j ) and ending at a bottom cell . ; if we have reached bottom ; find the largest sum by considering all possible next elements in sequence . ; returns largest possible sum of a zizag sequence starting from top and ending at bottom . ; consider all cells of top row as starting point ; 

MAX = 100
dp = [[0 for i in range(MAX)]for j in range(MAX)]


def largestZigZagSumRec(mat, i, j, n):
    if (dp[i][j] != -1):
        return dp[i][j]
    if (i == n - 1):
        dp[i][j] = mat[i][j]
        return (dp[i][j])
    zzs = 0
    for k in range(n):
        if (k != j):
            zzs = max(zzs, largestZigZagSumRec(mat, i + 1, k, n))
    dp[i][j] = (zzs + mat[i][j])
    return (dp[i][j])


def largestZigZag(mat, n):
    for i in range(MAX):
        for k in range(MAX):
            dp[i][k] = -1
    res = 0
    for j in range(n):
        res = max(res, largestZigZagSumRec(mat, 0, j, n))
    return res


if __name__ == '__main__':
    n = 3
    mat = [[4, 2, 1], [3, 9, 6], [11, 3, 15]]
    print("Largest zigzag sum: ", largestZigZag(mat, n))

# Expected output:
Largest zigzag sum:  28
# number of subsequences of the form a ^ i b ^ j c ^ k | returns count of subsequences of the form a ^ i b ^ j c ^ k ; initialize counts of different subsequences caused by different combination of 'a ; initialize counts of different subsequences caused by different combination of ' a ' and different combination of 'b ; initialize counts of different subsequences caused by different combination of ' a ' , ' b ' and ' c ' . ; traverse all characters of given string ; if current character is ' a ' , then there are following possibilities : a ) current character begins a new subsequence . b ) current character is part of acount subsequences . c ) current character is not part of acount subsequences . ; if current character is ' b ' , then there are following possibilities : a ) current character begins a new subsequence of b 's with acount subsequences. b) current character is part of bcount subsequences. c) current character is not  part of bcount subsequences. ; if current character is ' c ' , then there are following possibilities : a ) current character begins a new subsequence of c 's with bcount subsequences. b) current character is part of ccount subsequences. c) current character is not  part of ccount subsequences. ; 
def countSubsequences(s):
    aCount = 0
    bCount = 0
    cCount = 0
    for i in range(len(s)):
        if (s[i] == 'a'):
            aCount = (1 + 2 * aCount)
        elif (s[i] == 'b'):
            bCount = (aCount + 2 * bCount)
        elif (s[i] == 'c'):
            cCount = (bCount + 2 * cCount)

    return cCount


if __name__ == "__main__":
    s = "abbc"
    print(countSubsequences(s))

# Expected output:
3
# highway billboard problem | python3 program to find maximum revenue by placing billboard on the highway with given constraints . ; array to store maximum revenue at each miles . ; actual minimum distance between 2 billboards . ; check if all billboards are already placed . ; check if we have billboard for that particular mile . if not , copy the previous maximum revenue . ; we do have billboard for this mile . ; if current position is less than or equal to t , then we can have only one billboard . ; else we may have to remove previously placed billboard ; 
def maxRevenue(m, x, revenue, n, t):
    maxRev = [0] * (m + 1)
    nxtbb = 0
    for i in range(1, m + 1):
        if (nxtbb < n):
            if (x[nxtbb] != i):
                maxRev[i] = maxRev[i - 1]
            else:
                if (i <= t):
                    maxRev[i] = max(maxRev[i - 1], revenue[nxtbb])
                else:
                    maxRev[i] = max(maxRev[i - t - 1] +
                                    revenue[nxtbb], maxRev[i - 1])
                nxtbb += 1
        else:
            maxRev[i] = maxRev[i - 1]
    return maxRev[m]


if __name__ == "__main__":
    m = 20
    x = [6, 7, 12, 13, 14]
    revenue = [5, 6, 5, 3, 1]
    n = len(x)
    t = 5
    print(maxRevenue(m, x, revenue, n, t))

# Expected output:
10
# finding the maximum square sub | python 3 program to find maximum k such that k x k is a submatrix with equal elements . ; returns size of the largest square sub - matrix with all same elements . ; if elements is at top row or first column , it wont form a square matrix 's bottom-right ; check if adjacent elements are equal ; if not equal , then it will form a 1 x1 submatrix ; update result at each ( i , j ) ; 

Row = 6
Col = 6


def largestKSubmatrix(a):
    dp = [[0 for x in range(Row)]for y in range(Col)]
    result = 0
    for i in range(Row):
        for j in range(Col):
            if (i == 0 or j == 0):
                dp[i][j] = 1
            else:
                if (a[i][j] == a[i - 1][j] and a[i][j] == a[i]
                        [j - 1] and a[i][j] == a[i - 1][j - 1]):
                    dp[i][j] = min(
                        min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1
                else:
                    dp[i][j] = 1
            result = max(result, dp[i][j])
    return result


a = [[2, 2, 3, 3, 4, 4], [5, 5, 7, 7, 7, 4], [1, 2, 7, 7, 7, 4],
     [4, 4, 7, 7, 7, 4], [5, 5, 5, 1, 2, 7], [8, 7, 9, 4, 4, 4]]
print(largestKSubmatrix(a))

# Expected output:
3
# number of subsequences in a string divisible by n | returns count of subsequences of str divisible by n . ; division by n can leave only n remainder [ 0. . n - 1 ] . dp [ i ] [ j ] indicates number of subsequences in string [ 0. . i ] which leaves remainder j after division by n . ; filling value for first digit in str ; start a new subsequence with index i ; exclude i 'th character from all the  current subsequences of string [0...i-1] ; include i 'th character in all the current  subsequences of string [0...i-1] ; 
def countDivisibleSubseq(str, n):
    l = len(str)
    dp = [[0 for x in range(l)]for y in range(n)]
    dp[0][(ord(str[0]) - ord('0')) % n] += 1
    for i in range(1, l):
        dp[i][(ord(str[i]) - ord('0')) % n] += 1
        for j in range(n):
            dp[i][j] += dp[i - 1][j]
            dp[i][(j * 10 + (ord(str[i]) - ord('0'))) % n] += dp[i - 1][j]
    return dp[l - 1][0]


if __name__ == "__main__":
    str = "1234"
    n = 4
    print(countDivisibleSubseq(str, n))

# Expected output:
4
# size of array after repeated deletion of lis | function to construct maximum sum lis ; l [ i ] - the maximum sum increasing subsequence that ends with arr [ i ] ; l [ 0 ] is equal to arr [ 0 ] ; start from index 1 ; for every j less than i ; l [ i ] = maxsum ( l [ j ] ) + arr [ i ] where j < i and arr [ j ] < arr [ i ] ; l [ i ] ends with arr [ i ] ; set lis = lis whose size is max among all ; the > sign makes sure that the lis ending first is chose . ; function to minimize array ; find lis of current array ; if all elements are in decreasing order ; remove lis elements from current array . note that both lis [ ] and arr [ ] are sorted in increasing order . ; if first element of lis [ ] is found ; remove lis element from arr [ ] ; erase first element of lis [ ] ; print remaining element of array ; print - 1 for empty array ; 

from typing import List


def findLIS(arr: List[int], n: int) -> List[int]:
    L = [0] * n
    for i in range(n):
        L[i] = []
    L[0].append(arr[0])
    for i in range(1, n):
        for j in range(i):
            if (arr[i] > arr[j] and (len(L[i]) < len(L[j]))):
                L[i] = L[j].copy()
        L[i].append(arr[i])
    maxSize = 1
    lis: List[int] = []
    for x in L:
        if (len(x) > maxSize):
            lis = x .copy()
            maxSize = len(x)
    return lis


def minimize(input: List[int], n: int) -> None:
    arr = input .copy()
    while len(arr):
        lis = findLIS(arr, len(arr))
        if (len(lis) < 2):
            break
        i = 0
        while i < len(arr) and len(lis) > 0:
            if (arr[i] == lis[0]):
                arr .remove(arr[i])
                i -= 1
                lis .remove(lis[0])
            i += 1
    i = 0
    while i < len(arr):
        print(arr[i], end=" ")
        i += 1
    if (i == 0):
        print("-1")


if __name__ == "__main__":
    input = [3, 2, 6, 4, 5, 1]
    n = len(input)
    minimize(input, n)

# Expected output:
1
# count binary strings with k times appearing adjacent two set bits | python3 program to count number of binary strings with k times appearing consecutive 1 's. ; dp [ i ] [ j ] [ 0 ] stores count of binary strings of length i with j consecutive 1 ' s ▁ and ▁ ending ▁ at ▁ 0 . ▁ ▁ dp [ i ] [ j ] [1 ] ▁ stores ▁ count ▁ of ▁ binary ▁ ▁ strings ▁ of ▁ length ▁ i ▁ with ▁ j ▁ consecutive ▁ ▁ 1' s and ending at 1. ; if n = 1 and k = 0. ; number of adjacent 1 's can not exceed i-1 ; 
def countStrings(n, k):
    dp = [[[0, 0]for __ in range(k + 1)]for _ in range(n + 1)]
    dp[1][0][0] = 1
    dp[1][0][1] = 1
    for i in range(2, n + 1):
        for j in range(k + 1):
            dp[i][j][0] = (dp[i - 1][j][0] + dp[i - 1][j][1])
            dp[i][j][1] = dp[i - 1][j][0]
            if j >= 1:
                dp[i][j][1] += dp[i - 1][j - 1][1]
    return dp[n][k][0] + dp[n][k][1]


if __name__ == '__main__':
    n = 5
    k = 2
    print(countStrings(n, k))

# Expected output:
6
# check if all people can vote on two machines | returns true if n people can vote using two machines in x time . ; calculate total sum i . e total time taken by all people ; if total time is less than x then all people can definitely vote hence return true ; sort the list ; declare a list presum of same size as that of a and initialize it with 0 ; prefixsum for first element will be element itself ; fill the array ; set i and j and check if array from i to j - 1 gives sum <= x ; 
def canVote(a, n, x):
    total_sum = 0
    for i in range(len(a)):
        total_sum += a[i]
    if (total_sum <= x):
        return True
    a .sort()
    presum = [0 for i in range(len(a))]
    presum[0] = a[0]
    for i in range(1, len(presum)):
        presum[i] = presum[i - 1] + a[i]
    for i in range(0, len(presum)):
        for j in range(i + 1, len(presum)):
            arr1_sum = (presum[i] + (total_sum - presum[j]))
            if ((arr1_sum <= x) and (total_sum - arr1_sum) <= x):
                return True
    return False


n = 3
x = 4
a = [2, 4, 2]
if (canVote(a, n, x)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# friends pairing problem | python3 program for solution of friends pairing problem using recursion ; returns count of ways n people can remain single or paired up . ; 

dp = [-1] * 1000


def countFriendsPairings(n):
    global dp
    if (dp[n] != -1):
        return dp[n]
    if (n > 2):
        dp[n] = (countFriendsPairings(n - 1) + (n - 1)
                 * countFriendsPairings(n - 2))
        return dp[n]
    else:
        dp[n] = n
        return dp[n]


n = 4
print(countFriendsPairings(n))

# Expected output:
10
# maximum path sum in a triangle . | python program for dynamic programming implementation of max sum problem in a triangle ; function for finding maximum sum ; loop for bottom - up calculation ; for each element , check both elements just below the number and below right to the number add the maximum of them to it ; return the top element which stores the maximum sum ; 

N = 3


def maxPathSum(tri, m, n):
    for i in range(m - 1, -1, -1):
        for j in range(i + 1):
            if (tri[i + 1][j] > tri[i + 1][j + 1]):
                tri[i][j] += tri[i + 1][j]
            else:
                tri[i][j] += tri[i + 1][j + 1]
    return tri[0][0]


tri = [[1, 0, 0], [4, 8, 0], [1, 5, 3]]
print(maxPathSum(tri, 2, 2))

# Expected output:
14
# find maximum dot product of two arrays with insertion of 0 's | function compute maximum dot product and return it ; create 2d matrix that stores dot product dp [ i + 1 ] [ j + 1 ] stores product considering b [ 0. . i ] and a [ 0. . . j ] . note that since all m > n , we fill values in upper diagonal of dp [ ] [ ] ; traverse through all elements of b [ ] ; consider all values of a [ ] with indexes greater than or equal to i and compute dp [ i ] [ j ] ; two cases arise 1 ) include a [ j ] 2 ) exclude a [ j ] ( insert 0 in b [ ] ) ; return maximum dot product ; 
def MaxDotProduct(A, B, m, n):
    dp = [[0 for i in range(m + 1)]for j in range(n + 1)]
    for i in range(1, n + 1, 1):
        for j in range(i, m + 1, 1):
            dp[i][j] = max(
                (dp[i - 1][j - 1] + (A[j - 1] * B[i - 1])), dp[i][j - 1])
    return dp[n][m]


if __name__ == '__main__':
    A = [2, 3, 1, 7, 8]
    B = [3, 6, 7]
    m = len(A)
    n = len(B)
    print(MaxDotProduct(A, B, m, n))

# Expected output:
107
# lcs ( longest common subsequence ) of three strings | python3 program to find lcs of three strings ; returns length of lcs for x [ 0. . m - 1 ] , y [ 0. . n - 1 ] and z [ 0. . o - 1 ] ; 

X = "AGGT12"
Y = "12TXAYB"
Z = "12XBA"
dp = [[[-1 for i in range(100)]for j in range(100)]for k in range(100)]


def lcsOf3(i, j, k):
    if (i == -1 or j == -1 or k == -1):
        return 0
    if (dp[i][j][k] != -1):
        return dp[i][j][k]
    if (X[i] == Y[j] and Y[j] == Z[k]):
        dp[i][j][k] = 1 + lcsOf3(i - 1, j - 1, k - 1)
        return dp[i][j][k]
    else:
        dp[i][j][k] = max(
            max(lcsOf3(i - 1, j, k), lcsOf3(i, j - 1, k)), lcsOf3(i, j, k - 1))
        return dp[i][j][k]


if __name__ == "__main__":
    m = len(X)
    n = len(Y)
    o = len(Z)
    print("Length of LCS is", lcsOf3(m - 1, n - 1, o - 1))

# Expected output:
Length of LCS is 2