giulio98/xlcost-single-prompt huggingface dataset:
# maximize cost of deletions to obtain string having no pair of similar adjacent characters | function to find maximum cost to remove consecutive characters ; initialize the count ; maximum cost ; traverse from 0 to len ( s ) - 2 ; if characters are identical ; add cost [ i ] if its maximum ; add cost [ i + 1 ] if its maximum ; increment i ; return the final max count ; given string s ; 
def Maxcost(s, cost):
    count = 0
    maxcost = 0
    i = 0
    while i < len(s) - 1:
        if s[i] == s[i + 1]:
            if cost[i] > cost[i + 1]:
                maxcost += cost[i]
            else:
                maxcost += cost[i + 1]
                cost[i + 1] = cost[i]
        i += 1
    return maxcost


s = "abaac"
cost = [1, 2, 3, 4, 5]
print(Maxcost(s, cost))

# Expected output:
4
# maximum count of values of s modulo m lying in a range [ l , r ] after performing given operations on the array | lookup table ; function to count the value of s after adding arr [ i ] or arr [ i - 1 ] to the sum s at each time ; base case ; store the mod value ; if the mod value lies in the range then return 1 ; else return 0 ; store the current state ; if already computed , return the computed value ; recursively adding the elements to the sum adding ai value ; adding arr [ i ] - 1 value ; return the maximum count to check for root value as well ; avoid counting idx = 0 as possible solution we are using idx != 0 ; return the value of current state ; 

dp = {}


def countMagicNumbers(idx, sum, a, n, m, l, r):
    if (idx == n):
        temp = sum % m
        if (temp == l or temp == r or (temp > l and temp < r)):
            dp[(idx, sum)] = 1
            return dp[(idx, sum)]
        else:
            dp[(idx, sum)] = 0
            return dp[(idx, sum)]
    curr = (idx, sum)
    if (curr in dp):
        return dp[curr]
    ls = countMagicNumbers(idx + 1, sum + a[idx], a, n, m, l, r)
    rs = countMagicNumbers(idx + 1, sum + (a[idx] - 1), a, n, m, l, r)
    temp1 = max(ls, rs)
    temp = sum % m
    if ((temp == l or temp == r or (temp > l and temp < r)) and idx != 0):
        temp1 += 1
    dp[(idx, sum)] = temp1
    return dp[(idx, sum)]


if __name__ == '__main__':
    N = 5
    M = 22
    L = 14
    R = 16
    arr = [17, 11, 10, 8, 15]
    print(countMagicNumbers(0, 0, arr, N, M, L, R))

# Expected output:
3
# check if a path exists for a cell valued 1 to reach the bottom right corner of a matrix before any cell valued 2 | python3 program for the above approach ; function to check if cell with value 1 doesn 't reaches the bottom right cell or not ; number of rows and columns ; initialise the deque ; traverse the matrix ; push 1 to front of queue ; push 2 to back of queue ; store all the possible direction of the current cell ; run multi - source bfs ; get the front element ; if 1 reached corner first ; insert new poin queue ; if 1 can 't reach the bottom  right then return false ; 

from collections import deque


def reachesBottom(a):
    n = len(a)
    m = len(a[0])
    q = deque()
    for i in range(n):
        for j in range(m):
            if (a[i][j] == 1):
                q .appendleft([i, j, 1])
            elif (a[i][j] == 2):
                q .append([i, j, 2])
            a[i][j] = 0
    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]
    while (len(q) > 0):
        front = q .popleft()
        i = front[0]
        j = front[1]
        t = front[2]
        if (a[i][j]):
            continue
        a[i][j] = 1
        if (t == 1 and (i == n - 1 and j == m - 1)):
            return True
        for d in range(4):
            ni = i + dx[d]
            nj = j + dy[d]
            if (ni >= 0 and ni < n and nj >= 0 and nj < m):
                q .append([ni, nj, t])
    return False


if __name__ == '__main__':
    matrix = [[0, 2, 0], [0, 1, 0], [0, 2, 0]]
    if (reachesBottom(matrix)):
        print("YES")
    else:
        print("NO")

# Expected output:
NO
# smallest element from all square submatrices of size k from a given matrix | python3 program for the above approach ; function to returns a smallest elements of all kxk submatrices of a given nxm matrix ; stores the dimensions of the given matrix ; stores the required smallest elements ; update the smallest elements row - wise ; update the minimum column - wise ; store the final submatrix with required minimum values ; return the resultant matrix ; function call ; print resultant matrix with the minimum values of kxk sub - matrix ; given matrix ; 

import sys


def matrixMinimum(nums, K):
    N = len(nums)
    M = len(nums[0])
    res = [[0 for x in range(M - K + 1)]for y in range(N - K + 1)]
    for i in range(N):
        for j in range(M - K + 1):
            mn = sys .maxsize
            for k in range(j, j + K):
                mn = min(mn, nums[i][k])
            nums[i][j] = mn
    for j in range(M):
        for i in range(N - K + 1):
            mn = sys .maxsize
            for k in range(i, i + K):
                mn = min(mn, nums[k][j])
            nums[i][j] = mn
    for i in range(N - K + 1):
        for j in range(M - K + 1):
            res[i][j] = nums[i][j]
    return res


def smallestinKsubmatrices(arr, K):
    res = matrixMinimum(arr, K)
    for i in range(len(res)):
        for j in range(len(res[0])):
            print(res[i][j], end=" ")
        print()


arr = [[-1, 5, 4, 1, -3], [4, 3, 1, 1, 6],
       [2, -2, 5, 3, 1], [8, 5, 1, 9, -4], [12, 3, 5, 8, 1]]
K = 3
smallestinKsubmatrices(arr, K)

# Expected output:
-2 -2 -3 
-2 -2 -4 
-2 -2 -4
# split array into two subarrays such that difference of their sum is minimum | python3 program for the above approach ; function to return minimum difference between sum of two subarrays ; to store total sum of array ; calculate the total sum of the array ; stores the prefix sum ; stores the minimum difference ; traverse the given array ; to store minimum difference ; update mindiff ; return mindiff ; 

import sys


def minDiffSubArray(arr, n):
    total_sum = 0
    for i in range(n):
        total_sum += arr[i]
    prefix_sum = 0
    minDiff = sys .maxsize
    for i in range(n - 1):
        prefix_sum += arr[i]
        diff = abs((total_sum - prefix_sum) - prefix_sum)
        if (diff < minDiff):
            minDiff = diff
    return minDiff


arr = [7, 9, 5, 10]
n = len(arr)
print(minDiffSubArray(arr, n))

# Expected output:
1
# maximize count of non | function to count the maximum number of subarrays with sum k ; stores all the distinct prefixsums obtained ; stores the prefix sum of the current subarray ; stores the count of subarrays with sum k ; if a subarray with sum k is already found ; increase count ; reset prefix sum ; clear the set ; insert the prefix sum ; 
def CtSubarr(arr, N, K):
    st = set()
    prefixSum = 0
    st .add(prefixSum)
    res = 0
    for i in range(N):
        prefixSum += arr[i]
        if ((prefixSum - K) in st):
            res += 1
            prefixSum = 0
            st .clear()
            st .add(0)
        st .add(prefixSum)
    return res


arr = [-2, 6, 6, 3, 5, 4, 1, 2, 8]
N = len(arr)
K = 10
print(CtSubarr(arr, N, K))

# Expected output:
3
# count of subarrays consisting of only prime numbers | function to check if a number is prime or not . ; if n has any factor other than 1 , then n is non - prime . ; function to return the count of subarrays made up of prime numbers only ; stores the answer ; stores the count of continuous prime numbers in an array ; if the current array element is prime ; increase the count ; update count of subarrays ; if the array ended with a continuous prime sequence ; 
def is_prime(n):
    if (n <= 1):
        return 0
    i = 2
    while (i * i <= n):
        if (n % i == 0):
            return 0
        i += 1
    return 1


def count_prime_subarrays(ar, n):
    ans = 0
    count = 0
    for i in range(n):
        if (is_prime(ar[i])):
            count += 1
        else:
            if (count):
                ans += count * (count + 1) // 2
                count = 0
    if (count):
        ans += count * (count + 1) // 2
    return ans


N = 10
ar = [2, 3, 5, 6, 7, 11, 3, 5, 9, 3]
print(count_prime_subarrays(ar, N))

# Expected output:
17
# minimum subarray flips required to convert all elements of a binary array to k | function to count the minimum number of subarray flips required ; iterate the array ; if arr [ i ] and flag are equal ; return the answer ; 
def minSteps(arr, n, k):
    cnt = 0
    if (k == 1):
        flag = 0
    else:
        flag = 1
    for i in range(n):
        if (arr[i] == flag):
            cnt += 1
            flag = (flag + 1) % 2
    return cnt


arr = [1, 0, 1, 0, 0, 1, 1, 1]
n = len(arr)
k = 1
print(minSteps(arr, n, k))

# Expected output:
4
# minimize sum of an array by at most k reductions | function to obtain the minimum possible sum from the array by k reductions ;  ; insert elements into the maxheap ; remove the maximum ; insert maximum / 2 ; stores the sum of remaining elements ; 
def minSum(a, n, k):

    q = []
    for i in range(n):
        q.append(a[i])

    q = sorted(q)

    while (len(q) > 0 and k > 0):
        top = q[-1] // 2
        del q[-1]

        q.append(top)
        k -= 1
        q = sorted(q)

    sum = 0
    while (len(q) > 0):
        sum += q[-1]
        del q[-1]

    return sum


if __name__ == '__main__':

    n = 4
    k = 3

    a = [20, 7, 5, 4]

    print(minSum(a, n, k))

# Expected output:
17
# sum of indices of characters removed to obtain an empty string based on given conditions | python3 program to implement the above approach ; function to add index of the deleted character ; if index is beyond the range ; insert the index of the deleted characeter ; search over the subtrees to find the desired index ; function to return count of deleted indices which are to the left of the current index ; function to generate the sum of indices ; stores the original index of the characters in sorted order of key ; traverse the map ; extract smallest index of smallest character ; delete the character from the map if it has no remaining occurrence ; stores the original index ; count of elements removed to the left of current character ; current index of the current character ; for 1 - based indexing ; insert the deleted index in the segment tree ; final answer ; 

import math
import collections


def add_seg(seg, start, end, current, index):
    if (index > end or index < start):
        return
    if (start == end):
        seg[current] = 1
        return
    mid = int((start + end) / 2)
    add_seg(seg, start, mid, 2 * current + 1, index)
    add_seg(seg, mid + 1, end, 2 * current + 2, index)
    seg[current] = seg[2 * current + 1] + seg[2 * current + 2]


def deleted(seg, l, r, start, end, current):
    if (end < l or start > r):
        return 0
    if (start >= l and end <= r):
        return seg[current]
    mid = int((start + end) / 2)
    return deleted(seg, l, r, start, mid, 2 * current + 1) + \
        deleted(seg, l, r, mid + 1, end, 2 * current + 2)


def sumOfIndices(s):
    N = len(s)
    x = (int)(math .ceil(math .log(N) / math .log(2)))
    seg_size = 2 * pow(2, x) - 1
    segment = [0] * (seg_size)
    count = 4
    fre = {}
    for i in range(N):
        key = (ord)(s[i])
        if key in fre:
            que = fre[key]
        else:
            que = collections .deque([])
        que .append(i)
        fre[key] = que
    while len(fre) > 0:
        it = list(fre .keys())[0]
        if len(fre[it]) == 0:
            del fre[it]
        else:
            que = fre[it]
            original_index = que[0]
            curr_index = deleted(segment, 0, original_index - 1, 0, N - 1, 0)
            new_index = original_index - curr_index
            count += new_index + 1
            add_seg(segment, 0, N - 1, 0, original_index)
            que .popleft()
            fre[it] = que
    print(count)


s = "geeksforgeeks"
sumOfIndices(s)

# Expected output:
41
# maximum length of sequence of sums of prime factors generated by the given operations | python3 program to implement the above approach ; smallest prime factor array ; stores if a number is prime or not ; function to compute all primes using sieve of eratosthenes ; function for finding smallest prime factors for every integer ; function to find the sum of prime factors of number ; add smallest prime factor to the sum ; reduce n ; return the answer ; function to return the length of sequence of for the given number ; if the number is prime ; if a previously computed subproblem occurred ; calculate the sum of prime factors ; function to return the maximum length of sequence for the given range ; pre - calculate primes ; precalculate smallest prime factors ; iterate over the range ; update maximum length ; 

import sys
spf = [0] * 100005
prime = [False] * 100005
dp = [0] * 100005


def sieve():
    for i in range(2, 100005):
        prime[i] = True
    i = 2
    while i * i < 100005:
        if (prime[i]):
            for j in range(i * i, 100005, i):
                prime[j] = False
        i += 1


def smallestPrimeFactors():
    for i in range(10005):
        spf[i] = -1
    i = 2
    while i * i < 100005:
        for j in range(i, 100005, i):
            if (spf[j] == -1):
                spf[j] = i
        i += 1


def sumOfPrimeFactors(n):
    ans = 0
    while (n > 1):
        ans += spf[n]
        n //= spf[n]
    return ans


def findLength(n):
    if (prime[n]):
        return 1
    if (dp[n]):
        return dp[n]
    sum = sumOfPrimeFactors(n)
    dp[n] = 1 + findLength(sum)
    return dp[n]


def maxLength(n, m):
    sieve()
    smallestPrimeFactors()
    ans = -sys .maxsize - 1
    for i in range(n, m + 1):
        if (i == 4):
            continue
        ans = max(ans, findLength(i))
    return ans


n = 2
m = 14
print(maxLength(n, m))

# Expected output:
4
# longest subarray consisting of unique elements from an array | python3 program to implement the above approach ; function to find largest subarray with no duplicates ; stores index of array elements ; update j based on previous occurrence of a [ i ] ; update ans to store maximum length of subarray ; store the index of current occurrence of a [ i ] ; return final ans ; 

from collections import defaultdict


def largest_subarray(a, n):
    index = defaultdict(lambda: 0)
    ans = 0
    j = 0
    for i in range(n):
        j = max(index[a[i]], j)
        ans = max(ans, i - j + 1)
        index[a[i]] = i + 1
        i += 1
    return ans


arr = [1, 2, 3, 4, 5, 1, 2, 3]
n = len(arr)
print(largest_subarray(arr, n))

# Expected output:
5
# count of ways to obtain given sum from the given array elements | function to count the number of ways ; base case : reached the end of the array ; sum is equal to the required sum ; recursively check if required sum can be obtained by adding current element or by subtracting the current index element ; function to call dfs ( ) to calculate the number of ways ; 
def dfs(nums, S, curr_sum, index):
    if (index == len(nums)):
        if (S == curr_sum):
            return 1
        else:
            return 0
    return (dfs(nums,
                S,
                curr_sum + nums[index],
                index + 1) + dfs(nums,
                                 S,
                                 curr_sum - nums[index],
                                 index + 1))


def findWays(nums, S):
    return dfs(nums, S, 0, 0)


if __name__ == '__main__':
    S = 3
    arr = [1, 2, 3, 4, 5]
    answer = findWays(arr, S)
    print(answer)

# Expected output:
3
# minimum sum of a pair at least k distance apart from an array | python3 program to implement the above approach ; function to find the minimum sum of two elements that are atleast k distance apart ; length of the array ; iterate over the array ; initialize the min value ; iterate from i + k to n ; find the minimum ; update the minimum sum ; prthe answer ; 

import sys


def findMinSum(A, K):
    n = len(A)
    minimum_sum = sys .maxsize
    for i in range(n):
        minimum = sys .maxsize
        for j in range(i + K, n, 1):
            minimum = min(minimum, A[j])
        if (minimum == sys .maxsize):
            continue
        minimum_sum = min(minimum_sum, A[i] + minimum)
    print(minimum_sum)


if __name__ == '__main__':
    A = [4, 2, 5, 4, 3, 2, 5]
    K = 3
    findMinSum(A, K)

# Expected output:
4
# count of all possible pairs having sum of lcm and gcd equal to n | recursive function to return gcd of a and b ; function to calculate and return lcm of two numbers ; function to count pairs whose sum of gcd and lcm is equal to n ; 
def __gcd(a, b):
    if b == 0:
        return a
    else:
        return __gcd(b, a % b)


def lcm(a, b):
    return (a * b) // __gcd(a, b)


def countPair(N):
    count = 0
    for i in range(1, N + 1):
        for j in range(1, N + 1):
            if (__gcd(i, j) + lcm(i, j) == N):
                count += 1
    return count


if __name__ == "__main__":
    N = 14
    print(countPair(N))

# Expected output:
7
# maximize count of set bits in a root to leaf path in a binary tree | python3 program to implement the above approach ; node class ; initialise constructor ; function to count the number of 1 in number ; function to find the maximum count of setbits in a root to leaf ; check if root is null ; update the maximum count of setbits ; traverse left of binary tree ; traverse right of the binary tree ; 

maxm = 0


class Node:
    def __init__(self, x):
        self .val = x
        self .left = None
        self .right = None


def count_1(n):
    count = 0
    while (n):
        count += n & 1
        n >>= 1
    return count


def maxm_setbits(root, ans):
    global maxm
    if not root:
        return
    if (root .left is None and root .right is None):
        ans += count_1(root .val)
        maxm = max(ans, maxm)
        return
    maxm_setbits(root .left, ans + count_1(root .val))
    maxm_setbits(root .right, ans + count_1(root .val))


root = Node(15)
root .left = Node(3)
root .right = Node(7)
root .left .left = Node(5)
root .left .right = Node(1)
root .right .left = Node(31)
root .right .right = Node(9)
maxm_setbits(root, 0)
print(maxm)

# Expected output:
12
# minimize count of divisions by d to obtain at least k equal array elements | function to return minimum number of moves required ; stores the number of moves required to obtain respective values from the given array ; traverse the array ; insert 0 into v [ a [ i ] ] as it is the initial state ; insert the moves required to obtain current a [ i ] ; traverse v [ ] to obtain minimum count of moves ; check if there are at least k equal elements for v [ i ] ; add the sum of minimum k moves ; update answer ; return the final answer ; 
def getMinimumMoves(n, k, d, a):
    MAX = 100000
    v = []
    for i in range(MAX):
        v .append([])
    for i in range(n):
        cnt = 0
        v[a[i]] += [0]
        while (a[i] > 0):
            a[i] //= d
            cnt += 1
            v[a[i]] += [cnt]
    ans = float('inf')
    for i in range(MAX):
        if (len(v[i]) >= k):
            move = 0
            v[i].sort()
            for j in range(k):
                move += v[i][j]
            ans = min(ans, move)
    return ans


if __name__ == '__main__':
    N = 5
    K = 3
    D = 2
    A = [1, 2, 3, 4, 5]
    print(getMinimumMoves(N, K, D, A))

# Expected output:
2
# longest subarray with odd product | function to return length of longest subarray with odd product ; if even element is encountered ; update maximum ; 
def Maxlen(a, n):
    ans = 0
    count = 0
    for i in range(n):
        if a[i] % 2 == 0:
            count = 0
        else:
            count += 1
        ans = max(ans, count)
    return ans


arr = [1, 7, 2]
n = len(arr)
print(Maxlen(arr, n))

# Expected output:
2
# min difference between maximum and minimum element in all y size subarrays | function to get the maximum of all the subarrays of size y ; ith index of maxarr array will be the index upto which arr [ i ] is maximum ; stack is used to find the next larger element and keeps track of index of current iteration ; loop for remaining indexes ; j < i used to keep track whether jth element is inside or outside the window ; return submax ; function to get the minimum for all subarrays of size y ; ith index of minarr array will be the index upto which arr [ i ] is minimum ; stack is used to find the next smaller element and keeping track of index of current iteration ; loop for remaining indexes ; j < i used to keep track whether jth element is inside or outside the window ; return submin ; function to get minimum difference ; create submin and submax arrays ; store initial difference ; calculate temporary difference ; final minimum difference ; given array arr [ ] ; 
def get_submaxarr(arr, n, y):
    j = 0
    stk = []
    maxarr = [0] * n
    stk .append(0)
    for i in range(1, n):
        while (len(stk) > 0 and arr[i] > arr[stk[-1]]):
            maxarr[stk[-1]] = i - 1
            stk .pop()
        stk .append(i)
    while (stk):
        maxarr[stk[-1]] = n - 1
        stk .pop()
    submax = []
    for i in range(n - y + 1):
        while (maxarr[j] < i + y - 1 or j < i):
            j += 1
        submax .append(arr[j])
    return submax


def get_subminarr(arr, n, y):
    j = 0
    stk = []
    minarr = [0] * n
    stk .append(0)
    for i in range(1, n):
        while (stk and arr[i] < arr[stk[-1]]):
            minarr[stk[-1]] = i
            stk .pop()
        stk .append(i)
    while (stk):
        minarr[stk[-1]] = n
        stk .pop()
    submin = []
    for i in range(n - y + 1):
        while (minarr[j] <= i + y - 1 or j < i):
            j += 1
        submin .append(arr[j])
    return submin


def getMinDifference(Arr, N, Y):
    submin = get_subminarr(Arr, N, Y)
    submax = get_submaxarr(Arr, N, Y)
    minn = submax[0] - submin[0]
    b = len(submax)
    for i in range(1, b):
        diff = submax[i] - submin[i]
        minn = min(minn, diff)
    print(minn)


arr = [1, 2, 3, 3, 2, 2]
N = len(arr)
Y = 4
getMinDifference(arr, N, Y)

# Expected output:
1
# least root of given quadratic equation for value greater than equal to k | python3 program for the above approach ; function to calculate value of quadratic equation for some x ; function to calculate the minimum value of x such that f ( x ) >= k using binary search ; start and end value for binary search ; binary search ; computing f ( mid ) and f ( mid - 1 ) ; if f ( mid ) >= k and f ( mid - 1 ) < k return mid ; if f ( mid ) < k go to mid + 1 to end ; if f ( mid ) > k go to start to mid - 1 ; if no such value exist ; 

import math


def func(A, B, C, x):
    return (A * x * x + B * x + C)


def findMinx(A, B, C, K):
    start = 1
    end = math .ceil(math .sqrt(K))
    while (start <= end):
        mid = start + (end - start) // 2
        x = func(A, B, C, mid)
        Y = func(A, B, C, mid - 1)
        if (x >= K and Y < K):
            return mid
        elif (x < K):
            start = mid + 1
        else:
            end = mid - 1
    return -1


A = 3
B = 4
C = 5
K = 6
print(findMinx(A, B, C, K))

# Expected output:
1
# k | python3 program to find k - th term of n merged arithmetic progressions ; function to count and return the number of values less than equal to n present in the set ; check whether j - th bit is set bit or not ; function to implement binary search to find k - th element ; find middle index of the array ; search in the left half ; search in the right half ; if exactly k elements are present ; 

maxm = 1000000000


def count(v, n):
    odd, even = 0, 0
    t = 1 << len(v)
    size = len(v)
    for i in range(1, t):
        d, count = 1, 0
        for j in range(0, size):
            if (i & (1 << j)):
                d *= v[j]
                count += 1
        if (count & 1):
            odd += n // d
        else:
            even += n // d
    return (odd - even)


def BinarySearch(l, r, v, key):
    while (r - l > 1):
        mid = (l + r) // 2
        if (key <= count(v, mid)):
            r = mid
        else:
            l = mid
    if (key == count(v, l)):
        return l
    else:
        return r


N, K = 2, 10
v = [2, 3]
print(BinarySearch(1, maxm, v, K))

# Expected output:
15