giulio98/xlcost-single-prompt huggingface dataset:
# count of arrays of size n having absolute difference between adjacent elements at most 1 | function to find the count of possible arrays such that the absolute difference between any adjacent elements is atmost 1 ; stores the dp states where dp [ i ] [ j ] represents count of arrays of length i + 1 having their last element as j ; case where 1 st array element is missing ; all integers in range [ 1 , m ] are reachable ; only reachable integer is arr [ 0 ] ; iterate through all values of i ; if arr [ i ] is not missing ; only valid value of j is arr [ i ] ; if arr [ i ] is missing ; iterate through all possible values of j in range [ 1 , m ] ; stores the count of valid arrays ; calculate the total count of valid arrays ; return answer ; 
def countArray(arr, N, M):
    dp = [[0 for i in range(M + 2)]for j in range(N)]
    if (arr[0] == -1):
        for j in range(1, M + 1, 1):
            dp[0][j] = 1
    else:
        dp[0][arr[0]] = 1
    for i in range(1, N, 1):
        if (arr[i] != -1):
            j = arr[i]
            dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j] + dp[i - 1][j + 1]
        if (arr[i] == -1):
            for j in range(1, M + 1, 1):
                dp[i][j] += dp[i - 1][j - 1] + dp[i - 1][j] + dp[i - 1][j + 1]
    arrCount = 0
    for j in range(1, M + 1, 1):
        arrCount += dp[N - 1][j]
    return arrCount


if __name__ == '__main__':
    arr = [4, -1, 2, 1, -1, -1]
    N = len(arr)
    M = 10
    print(countArray(arr, N, M))

# Expected output:
5
# maximize sum of product of neighbouring elements of the element removed from array | function to calculate maximum possible score using the given operations ; iterate through all possible len1gths of the subarray ; iterate through all the possible starting indices i having len1gth len1 ; stores the rightmost index of the current subarray ; initial dp [ i ] [ j ] will be 0. ; iterate through all possible values of k in range [ i + 1 , j - 1 ] ; return the answer ; 
def maxMergingScore(A, N):
    dp = [[0 for i in range(101)]for j in range(101)]
    for len1 in range(1, N, 1):
        for i in range(0, N - len1, 1):
            j = i + len1
            dp[i][j] = 0
            for k in range(i + 1, j, 1):
                dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + A[i] * A[j])
    return dp[0][N - 1]


if __name__ == '__main__':
    N = 4
    A = [1, 2, 3, 4]
    print(maxMergingScore(A, N))
    N = 2
    B = [1, 55]
    print(maxMergingScore(B, N))

# Expected output:
12
0
# longest subarray with all even or all odd elements | function to calculate longest substring with odd or even elements ; initializing dp initializing dp with 1 ; ans will store the final answer ; traversing the array from index 1 to n - 1 ; checking both current and previous element is even or odd ; updating dp with ( previous dp value ) + 1 ; storing max element so far to ans ; returning the final answer ; 
def LongestOddEvenSubarray(A, N):
    dp = 1
    ans = 1
    for i in range(1, N):
        if ((A[i] %
             2 == 0 and A[i - 1] %
             2 == 0) or (A[i] %
                         2 != 0 and A[i - 1] %
                         2 != 0)):
            dp = dp + 1
            ans = max(ans, dp)
        else:
            dp = 1
    return ans


A = [2, 5, 7, 2, 4, 6, 8, 3]
N = len(A)
print(LongestOddEvenSubarray(A, N))

# Expected output:
4
# count of n | python program for the above approach ; function to find number of ' n ' digit numbers such that the element is mean of sum of its adjacent digits ; if digit = n + 1 , a valid n - digit number has been formed ; if the state has already been computed ; if current position is 1 , then any digit from [ 1 - 9 ] can be placed . if n = 1 , 0 can be also placed . ; if current position is 2 , then any digit from [ 1 - 9 ] can be placed . ; previous digit selected is the mean . ; mean = ( current + prev2 ) / 2 current = ( 2 * mean ) - prev2 ; check if current and current + 1 can be valid placements ; return answer ; 

dp = [[[-1 for i in range(10)]for col in range(20)]for row in range(100)]


def countOfNumbers(digit, prev1, prev2, n):
    if (digit == n + 1):
        return 1
    val = dp[digit][prev1][prev2]
    if (val != -1):
        return val
    val = 0
    if (digit == 1):
        start = 1
        if (n == 1):
            start = 0
        for i in range(start, 10):
            val += countOfNumbers(digit + 1, i, prev1, n)
    elif (digit == 2):
        for i in range(0, 10):
            val += countOfNumbers(digit + 1, i, prev1, n)
    else:
        mean = prev1
        current = (2 * mean) - prev2
        if (current >= 0 and current <= 9):
            val += countOfNumbers(digit + 1, current, prev1, n)
        if ((current + 1) >= 0 and (current + 1) <= 9):
            val += countOfNumbers(digit + 1, current + 1, prev1, n)
    return val


n = 2
print(countOfNumbers(1, 0, 0, n))

# Expected output:
90
# count half nodes in a binary tree ( iterative and recursive ) | a node structure ; iterative method to count half nodes of binary tree ; base case ; create an empty queue for level order traversal ; initialize count for half nodes ; enqueue left child ; enqueue right child ; 

class Node:
    def __init__(self, key):
        self .data = key
        self .left = None
        self .right = None


def gethalfCount(root):
    if root is None:
        return 0
    queue = []
    queue .append(root)
    count = 0
    while (len(queue) > 0):
        node = queue .pop(0)
        if node .left is not None and node .right is None or node .left is None and node .right is not None:
            count = count + 1
        if node .left is not None:
            queue .append(node .left)
        if node .right is not None:
            queue .append(node .right)
    return count


root = Node(2)
root .left = Node(7)
root .right = Node(5)
root .left .right = Node(6)
root .left .right .left = Node(1)
root .left .right .right = Node(11)
root .right .right = Node(9)
root .right .right .left = Node(4)
print("%d" % (gethalfCount(root)))

# Expected output:
3
# count n | python3 program for the above approach ; function to count n digit numbers whose digits are less than or equal to the absolute difference of previous two digits ; if all digits are traversed ; if the state has already been computed ; if the current digit is 1 , any digit from [ 1 - 9 ] can be placed . if n == 1 , 0 can also be placed . ; if the current digit is 2 , any digit from [ 0 - 9 ] can be placed ; for other digits , any digit from 0 to abs ( prev1 - prev2 ) can be placed ; return the answer ; 

dp = [[[-1 for i in range(10)]for j in range(10)]for k in range(50)]


def countOfNumbers(digit, prev1, prev2, N):
    if (digit == N + 1):
        return 1
    if (dp[digit][prev1][prev2] != -1):
        return dp[digit][prev1][prev2]
    dp[digit][prev1][prev2] = 0
    if (digit == 1):
        term = 0 if N == 1 else 1
        for j in range(term, 10, 1):
            dp[digit][prev1][prev2] += countOfNumbers(digit + 1, j, prev1, N)
    elif (digit == 2):
        for j in range(10):
            dp[digit][prev1][prev2] += countOfNumbers(digit + 1, j, prev1, N)
    else:
        for j in range(abs(prev1 - prev2) + 1):
            dp[digit][prev1][prev2] += countOfNumbers(digit + 1, j, prev1, N)
    return dp[digit][prev1][prev2]


if __name__ == '__main__':
    N = 3
    print(countOfNumbers(1, 0, 0, N))

# Expected output:
375
# count number of unique ways to paint a n x 3 grid | function to count the number of ways to paint n * 3 grid based on given conditions ; count of ways to pain a row with same colored ends ; count of ways to pain a row with different colored ends ; traverse up to ( n - 1 ) th row ; for same colored ends ; for different colored ends ; print the total number of ways ; 
def waysToPaint(n):
    same = 6
    diff = 6
    for _ in range(n - 1):
        sameTmp = 3 * same + 2 * diff
        diffTmp = 2 * same + 2 * diff
        same = sameTmp
        diff = diffTmp
    print(same + diff)


N = 2
waysToPaint(N)

# Expected output:
54
# maximize sum by selecting x different | function to find maximum sum of at most n with different index array elements such that at most x are from a [ ] , y are from b [ ] and z are from c [ ] ; base cases ; selecting i - th element from a [ ] ; selecting i - th element from b [ ] ; selecting i - th element from c [ ] ; i - th elements not selected from any of the arrays ; select the maximum sum from all the possible calls ; 
def FindMaxS(X, Y, Z, n):
    global A, B, C
    if (X < 0 or Y < 0 or Z < 0):
        return -10 ** 9
    if (n < 0):
        return 0
    ch = A[n] + FindMaxS(X - 1, Y, Z, n - 1)
    ca = B[n] + FindMaxS(X, Y - 1, Z, n - 1)
    co = C[n] + FindMaxS(X, Y, Z - 1, n - 1)
    no = FindMaxS(X, Y, Z, n - 1)
    maximum = max(ch, max(ca, max(co, no)))
    return maximum


if __name__ == '__main__':
    X = 1
    Y = 1
    Z = 1
    A = [10, 0, 5]
    B = [5, 10, 0]
    C = [0, 5, 10]
    n = len(B)
    print(FindMaxS(X, Y, Z, n - 1))

# Expected output:
30
# rearrange array by interchanging positions of even and odd elements in the given array | function to replace each even element by odd and vice - versa in a given array ; traverse array ; if current element is even then swap it with odd ; perform swap ; change the sign ; if current element is odd then swap it with even ; perform swap ; change the sign ; marked element positive ; print final array ; 
def replace(arr, n):
    for i in range(n):
        for j in range(i + 1, n):
            if (arr[i] >= 0 and arr[j] >= 0 and arr[i] %
                    2 == 0 and arr[j] % 2 != 0):
                tmp = arr[i]
                arr[i] = arr[j]
                arr[j] = tmp
                arr[j] = -arr[j]
                break
            elif (arr[i] >= 0 and arr[j] >= 0 and arr[i] % 2 != 0 and arr[j] % 2 == 0):
                tmp = arr[i]
                arr[i] = arr[j]
                arr[j] = tmp
                arr[j] = -arr[j]
                break
    for i in range(n):
        arr[i] = abs(arr[i])
    for i in range(n):
        print(arr[i], end=" ")


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

# Expected output:
2 4 1 3
# minimize cost to reduce array to a single element by replacing k consecutive elements by their sum | function to find the minimum cost to reduce given array to a single element by replacing consecutive k array elements ; stores length of arr ; if ( n - 1 ) is not multiple of ( k - 1 ) ; store prefix sum of the array ; iterate over the range [ 1 , n ] ; update prefixsum [ i ] ; dp [ i ] [ j ] : store minimum cost to merge array elements interval [ i , j ] ; l : stores length of interval [ i , j ] ; iterate over each interval [ i , j ] of length l in in [ 0 , n ] ; stores index of last element of the interval [ i , j ] ; if l is greater than k ; update dp [ i ] [ j ] ; if ( l - 1 ) is multiple of ( k - 1 ) ; update dp [ i ] [ j ] ; return dp [ 0 ] [ n - 1 ] ; 
def minimumCostToMergeK(arr, K):
    N = len(arr)
    if (N - 1) % (K - 1) != 0:
        return -1
    prefixSum = [0] * (N + 1)
    for i in range(1, N + 1):
        prefixSum[i] = (prefixSum[i - 1] + arr[i - 1])
    dp = [[0] * N for _ in range(N)]
    for L in range(K, N + 1):
        for i in range(N - L + 1):
            j = i + L - 1
            if L > K:
                dp[i][j] = (min([dp[i][x] + dp[x + 1][j]
                            for x in range(i, j, K - 1)]))
            if (L - 1) % (K - 1) == 0:
                dp[i][j] += (prefixSum[j + 1] - prefixSum[i])
    return dp[0][N - 1]


if __name__ == "__main__":
    arr = [3, 5, 1, 2, 6]
    K = 3
print(minimumCostToMergeK(arr, K))

# Expected output:
25
# check if end of a sorted array can be reached by repeated jumps of one more , one less or same number of indices as previous jump | python3 program for the above approach ; utility function to check if it is possible to move from index 1 to n - 1 ; successfully reached end index ; memo [ i ] [ j ] is already calculated ; check if there is any index having value of a [ i ] + j - 1 , a [ i ] + j or a [ i ] + j + 1 ; if a [ k ] > a [ i ] + j + 1 , can 't make a move further ; it 's possible to move a[k] ; check is it possible to move from index k having previously taken a [ k ] - a [ i ] steps ; if yes then break the loop ; store value of flag in memo ; return memo [ i ] [ j ] ; function to check if it is possible to move from index 1 to n - 1 ; stores the memoized state ; initialize all values as - 1 ; initially , starting index = 1 ; function call ; 

N = 8


def check(memo, i, j, A):
    if (i == N - 1):
        return 1
    if (memo[i][j] != -1):
        return memo[i][j]
    flag = 0
    for k in range(i + 1, N):
        if (A[k] - A[i] > j + 1):
            break
        if (A[k] - A[i] >= j - 1 and A[k] - A[i] <= j + 1):
            flag = check(memo, k, A[k] - A[i], A)
        if (flag != 0):
            break
    memo[i][j] = flag
    return memo[i][j]


def checkEndReach(A, K):
    memo = [[0] * N] * N
    for i in range(0, N):
        for j in range(0, N):
            memo[i][j] = -1
    startIndex = 1
    if (check(memo, startIndex, K, A) != 0):
        return True
    else:
        return False


if __name__ == '__main__':
    A = [0, 1, 3, 5, 6, 8, 12, 17]
    K = 1
    if (checkEndReach(A, K)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# maximum subsequence sum such that no k elements are consecutive | function to find the maximum sum of a subsequence consisting of no k consecutive array elements ; stores states of dp ; stores the prefix sum ; update the prefix sum ; base case for i < k ; for indices less than k take all the elements ; for i >= k case ; skip each element from i to ( i - k + 1 ) to ensure that no k elements are consecutive ; update the current dp state ; dp [ n ] stores the maximum sum ; 
def Max_Sum(arr, K, N):
    dp = [0] * (N + 1)
    prefix = [None] * (N + 1)
    prefix[0] = 0
    for i in range(1, N + 1):
        prefix[i] = prefix[i - 1] + arr[i - 1]
    dp[0] = 0
    for i in range(1, K):
        dp[i] = prefix[i]
    for i in range(K, N + 1):
        for j in range(i, i - K, -1):
            dp[i] = max(dp[i], dp[j - 1] + prefix[i] - prefix[j])
    return dp[N]


if __name__ == "__main__":
    arr = [4, 12, 22, 18, 34, 12, 25]
    N = len(arr)
    K = 5
    print(Max_Sum(arr, K, N))

# Expected output:
111
# count possible splits of sum n into k integers such that the minimum is at least p | function that finds the value of the binomial coefficient c ( n , k ) ; stores the value of binomial coefficient in bottom up manner ; base case ; find the value using previously stored values ; return the value of c ( n , k ) ; function that count the number of ways to divide n into k integers >= p such that their sum is n ; update the value of n ; find the binomial coefficient recursively ; 
def binomialCoeff(n, k):
    C = [[0 for x in range(k + 1)]for y in range(n + 1)]
    for i in range(n + 1):
        for j in range(min(i, k) + 1):
            if (j == 0 or j == i):
                C[i][j] = 1
            else:
                C[i][j] = (C[i - 1][j - 1] + C[i - 1][j])
    return C[n][k]


def waysToSplitN(k, n, P):
    new_N = n - k * P
    return binomialCoeff(new_N + k - 1, new_N)


K = 3
N = 8
P = 2
print(waysToSplitN(K, N, P))

# Expected output:
6
# minimum pair merge operations required to make array non | function to find the minimum operations to make the array non - increasing ; size of the array ; dp table initialization ; dp [ i ] : stores minimum number of operations required to make subarray { a [ i ] , ... , a [ n ] } non - increasing ; increment the value of j ; add current value to sum ; update the dp tables ; return the answer ; 
def solve(a):
    n = len(a)
    dp = [0] * (n + 1)
    val = [0] * (n + 1)
    for i in range(n - 1, -1, -1):
        sum = a[i]
        j = i
        while (j + 1 < n and sum < val[j + 1]):
            j += 1
            sum += a[j]
        dp[i] = (j - i) + dp[j + 1]
        val[i] = sum
    return dp[0]


arr = [1, 5, 3, 9, 1]
print(solve(arr))

# Expected output:
2
# count full nodes in a binary tree ( iterative and recursive ) | a node structure ; iterative method to count full nodes of binary tree ; base case ; create an empty queue for level order traversal ; enqueue root and initialize count ; 

class Node:
    def __init__(self, key):
        self .data = key
        self .left = None
        self .right = None


def getfullCount(root):
    if root is None:
        return 0
    queue = []
    queue .append(root)
    count = 0
    while (len(queue) > 0):
        node = queue .pop(0)
        if node .left is not None and node .right is not None:
            count = count + 1
        if node .left is not None:
            queue .append(node .left)
        if node .right is not None:
            queue .append(node .right)
    return count


root = Node(2)
root .left = Node(7)
root .right = Node(5)
root .left .right = Node(6)
root .left .right .left = Node(1)
root .left .right .right = Node(11)
root .right .right = Node(9)
root .right .right .left = Node(4)
print("%d" % (getfullCount(root)))

# Expected output:
2
# count of distinct substrings occurring consecutively in a given string | function to count the distinct substrings placed consecutively in the given string ; length of the string ; if length of the string does not exceed 1 ; initialize a dp - table ; stores the distinct substring ; iterate from end of the string ; iterate backward until dp table is all computed ; if character at i - th index is same as character at j - th index ; update dp [ i ] [ j ] based on previously computed value ; otherwise ; condition for consecutively placed similar substring ; return the count ; 
def distinctSimilarSubstrings(str):
    n = len(str)
    if (n <= 1):
        return 0
    dp = [[0 for x in range(n + 1)]for y in range(n + 1)]
    substrings = set()
    for j in range(n - 1, -1, -1):
        for i in range(j - 1, -1, -1):
            if (str[i] == str[j]):
                dp[i][j] = dp[i + 1][j + 1] + 1
            else:
                dp[i][j] = 0
            if (dp[i][j] >= j - i):
                substrings .add(str[i:j - i])
    return len(substrings)


str = "geeksgeeksforgeeks"
print(distinctSimilarSubstrings(str))

# Expected output:
2
# count sequences of length k having each term divisible by its preceding term | stores the factors of i - th element in v [ i ] ; function to find all the factors of n ; iterate upto sqrt ( n ) ; function to return the count of sequences of length k having all terms divisible by its preceding term ; calculate factors of i ; initialize dp [ 0 ] [ i ] = 0 : no subsequence of length 0 ending with i - th element exists ; initialize dp [ 0 ] [ i ] = 1 : only 1 subsequence of length 1 ending with i - th element exists ; iterate [ 2 , k ] to obtain sequences of each length ; calculate sum of all dp [ i - 1 ] [ vp [ j ] [ k ] ] ; vp [ j ] [ k ] stores all factors of j ; store the sum in a [ i ] [ j ] ; sum of all dp [ k ] [ j ] obtain all k length sequences ending with j ; 

vp = [[]for i in range(2009)]


def finding_factors(n):
    i = 1
    a = 0
    global vp
    while (i * i <= n):
        if (n % i == 0):
            if (i * i == n):
                vp[n].append(i)
            else:
                vp[n].append(i)
                vp[n].append(int(n / i))
        i += 1


def countSeq(N, K):
    i = 0
    j = 0
    k = 0
    dp = [[0 for i in range(109)]for j in range(109)]
    for i in range(1, N + 1):
        finding_factors(i)
        dp[0][i] = 0
        dp[1][i] = 1
    for i in range(2, K + 1):
        for j in range(1, N + 1):
            Sum = 0
            for k in range(len(vp[j])):
                Sum += dp[i - 1][vp[j][k]]
            dp[i][j] = Sum
    ans = 0
    for j in range(1, N + 1):
        ans += dp[K][j]
    return ans


N = 3
K = 2
print(countSeq(N, K))

# Expected output:
5
# largest possible square submatrix with maximum and value | function to calculate and return the length of square submatrix with maximum and value ; extract dimensions ; auxiliary array initialize auxiliary array ; c : stores the maximum value in the matrix p : stores the number of elements in the submatrix having maximum and value ; iterate over the matrix to fill the auxiliary matrix ; find the max element in the matrix side by side ; fill first row and column with 1 's ; for every cell , check if the elements at the left , top and top left cells from the current cell are equal or not ; store the minimum possible submatrix size these elements are part of ; store 1 otherwise ; checking maximum value ; if the maximum and value occurs more than once ; update the maximum size of submatrix ; final output ; 
def MAX_value(arr):
    row = len(arr)
    col = len(arr)
    dp = [[0 for i in range(col)]for j in range(row)]
    i, j = 0, 0
    c, p = arr[0][0], 0
    d = row
    for i in range(d):
        for j in range(d):
            if (c < arr[i][j]):
                c = arr[i][j]
            if (i == 0 or j == 0):
                dp[i][j] = 1
            else:
                if (arr[i - 1][j - 1] == arr[i][j] and arr[i - 1][j]
                        == arr[i][j] and arr[i][j - 1] == arr[i][j]):
                    dp[i][j] = min(dp[i - 1][j - 1],
                                   min(dp[i - 1][j], dp[i][j - 1])) + 1
                else:
                    dp[i][j] = 1
    for i in range(d):
        for j in range(d):
            if (arr[i][j] == c):
                if (p < dp[i][j]):
                    p = dp[i][j]
    return p * p


arr = [[9, 9, 3, 3, 4, 4], [9, 9, 7, 7, 7, 4], [1, 2, 7, 7, 7, 4],
       [4, 4, 7, 7, 7, 4], [5, 5, 1, 1, 2, 7], [2, 7, 1, 1, 4, 4]]
print(MAX_value(arr))

# Expected output:
4
# smallest power of 2 consisting of n digits | python3 program to implement the above approach ; function to return smallest power of 2 with n digits ; iterate through all powers of 2 ; 

from math import log10, log


def smallestNum(n):
    res = 1
    i = 2
    while (True):
        length = int(log10(i) + 1)
        if (length == n):
            return int(log(i) // log(2))
        i *= 2


n = 4
print(smallestNum(n))

# Expected output:
10
# count possible decodings of a given digit sequence in o ( n ) time and constant auxiliary space | a dynamic programming based function to count decodings in digit sequence ; for base condition "01123" should return 0 ; using last two calculated values , calculate for ith index ; change boolean to int ; return the required answer ; 
def countDecodingDP(digits, n):
    if (digits[0] == '0'):
        return 0
    count0 = 1
    count1 = 1
    for i in range(2, n + 1):
        dig1 = 0
        dig3 = 0
        if (digits[i - 1] != '0'):
            dig1 = 1
        if (digits[i - 2] == '1'):
            dig2 = 1
        else:
            dig2 = 0
        if (digits[i - 2] == '2' and digits[i - 1] < '7'):
            dig3 = 1
        count2 = dig1 * count1 + dig2 + dig3 * count0
        count0 = count1
        count1 = count2
    return count1


if __name__ == '__main__':
    digits = "1234"
    n = len(digits)
    print(countDecodingDP(digits, n))

# Expected output:
3