giulio98/xlcost-single-prompt huggingface dataset:
# find the numbers from 1 to n that contains exactly k non | function to find number less than n having k non - zero digits ; store the memorised values ; initialise ; base ; calculate all states for every state , from numbers 1 to n , the count of numbers which contain exactly j non zero digits is being computed and updated in the dp array . ; return the required answer ; 
def k_nonzero_numbers(s, n, k):
    dp = [[[0 for i in range(k + 2)]for i in range(2)]for i in range(n + 2)]
    for i in range(n + 1):
        for j in range(2):
            for x in range(k + 1):
                dp[i][j][x] = 0
    dp[0][0][0] = 1
    for i in range(n):
        sm = 0
        while (sm < 2):
            for j in range(k + 1):
                x = 0
                y = 0
                if sm:
                    y = 9
                else:
                    y = ord(s[i]) - ord('0')
                while (x <= y):
                    dp[i + 1][(sm or x < (ord(s[i]) - ord('0')))
                              ][j + (x > 0)] += dp[i][sm][j]
                    x += 1
            sm += 1
    return dp[n][0][k] + dp[n][1][k]


if __name__ == '__main__':
    s = "25"
    k = 2
    n = len(s)
    print(k_nonzero_numbers(s, n, k))

# Expected output:
14
# count maximum occurrence of subsequence in string such that indices in subsequence is in a . p . | function to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; frequencies of subsequence ; loop to find the frequencies of subsequence of length 1 ; loop to find the frequencies subsequence of length 2 ; finding maximum frequency ; 
def maximumOccurrence(s):
    n = len(s)
    freq = {}
    for i in s:
        temp = ""
        temp += i
        freq[temp] = freq .get(temp, 0) + 1
    for i in range(n):
        for j in range(i + 1, n):
            temp = ""
            temp += s[i]
            temp += s[j]
            freq[temp] = freq .get(temp, 0) + 1
    answer = -10 ** 9
    for it in freq:
        answer = max(answer, freq[it])
    return answer


if __name__ == '__main__':
    s = "xxxyy"
    print(maximumOccurrence(s))

# Expected output:
6
# count ways to partition a string such that both parts have equal distinct characters | function to count the distinct characters in the string ; frequency of each character ; loop to count the frequency of each character of the string ; if frequency is greater than 0 then the character occured ; function to count the number of ways to partition the string such that each partition have same number of distinct character ; loop to choose the partition index for the string ; divide in two parts ; check whether number of distinct characters are equal ; 
def distinctChars(s):
    freq = [0] * 26
    count = 0
    for i in range(len(s)):
        freq[ord(s[i]) - ord('a')] += 1
    for i in range(26):
        if (freq[i] > 0):
            count += 1
    return count


def waysToSplit(s):
    n = len(s)
    answer = 0
    for i in range(1, n):
        left = s[0:i]
        right = s[i:n]
        if (distinctChars(left) == distinctChars(right)):
            answer += 1
    return answer


if __name__ == "__main__":
    s = "ababa"
    print(waysToSplit(s))

# Expected output:
2
# count ways to partition a string such that both parts have equal distinct characters | function to count the number of ways to partition the string such that each partition have same number of distinct character ; prefix and suffix array for distinct character from start and end ; to check whether a character has appeared till ith index ; calculating prefix array ; character appears for the first time in string ; character is visited ; resetting seen for suffix calculation ; calculating the suffix array ; character appears for the first time ; this character has now appeared ; loop to calculate the number partition points in the string ; check whether number of distinct characters are equal ; 
def waysToSplit(s):
    n = len(s)
    answer = 0
    prefix = [0] * n
    suffix = [0] * n
    seen = [0] * 26
    for i in range(n):
        prev = prefix[i - 1]if (i - 1 >= 0)else 0
        if (seen[ord(s[i]) - ord('a')] == 0):
            prefix[i] += (prev + 1)
        else:
            prefix[i] = prev
        seen[ord(s[i]) - ord('a')] = 1
    seen = [0] * len(seen)
    suffix[n - 1] = 0
    for i in range(n - 1, 0, -1):
        prev = suffix[i]
        if (seen[ord(s[i]) - ord('a')] == 0):
            suffix[i - 1] += (prev + 1)
        else:
            suffix[i - 1] = prev
        seen[ord(s[i]) - ord('a')] = 1
    for i in range(n):
        if (prefix[i] == suffix[i]):
            answer += 1
    return answer


if __name__ == "__main__":
    s = "ababa"
    print(waysToSplit(s))

# Expected output:
2
# counts paths from a point to reach origin : memory optimized | function to count the paths from a point to the origin ; base case when the point is already at origin ; base case when the point is on the x or y - axis ; loop to fill all the position as 1 in the array ; loop to count the number of paths from a point to origin in bottom - up manner ; 
def Count_Paths(x, y):
    if (x == 0 and y == 0):
        return 0
    if (x == 0 and y == 0):
        return 1
    dp = [0] * (max(x, y) + 1)
    p = max(x, y)
    q = min(x, y)
    for i in range(p + 1):
        dp[i] = 1
    for i in range(1, q + 1):
        for j in range(1, p + 1):
            dp[j] += dp[j - 1]
    return dp[p]


x = 3
y = 3
print("Number of Paths ", Count_Paths(x, y))

# Expected output:
Number of Paths  20
# count the number of ways to divide n in k groups incrementally | function to count the number of ways to divide the number n in groups such that each group has k number of elements ; base case ; if n is divides completely into less than k groups ; put all possible values greater equal to prev ; function to count the number of ways to divide the number n ; 
def calculate(pos, prev, left, k):
    if (pos == k):
        if (left == 0):
            return 1
        else:
            return 0
    if (left == 0):
        return 0
    answer = 0
    for i in range(prev, left + 1):
        answer += calculate(pos + 1, i, left - i, k)
    return answer


def countWaystoDivide(n, k):
    return calculate(0, 1, n, k)


if __name__ == '__main__':
    N = 8
    K = 4
    print(countWaystoDivide(N, K))

# Expected output:
5
# count the number of ways to divide n in k groups incrementally | dp table ; function to count the number of ways to divide the number n in groups such that each group has k number of elements ; base case ; if n is divides completely into less than k groups ; if the subproblem has been solved , use the value ; put all possible values greater equal to prev ; function to count the number of ways to divide the number n in groups ; initialize dp table as - 1 ; 

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


def calculate(pos, prev, left, k):
    if (pos == k):
        if (left == 0):
            return 1
        else:
            return 0
    if (left == 0):
        return 0
    if (dp[pos][prev][left] != -1):
        return dp[pos][prev][left]
    answer = 0
    for i in range(prev, left + 1):
        answer += calculate(pos + 1, i, left - i, k)
    dp[pos][prev][left] = answer
    return dp[pos][prev][left]


def countWaystoDivide(n, k):
    for i in range(50):
        for j in range(50):
            for l in range(50):
                dp[i][j][l] = -1
    return calculate(0, 1, n, k)


if __name__ == '__main__':
    N = 8
    K = 4
    print(countWaystoDivide(N, K))

# Expected output:
5
# maximum score possible after performing given operations on an array | function to calculate maximum score recursively ; base case ; sum of array in range ( l , r ) ; if the operation is even - numbered the score is decremented ; exploring all paths , by removing leftmost and rightmost element and selecting the maximum value ; function to find the max score ; prefix sum array ; calculating prefix_sum ; 
def maxScore(l, r, prefix_sum, num):
    if (l > r):
        return 0
    if ((l - 1) >= 0):
        current_sum = (prefix_sum[r] - prefix_sum[l - 1])
    else:
        current_sum = prefix_sum[r] - 0
    if (num % 2 == 0):
        current_sum *= -1
    return current_sum + max(maxScore(l + 1, r, prefix_sum,
                             num + 1), maxScore(l, r - 1, prefix_sum, num + 1))


def findMaxScore(a, n):
    prefix_sum = [0] * n
    prefix_sum[0] = a[0]
    for i in range(1, n):
        prefix_sum[i] = prefix_sum[i - 1] + a[i]
    return maxScore(0, n - 1, prefix_sum, 1)


n = 6
A = [1, 2, 3, 4, 2, 6]
ans = findMaxScore(A, n)
print(ans)

# Expected output:
13
# make all array elements divisible by a number k | function to make array divisible ; for each element of array how much number to be subtracted to make it divisible by k ; for each element of array how much number to be added to make it divisible by k ; calculate minimum difference ; 
def makeDivisble(arr, k):
    n = len(arr)
    b1 = []
    b2 = []
    for i in range(n):
        b1 .append(arr[i] % k)
    for j in range(n):
        if ((arr[j] % k) != 0):
            b2 .append(k - (arr[j] % k))
        else:
            b2 .append(0)
    c = 0
    mini = float('inf')
    suml = 0
    sumr = 0
    index = -1
    for c in range(0, n + 1, 1):
        suml = sum(b1[:c + 1])
        sumr = sum(b2)
        if suml >= sumr:
            rem = suml - sumr
            if rem < mini:
                mini = rem
                index = c
    return index, mini


if __name__ == "__main__":
    arr = [1, 14, 4, 41, 1]
    k = 7
    index, diff = makeDivisble(arr, k)
    print(index, diff)

# Expected output:
-1 inf
# finding powers of any number p in n ! | python3 program to find the power of p in n ! ; map to store all the prime factors of p ; function to find the prime factors of n im map ; clear map ; check for factors of 2 ; find all the prime factors ; if i is a factors then increase the frequency of i ; function to find the power of prime number p in n ! ; loop until temp <= n ; add the number of numbers divisible by n ; each time multiply temp by p ; returns ans ; function that find the powers of any p in n ! ; find all prime factors of number p ; to store the powers of all prime factors ; traverse the map ; prime factor and corres . powers ; find power of prime factor primefac ; divide frequency by facpow ; store the power of primefac ^ facpow ; return the minimum element in power array ; 

import math
Map = {}


def findPrimeFactors(N):
    Map .clear()
    while (N % 2 == 0):
        if 2 in Map:
            Map[2] += 1
        else:
            Map[2] = 1
        N = N // 2
    for i in range(3, int(math .sqrt(N)) + 1, 2):
        while (N % i == 0):
            if i in Map:
                Map[i] += 1
            else:
                Map[i] = 1
            N = N // i
    if (N > 2):
        if N in Map:
            Map[N] += 1
        else:
            Map[N] = 1


def PowInFactN(N, P):
    ans = 0
    temp = P
    while (temp <= N):
        ans = ans + (N // temp)
        temp = temp * P
    return ans


def findPowers(N, P):
    findPrimeFactors(P)
    Powers = []
    for it1, it2 in Map .items():
        primeFac = it1
        facPow = it2
        p = PowInFactN(N, primeFac)
        p = p // facPow
        Powers .append(p)
    return min(Powers)


N, P = 24, 4
if __name__ == "__main__":
    print(findPowers(N, P))

# Expected output:
11
# longest common subarray in the given two arrays | function to find the maximum length of equal subarray ; auxiliary dp [ ] [ ] array ; updating the dp [ ] [ ] table in bottom up approach ; if a [ i ] is equal to b [ i ] then dp [ j ] [ i ] = dp [ j + 1 ] [ i + 1 ] + 1 ; find maximum of all the values in dp [ ] [ ] array to get the maximum length ; update the length ; return the maximum length ; 
def FindMaxLength(A, B):
    n = len(A)
    m = len(B)
    dp = [[0 for i in range(n + 1)]for i in range(m + 1)]
    for i in range(n - 1, -1, -1):
        for j in range(m - 1, -1, -1):
            if A[i] == B[j]:
                dp[j][i] = dp[j + 1][i + 1] + 1
    maxm = 0
    for i in dp:
        for j in i:
            maxm = max(maxm, j)
    return maxm


if __name__ == '__main__':
    A = [1, 2, 8, 2, 1]
    B = [8, 2, 1, 4, 7]
    print(FindMaxLength(A, B))

# Expected output:
3
# maximum contiguous decreasing sequence obtained by removing any one element | function to find the maximum length ; initialise maximum length to 1 ; initialise left [ ] to find the length of decreasing sequence from left to right ; initialise right [ ] to find the length of decreasing sequence from right to left ; initially store 1 at each index of left and right array ; iterate over the array arr [ ] to store length of decreasing sequence that can be obtained at every index in the right array ; store the length of longest continuous decreasing sequence in maximum ; iterate over the array arr [ ] to store length of decreasing sequence that can be obtained at every index in the left array ; check if we can obtain a longer decreasing sequence after removal of any element from the array arr [ ] with the help of left [ ] & right [ ] ; return maximum length of sequence ; 
def maxLength(a, n):
    maximum = 1
    left = [0] * n
    right = [0] * n
    for i in range(n):
        left[i] = 1
        right[i] = 1
    for i in range(n - 2, -1, -1):
        if (a[i] > a[i + 1]):
            right[i] = right[i + 1] + 1
        maximum = max(maximum, right[i])
    for i in range(1, n):
        if (a[i] < a[i - 1]):
            left[i] = left[i - 1] + 1
    if (n > 2):
        for i in range(1, n - 1):
            if (a[i - 1] > a[i + 1]):
                maximum = max(maximum, left[i - 1] + right[i + 1])
    return maximum


if __name__ == "__main__":
    arr = [8, 7, 3, 5, 2, 9]
    n = len(arr)
    print(maxLength(arr, n))

# Expected output:
4
# number of subsequences with negative product | python 3 implementation of the approach ; function to return the count of all the subsequences with negative product ; to store the count of positive elements in the array ; to store the count of negative elements in the array ; if the current element is positive ; if the current element is negative ; for all the positive elements of the array ; for all the negative elements of the array ; 

import math


def cntSubSeq(arr, n):
    pos_count = 0
    neg_count = 0
    for i in range(n):
        if (arr[i] > 0):
            pos_count += 1
        if (arr[i] < 0):
            neg_count += 1
    result = int(math .pow(2, pos_count))
    if (neg_count > 0):
        result *= int(math .pow(2, neg_count - 1))
    else:
        result = 0
    return result


arr = [2, -3, -1, 4]
n = len(arr)
print(cntSubSeq(arr, n))

# Expected output:
8
# find minimum number of steps to reach the end of string | python3 implementation of the approach ; function to return the minimum number of steps to reach the end ; if the end can 't be reached ; already at the end ; if the length is 2 or 3 then the end can be reached in a single step ; for the other cases , solve the problem using dynamic programming ; it requires no move from the end to reach the end ; from the 2 nd last and the 3 rd last index , only a single move is required ; update the answer for every index ; if the current index is not reachable ; to store the minimum steps required from the current index ; if it is a valid move then update the minimum steps required ; update the minimum steps required starting from the current index ; cannot reach the end starting from str [ 0 ] ; return the minimum steps required ; 

import sys
INT_MAX = sys .maxsize


def minSteps(string, n, k):
    if (string[n - 1] == '0'):
        return -1
    if (n == 1):
        return 0
    if (n < 4):
        return 1
    dp = [0] * n
    dp[n - 1] = 0
    dp[n - 2] = 1
    dp[n - 3] = 1
    for i in range(n - 4, -1, -1):
        if (string[i] == '0'):
            continue
        steps = INT_MAX
        if (i + k < n and string[i + k] == '1'):
            steps = min(steps, dp[i + k])
        if (string[i + 1] == '1'):
            steps = min(steps, dp[i + 1])
        if (string[i + 2] == '1'):
            steps = min(steps, dp[i + 2])
        dp[i] = steps if (steps == INT_MAX)else (1 + steps)
    if (dp[0] == INT_MAX):
        return -1
    return dp[0]


if __name__ == "__main__":
    string = "101000011"
    n = len(string)
    k = 5
    print(minSteps(string, n, k))

# Expected output:
3
# eggs dropping puzzle | set 2 | function to return the minimum number of trials needed in the worst case with n eggs and k floors ; fill all the entries in table using optimal substructure property ; return the minimum number of moves ; 
def eggDrop(n, k):
    dp = [[0 for i in range(n + 1)]for j in range(k + 1)]
    x = 0
    while (dp[x][n] < k):
        x += 1
        for i in range(1, n + 1):
            dp[x][i] = dp[x - 1][i - 1] + dp[x - 1][i] + 1
    return x


if __name__ == '__main__':
    n = 2
    k = 36
    print(eggDrop(n, k))

# Expected output:
8
# maximum length of strictly increasing sub | function to return the maximum length of strictly increasing subarray after removing atmost one element ; create two arrays pre and pos ; find out the contribution of the current element in array [ 0 , i ] and update pre [ i ] ; find out the contribution of the current element in array [ n - 1 , i ] and update pos [ i ] ; calculate the maximum length of the stricly increasing subarray without removing any element ; calculate the maximum length of the strictly increasing subarray after removing the current element ; 
def maxIncSubarr(a, n):
    pre = [0] * n
    pos = [0] * n
    pre[0] = 1
    pos[n - 1] = 1
    l = 0
    for i in range(1, n):
        if (a[i] > a[i - 1]):
            pre[i] = pre[i - 1] + 1
        else:
            pre[i] = 1
    l = 1
    for i in range(n - 2, -1, -1):
        if (a[i] < a[i + 1]):
            pos[i] = pos[i + 1] + 1
        else:
            pos[i] = 1
    ans = 0
    l = 1
    for i in range(1, n):
        if (a[i] > a[i - 1]):
            l += 1
        else:
            l = 1
        ans = max(ans, l)
    for i in range(1, n - 1):
        if (a[i - 1] < a[i + 1]):
            ans = max(pre[i - 1] + pos[i + 1], ans)
    return ans


if __name__ == '__main__':
    arr = [1, 2]
    n = len(arr)
    print(maxIncSubarr(arr, n))

# Expected output:
2
# number of square matrices with all 1 s | python3 program to return the number of square submatrices with all 1 s ; function to return the number of square submatrices with all 1 s ; initialize count variable ; if a [ i ] [ j ] is equal to 0 ; calculate number of square submatrices ending at ( i , j ) ; calculate the sum of the array ; 

n = 3
m = 3


def countSquareMatrices(a, N, M):
    count = 0
    for i in range(1, N):
        for j in range(1, M):
            if (a[i][j] == 0):
                continue
            a[i][j] = min([a[i - 1][j], a[i][j - 1], a[i - 1][j - 1]]) + 1
    for i in range(N):
        for j in range(M):
            count += a[i][j]
    return count


arr = [[1, 0, 1], [1, 1, 0], [1, 1, 0]]
print(countSquareMatrices(arr, n, m))

# Expected output:
7
# count number of increasing sub | python3 implementation of the approach ; segment tree array ; function for point update in segment tree ; base case ; if l == r == up ; mid element ; updating the segment tree ; function for the range sum - query ; base case ; mid element ; calling for the left and the right subtree ; function to return the count ; copying array arr to sort it ; sorting array brr ; map to store the rank of each element ; dp array ; to store the final answer ; updating the dp array ; rank of the element ; solving the dp - states using segment tree ; updating the final answer ; updating the segment tree ; returning the final answer ; 

N = 10000
seg = [0] * (3 * N)


def update(In, l, r, up_In, val):
    if (r < up_In or l > up_In):
        return seg[In]
    if (l == up_In and r == up_In):
        seg[In] = val
        return val
    m = (l + r) // 2
    seg[In] = update(2 * In + 1, l, m, up_In, val) + \
        update(2 * In + 2, m + 1, r, up_In, val)
    return seg[In]


def query(In, l, r, l1, r1):
    if (l > r):
        return 0
    if (r < l1 or l > r1):
        return 0
    if (l1 <= l and r <= r1):
        return seg[In]
    m = (l + r) // 2
    return query(2 * In + 1, l, m, l1, r1) + \
        query(2 * In + 2, m + 1, r, l1, r1)


def fIndCnt(arr, n):
    brr = [0] * n
    for i in range(n):
        brr[i] = arr[i]
    brr = sorted(brr)
    r = dict()
    for i in range(n):
        r[brr[i]] = i + 1
    dp = [0] * n
    ans = 0
    for i in range(n - 1, -1, -1):
        rank = r[arr[i]]
        dp[i] = 1 + query(0, 0, n - 1, rank, n - 1)
        ans += dp[i]
        update(
            0,
            0,
            n -
            1,
            rank -
            1,
            dp[i] +
            query(
                0,
                0,
                n -
                1,
                rank -
                1,
                rank -
                1))
    return ans


arr = [1, 2, 10, 9]
n = len(arr)
print(fIndCnt(arr, n))

# Expected output:
11
# minimum cost to build n blocks from one block | function to calculate min cost to build n blocks ; initialize base case ; recurence when i is odd ; recurence when i is even ; 
def minCost(n, x, y, z):
    dp = [0] * (n + 1)
    dp[0] = dp[1] = 0
    for i in range(2, n + 1):
        if (i % 2 == 1):
            dp[i] = min(dp[(i + 1) // 2] + x + z, dp[i - 1] + y)
        else:
            dp[i] = min(dp[i // 2] + x, dp[i - 1] + y)
    return dp[n]


n = 5
x = 2
y = 1
z = 3
print(minCost(n, x, y, z))

# Expected output:
4
# size of the largest divisible subset in an array | python3 implementation of the above approach ; function to find the size of the largest divisible subarray ; mark all elements of the array ; traverse reverse ; for all multiples of i ; return the required answer ; 

N = 1000005


def maximum_set(a, n):
    dp = [0 for i in range(N)]
    for i in a:
        dp[i] = 1
    ans = 1
    for i in range(N - 1, 0, -1):
        if (dp[i] != 0):
            for j in range(2 * i, N, i):
                dp[i] = max(dp[i], 1 + dp[j])
                ans = max(ans, dp[i])
    return ans


arr = [3, 4, 6, 8, 10, 18, 21, 24]
n = len(arr)
print(maximum_set(arr, n))

# Expected output:
3
# longest sub | python3 implementation of the approach ; function to return the length of the largest sub - string divisible by 3 ; base - case ; if the state has been solved before then return its value ; marking the state as solved ; recurrence relation ; 

import numpy as np
import sys
N = 100
INT_MIN = -(sys .maxsize - 1)
dp = np .zeros((N, 3))
v = np .zeros((N, 3))


def findLargestString(s, i, r):
    if (i == len(s)):
        if (r == 0):
            return 0
        else:
            return INT_MIN
    if (v[i][r]):
        return dp[i][r]
    v[i][r] = 1
    dp[i][r] = max(1 +
                   findLargestString(s, i +
                                     1, (r *
                                         2 +
                                         (ord(s[i]) -
                                          ord('0'))) %
                                     3), findLargestString(s, i +
                                                           1, r))
    return dp[i][r]


if __name__ == "__main__":
    s = "101"
    print(findLargestString(s, 0, 0))

# Expected output:
2.0
# number of sub | python3 implementation of th approach ; function to return the number of sub - sequences divisible by 3 ; base - cases ; if the state has been solved before then return its value ; marking the state as solved ; recurrence relation ; 

import numpy as np
N = 100
dp = np .zeros((N, 3))
v = np .zeros((N, 3))


def findCnt(s, i, r):
    if (i == len(s)):
        if (r == 0):
            return 1
        else:
            return 0
    if (v[i][r]):
        return dp[i][r]
    v[i][r] = 1
    dp[i][r] = findCnt(s, i + 1, (r * 2 + (ord(s[i]) - ord('0'))) %
                       3) + findCnt(s, i + 1, r)
    return dp[i][r]


if __name__ == "__main__":
    s = "11"
    print(findCnt(s, 0, 0) - 1)

# Expected output:
1.0