giulio98/xlcost-single-prompt huggingface dataset:
# subsequences of given string consisting of non | function to find all the subsequences of the str1ing with non - repeating ch1aracters ; base case ; insert current subsequence ; if str1 [ i ] is not present in the current subsequence ; insert str1 [ i ] into the set ; insert str1 [ i ] into the current subsequence ; remove str1 [ i ] from current subsequence ; remove str1 [ i ] from the set ; not including str1 [ i ] from the current subsequence ; utility function to print all subsequences of str1ing with non - repeating ch1aracters ; stores all possible subsequences with non - repeating ch1aracters ; stores subsequence with non - repeating ch1aracters ; traverse all possible subsequences containing non - repeating ch1aracters ; print subsequence ; 
def FindSub(sub, ch1, str1, res, i):
    if (i == len(str1)):
        sub .add(res)
        return
    if (str1[i]not in ch1):
        ch1 .add(str1[i])
        FindSub(sub, ch1, str1, res + str1[i], i + 1)
        res += str1[i]
        res = res[0:len(res) - 1]
        ch1 .remove(str1[i])
    FindSub(sub, ch1, str1, res, i + 1)


def printSubwithUniquech1ar(str1, N):
    sub = set()
    ch1 = set()
    FindSub(sub, ch1, str1, "", 0)
    temp = []
    for substr1ing in sub:
        temp .append(substr1ing)
    temp .sort(reverse=False)
    for x in temp:
        print(x, end=" ")


if __name__ == '__main__':
    str2 = "abac"
    N = len(str2)
    printSubwithUniquech1ar(str2, N)

# Expected output:
 a ab abc ac b ba bac bc c
# count lexicographically increasing k | function to count k - length strings from first n alphabets ; to keep track of column sum in dp ; auxiliary 2d dp array ; initialize dp [ 0 ] [ i ] = 1 and update the column_sum ; iterate for k times ; iterate for n times ; dp [ i ] [ j ] : stores the number of ways to form i - length strings consisting of j letters ; update the column_sum ; print number of ways to arrange k - length strings with n alphabets ; 
def waysToArrangeKLengthStrings(N, K):
    column_sum = [0 for i in range(N + 1)]
    i = 0
    j = 0
    dp = [[0 for i in range(N + 1)]for j in range(K + 1)]
    for i in range(N + 1):
        dp[0][i] = 1
        column_sum[i] = 1
    for i in range(1, K + 1):
        for j in range(1, N + 1):
            dp[i][j] += column_sum[j - 1]
            column_sum[j] += dp[i][j]
    print(dp[K][N])


if __name__ == '__main__':
    N = 5
    K = 2
    waysToArrangeKLengthStrings(N, K)

# Expected output:
15
# count n | function to count n - length strings consisting of vowels only sorted lexicographically ; stores count of strings consisting of vowels sorted lexicographically of all possible lengths ; initialize dp [ 1 ] [ 1 ] ; traverse the matrix row - wise ; base case ; return the result ; 
def findNumberOfStrings(n):
    DP = [[0 for i in range(6)]for i in range(n + 1)]
    DP[1][1] = 1
    for i in range(1, n + 1):
        for j in range(1, 6):
            if (i == 1):
                DP[i][j] = DP[i][j - 1] + 1
            else:
                DP[i][j] = DP[i][j - 1] + DP[i - 1][j]
    return DP[n][5]


if __name__ == '__main__':
    N = 2
    print(findNumberOfStrings(N))

# Expected output:
15
# largest subtree sum for each vertex of given n | python3 program for the above approach ; function to perform the dfs traversal on the given tree ; to check if v is leaf vertex ; initialize answer for vertex v ; traverse adjacency list of v ; update maximum subtree sum ; if v is leaf ; function to calculate maximum subtree sum for each vertex ; add edegs to the list ; calculate answer ; prthe result ; 

V = 3
M = 2


def dfs(v, p):
    isLeaf = 1
    ans[v] = -10 ** 9
    for u in adj[v]:
        if (u == p):
            continue
        isLeaf = 0
        dfs(u, v)
        ans[v] = max(ans[u] + vals[v], max(ans[u], vals[u]))
    if (isLeaf):
        ans[v] = vals[v]


def printAnswer(n, edges, vals):
    for i in range(n - 1):
        u = edges[i][0] - 1
        v = edges[i][1] - 1
        adj[u].append(v)
        adj[v].append(u)
    dfs(0, -1)
    for x in ans:
        print(x, end=" ")


if __name__ == '__main__':
    N = 4
    edges = [[1, 2], [1, 3], [3, 4]]
    adj = [[]for i in range(N)]
    ans = [0 for i in range(N)]
    vals = [1, -1, 0, 1]
    printAnswer(N, edges, vals)

# Expected output:
2 -1 1 1
# minimum cost required to rearrange a given array to make it equal to another given array | function to find lower_bound ; function to find length of the longest common subsequence ; find position where element is to be inserted ; return the length of lcs ; function to find the minimum cost required to convert the sequence a exactly same as b ; auxiliary array ; stores positions of elements of a [ ] initialize index array with - 1 ; update the index array with index of corresponding elements of b ; place only a 's array values  with its mapped values  into nums array ; find lcs ; no of elements to be added in array a [ ] ; stores minimum cost ; print the minimum cost ; given array a [ ] ; 
def LowerBound(a, k, x):
    l = -1
    r = k
    while (l + 1 < r):
        m = (l + r) >> 1
        if (a[m] >= x):
            r = m
        else:
            l = m
    return r


def findLCS(nums, N):
    k = 0
    for i in range(N):
        pos = LowerBound(nums, k, nums[i])
        nums[pos] = nums[i]
        if (k == pos):
            k = pos + 1
    return k


def minimumCost(A, B, M, N, C):
    nums = [0] * 100000
    index = [-1] * 100000
    for i in range(N):
        index[B[i]] = i
    k = 0
    for i in range(M):
        if (index[A[i]] != -1):
            k += 1
            nums[k] = index[A[i]]
    lcs_length = findLCS(nums, k)
    elements_to_be_added = N - lcs_length
    min_cost = elements_to_be_added * C
    print(min_cost)


A = [1, 6, 3, 5, 10]
B = [3, 1, 5]
C = 2
M = len(A)
N = len(B)
minimumCost(A, B, M, N, C)

# Expected output:
2
# maximize count of array elements required to obtain given sum | function that count the maximum number of elements to obtain sum v ; stores the maximum number of elements required to obtain v ; base case ; initialize all table values as infinite ; find the max arr required for all values from 1 to v ; go through all arr smaller than i ; if current coin value is less than i ; update table [ i ] ; return the final count ; 
def maxCount(arr, m, V):
    table = [0 for i in range(V + 1)]
    table[0] = 0
    for i in range(1, V + 1, 1):
        table[i] = -1
        for i in range(1, V + 1, 1):
            for j in range(0, m, 1):
                if (arr[j] <= i):
                    sub_res = table[i - arr[j]]
                    if (sub_res != -1 and sub_res + 1 > table[i]):
                        table[i] = sub_res + 1
    return table[V]


if __name__ == '__main__':
    arr = [25, 10, 5]
    m = len(arr)
    V = 30
    print('Maximumnumberofarrayelementsrequired:', maxCount(arr, m, V))

# Expected output:
Maximumnumberofarrayelementsrequired: 6
# maximize path sum from top | function to get the maximum path sum from top - left cell to all other cells of the given matrix ; store the maximum path sum initialize the value of dp [ i ] [ j ] to 0. ; base case ; compute the value of dp [ i ] [ j ] using the recurrence relation ; print maximum path sum from the top - left cell ; 
def pathSum(mat, N, M):
    dp = [[0 for x in range(M)]for y in range(N)]
    dp[0][0] = mat[0][0]
    for i in range(1, N):
        dp[i][0] = (mat[i][0] + dp[i - 1][0])
    for j in range(1, M):
        dp[0][j] = (mat[0][j] + dp[0][j - 1])
    for i in range(1, N):
        for j in range(1, M):
            dp[i][j] = (mat[i][j] + max(dp[i - 1][j], dp[i][j - 1]))
    for i in range(N):
        for j in range(M):
            print(dp[i][j], end=" ")
        print()


if __name__ == '__main__':
    mat = [[3, 2, 1], [6, 5, 4], [7, 8, 9]]
    N = 3
    M = 3
    pathSum(mat, N, M)

# Expected output:
3 5 6 
9 14 18 
16 24 33
# length of longest palindrome substring | function to find the length of the longest palindromic substring ; length of string str ; stores the dp states ; all substrings of length 1 are palindromes ; check for sub - string of length 2 ; if adjacent character are same ; update table [ i ] [ i + 1 ] ; check for lengths greater than 2 k is length of substring ; fix the starting index ; ending index of substring of length k ; check for palindromic substring str [ i , j ] ; mark true ; update the maximum length ; return length of lps ; 
def longestPalSubstr(str):
    n = len(str)
    table = [[False for i in range(n)]for j in range(n)]
    maxLength = 1
    for i in range(n):
        table[i][i] = True
    start = 0
    for i in range(n - 1):
        if (str[i] == str[i + 1]):
            table[i][i + 1] = True
            start = i
            maxLength = 2
    for k in range(3, n + 1):
        for i in range(n - k + 1):
            j = i + k - 1
            if (table[i + 1][j - 1] and str[i] == str[j]):
                table[i][j] = True
                if (k > maxLength):
                    start = i
                    maxLength = k
    return maxLength


if __name__ == '__main__':
    str = "forgeeksskeegfor"
    print(longestPalSubstr(str))

# Expected output:
10
# maximize sum of an array by flipping sign of all elements of a single subarray | python3 program for the above approach ; function to find the maximum sum after flipping a subarray ; stores the total sum of array ; initialize the maximum sum ; iterate over all possible subarrays ; initialize sum of the subarray before flipping sign ; initialize sum of subarray after flipping sign ; calculate the sum of original subarray ; subtract the original subarray sum and add the flipped subarray sum to the total sum ; return the max_sum ; 

import sys


def maxSumFlip(a, n):
    total_sum = 0
    for i in range(n):
        total_sum += a[i]
    max_sum = -sys .maxsize - 1
    for i in range(n):
        sum = 0
        flip_sum = 0
        for j in range(i, n):
            sum += a[j]
            max_sum = max(max_sum, total_sum - 2 * sum)
    return max(max_sum, total_sum)


arr = [-2, 3, -1, -4, -2]
N = len(arr)
print(maxSumFlip(arr, N))

# Expected output:
8
# minimum repeated addition of even divisors of n required to convert n to m | inf is the maximum value which indicates impossible state ; stores the dp states ; recursive function that considers all possible even divisors of cur ; indicates impossible state ; check dp [ cur ] is already calculated or not ; initially it is set to inf that meanswe cur can 't be transform to m ; loop to find even divisors of cur ; if i is divisor of cur ; if i is even ; find recursively for cur + i ; check another divisor ; find recursively for cur + ( cur / i ) ; finally store the current state result and return the answer ; function that counts the minimum operation to reduce n to m ; initialise dp state ; function call ; 

INF = 10000007
max_size = 100007
dp = [0 for i in range(max_size)]


def min_op(cur, M):
    if (cur > M):
        return INF
    if (cur == M):
        return 0
    if (dp[cur] != -1):
        return dp[cur]
    op = INF
    i = 2
    while (i * i <= cur):
        if (cur % i == 0):
            if (i % 2 == 0):
                op = min(op, 1 + min_op(cur + i, M))
            if ((cur // i) != i and (cur // i) % 2 == 0):
                op = min(op, 1 + min_op(cur + (cur // i), M))
        i += 1
    dp[cur] = op
    return op


def min_operations(N, M):
    for i in range(N, M + 1):
        dp[i] = -1
    return min_op(N, M)


if __name__ == "__main__":
    N = 6
    M = 24
    op = min_operations(N, M)
    if (op >= INF):
        print(-1)
    else:
        print(op)

# Expected output:
4
# maximize sum possible from an array by the given moves | function to find the maximum sum possible by given moves from the array ; checking for boundary ; if previously computed subproblem occurs ; if element can be moved left ; calculate maximum possible sum by moving left from current index ; if element can be moved right ; calculate maximum possible sum by moving right from current index and update the maximum sum ; store the maximum sum ; 
def maxValue(a, n, pos, moves, left, dp):
    if (moves == 0 or (pos > n - 1 or pos < 0)):
        return 0
    if (dp[pos][left] != -1):
        return dp[pos][left]
    value = 0
    if (left > 0 and pos >= 1):
        value = max(
            value,
            a[pos] +
            maxValue(
                a,
                n,
                pos -
                1,
                moves -
                1,
                left -
                1,
                dp))
    if (pos <= n - 1):
        value = max(
            value,
            a[pos] +
            maxValue(
                a,
                n,
                pos +
                1,
                moves -
                1,
                left,
                dp))
    dp[pos][left] = value
    return dp[pos][left]


n = 5
a = [1, 5, 4, 3, 2]
k = 1
m = 4
dp = [[-1 for x in range(k + 1)]for y in range(n + 1)]
print(a[0] + maxValue(a, n, 1, m, k, dp))

# Expected output:
19
# maximize the sum of a subsequence from an array based on given conditions | function to select the array elements to maximize the sum of the selected elements ; if the entire array is solved ; memoized subproblem ; calculate sum considering the current element in the subsequence ; calculate sum without considering the current element in the subsequence ; update the maximum of the above sums in the dp [ ] [ ] table ; 
def maximumSum(a, count, index, n, dp):
    if (index == n):
        return 0
    if (dp[index][count] != -1):
        return dp[index][count]
    take_element = (
        a[index] *
        count +
        maximumSum(
            a,
            count +
            1,
            index +
            1,
            n,
            dp))
    dont_take = maximumSum(a, count, index + 1, n, dp)
    dp[index][count] = max(take_element, dont_take)
    return dp[index][count]


n = 5
a = [-1, -9, 0, 5, -7]
dp = [[-1 for x in range(n + 1)]for y in range(n + 1)]
print(maximumSum(a, 1, 0, n, dp))

# Expected output:
14
# queries to find sum of distance of a given node to every leaf node in a weighted tree | max size ; graph with { destination , weight } ; for storing the sum for ith node ; leaves in subtree of ith . ; dfs to find sum of distance of leaves in the subtree of a node ; flag is the node is leaf or not ; skipping if parent ; setting flag to false ; doing dfs call ; doing calculation in postorder . ; if the node is leaf then we just increment the no . of leaves under the subtree of a node ; adding num of leaves ; calculating answer for the sum in the subtree ; dfs function to find the sum of distance of leaves outside the subtree ; number of leaves other than the leaves in the subtree of i ; adding the contribution of leaves outside to the ith node ; adding the leafs outside to ith node 's leaves. ; calculating the sum of distance of leaves in the subtree of a node assuming the root of the tree is 1 ; calculating the sum of distance of leaves outside the subtree of node assuming the root of the tree is 1 ; answering the queries ; 

N = 10 ** 5 + 5
v = [[]for i in range(N)]
dp = [0] * N
leaves = [0] * (N)
n = 0


def dfs(a, par):
    leaf = 1
    for i in v[a]:
        if (i[0] == par):
            continue
        leaf = 0
        dfs(i[0], a)
    if (leaf == 1):
        leaves[a] += 1
    else:
        for i in v[a]:
            if (i[0] == par):
                continue
            leaves[a] += leaves[i[0]]
            dp[a] = (dp[a] + dp[i[0]] + leaves[i[0]] * i[1])


def dfs2(a, par):
    for i in v[a]:
        if (i[0] == par):
            continue
        leafOutside = leaves[a] - leaves[i[0]]
        dp[i[0]] += (dp[a] - dp[i[0]])
        dp[i[0]] += i[1] * (leafOutside - leaves[i[0]])
        leaves[i[0]] += leafOutside
        dfs2(i[0], a)


def answerQueries(queries):
    dfs(1, 0)
    dfs2(1, 0)
    for i in range(len(queries)):
        print(dp[queries[i]])


if __name__ == '__main__':
    n = 5
    v[1].append([4, 4])
    v[4].append([1, 4])
    v[1].append([2, 2])
    v[2].append([1, 2])
    v[2].append([3, 3])
    v[3].append([2, 3])
    v[2].append([5, 5])
    v[5].append([2, 5])
    queries = [1, 3, 5]
    answerQueries(queries)

# Expected output:
16
17
19
# minimum changes required to make each path in a matrix palindrome | function for counting changes ; maximum distance possible is ( n - 1 + m - 1 ) ; stores the maximum element ; update the maximum ; stores frequencies of values for respective distances ; initialize frequencies of cells as 0 ; count frequencies of cell values in the matrix ; increment frequency of value at distance i + j ; store the most frequent value at i - th distance from ( 0 , 0 ) and ( n - 1 , m - 1 ) ; calculate max frequency and total cells at distance i ; count changes required to convert all cells at i - th distance to most frequent value ; 
def countChanges(matrix, n, m):
    dist = n + m - 1
    Max_element = 0
    for i in range(n):
        for j in range(m):
            Max_element = max(Max_element, matrix[i][j])
    freq = [[0 for i in range(Max_element + 1)]for j in range(dist)]
    for i in range(dist):
        for j in range(Max_element + 1):
            freq[i][j] = 0
    for i in range(n):
        for j in range(m):
            freq[i + j][matrix[i][j]] += 1
    min_changes_sum = 0
    for i in range(dist // 2):
        maximum = 0
        total_values = 0
        for j in range(Max_element + 1):
            maximum = max(maximum, freq[i][j] + freq[n + m - 2 - i][j])
            total_values += (freq[i][j] + freq[n + m - 2 - i][j])
        min_changes_sum += total_values - maximum
    return min_changes_sum


if __name__ == '__main__':
    mat = [[7, 0, 3, 1, 8, 1, 3], [0, 4, 0, 1, 0, 4, 0], [3, 1, 8, 3, 1, 0, 7]]
    minChanges = countChanges(mat, 3, 7)
    print(minChanges)

# Expected output:
6
# count of numbers upto n having absolute difference of at most k between any two adjacent digits | table to store solution of each subproblem ; function to calculate all possible numbers ; check if position reaches end that is equal to length of n ; check if the result is already computed simply return it ; maximum limit upto which we can place digit . if tight is false , means number has already become smaller so we can place any digit , otherwise n [ pos ] ; chekc if start is false the number has not started yet ; check if we do not start the number at pos then recur forward ; if we start the number we can place any digit from 1 to upper_limit ; finding the new tight ; condition if the number has already started ; we can place digit upto upperbound & absolute difference with previous digit much be atmost k ; absolute difference atmost k ; store the solution to this subproblem ; 

dp = [[[[-1 for i in range(2)]for j in range(2)]
       for i in range(10)]for j in range(1002)]


def possibleNumber(pos, previous, tight, start, N, K):
    if (pos == len(N)):
        return 1
    if (dp[pos][previous][tight][start] != -1):
        return dp[pos][previous][tight][start]
    res = 0
    if (tight):
        upper_limit = ord(N[pos]) - ord('0')
    else:
        upper_limit = 9
    if (not start):
        res = possibleNumber(pos + 1, previous, False, False, N, K)
        for i in range(1, upper_limit + 1):
            if (tight and i == upper_limit):
                new_tight = 1
            else:
                new_tight = 0
            res += possibleNumber(pos + 1, i, new_tight, True, N, K)
    else:
        for i in range(upper_limit + 1):
            if (tight and i == upper_limit):
                new_tight = 1
            else:
                new_tight = 0
            if (abs(i - previous) <= K):
                res += possibleNumber(pos + 1, i, new_tight, True, N, K)
    dp[pos][previous][tight][start] = res
    return dp[pos][previous][tight][start]


if __name__ == '__main__':
    N = "20"
    K = 2
    print(possibleNumber(0, 0, True, False, N, K))

# Expected output:
15
# minimum cost of reducing array by merging any adjacent elements repetitively | python3 program for the above approach ; function to find the total minimum cost of merging two consecutive numbers ; find the size of numbers [ ] ; if array is empty , return 0 ; to store the prefix sum of numbers array numbers [ ] ; traverse numbers [ ] to find the prefix sum ; dp table to memoised the value ; for single numbers cost is zero ; iterate for length >= 1 ; find sum in range [ i . . j ] ; initialise dp [ i ] [ j ] to _max ; iterate for all possible k to find the minimum cost ; update the minimum sum ; return the final minimum cost ; 

import sys


def mergeTwoNumbers(numbers):
    n = len(numbers)
    if (len(numbers) == 0):
        return 0
    prefixSum = [0] * (n + 1)
    for i in range(1, n + 1):
        prefixSum[i] = (prefixSum[i - 1] + numbers[i - 1])
    dp = [[0 for i in range(n + 1)]for j in range(n + 1)]
    for i in range(1, n + 1):
        dp[i][i] = 0
    for p in range(2, n + 1):
        for i in range(1, n - p + 2):
            j = i + p - 1
            sum = prefixSum[j] - prefixSum[i - 1]
            dp[i][j] = sys .maxsize
            for k in range(i, j):
                dp[i][j] = min(dp[i][j], (dp[i][k] + dp[k + 1][j] + sum))
    return dp[1][n]


arr1 = [6, 4, 4, 6]
print(mergeTwoNumbers(arr1))

# Expected output:
40
# count of pairs in an array with same number of set bits | function to return the count of pairs ; get the maximum element ; array to store count of bits of all elements upto maxm ; store the set bits for powers of 2 ; compute the set bits for the remaining elements ; store the frequency of respective counts of set bits ; 
def countPairs(arr, N):
    maxm = max(arr)
    i = 0
    k = 0
    bitscount = [0 for i in range(maxm + 1)]
    i = 1
    while i <= maxm:
        bitscount[i] = 1
        i *= 2
    for i in range(1, maxm + 1):
        if (bitscount[i] == 1):
            k = i
        if (bitscount[i] == 0):
            bitscount[i] = (bitscount[k] + bitscount[i - k])
    setbits = dict()
    for i in range(N):
        if bitscount[arr[i]] in setbits:
            setbits[bitscount[arr[i]]] += 1
        else:
            setbits[bitscount[arr[i]]] = 1
    ans = 0
    for it in setbits .values():
        ans += it * (it - 1) // 2
    return ans


if __name__ == '__main__':
    N = 12
    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    print(countPairs(arr, N))

# Expected output:
22