giulio98/xlcost-single-prompt huggingface dataset:
# number of longest increasing subsequences | function to count the number of lis in the array nums [ ] ; base case ; initialize dp_l array with 1 s ; initialize dp_c array with 1 s ; if current element is smaller ; store the maximum element from dp_l ; stores the count of lis ; traverse dp_l and dp_c simultaneously ; update the count ; return the count of lis ; 
def findNumberOfLIS(nums):
    if not nums:
        return 0
    n = len(nums)
    dp_l = [1] * n
    dp_c = [1] * n
    for i, num in enumerate(nums):
        for j in range(i):
            if nums[i] <= nums[j]:
                continue
            if dp_l[j] + 1 > dp_l[i]:
                dp_l[i] = dp_l[j] + 1
                dp_c[i] = dp_c[j]
            elif dp_l[j] + 1 == dp_l[i]:
                dp_c[i] += dp_c[j]
    max_length = max(x for x in dp_l)
    count = 0
    for l, c in zip(dp_l, dp_c):
        if l == max_length:
            count += c
    return count


arr = [1, 3, 5, 4, 7]
print(findNumberOfLIS(arr))

# Expected output:
2
# longest span with same sum in two binary arrays | returns largest common subarray with equal number of 0 s and 1 s ; find difference between the two ; creates an empty hashmap hm ; initialize sum of elements ; initialize result ; traverse through the given array ; add current element to sum ; to handle sum = 0 at last index ; if this sum is seen before , then update max_len if required ; else put this sum in hash table ; 
def longestCommonSum(arr1, arr2, n):
    arr = [0 for i in range(n)]
    for i in range(n):
        arr[i] = arr1[i] - arr2[i]
    hm = {}
    sum = 0
    max_len = 0
    for i in range(n):
        sum += arr[i]
        if (sum == 0):
            max_len = i + 1
        if sum in hm:
            max_len = max(max_len, i - hm[sum])
        else:
            hm[sum] = i
    return max_len


arr1 = [0, 1, 0, 1, 1, 1, 1]
arr2 = [1, 1, 1, 1, 1, 0, 1]
n = len(arr1)
print(longestCommonSum(arr1, arr2, n))

# Expected output:
6
# minimum length of run length encoding possible by removing at most k characters from a given string | python3 program to implement the above approach ; function which solves the desired problem ; base case ; if the entire string has been traversed ; if precomputed subproblem occurred ; minimum run length encoding by removing the current character ; minimum run length encoding by retaining the current character ; if the current and the previous characters match ; otherwise ; function to return minimum run - length encoding for string s by removing atmost k characters ; 

maxN = 20
dp = [[[[0 for i in range(maxN)]for j in range(27)]
       for k in range(27)]for l in range(maxN)]


def solve(s, n, idx, k, last, count):
    if (k < 0):
        return n + 1
    if (idx == n):
        return 0
    ans = dp[idx][k][ord(last) - ord('a')][count]
    if (ans != -1):
        return ans
    ans = n + 1
    ans = min(ans, solve(s, n, idx + 1, k - 1, last, count))
    inc = 0
    if (count == 1 or count == 9 or count == 99):
        inc = 1
    if (last == s[idx]):
        ans = min(ans, inc + solve(s, n, idx + 1, k, s[idx], count + 1))
    else:
        ans = max(ans, 1 + solve(s, n, idx + 1, k, s[idx], 1))
    dp[idx][k][ord(last) - ord('a')][count] = ans
    print(ans)
    return dp[idx][k][ord(last) - ord('a')][count]


def MinRunLengthEncoding(s, n, k):
    for i in range(maxN):
        for j in range(27):
            for k in range(27):
                for l in range(maxN):
                    dp[i][j][k][l] = -1
    return solve(s, n, 0, k, chr(123), 0) - 1


if __name__ == '__main__':
    S = "abbbcdcdd"
    N = 9
    K = 2
    print(MinRunLengthEncoding(S, N, K))

# Expected output:
1
0
1
1
0
1
2
0
0
1
0
1
2
3
1
1
1
0
0
1
0
1
2
3
4
1
1
2
3
1
1
1
0
0
1
0
1
2
3
4
5
1
1
2
3
1
1
1
0
0
1
0
1
2
3
4
4
5
1
1
2
3
1
1
1
0
0
1
0
1
2
3
4
4
4
5
1
1
2
3
4
1
1
2
3
4
5
1
1
2
3
4
4
5
1
1
2
3
1
1
1
0
0
1
0
1
2
3
4
4
4
5
6
5
# count unique paths is a matrix whose product of elements contains odd number of divisors | python3 program for the above approach ; function to calculate and store all the paths product in vector ; base case ; if reaches the bottom right corner and product is a perfect square ; find square root ; if square root is an integer ; move towards down in the matrix ; move towards right in the matrix ; 

import math
countPaths = 0


def CountUniquePaths(a, i, j, m, n, ans):
    if (i >= m or j >= n):
        return
    global countPaths
    if (i == m - 1 and j == n - 1):
        sr = math .sqrt(ans * a[i][j])
        if ((sr - math .floor(sr)) == 0):
            countPaths += 1
    CountUniquePaths(a, i + 1, j, m, n, ans * a[i][j])
    CountUniquePaths(a, i, j + 1, m, n, ans * a[i][j])


if __name__ == '__main__':
    M = 3
    N = 2
    mat = [[1, 1], [3, 1], [3, 1]]
    CountUniquePaths(mat, 0, 0, M, N, 1)
    print(countPaths)

# Expected output:
2
# maximize sum by selecting m elements from the start or end of rows of a matrix | function to select m elements having maximum sum ; base case ; if precomputed subproblem occurred ; either skip the current row ; iterate through all the possible segments of current row ; check if it is possible to select elements from i to j ; compuete the sum of i to j as calculated ; store the computed answer and return ; function to precompute the prefix sum for every row of the matrix ; preprocessing to calculate sum from i to j ; utility function to select m elements having maximum sum ; preprocessing step ; initialize dp array with - 1 ; stores maximum sum of m elements ; 
def mElementsWithMaxSum(matrix, M, block, dp):
    if block == len(matrix):
        return 0
    if (dp[block][M] != -1):
        return dp[block][M]
    ans = mElementsWithMaxSum(matrix, M, block + 1, dp)
    for i in range(len(matrix[block])):
        for j in range(i, len(matrix[block])):
            if (j - i + 1 <= M):
                x = 0
                if i - 1 >= 0:
                    x = matrix[block][i - 1]
                ans = max(
                    ans,
                    matrix[block][j] -
                    x +
                    mElementsWithMaxSum(
                        matrix,
                        M -
                        j +
                        i -
                        1,
                        block +
                        1,
                        dp))
    dp[block][M] = ans
    return ans


def preComputing(matrix, N):
    for i in range(N):
        for j in range(len(matrix[i])):
            if j > 0:
                matrix[i][j] = matrix[i][j - 1]
    return matrix


def mElementsWithMaxSumUtil(matrix, M, N):
    matrix = preComputing(matrix, N)
    sum = 20
    dp = [[-1 for i in range(M + 5)]for i in range(N + 5)]
    sum += mElementsWithMaxSum(matrix, M, 0, dp)
    print(sum)


if __name__ == '__main__':
    N = 3
    M = 4
    matrix = [[2, 3, 5], [-1, 7], [8, 10]]
    mElementsWithMaxSumUtil(matrix, M, N)

# Expected output:
30
# find the last remaining element after repeated removal of odd and even indexed elements alternately | function to calculate the last remaining element from the sequence ; if dp [ n ] is already calculated ; base case : ; recursive call ; return the value of dp [ n ] ; 
def lastRemaining(n, dp):
    if n in dp:
        return dp[n]
    if n == 1:
        return 1
    else:
        dp[n] = 2 * (1 + n // 2 - lastRemaining(n // 2, dp))
    return dp[n]


N = 5
dp = {}
print(lastRemaining(N, dp))

# Expected output:
2
# maximum subsequence sum possible by multiplying each element by its index | initialize dp array ; function to find the maximum sum of the subsequence formed ; base case ; if already calculated state occurs ; include the current element ; exclude the current element ; update the maximum ans ; function to calculate maximum sum of the subsequence obtained ; print the maximum sum possible ; 

dp = [[-1 for x in range(1005)]for y in range(1005)]


def maximumSumUtil(a, index, count, n):
    if (index > n or count > n + 1):
        return 0
    if (dp[index][count] != -1):
        return dp[index][count]
    ans1 = (maximumSumUtil(a, index + 1, count + 1, n) + a[index] * count)
    ans2 = maximumSumUtil(a, index + 1, count, n)
    dp[index][count] = max(ans1, ans2)
    return dp[index][count]


def maximumSum(arr, N):
    print(maximumSumUtil(arr, 0, 1, N - 1))


arr = [-1, 2, -10, 4, -20]
N = len(arr)
maximumSum(arr, N)

# Expected output:
15
# minimum steps to obtain n from 1 by the given operations | python3 program to implement the above approach ; base case ; recursive call for n - 1 ; check if n is divisible by 2 ; check if n is divisible by 3 ; returns a tuple ( a , b ) , where a : minimum steps to obtain x from 1 b : previous number ; function that find the optimal solution ; print the length ; exit condition for loop = - 1 when n has reached 1 ; return the sequence in reverse order ; 
def find_sequence(n):
    if n == 1:
        return 1, -1
    ans = (find_sequence(n - 1)[0] + 1, n - 1)
    if n % 2 == 0:
        div_by_2 = find_sequence(n // 2)
        if div_by_2[0] < ans[0]:
            ans = (div_by_2[0] + 1, n // 2)
    if n % 3 == 0:
        div_by_3 = find_sequence(n // 3)
        if div_by_3[0] < ans[0]:
            ans = (div_by_3[0] + 1, n // 3)
    return ans


def find_solution(n):
    a, b = find_sequence(n)
    print(a)
    sequence = []
    sequence .append(n)
    while b != -1:
        sequence .append(b)
        _, b = find_sequence(b)
    return sequence[::-1]


n = 5
print(*find_solution(n))

# Expected output:
4
1 2 4 5
# count of vessels completely filled after a 
def FindNoOfFullVessels(n, t):
    Matrix = [[0 for i in range(n)]for j in range(n)]
    Matrix[0][0] = t * 1.0
    ans = 0
    for i in range(n):
        for j in range(i + 1):
            exceededwater = Matrix[i][j] - 1.0
            if (exceededwater < 0):
                continue
            ans += 1
            if (i + 1 < n):
                Matrix[i + 1][j] += exceededwater / 2
            if (i + 1 < n and j + 1 < n):
                Matrix[i + 1][j + 1] += exceededwater / 2
    return ans


N = 3
T = 4
print(FindNoOfFullVessels(N, T))

# Expected output:
3
# sort an array in wave form | python function to sort the array arr [ 0. . n - 1 ] in wave form , i . e . , arr [ 0 ] >= arr [ 1 ] <= arr [ 2 ] >= arr [ 3 ] <= arr [ 4 ] >= arr [ 5 ] ; sort the array ; swap adjacent elements ; 
def sortInWave(arr, n):
    arr .sort()
    for i in range(0, n - 1, 2):
        arr[i], arr[i + 1] = arr[i + 1], arr[i]


arr = [10, 90, 49, 2, 1, 5, 23]
sortInWave(arr, len(arr))
for i in range(0, len(arr)):
    print(arr[i])

# Expected output:
2
1
10
5
49
23
90
# count of maximum occurring subsequence using only those characters whose indices are in gp | function to count maximum occurring subsequence using only those characters whose indexes are in gp ; initialize 1 - d array and 2 - d dp array to 0 ; iterate till the length of the given string ; update ans for 1 - length subsequence ; update ans for 2 - length subsequence ; return the answer ; 
def findMaxTimes(S):
    arr = [0] * 26
    dp = [[0 for x in range(26)]for y in range(26)]
    for i in range(len(S)):
        now = ord(S[i]) - ord('a')
        for j in range(26):
            dp[j][now] += arr[j]
        arr[now] += 1
    ans = 0
    for i in range(26):
        ans = max(ans, arr[i])
    for i in range(26):
        for j in range(26):
            ans = max(ans, dp[i][j])
    return ans


S = "ddee"
print(findMaxTimes(S))

# Expected output:
4
# sort an array in wave form | python function to sort the array arr [ 0. . n - 1 ] in wave form , i . e . , arr [ 0 ] >= arr [ 1 ] <= arr [ 2 ] >= arr [ 3 ] <= arr [ 4 ] >= arr [ 5 ] ; traverse all even elements ; if current even element is smaller than previous ; if current even element is smaller than next ; 
def sortInWave(arr, n):
    for i in range(0, n, 2):
        if (i > 0 and arr[i] < arr[i - 1]):
            arr[i], arr[i - 1] = arr[i - 1], arr[i]
        if (i < n - 1 and arr[i] < arr[i + 1]):
            arr[i], arr[i + 1] = arr[i + 1], arr[i]


arr = [10, 90, 49, 2, 1, 5, 23]
sortInWave(arr, len(arr))
for i in range(0, len(arr)):
    print(arr[i])

# Expected output:
90
10
49
1
5
2
23
# count all possible unique sum of series k , k + 1 , k + 2 , k + 3 , k + 4 , ... , k + n | function to count the unique sum ; set fsum [ 0 ] as ar [ 0 ] ; set rsum [ 0 ] as ar [ n ] ; for each i update fsum [ i ] with ar [ i ] + fsum [ i - 1 ] ; for each i from n - 1 , update rsum [ i ] with ar [ i ] + fsum [ i + 1 ] ; k represent size of subset as explained above ; using above relation ; return the result ; 
def count_unique_sum(n):
    ar = [0] * (n + 1)
    fsum = [0] * (n + 1)
    rsum = [0] * (n + 1)
    ans = 1
    for i in range(0, n + 1):
        ar[i] = i
    fsum[0] = ar[0]
    rsum[n] = ar[n]
    for i in range(1, n + 1):
        fsum[i] = ar[i] + fsum[i - 1]
    for i in range(n - 1, -1, -1):
        rsum[i] = ar[i] + rsum[i + 1]
    for k in range(2, n + 1):
        ans += (1 + rsum[n + 1 - k] - fsum[k - 1])
    return ans


N = 4
print(count_unique_sum(N))

# Expected output:
20
# count of n | function to return the count of such numbers ; for 1 - digit numbers , the count is 10 irrespective of k ; dp [ j ] stores the number of such i - digit numbers ending with j ; stores the results of length i ; initialize count for 1 - digit numbers ; compute values for count of digits greater than 1 ; find the range of allowed numbers if last digit is j ; perform range update ; prefix sum to find actual count of i - digit numbers ending with j ; update dp [ ] ; stores the final answer ; return the final answer ; 
def getCount(n, K):
    if (n == 1):
        return 10
    dp = [0] * 11
    next = [0] * 11
    for i in range(1, 9 + 1):
        dp[i] = 1
    for i in range(2, n + 1):
        for j in range(9 + 1):
            l = max(0, j - k)
            r = min(9, j + k)
            next[l] += dp[j]
            next[r + 1] -= dp[j]
        for j in range(1, 9 + 1):
            next[j] += next[j - 1]
        for j in range(10):
            dp[j] = next[j]
            next[j] = 0
    count = 0
    for i in range(9 + 1):
        count += dp[i]
    return count


if __name__ == '__main__':
    n = 2
    k = 1
    print(getCount(n, k))

# Expected output:
26
# sort 1 to n by swapping adjacent elements | return true if array can be sorted otherwise false ; check bool array b and sorts elements for continuous sequence of 1 ; sort array a from i to j ; check if array is sorted or not ; 
def sortedAfterSwap(A, B, n):
    for i in range(0, n - 1):
        if (B[i] == 1):
            j = i
            while (B[j] == 1):
                j = j + 1
            A = A[0:i] + sorted(A[i:j + 1]) + A[j + 1:]
            i = j
    for i in range(0, n):
        if (A[i] != i + 1):
            return False
    return True


A = [1, 2, 5, 3, 4, 6]
B = [0, 1, 1, 1, 0]
n = len(A)
if (sortedAfterSwap(A, B, n)):
    print("A can be sorted")
else:
    print("A can not be sorted")

# Expected output:
A can be sorted
# sort 1 to n by swapping adjacent elements | return true if array can be sorted otherwise false ; check if array is sorted or not ; 
def sortedAfterSwap(A, B, n):
    for i in range(0, n - 1):
        if B[i]:
            if A[i] != i + 1:
                A[i], A[i + 1] = A[i + 1], A[i]
    for i in range(n):
        if A[i] != i + 1:
            return False
    return True


if __name__ == '__main__':
    A = [1, 2, 5, 3, 4, 6]
    B = [0, 1, 1, 1, 0]
    n = len(A)
    if (sortedAfterSwap(A, B, n)):
        print("A can be sorted")
    else:
        print("A can not be sorted")

# Expected output:
A can be sorted
# sort an array containing two types of elements | method for segregation 0 and 1 given input array ; 
def segregate0and1(arr, n):
    type0 = 0
    type1 = n - 1
    while (type0 < type1):
        if (arr[type0] == 1):
            arr[type0], arr[type1] = arr[type1], arr[type0]
            type1 -= 1
        else:
            type0 += 1


arr = [1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1]
n = len(arr)
segregate0and1(arr, n)
for i in range(0, n):
    print(arr[i], end=" ")

# Expected output:
0 0 0 1 1 1 1 1 1 1 1
# pentanacci numbers | recursive program to find the nth pentanacci number ; function to print the nth pentanacci number ; 
def printpentaRec(n):
    if (n == 0 or n == 1 or n == 2 or n == 3 or n == 4):
        return 0
    elif (n == 5):
        return 1
    else:
        return (
            printpentaRec(
                n -
                1) +
            printpentaRec(
                n -
                2) +
            printpentaRec(
                n -
                3) +
            printpentaRec(
                n -
                4) +
            printpentaRec(
                n -
                5))


def printPenta(n):
    print(printpentaRec(n))


n = 10
printPenta(n)

# Expected output:
16
# count inversions in an array | set 1 ( using merge sort ) | python3 program to count inversions in an array ; 
def getInvCount(arr, n):
    inv_count = 0
    for i in range(n):
        for j in range(i + 1, n):
            if (arr[i] > arr[j]):
                inv_count += 1
    return inv_count


arr = [1, 20, 6, 4, 5]
n = len(arr)
print("Number of inversions are", getInvCount(arr, n))

# Expected output:
Number of inversions are 5
# range queries for alternatively addition and subtraction on given array | function to find the result of alternatively adding and subtracting elements in the range [ l , r ] ; a boolean variable flag to alternatively add and subtract ; iterate from [ l , r ] ; if flag is false , then add & toggle the flag ; if flag is true subtract and toggle the flag ; return the final result ; function to find the value for each query ; iterate for each query ; 
def findResultUtil(arr, L, R):
    result = 0
    flag = False
    for i in range(L, R + 1):
        if (flag == False):
            result = result + arr[i]
            flag = True
        else:
            result = result - arr[i]
            flag = False
    return result


def findResult(arr, n, q, m):
    for i in range(m):
        print(findResultUtil(arr, q[i][0], q[i][1]), end=" ")


if __name__ == '__main__':
    arr = [10, 13, 15, 2, 45, 31, 22, 3, 27]
    n = len(arr)
    q = [[2, 5], [6, 8], [1, 7], [4, 8], [0, 5]]
    m = len(q)
    findResult(arr, n, q, m)

# Expected output:
27 46 -33 60 24
# two elements whose sum is closest to zero | python3 code to find two elements whose sum is closest to zero ; array should have at least two elements ; initialization of values ; 
def minAbsSumPair(arr, arr_size):
    inv_count = 0
    if arr_size < 2:
        print("Invalid Input")
        return
    min_l = 0
    min_r = 1
    min_sum = arr[0] + arr[1]
    for l in range(0, arr_size - 1):
        for r in range(l + 1, arr_size):
            sum = arr[l] + arr[r]
            if abs(min_sum) > abs(sum):
                min_sum = sum
                min_l = l
                min_r = r
    print(
        "The two elements whose sum is minimum are",
        arr[min_l],
        "and ",
        arr[min_r])


arr = [1, 60, -10, 70, -80, 85]
minAbsSumPair(arr, 6)

# Expected output:
The two elements whose sum is minimum are -80 and  85
# maximize sum of topmost elements of s stacks by popping at most n elements | python3 program to maximize the sum of top of the stack values of s stacks by popping at most n element ; function for computing the maximum sum at the top of the stacks after popping at most n elements from s stack ; constructing a dp matrix of dimensions ( s + 1 ) x ( n + 1 ) ; loop over all i stacks ; store the maximum of popping j elements up to the current stack by popping k elements from current stack and j - k elements from all previous stacks combined ; store the maximum sum of popping n elements across all stacks ; dp [ s ] [ n ] has the maximum sum ; 

import sys


def maximumSum(S, M, N, stacks):
    dp = [[0 for x in range(N + 1)]for y in range(S + 1)]
    for i in range(S):
        for j in range(N + 1):
            for k in range(min(j, M) + 1):
                dp[i + 1][j] = max(dp[i + 1][j], stacks[i][k] + dp[i][j - k])
    result = -sys .maxsize - 1
    for i in range(N + 1):
        result = max(result, dp[S][i])
    return result


if __name__ == "__main__":
    S = 2
    M = 4
    stacks = [[2, 6, 4, 5], [1, 6, 15, 10]]
    N = 3
    print(maximumSum(S, M, N, stacks))

# Expected output:
21
# abstraction of binary search | ''function to find x such that it is less than the target value and function is f(x) = x ^ 2 ; '' initialise start and end ; '' loop till start <= end ; '' find the mid ; '' check for the left half ; store the result ; reinitialize the start point ; '' check for the right half ; '' print maximum value of x  such that x ^ 2 is less than the  targetvalue ; ''
def findX(targetValue):
    start = 0
    end = targetValue
    mid = 0
    while (start <= end):
        mid = start + (end - start) // 2
        if (mid * mid <= targetValue):
            result = mid
            start = mid + 1
        else:
            end = mid - 1
    print(result)


if __name__ == '__main__':
    targetValue = 81
    findX(targetValue)

# Expected output:
9
# two elements whose sum is closest to zero | python3 implementation using stl ; modified to sort by abolute values ; absolute value shows how close it is to zero ; if found an even close value update min and store the index ; 

import sys


def findMinSum(arr, n):
    for i in range(1, n):
        if (not abs(arr[i - 1]) < abs(arr[i])):
            arr[i - 1], arr[i] = arr[i], arr[i - 1]
    Min = sys .maxsize
    x = 0
    y = 0
    for i in range(1, n):
        if (abs(arr[i - 1] + arr[i]) <= Min):
            Min = abs(arr[i - 1] + arr[i])
            x = i - 1
            y = i
    print("The two elements whose sum is minimum are", arr[x], "and", arr[y])


arr = [1, 60, -10, 70, -80, 85]
n = len(arr)
findMinSum(arr, n)

# Expected output:
The two elements whose sum is minimum are -80 and 85
# shortest un | bool function for checking an array elements are in increasing ; bool function for checking an array elements are in decreasing ; increasing and decreasing are two functions . if function return true value then print 0 otherwise 3. ; 
def increasing(a, n):
    for i in range(0, n - 1):
        if (a[i] >= a[i + 1]):
            return False
    return True


def decreasing(a, n):
    for i in range(0, n - 1):
        if (a[i] < a[i + 1]):
            return False
    return True


def shortestUnsorted(a, n):
    if (increasing(a, n) or decreasing(a, n)):
        return 0
    else:
        return 3


ar = [7, 9, 10, 8, 11]
n = len(ar)
print(shortestUnsorted(ar, n))

# Expected output:
3
# minimum number of swaps required to sort an array | function returns the minimum number of swaps required to sort the array ; create two arrays and use as pairs where first array is element and second array is position of first element ; sort the array by array element values to get right position of every element as the elements of second array . ; to keep track of visited elements . initialize all elements as not visited or false . ; initialize result ; traverse array elements ; alreadt swapped or alreadt present at correct position ; find number of nodes in this cycle and add it to ans ; move to next node ; update answer by adding current cycle ; return answer ; 
def minSwaps(arr):
    n = len(arr)
    arrpos = [*enumerate(arr)]
    arrpos .sort(key=lambda it: it[1])
    vis = {k: False for k in range(n)}
    ans = 0
    for i in range(n):
        if vis[i] or arrpos[i][0] == i:
            continue
        cycle_size = 0
        j = i
        while not vis[j]:
            vis[j] = True
            j = arrpos[j][0]
            cycle_size += 1
        if cycle_size > 0:
            ans += (cycle_size - 1)
    return ans


arr = [1, 5, 4, 3, 2]
print(minSwaps(arr))

# Expected output:
2