giulio98/xlcost-single-prompt huggingface dataset:
# count of ways to split an array into three contiguous subarrays having increasing sum | function to count the number of ways to split array into three contiguous subarrays of the required type ; stores the prefix sums ; stores the suffix sums ; traverse the given array ; updating curr_subarray_sum until it is less than prefix_sum [ s - 1 ] ; increase count ; decrease curr_subarray_sum by arr [ s [ ] ; return count ; 
def findCount(arr, n):
    prefix_sum = [0 for x in range(n)]
    prefix_sum[0] = arr[0]
    for i in range(1, n):
        prefix_sum[i] = prefix_sum[i - 1] + arr[i]
    suffix_sum = [0 for x in range(n)]
    suffix_sum[n - 1] = arr[n - 1]
    for i in range(n - 2, -1, -1):
        suffix_sum[i] = suffix_sum[i + 1] + arr[i]
    s = 1
    e = 1
    curr_subarray_sum = 0
    count = 0
    while (s < n - 1 and e < n - 1):
        while (e < n - 1 and curr_subarray_sum < prefix_sum[s - 1]):
            curr_subarray_sum += arr[e]
            e += 1
        if (curr_subarray_sum <= suffix_sum[e]):
            count += 1
        curr_subarray_sum -= arr[s]
        s += 1
    return count


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

# Expected output:
2
# minimum number of operations required to maximize the binary string | function to find the number of operations required ; count of 1 's ; count of 0 's upto (cnt1)-th index ; return the answer ; 
def minOperation(s, n):
    cnt1 = 0
    for i in range(n):
        if (ord(s[i]) == ord('1')):
            cnt1 += 1
    cnt0 = 0
    for i in range(0, cnt1):
        if (s[i] == '0'):
            cnt0 += 1
    return cnt0


if __name__ == '__main__':
    n = 8
    s = "01001011"
    ans = minOperation(s, n)
    print(ans)

# Expected output:
3
# minimum number of operations required to maximize the binary string | function to find the number of operations required ; swap 0 ' s ▁ and ▁ 1' s ; return the answer ; 
def minOperation(s, n):
    ans = 0
    i = 0
    j = n - 1
    while (i < j):
        if (s[i] == '0' and s[j] == '1'):
            ans += 1
            i += 1
            j -= 1
            continue
        if (s[i] == '1'):
            i += 1
        if (s[j] == '0'):
            j -= 1
    return ans


if __name__ == '__main__':
    n = 8
    s = "10100101"
    print(minOperation(s, n))

# Expected output:
2
# count of n digit numbers having no pair of equal consecutive digits | function to count the number of n - digit numbers with no equal pair of consecutive digits ; base case ; calculate the total count of valid ( i - 1 ) - digit numbers ; update dp table ; calculate the count of required n - digit numbers ; 
def count(N):
    if (N == 1):
        print(10)
        return
    dp = [[0 for i in range(10)]for j in range(N)]
    for i in range(1, 10):
        dp[0][i] = 1
    for i in range(1, N):
        temp = 0
        for j in range(10):
            temp += dp[i - 1][j]
        for j in range(10):
            dp[i][j] = temp - dp[i - 1][j]
    ans = 0
    for i in range(10):
        ans += dp[N - 1][i]
    print(ans)


if __name__ == '__main__':
    N = 2
    count(N)

# Expected output:
81
# count of n digit numbers having no pair of equal consecutive digits | iterative function to calculate ( x ^ y ) % mod in o ( log y ) ; initialize result ; update x if x >= mod ; if x is divisible by mod ; if y is odd , multiply x with result ; y must be even now y = y / 2 ; function to count the number of n - digit numbers with no equal pair of consecutive digits ; base case ; 
def power(x, y, mod):
    res = 1
    x = x % mod
    if (x == 0):
        return 0
    while (y > 0):
        if ((y & 1) == 1):
            res = (res * x) % mod
        y = y >> 1
        x = (x * x) % mod
    return res


def count(N):
    if (N == 1):
        print(10)
        return
    print(power(9, N, 1000000007))


if __name__ == '__main__':
    N = 3
    count(N)

# Expected output:
729
# smallest string consisting of a string s exactly k times as a substring | kmp algorithm ; function to return the required string ; finding the longest proper prefix which is also suffix ; ans string ; update ans appending the substring k - 1 times ; append the original string ; returning min length string which contain exactly k substring of given string ; 
def kmp(s):
    n = len(s)
    lps = [None] * n
    lps[0] = 0
    i, Len = 1, 0
    while (i < n):
        if (s[i] == s[Len]):
            Len += 1
            lps[i] = Len
            i += 1
        else:
            if (Len != 0):
                Len = lps[Len - 1]
            else:
                lps[i] = 0
                i += 1
    return lps


def findString(s, k):
    n = len(s)
    lps = kmp(s)
    ans = ""
    suff = s[0:n - lps[n - 1]:1]
    for i in range(k - 1):
        ans += suff
    ans += s
    return ans


k = 3
s = "geeksforgeeks"
print(findString(s, k))

# Expected output:
geeksforgeeksforgeeksforgeeks
# check if an array can be sorted by picking only the corner array elements | function to check if an array can be sorted using given operations ; if sequence becomes increasing after an already non - decreasing to non - increasing pattern ; if a decreasing pattern is observed ; 
def check(arr, n):
    g = 0
    for i in range(1, n):
        if (arr[i] - arr[i - 1] > 0 and g == 1):
            return False
        if (arr[i] - arr[i] < 0):
            g = 1
    return True


arr = [2, 3, 4, 10, 4, 3, 1]
n = len(arr)
if (check(arr, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# queries to find the count of connected non | count of connected cells ; function to return the representative of the set to which x belongs ; if x is parent of itself ; x is representative of the set ; otherwise ; path compression ; unites the set that includes x and the set that includes y ; find the representatives ( or the root nodes ) for x an y ; if both are in the same set ; decrement count ; if x ' s ▁ rank ▁ is ▁ less ▁ than ▁ y ' s rank ; otherwise ; then move x under y ( doesn 't matter which one goes where) ; and increment the result tree 's rank by 1 ; function to count the number of connected cells in the matrix ; store result for queries ; store representative of each element ; initially , all elements are in their own set ; stores the rank ( depth ) of each node ; if the grid [ x * m + y ] is already set , store the result ; set grid [ x * m + y ] to 1 ; increment count . ; check for all adjacent cells to do a union with neighbour 's  set if neighbour is also 1 ; store result . ; 

ctr = 0


def find(parent, x):
    if (parent[x] == x):
        return x
    parent[x] = find(parent, parent[x])
    return parent[x]


def setUnion(parent, rank, x, y):
    global ctr
    parentx = find(parent, x)
    parenty = find(parent, y)
    if (parenty == parentx):
        return
    ctr -= 1
    if (rank[parentx] < rank[parenty]):
        parent[parentx] = parenty
    elif (rank[parentx] > rank[parenty]):
        parent[parenty] = parentx
    else:
        parent[parentx] = parenty
        rank[parenty] += 1


def solve(n, m, query):
    global ctr
    result = [0] * len(query)
    parent = [0] * (n * m)
    for i in range(n * m):
        parent[i] = i
    rank = [1] * (n * m)
    grid = [0] * (n * m)
    for i in range(len(query)):
        x = query[i][0]
        y = query[i][1]
        if (grid[m * x + y] == 1):
            result[i] = ctr
            continue
        grid[m * x + y] = 1
        ctr += 1
        if (x > 0 and grid[m * (x - 1) + y] == 1):
            setUnion(parent, rank, m * x + y, m * (x - 1) + y)
        if (y > 0 and grid[m * (x) + y - 1] == 1):
            setUnion(parent, rank, m * x + y, m * (x) + y - 1)
        if (x < n - 1 and grid[m * (x + 1) + y] == 1):
            setUnion(parent, rank, m * x + y, m * (x + 1) + y)
        if (y < m - 1 and grid[m * (x) + y + 1] == 1):
            setUnion(parent, rank, m * x + y, m * (x) + y + 1)
        result[i] = ctr
    return result


if __name__ == "__main__":
    N = 3
    M = 3
    K = 4
    query = [[0, 0], [1, 1], [1, 0], [1, 2]]
    result = solve(N, M, query)
    for i in range(K):
        print(result[i], end=" ")

# Expected output:
1 2 1 1
# 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 ; find the suffix array ; iterate in the array ; update minimum sum ; print the answer ; 

import sys


def findMinSum(A, K):
    n = len(A)
    suffix_min = [0] * n
    suffix_min[n - 1] = A[n - 1]
    for i in range(n - 2, -1, -1):
        suffix_min[i] = min(suffix_min[i + 1], A[i])
    min_sum = sys .maxsize
    for i in range(n):
        if (i + K < n):
            min_sum = min(min_sum, A[i] + suffix_min[i + K])
    print(min_sum)


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

# Expected output:
4
# maximum number of envelopes that can be put inside other bigger envelopes | function that returns the maximum number of envelopes that can be inserted into another envelopes ; number of envelopes ; sort the envelopes in non - decreasing order ; initialize dp [ ] array ; to store the result ; loop through the array ; find envelopes count for each envelope ; store maximum envelopes count ; return the result ; 
def maxEnvelopes(envelopes):
    N = len(envelopes)
    if (N == 0):
        return N
    envelopes = sorted(envelopes)
    dp = [0] * N
    max_envelope = 1
    dp[0] = 1
    for i in range(1, N):
        dp[i] = 1
        for j in range(i):
            if (envelopes[i][0] > envelopes[j][0] and envelopes[i]
                    [1] > envelopes[j][1] and dp[i] < dp[j] + 1):
                dp[i] = dp[j] + 1
        max_envelope = max(max_envelope, dp[i])
    return max_envelope


if __name__ == '__main__':
    envelopes = [[4, 3], [5, 3], [5, 6], [1, 2]]
    print(maxEnvelopes(envelopes))

# Expected output:
3
# maximize difference between the sum of the two halves of the array after removal of n elements | function to print the maximum difference possible between the two halves of the array ; stores n maximum values from the start ; insert first n elements ; update sum of largest n elements from left ; for the remaining elements ; obtain minimum value in the set ; insert only if it is greater than minimum value ; update sum from left ; remove the minimum ; insert the current element ; clear the set ; store n minimum elements from the end ; insert the last n elements ; update sum of smallest n elements from right ; for the remaining elements ; obtain the minimum ; insert only if it is smaller than maximum value ; update sum from right ; remove the minimum ; insert the new element ; compare the difference and store the maximum ; return the maximum possible difference ; 
def FindMaxDif(a, m):
    n = m // 3
    l = [0] * (m + 5)
    r = [0] * (m + 5)
    s = []
    for i in range(1, m + 1):
        if (i <= n):
            l[i] = a[i - 1] + l[i - 1]
            s .append(a[i - 1])
        else:
            l[i] = l[i - 1]
            s .sort()
            d = s[0]
            if (a[i - 1] > d):
                l[i] -= d
                l[i] += a[i - 1]
                s .remove(d)
                s .append(a[i - 1])
    s .clear()
    for i in range(m, 0, -1):
        if (i >= m - n + 1):
            r[i] = a[i - 1] + r[i + 1]
            s .append(a[i - 1])
        else:
            r[i] = r[i + 1]
            s .sort()
            d = s[-1]
            if (a[i - 1] < d):
                r[i] -= d
                r[i] += a[i - 1]
                s .remove(d)
                s .append(a[i - 1])
    ans = -9e18
    for i in range(n, m - n + 1):
        ans = max(ans, l[i] - r[i + 1])
    return ans


vtr = [3, 1, 4, 1, 5, 9]
n = len(vtr)
print(FindMaxDif(vtr, n))

# Expected output:
1
# check if each element of an array is the sum of any two elements of another array | function to check if each element of b [ ] can be formed by adding two elements of array a [ ] ; store each element of b [ ] ; traverse all possible pairs of array ; if a [ i ] + a [ j ] is present in the set ; remove a [ i ] + a [ j ] from the set ; if set is empty ; otherwise ; 
def checkPossible(A, B, n):
    values = set([])
    for i in range(n):
        values .add(B[i])
    for i in range(n):
        for j in range(n):
            if ((A[i] + A[j]) in values):
                values .remove(A[i] + A[j])
                if (len(values) == 0):
                    break
    if (len(values) == 0):
        return "Yes"
    else:
        return "No"


if __name__ == "__main__":
    N = 5
    A = [3, 5, 1, 4, 2]
    B = [3, 4, 5, 6, 7]
    print(checkPossible(A, B, N))

# Expected output:
Yes
# count of array elements greater than or equal to twice the median of k trailing array elements | python3 program to implement the above approach ; function to find the count of array elements >= twice the median of k trailing array elements ; stores frequencies ; stores the array elements ; count the frequencies of the array elements ; iterating from d to n - 1 index means ( d + 1 ) th element to nth element ; to check the median ; iterate over the frequencies of the elements ; add the frequencies ; check if the low_median value is obtained or not , if yes then do not change as it will be minimum ; check if the high_median value is obtained or not , if yes then do not change it as it will be maximum ; store 2 * median of k trailing elements ; if the current >= 2 * median ; decrease the frequency for ( k - 1 ) - th element ; increase the frequency of the current element ; print the count ; 

import math
N = 200000
V = 500


def solve(n, d, input1):
    a = [0] * N
    cnt = [0] * (V + 1)
    for i in range(n):
        a[i] = input1[i]
    answer = 0
    for i in range(d):
        cnt[a[i]] += 1
    for i in range(d, n):
        acc = 0
        low_median = -1
        high_median = -1
        for v in range(V + 1):
            acc += cnt[v]
            if (low_median == -1 and acc >= int(math .floor((d + 1) / 2.0))):
                low_median = v
            if (high_median == -1 and acc >= int(math .ceil((d + 1) / 2.0))):
                high_median = v
        double_median = low_median + high_median
        if (a[i] >= double_median):
            answer += 1
        cnt[a[i - d]] -= 1
        cnt[a[i]] += 1
    print(answer)


if __name__ == "__main__":
    input1 = [1, 2, 2, 4, 5]
    n = len(input1)
    k = 3
    solve(n, k, input1)

# Expected output:
2
# smallest positive integer x satisfying the given equation | python3 program to implement the above approach ; function to find out the smallest positive integer for the equation ; stores the minimum ; iterate till k ; check if n is divisible by i ; return the answer ; 

import sys


def findMinSoln(n, k):
    minSoln = sys .maxsize
    for i in range(1, k):
        if (n % i == 0):
            minSoln = min(minSoln, (n // i) * k + i)
    return minSoln


if __name__ == '__main__':
    n = 4
    k = 6
    print(findMinSoln(n, k))

# Expected output:
10
# queries to find the lower bound of k from prefix sum array with updates using fenwick tree | function to calculate and return the sum of arr [ 0. . index ] ; traverse ancestors of bitree [ index ] ; update the sum of current element of bit to ans ; update index to that of the parent node in getsum ( ) view by subtracting lsb ( least significant bit ) ; function to update the binary index tree by replacing all ancestors of index by their respective sum with val ; traverse all ancestors and sum with ' val ' . ; add ' val ' to current node of bit ; update index to that of the parent node in updatebit ( ) view by adding lsb ( least significant bit ) ; function to construct the binary indexed tree for the given array ; initialize the binary indexed tree ; store the actual values in bitree [ ] using update ( ) ; function to obtain and return the index of lower_bound of k ; store the binary indexed tree ; solve each query in q ; update the values of all ancestors of idx ; 
def getSum(BITree, index):
    ans = 0
    index += 1
    while (index > 0):
        ans += BITree[index]
        index -= index & (-index)
    return ans


def updateBIT(BITree, n, index, val):
    index = index + 1
    while (index <= n):
        BITree[index] += val
        index += index & (-index)


def constructBITree(arr, n):
    BITree = [0] * (n + 1)
    for i in range(n + 1):
        BITree[i] = 0
    for i in range(n):
        updateBIT(BITree, n, i, arr[i])
    return BITree


def getLowerBound(BITree, arr, n, k):
    lb = -1
    l = 0
    r = n - 1
    while (l <= r):
        mid = l + (r - l) // 2
        if (getSum(BITree, mid) >= k):
            r = mid - 1
            lb = mid
        else:
            l = mid + 1
    return lb


def performQueries(A, n, q):
    BITree = constructBITree(A, n)
    for i in range(len(q)):
        id = q[i][0]
        if (id == 1):
            idx = q[i][1]
            val = q[i][2]
            A[idx] += val
            updateBIT(BITree, n, idx, val)
        else:
            k = q[i][1]
            lb = getLowerBound(BITree, A, n, k)
            print(lb)


if __name__ == "__main__":
    A = [1, 2, 3, 5, 8]
    n = len(A)
    q = [[1, 0, 2], [2, 5, 0], [1, 3, 5]]
    performQueries(A, n, q)

# Expected output:
1
# minimum number of leaves required to be removed from a tree to satisfy the given condition | stores the count of safe nodes ; function to perform dfs on the tree to obtain the count of vertices that are not required to be deleted ; update cost to reach the vertex ; if the vertex does not satisfy the condition ; otherwise ; traverse its subtree ; 

cnt = 0


def dfs(val, cost, tr, u, s):
    global cnt
    s = s + cost[u]
    if (s < 0):
        s = 0
    if (s > val[u]):
        return
    cnt += 1
    for i in range(0, len(tr[u])):
        dfs(val, cost, tr, tr[u][i], s)


if __name__ == "__main__":
    n = 9
    val = [88, 22, 83, 14, 95, 91, 98, 53, 11]
    cost = [-1, 24, -8, 67, 64, 65, 12, -80, 8]
    tr = [[]for i in range(n + 1)]
    tr[0].append(3)
    tr[0].append(4)
    tr[4].append(6)
    tr[6].append(2)
    tr[2].append(1)
    tr[2].append(8)
    tr[8].append(5)
    tr[5].append(7)
    dfs(val, cost, tr, 0, 0)
    print(n - cnt)

# Expected output:
5
# check if an array is made up of subarrays of continuous repetitions of every distinct element | function to check if the array is made up of subarrays of repetitions ; base case ; stores the size of current subarray ; if a different element is encountered ; if the previous subarray was a single element ; reset to new subarray ; increase size of subarray ; if last element differed from the second last element ; 
def ContinuousElements(a, n):
    if (n == 1):
        return False
    curr = 1
    for i in range(1, n):
        if (a[i] != a[i - 1]):
            if (curr == 1):
                return False
            else:
                curr = 0
                curr += 1
                if (curr == 1):
                    return False

                return True


if __name__ == "__main__":
    a = [1, 1, 2, 2, 1, 3, 3]
    n = len(a)
    if (ContinuousElements(a, n)):
        print("Yes")
    else:
        print("No")

# Expected output:
No
# find a pair in array with second largest product | function to find second largest product pair in arr [ 0. . n - 1 ] ; no pair exits ; sort the array ; initialize smallest element of the array ; initialize largest element of the array ; prsecond largest product pair ; 
def maxProduct(arr, N):
    if (N < 3):
        return
    arr .sort()
    smallest1 = arr[0]
    smallest3 = arr[2]
    largest1 = arr[N - 1]
    largest3 = arr[N - 3]
    if (smallest1 * smallest3 >= largest1 * largest3):
        print(smallest1, " ", smallest3)
    else:
        print(largest1, " ", largest3)


if __name__ == '__main__':
    arr = [5, 2, 67, 45, 160, 78]
    N = len(arr)
    maxProduct(arr, N)

# Expected output:
160   67
# maximize length of subarray of 1 's after removal of a pair of consecutive array elements | function to find the maximum subarray length of ones ; stores the length , starting index and ending index of the subarrays ; s : starting index of the sub - array ; traverse only continuous 1 s ; calculate length of the sub - array ; v [ i ] [ 0 ] : length of subarray v [ i ] [ 1 ] : starting index of subarray v [ i ] [ 2 ] : ending index of subarray ; if no such sub - array exists ; traversing through the subarrays ; update maximum length ; v [ i + 1 ] [ 1 ] - v [ i ] [ 2 ] - 1 : count of zeros between the two sub - arrays ; update length of both subarrays to the maximum ; update length of both subarrays - 1 to the maximum ; check if the last subarray has the maximum length ; 
def maxLen(A, N):
    v = []
    i = 0
    while i < N:
        if (A[i] == 1):
            s = i
            while (i < N and A[i] == 1):
                i += 1
            le = i - s
            v .append([le, s, i - 1])
        i += 1
    if (len(v) == 0):
        return -1
    ans = 0
    for i in range(len(v) - 1):
        ans = max(ans, v[i][0])
        if (v[i + 1][1] - v[i][2] - 1 == 2):
            ans = max(ans, v[i][0] + v[i + 1][0])
        if (v[i + 1][1] - v[i][2] - 1 == 1):
            ans = max(ans, v[i][0] + v[i + 1][0] - 1)
    ans = max(v[len(v) - 1][0], ans)
    return ans


if __name__ == "__main__":
    arr = [1, 0, 1, 0, 0, 1]
    N = len(arr)
    print(maxLen(arr, N))

# Expected output:
2
# rearrange an array such that sum of same | function to rearrange the array such that no same - indexed subset have sum equal to that in the original array ; initialize a vector ; iterate the array ; sort the vector ; shift of elements to the index of its next cyclic element ; print the answer ; 
def printNewArray(a, n):
    v = []
    for i in range(n):
        v .append((a[i], i))
    v .sort()
    ans = [0] * n
    for i in range(n):
        ans[v[(i + 1) % n][1]] = v[i][0]
    for i in range(n):
        print(ans[i], end=" ")


if __name__ == "__main__":
    a = [4, 1, 2, 5, 3]
    n = len(a)
    printNewArray(a, n)

# Expected output:
3 5 1 4 2
# minimize count of array elements to be removed to maximize difference between any pair up to k | python3 program to implement the above approach ; function to count the number of elements to be removed from the array based on the given condition ; sort the array ; initialize the variable ; iterate for all possible pairs ; check the difference between the numbers ; update the minimum removals ; return the answer ; 

import sys


def min_remove(arr, n, k):
    arr .sort()
    ans = sys .maxsize
    for i in range(n):
        for j in range(i, n):
            if (arr[j] - arr[i] <= k):
                ans = min(ans, n - j + i - 1)
    return ans


if __name__ == "__main__":
    k = 3
    arr = [1, 2, 3, 4, 5]
    n = len(arr)
    print(min_remove(arr, n, k))

# Expected output:
1
# reduce a given binary array to a single element by removal of triplets | function to check if it is possible to reduce the array to a single element ; stores frequency of 0 's ; stores frequency of 1 's ; condition for array to be reduced ; otherwise ; 
def solve(arr, n):
    countzeroes = 0
    countones = 0
    for i in range(n):
        if (arr[i] == 0):
            countzeroes += 1
        else:
            countones += 1
    if (abs(countzeroes - countones) == 1):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    arr = [0, 1, 0, 0, 1, 1, 1]
    n = len(arr)
    solve(arr, n)

# Expected output:
Yes