giulio98/xlcost-single-prompt huggingface dataset:
# smallest subarray from a given array with sum greater than or equal to k | set 2 | python3 program for the above approach ; function to find the smallest subarray with sum greater than or equal target ; dp table to store the computed subproblems ; initialize first column with 0 ; initialize first row with 0 ; check for invalid condition ; fill up the dp table ; print the minimum length ; 

import sys


def minlt(arr, target, n):
    dp = [[-1 for _ in range(target + 1)] for _ in range(len(arr) + 1)]
    for i in range(len(arr) + 1):
        dp[i][0] = 0
    for j in range(target + 1):
        dp[0][j] = sys .maxsize
    for i in range(1, len(arr) + 1):
        for j in range(1, target + 1):
            if arr[i - 1] > j:
                dp[i][j] = dp[i - 1][j]
            else:
                dp[i][j] = min(dp[i - 1][j], 1 + dp[i][j - arr[i - 1]])
    return dp[-1][-1]
    if dp[-1][-1] == sys .maxsize:
        return (-1)
    else:
        return dp[-1][-1]


arr = [2, 3, 5, 4, 1]
target = 11
n = len(arr)
print(minlt(arr, target, n))

# Expected output:
3
# minimum absolute difference of server loads | function which returns the minimum difference of loads ; compute the overall server load ; stores the results of subproblems ; fill the partition table in bottom up manner ; if i - th server is included ; if i - th server is excluded ; server a load : total_sum - ans server b load : ans diff : abs ( total_sum - 2 * ans ) ; 
def minServerLoads(n, servers):
    totalLoad = sum(servers)
    requiredLoad = totalLoad // 2
    dp = [[0 for col in range(requiredLoad + 1)]for row in range(n + 1)]
    for i in range(1, n + 1):
        for j in range(1, requiredLoad + 1):
            if servers[i - 1] > j:
                dp[i][j] = dp[i - 1][j]
            else:
                dp[i][j] = max(dp[i - 1][j], servers[i - 1] +
                               dp[i - 1][j - servers[i - 1]])
    return totalLoad - 2 * dp[n][requiredLoad]


N = 5
servers = [1, 2, 3, 4, 5]
print(minServerLoads(N, servers))

# Expected output:
1
# length of longest subarray with positive product | function to find the length of longest subarray whose product is positive ; stores the length of current subarray with positive product ; stores the length of current subarray with negative product ; stores the length of the longest subarray with positive product ; reset the value ; if current element is positive ; increment the length of subarray with positive product ; if at least one element is present in the subarray with negative product ; update res ; if current element is negative ; increment the length of subarray with negative product ; if at least one element is present in the subarray with positive product ; update res ; 
def maxLenSub(arr, N):
    Pos = 0
    Neg = 0
    res = 0
    for i in range(N):
        if (arr[i] == 0):
            Pos = Neg = 0
        elif (arr[i] > 0):
            Pos += 1
            if (Neg != 0):
                Neg += 1
            res = max(res, Pos)
        else:
            Pos, Neg = Neg, Pos
            Neg += 1
            if (Pos != 0):
                Pos += 1
            res = max(res, Pos)
    return res


if __name__ == '__main__':
    arr = [-1, -2, -3, 0, 1]
    N = len(arr)
    print(maxLenSub(arr, N))

# Expected output:
2
# print all strings of maximum length from an array of strings | python3 program to implement the above approach ; function to find the length of the longest string from the given array of strings ; traverse the array ; stores the length of current string ; update maximum length ; return the maximum length ; function to print the longest strings from the array ; find the strings having length equals to lenn ; print the resultant vector of strings ; function to print all the longest strings from the array ; find the length of longest string ; find and print all the strings having length equals to max ; 

import sys


def maxLength(arr):
    lenn = -sys .maxsize - 1
    N = len(arr)
    for i in range(N):
        l = len(arr[i])
        if (lenn < l):
            lenn = l
    return lenn


def maxStrings(arr, lenn):
    N = len(arr)
    ans = []
    for i in range(N):
        if (lenn == len(arr[i])):
            ans .append(arr[i])
    for i in range(len(ans)):
        print(ans[i], end=" ")


def printStrings(arr):
    max = maxLength(arr)
    maxStrings(arr, max)


if __name__ == '__main__':
    arr = ["aba", "aa", "ad", "vcd", "aba"]
    printStrings(arr)

# Expected output:
aba vcd aba
# minimize count of flips required such that no substring of 0 s have length exceeding k | function to return minimum number of flips required ; base case ; stores the count of minimum number of flips ; stores the count of zeros in current sub ; if current character is 0 ; continue ongoing sub ; start a new sub ; if k consecutive zeroes are obtained ; end segment ; return the result ; 
def min_flips(strr, k):
    if (len(strr) == 0):
        return 0
    ans = 0
    cnt_zeros = 0
    for ch in strr:
        if (ch == '0'):
            cnt_zeros += 1
        else:
            cnt_zeros = 0
        if (cnt_zeros == k):
            ans += 1
            cnt_zeros = 0
    return ans


if __name__ == '__main__':
    strr = "11100000011"
    k = 3
    print(min_flips(strr, k))

# Expected output:
2
# find all possible subarrays having product less than or equal to k | function to return all possible subarrays having product less than or equal to k ; store the required subarrays ; stores the product of current subarray ; stores the starting index of the current subarray ; check for empty array ; iterate over the array ; calculate product ; if product exceeds k ; reduce product ; increase starting index of current subarray ; stores the subarray elements ; store the subarray elements ; add the subarrays to the li ; return the final li of subarrays ; 
def maxSubArray(arr, n, K):
    solution = []
    multi = 1
    start = 0
    if (n <= 1 or K < 0):
        return solution
    for i in range(n):
        multi = multi * arr[i]
        while (multi > K):
            multi = multi // arr[start]
            start += 1
        li = []
        j = i
        while (j >= start):
            li .insert(0, arr[j])
            solution .append(list(li))
            j -= 1
    return solution


if __name__ == '__main__':
    arr = [2, 7, 1, 4]
    n = len(arr)
    K = 7
    v = maxSubArray(arr, n, K)
    print(v)

# Expected output:
[[2], [7], [1], [7, 1], [4], [1, 4]]
# count of collisions at a point ( x , y ) | function to find the count of possible pairs of collisions ; stores the time at which points reach the origin ; calculate time for each point ; sort the times ; counting total collisions ; count of elements arriving at a given point at the same time ; 
def solve(D, N, X, Y):
    T = []
    for i in range(N):
        x = D[i][0]
        y = D[i][1]
        speed = D[i][2]
        time = ((x * x - X * X) + (y * y - Y * Y)) / (speed * speed)
        T .append(time)
    T .sort()
    i = 0
    total = 0
    while i < len(T) - 1:
        count = 1
        while i < len(T) - 1 and T[i] == T[i + 1]:
            count += 1
            i += 1
        total += (count * (count - 1)) / 2
        i += 1
    return total


N = 5
D = [[5, 12, 1], [16, 63, 5], [-10, 24, 2], [7, 24, 2], [-24, 7, 2]]
X = 0
Y = 0
print(solve(D, N, X, Y))

# Expected output:
4.0
# longest subarray forming an arithmetic progression ( ap ) | function to return the length of longest subarray forming an ap ; minimum possible length of required subarray is 2 ; stores the length of the current subarray ; stores the common difference of the current ap ; stores the common difference of the previous ap ; if the common differences are found to be equal ; continue the previous subarray ; start a new subarray ; update the length to store maximum length ; update the length to store maximum length ; return the length of the longest subarray ; 
def getMaxLength(arr, N):
    res = 2
    dist = 2
    curradj = (arr[1] - arr[0])
    prevadj = (arr[1] - arr[0])
    for i in range(2, N):
        curradj = arr[i] - arr[i - 1]
        if (curradj == prevadj):
            dist += 1
        else:
            prevadj = curradj
            res = max(res, dist)
            dist = 2
    res = max(res, dist)
    return res


if __name__ == "__main__":
    arr = [10, 7, 4, 6, 8, 10, 11]
    N = len(arr)
    print(getMaxLength(arr, N))

# Expected output:
4
# minimize cost to empty a given string by removing characters alphabetically | function to find the minimum cost required to remove each character of the string in alphabetical order ; stores the frequency of characters of the string ; iterate through the string ; count the number of characters smaller than the present character ; if no smaller character precedes current character ; increase the frequency of the current character ; return the total cost ; 
def minSteps(str, N):
    cost = 0
    f = [0] * 26
    for i in range(N):
        curr_ele = ord(str[i]) - ord('a')
        smaller = 0
        for j in range(curr_ele + 1):
            if (f[j]):
                smaller += f[j]
        if (smaller == 0):
            cost += (i + 1)
        else:
            cost += (i - smaller + 1)
        f[ord(str[i]) - ord('a')] += 1
    return cost


str = "abcab"
N = len(str)
print(minSteps(str, N))

# Expected output:
8
# count of rectangles with area k made up of only 1 s from given binary arrays | function to find the subarrays of all possible lengths made up of only 1 s ; stores the frequency of the subarrays ; check if the previous value was also 0 ; if the previous value was 1 ; find the subarrays of each size from 1 to count ; if a [ ] is of the form ... .111 ; function to find the count of all possible rectangles ; size of each of the arrays ; stores the count of subarrays of each size consisting of only 1 s from array a [ ] ; stores the count of subarrays of each size consisting of only 1 s from array b [ ] ; iterating over all subarrays consisting of only 1 s in a [ ] ; if i is a factor of k , then there is a subarray of size k / i in b [ ] ; 
def findSubarrays(a):
    n = len(a)
    freq = [0] * (n + 1)
    count = 0
    for i in range(n):
        if (a[i] == 0):
            if (count == 0):
                continue
            else:
                value = count
                for j in range(1, count + 1):
                    freq[j] += value
                    value -= 1
                count = 0
        else:
            count += 1
    if (count > 0):
        value = count
        for j in range(1, count + 1):
            freq[j] += value
            value -= 1
    return freq


def countRectangles(a, b, K):
    n = len(a)
    m = len(b)
    subA = []
    subA = findSubarrays(a)
    subB = []
    subB = findSubarrays(b)
    total = 0
    for i in range(1, len(subA)):
        if (K % i == 0 and (K // i) <= m):
            total = total + subA[i] * subB[K // i]
    print(total)


a = [0, 0, 1, 1]
b = [1, 0, 1]
K = 2
countRectangles(a, b, K)

# Expected output:
2
# print longest bitonic subsequence ( space optimized approach ) | function to print the longest bitonic subsequence ; function to generate the longest bitonic subsequence ; store the lengths of lis ending at every index ; store the lengths of lds ending at every index ; compute lis for all indices ; compute lds for all indices ; find the index having maximum value of lis [ i ] + lds [ i ] + 1 ; stores the count of elements in increasing order in bitonic subsequence ; store the increasing subsequence ; sort the bitonic subsequence to arrange smaller elements at the beginning ; stores the count of elements in decreasing order in bitonic subsequence ; print the longest bitonic sequence ; 
def printRes(res):
    n = len(res)
    for i in range(n):
        print(res[i], end=" ")


def printLBS(arr, N):
    lis = [0] * N
    lds = [0] * N
    for i in range(N):
        lis[i] = lds[i] = 1
    for i in range(N):
        for j in range(i):
            if arr[j] < arr[i]:
                if lis[i] < lis[j] + 1:
                    lis[i] = lis[j] + 1
    for i in range(N - 1, -1, -1):
        for j in range(N - 1, i, -1):
            if arr[j] < arr[i]:
                if lds[i] < lds[j] + 1:
                    lds[i] = lds[j] + 1
    MaxVal = arr[0]
    inx = 0
    for i in range(N):
        if MaxVal < lis[i] + lds[i] - 1:
            MaxVal = lis[i] + lds[i] - 1
            inx = i
    ct1 = lis[inx]
    res = []
    i = inx
    while i >= 0 and ct1 > 0:
        if lis[i] == ct1:
            res .append(arr[i])
            ct1 -= 1
        i -= 1
    res .reverse()
    ct2 = lds[inx] - 1
    i = inx
    while i < N and ct2 > 0:
        if lds[i] == ct2:
            res .append(arr[i])
            ct2 -= 1
        i += 1
    printRes(res)


arr = [80, 60, 30, 40, 20, 10]
N = len(arr)
printLBS(arr, N)

# Expected output:
80 60 30 20 10
# minimum possible value t such that at most d partitions of the array having at most sum t is possible | function to check if the array can be partitioned into atmost d subarray with sum atmost t ; initial partition ; current sum ; if current sum exceeds t ; create a new partition ; if count of partitions exceed d ; function to find the minimum possible value of t ; stores the maximum and total sum of elements ; maximum element ; sum of all elements ; calculate median t ; if atmost d partitions possible ; check for smaller t ; otherwise ; check for larger t ; print the minimum t required ; 
def possible(T, arr, n, d):
    partition = 1
    total = 0
    for i in range(n):
        total = total + arr[i]
        if (total > T):
            partition = partition + 1
            total = arr[i]
            if (partition > d):
                return False
    return True


def calcT(n, d, arr):
    mx = -1
    sum = 0
    for i in range(n):
        mx = max(mx, arr[i])
        sum = sum + arr[i]
    lb = mx
    ub = sum
    while (lb < ub):
        T_mid = lb + (ub - lb) // 2
        if (possible(T_mid, arr, n, d)):
            ub = T_mid
        else:
            lb = T_mid + 1
    print(lb)


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

# Expected output:
3
# minimize splits to generate monotonous substrings from given string | function to return final result ; initialize variable to keep track of ongoing sequence ; if current sequence is neither increasing nor decreasing ; if prev char is greater ; if prev char is same ; otherwise ; if current sequence is non - decreasing ; if prev char is smaller ; if prev char is same ; update ongoing ; otherwise ; update ongoing ; increase count ; if current sequence is non - increasing ; if prev char is greater , then update ongoing with d ; if prev char is equal , then update current with d ; otherwise , update ongoing with n and increment count ; return count + 1 ; 
def minReqSubstring(s, n):
    ongoing = 'N'
    count, l = 0, len(s)
    for i in range(1, l):
        if ongoing == 'N':
            if s[i] < s[i - 1]:
                ongoing = 'D'
            elif s[i] == s[i - 1]:
                ongoing = 'N'
            else:
                ongoing = 'I'
        elif ongoing == 'I':
            if s[i] > s[i - 1]:
                ongoing = 'I'
            elif s[i] == s[i - 1]:
                ongoing = 'I'
            else:
                ongoing = 'N'
                count += 1
        else:
            if s[i] < s[i - 1]:
                ongoing = 'D'
            elif s[i] == s[i - 1]:
                ongoing = 'D'
            else:
                ongoing = 'N'
                count += 1
    return count + 1


S = "aeccdhba"
n = len(S)
print(minReqSubstring(S, n))

# Expected output:
3
# minimum decrements required such that sum of all adjacent pairs in an array does not exceed k | function to calculate the minimum number of operations required ; stores the total number of operations ; iterate over the array ; if the sum of pair of adjacent elements exceed k . ; if current element exceeds k ; reduce arr [ i ] to k ; update arr [ i + 1 ] accordingly ; update answer ; 
def minimum_required_operations(arr, n, k):
    answer = 0
    mod = 10 ** 9 + 7
    for i in range(n - 1):
        if arr[i] + arr[i + 1] > k:
            if arr[i] > k:
                answer += (arr[i] - k)
                arr[i] = k
            answer += (arr[i] + arr[i + 1]) - k
            arr[i + 1] = (k - arr[i])
            answer %= mod
    return answer


a = [9, 50, 4, 14, 42, 89]
k = 10
print(minimum_required_operations(a, len(a), k))

# Expected output:
178
# lexicographic smallest permutation of a string containing the second string as a substring | function to print the desired lexicographic smaller string ; calculate length of the string ; stores the frequencies of characters of string str1 ; stores the frequencies of characters of string str2 ; decrease the frequency of second string from that of of the first string ; to store the resultant string ; to find the index of first character of the string str2 ; append the characters in lexicographical order ; append all the current character ( i + ' a ' ) ; if we reach first character of string str2 append str2 ; return the resultant string ; 
def findSmallestString(str1, str2):
    freq1 = [0] * 26
    freq2 = [0] * 26
    n1 = len(str1)
    n2 = len(str2)
    for i in range(n1):
        freq1[ord(str1[i]) - ord('a')] += 1
    for i in range(n2):
        freq2[ord(str2[i]) - ord('a')] += 1
    for i in range(26):
        freq1[i] -= freq2[i]
    res = ""
    minIndex = ord(str2[0]) - ord('a')
    for i in range(26):
        for j in range(freq1[i]):
            res += chr(i + ord('a'))
        if i == minIndex:
            res += str2
    return res


str1 = "geeksforgeeksfor"
str2 = "for"
print(findSmallestString(str1, str2))

# Expected output:
eeeefforggkkorss
# restore original string from given encrypted string by the given operations | function to decrypt and print the original strings ; if length is exceeded ; reverse the string ; 
def decryptString(s, N):
    for i in range(0, len(s), 2 * N):
        if (i + N < len(s)):
            end = s[i + N]
        if (i + N > len(s)):
            end = s[-1]
        if (i == 0):
            s = s[i + N - 1::-1] + s[i + N:]
        else:
            s = s[:i] + s[i + N - 1:i - 1:-1] + s[i + N:]
    print(s)


if __name__ == "__main__":
    s = "ihTs suohld ebeas!y"
    N = 3
    decryptString(s, N)

# Expected output:
This should ebeas!y
# determine the winner of a game of deleting characters from a string | function to find the winner of the game when both players play optimally ; stores the frequency of all digit ; stores the scores of player1 and player2 respectively ; iterate to store frequencies ; turn for the player1 ; add score of player1 ; add score of player2 ; check if its a draw ; if score of player 1 is greater ; otherwise ; 
def determineWinner(str):
    A = [0 for i in range(9)]
    sum1 = 0
    sum2 = 0
    for i in range(0, len(str)):
        A[int(str[i])] += 1
    for i in range(0, 9):
        if (i % 2 != 0):
            sum1 = sum1 + A[i]
        else:
            sum2 = sum2 + A[i]
    if (sum1 == sum2):
        print("-1")
    elif (sum1 > sum2):
        print("Player 1")
    else:
        print("Player 2")


if __name__ == '__main__':
    str = "78787"
    determineWinner(str)

# Expected output:
Player 1
# generate a string from given strings p and q based on the given conditions | function to generate a string s from string p and q according to the given conditions ; stores the frequencies ; counts occurrences of each characters ; reduce the count of the character which is also present in q ; stores the resultant string ; index in freq [ ] to segregate the string ; add q to the resulting string ; 
def manipulateStrings(P, Q):
    freq = [0 for i in range(26)]
    for i in range(len(P)):
        freq[ord(P[i]) - ord('a')] += 1
    for i in range(len(Q)):
        freq[ord(Q[i]) - ord('a')] -= 1
    sb = ""
    pos = ord(Q[0]) - ord('a')
    for i in range(pos + 1):
        while freq[i] > 0:
            sb += chr(ord('a') + i)
            freq[i] -= 1
    sb += Q
    for i in range(pos + 1, 26):
        while freq[i] > 0:
            sb += chr(ord('a') + i)
            freq[i] -= 1
    print(sb)


if __name__ == "__main__":
    P = "geeksforgeeksfor"
    Q = "for"
    manipulateStrings(P, Q)

# Expected output:
eeeefforggkkorss
# minimum moves required to type a word in qwerty based keyboard | function that calculates the moves required to prthe current string ; row1 has qwertyuiop , row2 has asdfghjkl , and row3 has zxcvbnm store the row number of each character ; string length ; initialise move to 1 ; traverse the string ; if current row number is not equal to previous row then increment the moves ; return the moves ; 
def numberMoves(s):
    row = [2, 3, 3, 2, 1, 2, 2, 2, 1, 2, 2, 2,
           3, 3, 1, 1, 1, 1, 2, 1, 1, 3, 1, 3, 1, 3]
    n = len(s)
    move = 1
    for i in range(1, n):
        if (row[ord(s[i]) - ord('a')] != row[ord(s[i - 1]) - ord('a')]):
            move += 1
    return move


if __name__ == '__main__':
    str = "geeksforgeeks"
    print(numberMoves(str))

# Expected output:
7
# count of distinct strings possible by swapping prefixes of pairs of strings from the array | python3 program to implement the above approach ; function to count the distinct strings possible after swapping the prefixes between two possible strings of the array ; stores the count of unique characters for each index ; store current string ; stores the total number of distinct strings possible ; return the answer ; 

from collections import defaultdict
mod = 1000000007


def countS(string: list, n: int, m: int) -> int:
    counts = defaultdict(lambda: set())
    for i in range(n):
        s = string[i]
        for j in range(m):
            counts[j].add(s[j])
    result = 1
    for index in counts:
        result = (result * len(counts[index])) % mod
    return result


if __name__ == "__main__":
    string = ["112", "211"]
    N = 2
    M = 3
    print(countS(string, N, M))

# Expected output:
4
# longest subarrays having each array element as the maximum | function to find the maximum length of subarrays for each element of the array having it as the maximum ; initialise the bounds ; iterate to find greater element on the left ; if greater element is found ; decrement left pointer ; if boundary is exceeded ; iterate to find greater element on the right ; if greater element is found ; increment right pointer ; if boundary is exceeded ; length of longest subarray where arr [ i ] is the largest ; print the answer ; 
def solve(n, arr):
    ans = 0
    for i in range(n):
        left = max(i - 1, 0)
        right = min(n - 1, i + 1)
        while left >= 0:
            if arr[left] > arr[i]:
                left += 1
                break
            left -= 1
        if left < 0:
            left += 1
        while right < n:
            if arr[right] > arr[i]:
                right -= 1
                break
            right += 1
        if right >= n:
            right -= 1
        ans = 1 + right - left
        print(ans, end=" ")


arr = [4, 2, 1]
n = len(arr)
solve(n, arr)

# Expected output:
3 2 1
# count of substrings having sum equal to their length | python3 program to implement the above approach ; function to count the number of substrings with sum equal to length ; stores the count of substrings ; add character to sum ; add count of substrings to result ; increase count of subarrays ; return count ; 

from collections import defaultdict


def countSubstrings(s, n):
    count, sum = 0, 0
    mp = defaultdict(lambda: 0)
    mp[0] += 1
    for i in range(n):
        sum += ord(s[i]) - ord('0')
        count += mp[sum - (i + 1)]
        mp[sum - (i + 1)] += 1
    return count


str = '112112'
n = len(str)
print(countSubstrings(str, n))

# Expected output:
6