giulio98/xlcost-single-prompt huggingface dataset:
# minimize the sum of pair which upon removing divides the array into 3 subarrays | python 3 implementation of the above approach ; function to find minimum possible sum of pair which breaks the array into 3 non - empty subarrays ; prefixmin [ i ] contains minimum element till i ; 

import sys


def minSumPair(arr, N):
    if (N < 5):
        return -1
    prefixMin = [0 for i in range(N)]
    prefixMin[0] = arr[0]
    for i in range(1, N - 1, 1):
        prefixMin[i] = min(arr[i], prefixMin[i - 1])
    ans = sys .maxsize
    for i in range(3, N - 1, 1):
        ans = min(ans, arr[i] + prefixMin[i - 2])
    return ans


if __name__ == '__main__':
    arr = [5, 2, 4, 6, 3, 7]
    N = len(arr)
    print(minSumPair(arr, N))

# Expected output:
5
# minimum time remaining for safety alarm to start | function to check if the value of mid as the minimum number of hours satisfies the condition ; stores the sum of speed ; iterate over the range [ 0 , n ] ; find the value of speed ; if the bike is considered to be fast add it in sum ; return the resultant sum ; function to find the minimum number of time required ; stores the range of binary search ; stores the minimum number of time required ; find the value of mid ; if the mid is the resultant speed required ; update the ans and high ; otherwise ; return the minimum number of hours ; 
def check(H, A, mid, N, M, L):
    sum = 0
    for i in range(N):
        speed = mid * A[i] + H[i]
        if (speed >= L):
            sum += speed
    return sum


def buzzTime(N, M, L, H, A):
    low = 0
    high = 1e10
    ans = 0
    while (high >= low):
        mid = low + (high - low) // 2
        if (check(H, A, mid, N, M, L) >= M):
            ans = mid
            high = mid - 1
        else:
            low = mid + 1
    return int(ans)


if __name__ == '__main__':
    M = 400
    L = 120
    H = [20, 50, 20]
    A = [20, 70, 90]
    N = len(A)
    print(buzzTime(N, M, L, H, A))

# Expected output:
3
# count of different numbers divisible by 3 that can be obtained by changing at most one digit | function to count the number of possible numbers divisible by 3 ; calculate the sum ; store the answer ; iterate over the range ; decreasing the sum ; iterate over the range ; checking if the new sum is divisible by 3 or not ; if yes increment the value of the count ; 
def findCount(number):
    sum = 0
    for i in range(len(number)):
        sum += int(number[i]) - 48
    count = 0
    for i in range(len(number)):
        remaining_sum = sum - (int(number[i]) - 48)
        for j in range(10):
            if ((remaining_sum + j) % 3 == 0 and j != int(number[i]) - 48):
                count += 1
    print(count)


number = "235"
findCount(number)

# Expected output:
9
# maximum number of teams of size k possible with each player from different country | function to find if t number of teams can be formed or not ; store the sum of array elements ; traverse the array teams [ ] ; required condition ; function to find the maximum number of teams possible ; lower and upper part of the range ; perform the binary search ; find the value of mid ; perform the binary search ; otherwise , update the search range ; otherwise , update the search range ; 
def is_possible(teams, T, k):
    sum = 0
    for i in range(len(teams)):
        sum += min(T, teams[i])
    return (sum >= (T * k))


def countOfTeams(teams_list, N, K):
    lb = 0
    ub = 1000000000
    while (lb <= ub):
        mid = lb + (ub - lb) // 2
        if (is_possible(teams_list, mid, K)):
            if (is_possible(teams_list, mid + 1, K) == False):
                return mid
            else:
                lb = mid + 1
        else:
            ub = mid - 1
    return 0


if __name__ == '__main__':
    arr = [2, 3, 4]
    K = 2
    N = len(arr)
    print(countOfTeams(arr, N, K))

# Expected output:
4
# minimum number of decrements by 1 required to reduce all elements of a circular array to 0 | function to find minimum operation require to make all elements 0 ; stores the maximum element and its position in the array ; traverse the array ; update the maximum element and its index ; print the minimum number of operations required ; 
def minimumOperations(arr, N):
    mx = 0
    pos = 0
    for i in range(N):
        if (arr[i] >= mx):
            mx = arr[i]
            pos = i
    print((mx - 1) * N + pos + 1)


if __name__ == '__main__':
    arr = [2, 0, 2]
    N = len(arr)
    minimumOperations(arr, N)

# Expected output:
6
# maximize the smallest array element by incrementing all elements in a k | python 3 program for above approach ; function to check if the smallest value of v is achievable or not ; create array to store previous moves ; remove previous moves ; add balance to ans ; update contiguous subarray of length k ; number of moves should not exceed m ; function to find the maximum value of the smallest array element that can be obtained ; perform binary search ; 

from math import pow
n = 0
m = 0
k = 0
l = 0
r = 0
i = 0


def check(v, a):
    tec = 0
    ans = 0
    b = [0 for i in range(n + k + 1)]
    for i in range(n):
        tec -= b[i]
        if (a[i] + tec < v):
            mov = v - a[i] - tec
            ans = ans + mov
            tec += mov
            b[i + k] = mov
    return (ans <= m)


def FindLargest(a):
    l = 1
    r = pow(10, 10)
    while (r - l > 0):
        tm = (l + r + 1) // 2
        if (check(tm, a)):
            l = tm
        else:
            r = tm - 1
    return l


if __name__ == '__main__':
    a = [2, 2, 2, 2, 1, 1]
    m = 2
    k = 3
    n = len(a)
    print(int(FindLargest(a)))

# Expected output:
2
# altitude of largest triangle that can be inscribed in a rectangle | function to find the greatest altitude of the largest triangle triangle that can be inscribed in the rectangle ; if l is greater than b ; variables to perform binary search ; stores the maximum altitude possible ; iterate until low is less than high ; stores the mid value ; if mide is less than or equal to the b / 2 ; update res ; update low ; update high ; print the result ; 
def largestAltitude(L, B):
    if (L > B):
        temp = B
        B = L
        L = temp
    low = 0
    high = L
    res = 0
    while (low <= high):
        mid = low + (high - low) // 2
        if (mid <= (B / 2)):
            res = mid
            low = mid + 1
        else:
            high = mid - 1
    return res


if __name__ == '__main__':
    L = 3
    B = 4
    print(largestAltitude(L, B))

# Expected output:
2
# find the frequency of each element in a sorted array | function to print the frequency of each element of the sorted array ; stores the frequency of an element ; traverse the array arr [ ] ; if the current element is equal to the previous element ; increment the freq by 1 ; otherwise , ; update freq ; print the frequency of the last element ; 
def printFreq(arr, N):
    freq = 1
    for i in range(1, N, 1):
        if (arr[i] == arr[i - 1]):
            freq += 1
        else:
            print("Frequency of", arr[i - 1], "is:", freq)
            freq = 1
    print("Frequency of", arr[N - 1], "is:", freq)


if __name__ == '__main__':
    arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10]
    N = len(arr)
    printFreq(arr, N)

# Expected output:
Frequency of 1 is: 3
Frequency of 2 is: 1
Frequency of 3 is: 2
Frequency of 5 is: 2
Frequency of 8 is: 3
Frequency of 9 is: 2
Frequency of 10 is: 1
# count pairs from a given array whose sum lies from a given range | python3 program for the above approach ; function to count pairs whose sum lies over the range [ l , r ] ; sort the given array ; iterate until right > 0 ; starting index of element whose sum with arr [ right ] >= l ; ending index of element whose sum with arr [ right ] <= r ; update the value of end ; add the count of elements to the variable count ; return the value of count ; 

from bisect import bisect_left, bisect_right


def countPairSum(arr, L, R, N):
    arr .sort()
    right = N - 1
    count = 0
    while (right > 0):
        it1 = bisect_left(arr, L - arr[right])
        start = it1
        it2 = bisect_right(arr, R - arr[right])
        it2 -= 1
        end = it2
        end = min(end, right - 1)
        if (end - start >= 0):
            count += (end - start + 1)
        right -= 1
    return count


if __name__ == '__main__':
    arr = [5, 1, 2, 4, 3]
    L = 5
    R = 8
    N = len(arr)
    print(countPairSum(arr, L, R, N))

# Expected output:
7
# maximize median of a kxk sub | function to determine if a given value can be median ; stores the prefix sum array ; traverse the matrix arr [ ] [ ] ; update pre [ i + 1 ] [ j + 1 ] ; if arr [ i ] [ j ] is less than or equal to mid ; stores the count of elements should be less than mid ; stores if the median mid can be possible or not ; iterate over the range [ k , n ] ; iterate over the range [ k , n ] ; stores count of elements less than or equal to the value mid in submatrix with bottom right vertices at ( i , j ) ; if x is less than or equal to required ; return flag ; function to find the maximum median of a subsquare of the given size ; stores the range of the search space ; iterate until low is less than high ; stores the mid value of the range [ low , high ] ; if the current median can be possible ; update the value of low ; update the value of high ; return value stored in low as answer ; 
def isMaximumMedian(arr, N, K, mid):
    Pre = [[0 for x in range(N + 5)]for y in range(N + 5)]
    for i in range(N):
        for j in range(N):
            Pre[i + 1][j + 1] = (Pre[i + 1][j] + Pre[i][j + 1] - Pre[i][j])
            if (arr[i][j] <= mid):
                Pre[i + 1][j + 1] += 1
    required = (K * K + 1) // 2
    flag = 0
    for i in range(K, N + 1):
        for j in range(K, N + 1):
            X = (Pre[i][j] - Pre[i - K][j] - Pre[i][j - K] + Pre[i - K][j - K])
            if (X < required):
                flag = 1
    return flag


def maximumMedian(arr, N, K):
    low = 0
    high = 1000000009
    while (low < high):
        mid = low + (high - low) // 2
        if (isMaximumMedian(arr, N, K, mid)):
            low = mid + 1
        else:
            high = mid
    return low


if __name__ == "__main__":
    arr = [[1, 5, 12], [6, 7, 11], [8, 9, 10]]
    N = len(arr)
    K = 2
    print(maximumMedian(arr, N, K))

# Expected output:
9
# minimum days to make array elements with value at least k sum at least x | function to find the minimum number of days such that the sum of array elements >= k is at least x ; initialize the boundaries of search space ; perform the binary search ; find the value of mid ; traverse the array , arr [ ] ; find the value of arr [ i ] after mid number of days ; check if temp is not less than k ; update the value of sum ; check if the value of sum is greater than x ; update value of high ; update the value of low ; print the minimum number of days ; 
def findMinDays(arr, R, N, X, K):
    low = 0
    high = X
    minDays = 0
    while (low <= high):
        mid = (low + high) // 2
        sum = 0
        for i in range(N):
            temp = arr[i] + R[i] * mid
            if (temp >= K):
                sum += temp
        if (sum >= X):
            minDays = mid
            high = mid - 1
        else:
            low = mid + 1
    print(minDays)


if __name__ == '__main__':
    X = 100
    K = 45
    arr = [2, 5, 2, 6]
    R = [10, 13, 15, 12]
    N = len(arr)
    findMinDays(arr, R, N, X, K)

# Expected output:
4
# count of indices pairs such that product of elements at these indices is equal to absolute difference of indices | function to count the number of pairs ( i , j ) such that arr [ i ] * arr [ j ] is equal to abs ( i - j ) ; stores the resultant number of pairs ; generate all possible pairs from the array arr [ ] ; if the given condition satisfy then increment the value of count ; return the resultant count ; 
def getPairsCount(a, n):
    count = 0
    for i in range(n - 1):
        for j in range(i + 1, n):
            if ((a[i] * a[j]) == abs(i - j)):
                count += 1
    return count


if __name__ == '__main__':
    arr = [1, 1, 2, 4]
    N = len(arr)
    print(getPairsCount(arr, N))

# Expected output:
2
# lexicographically smallest string formed repeatedly deleting character from substring 10 | function to find smallest lexicogra - phically smallest string ; stores the index of last occuring 0 ; stores the lexicographically smallest string ; traverse the s ; if str [ i ] is 0 ; assign i to lastze ; traverse the str ; if i is less than or equal to lastze and str [ i ] is 0 ; if i is greater than lastze ; return ans ; 
def lexicographicallySmallestString(S, N):
    LastZe = -1
    ans = ""
    for i in range(N - 1, -1, -1):
        if (S[i] == '0'):
            LastZe = i
            break
    for i in range(N):
        if (i <= LastZe and S[i] == '0'):
            ans += S[i]
        elif (i > LastZe):
            ans += S[i]
    return ans


if __name__ == '__main__':
    S = "11001101"
    N = len(S)
    print(lexicographicallySmallestString(S, N))

# Expected output:
0001
# count of nodes at distance k from s in its subtree for q queries | python3 program for the above approach ; function to add edges ; function to perform depth first search ; stores the entry time of a node ; stores the entering time of a node at depth d ; iterate over the children of node ; stores the exit time of a node ; function to find number of nodes at distance k from node s in the subtree of s ; distance from root node ; index of node with greater tin value then tin [ s ] ; index of node with greater tout value then tout [ s ] ; answer to the query ; function for performing dfs and answer to queries ; dfs function call ; traverse the array q [ ] ; 

from bisect import bisect_left, bisect_right
tin = [0] * 100
tout = [0] * 100
depth = [0] * 100
t = 0


def Add_edge(parent, child, adj):
    adj[parent].append(child)
    adj[child].append(parent)
    return adj


def dfs(node, parent, d):
    global tin, tout, depth, adj, levels, t
    tin[node] = t
    t += 1
    levels[d].append(tin[node])
    depth[node] = d
    for x in adj[node]:
        if (x != parent):
            dfs(x, node, d + 1)
    tout[node] = t
    t += 1


def numberOfNodes(node, dist):
    global levels, tin, tout
    dist += depth[node]
    start = bisect_left(levels[dist], tin[node])
    ed = bisect_left(levels[dist], tout[node])
    print(ed - start)


def numberOfNodesUtil(Q, M, N):
    global t, adj
    adj = Add_edge(1, 2, adj)
    adj = Add_edge(1, 3, adj)
    adj = Add_edge(2, 4, adj)
    adj = Add_edge(2, 5, adj)
    adj = Add_edge(2, 6, adj)
    t = 1
    dfs(1, 1, 0)
    for i in range(M):
        numberOfNodes(Q[i][0], Q[i][1])


if __name__ == '__main__':
    N = 6
    Q = [[2, 1], [1, 1]]
    M = len(Q)
    adj = [[]for i in range(N + 5)]
    levels = [[]for i in range(N + 5)]
    numberOfNodesUtil(Q, M, N)

# Expected output:
3
2
# maximize boxes required to keep at least one black and one white shirt | function to find the maximum number of boxes such that each box contains three shirts comprising of at least one white and black shirt ; stores the low and high pointers for binary search ; store the required answer ; loop while low <= high ; store the mid value ; check if the mid number of boxes can be used ; update answer and recur for the right half ; else , recur for the left half ; print result ; 
def numberofBoxes(W, B, O):
    low = 0
    high = min(W, B)
    ans = 0
    while (low <= high):
        mid = low + (high - low) // 2
        if (((W >= mid) and (B >= mid)) and ((W - mid) + (B - mid) + O) >= mid):
            ans = mid
            low = mid + 1
        else:
            high = mid - 1
    print(ans)


if __name__ == '__main__':
    W = 3
    B = 3
    O = 1
    numberofBoxes(W, B, O)

# Expected output:
2
# minimum swaps needed to convert given binary matrix a to binary matrix b | function to count the minimum number of swaps required to convert matrix a to matrix b ; stores number of cells such that matrix a contains 0 and matrix b contains 1 ; stores number of cells such that matrix a contains 1 and matrix b contains 0 ; iterate over the range [ 0 , n - 1 ] ; iterate over the range [ 0 , m - 1 ] ; if a [ i ] [ j ] = 1 and b [ i ] [ j ] = 0 ; if a [ i ] [ j ] = 0 and b [ i ] [ j ] = 1 ; if count01 is equal to count10 ; otherwise , ; 
def minSwaps(N, M, A, B):
    count01 = 0
    count10 = 0
    for i in range(0, N):
        for j in range(0, M):
            if (A[i][j] != B[i][j]):
                if (A[i][j] == 1):
                    count10 += 1
                else:
                    count01 += 1
    if (count01 == count10):
        return count01
    else:
        return -1


A = [[1, 1, 0], [0, 0, 1], [0, 1, 0]]
B = [[0, 0, 1], [0, 1, 0], [1, 1, 0]]
N = len(A)
M = len(B[0])
print(minSwaps(N, M, A, B))

# Expected output:
3
# maximize x such that sum of numbers in range [ 1 , x ] is at most k | function to count the elements with sum of the first that many natural numbers less than or equal to k ; if k equals to 0 ; stores sum of first i natural numbers ; stores the result ; iterate over the range [ 1 , n ] ; increment sum by i ; is sum is less than or equal to k ; otherwise , ; return res ; 
def Count(N, K):
    if (K == 0):
        return 0
    sum = 0
    res = 0
    for i in range(1, N + 1, 1):
        sum += i
        if (sum <= K):
            res += 1
        else:
            break
    return res


if __name__ == '__main__':
    N = 6
    K = 14
    print(Count(N, K))

# Expected output:
4
# remove last occurrence of a word from a given sentence string | function to remove last occurrence of w from s ; if m is greater than n ; iterate while i is greater than or equal to 0 ; of w has been found or not ; iterate over the range [ 0 , m ] ; if s [ j + 1 ] is not equal to w [ j ] ; mark flag true and break ; if occurrence has been found ; delete the subover the range [ i , i + m ] ; resize the s ; return s ; 
def removeLastOccurrence(S, W, N, M):
    S = [i for i in S]
    W = [i for i in W]
    if (M > N):
        return S
    for i in range(N - M, -1, -1):
        flag = 0
        for j in range(M):
            if (S[j + i] != W[j]):
                flag = 1
                break
        if (flag == 0):
            for j in range(i, N - M):
                S[j] = S[j + M]
            S = S[:N - M]
            break
    return "".join(S)


if __name__ == '__main__':
    S = "This is GeeksForGeeks"
    W = "Geeks"
    N = len(S)
    M = len(W)
    print(removeLastOccurrence(S, W, N, M))

# Expected output:
This is GeeksFor
# rearrange the array to maximize the elements which is smaller than both its adjacent elements | function to rearrange array such that count of element that are smaller than their adjacent elements is maximum ; stores the rearranged array ; stores the maximum count of elements ; sort the 
def maximumIndices(arr, N):
    temp = [0] * N
    maxIndices = (N - 1) // 2
    arr .sort()
    for i in range(maxIndices):
        temp[2 * i + 1] = arr[i]
    j = 0
    i = maxIndices
    while (i < N):
        if (temp[j] == 0):
            temp[j] = arr[i]
            i += 1
        j += 1
    for i in range(N):
        print(temp[i], end=" ")


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

# Expected output:
2 1 3 4
# check if given strings can be made equal by inserting at most 1 string | python3 program for the above approach ; function to check whether two sentences can be made equal by inserting at most one sentence in one of them ; size of sentence s1 ; size of sentence s2 ; check if s1 and s2 are of equal sizes ; if both sentences are the same , return true ; otherwise , return false ; declare 2 deques x and y ; insert ' ▁ ' at the end of both sentences so that the last word can be identified ; traverse the sentence s1 ; push temp in deque when a space comes in sentence i . e a word has been formed ; temp stores words of the sentence ; traverse the sentence s1 ; push temp in deque when a space comes in sentence i . e a word has been formed ; temp stores words of the sentence ; check for prefixes of both sentences ; pop the prefix from both deques till they are equal ; check for suffixes of both sentences ; pop the suffix from both deques till they are equal ; if any of the deques is empty return true ; if both the deques are not empty return false ; 

from collections import deque


def areSimilar(S1, S2):
    S1 = [i for i in S1]
    S2 = [i for i in S2]
    N = len(S1)
    M = len(S2)
    if (N == M):
        if (S1 == S2):
            return True
        return False
    X, Y = deque(), deque()
    S1 .append(' ')
    S2 .append(' ')
    temp = ""
    for i in range(N + 1):
        if (S1[i] == ' '):
            X .append(temp)
            temp = ""
        else:
            temp += S1[i]
    for i in range(M + 1):
        if (S2[i] == ' '):
            Y .append(temp)
            temp = ""
        else:
            temp += S2[i]
    while (len(X) > 0 and len(Y) > 0 and X[0] == Y[0]):
        X .popleft()
        Y .popleft()
    while (len(X) > 0 and len(Y) > 0 and X[-1] == Y[-1]):
        X .pop()
        Y .pop()
    if (len(X) == 0 or len(Y) == 0):
        return True
    return False


if __name__ == '__main__':
    S1 = "Start practicing on GeeksforGeeks"
    S2 = "Start GeeksforGeeks"
    if (areSimilar(S1, S2)):
        print("True")
    else:
        print("False")

# Expected output:
True
# find the repeating element in an array of size n consisting of first m natural numbers | function to calculate the repeating character in a given permutation ; variables to store maximum element and sum of the array respectively . ; calculate sum of array ; calculate maximum element in the array ; calculating sum of permutation ; calculate required answer ; 
def repeatingElement(arr, N):
    M = 0
    sum = 0
    for i in range(N):
        sum += arr[i]
        M = max(M, arr[i])
    sum1 = M * (M + 1) // 2
    ans = (sum - sum1) // (N - M)
    return ans


if __name__ == '__main__':
    arr = [2, 6, 4, 3, 1, 5, 2]
    N = len(arr)
    print(repeatingElement(arr, N))

# Expected output:
2
# maximize value at kth index to create n size array with adjacent difference 1 and sum less than m | function to calculate maximum value that can be placed at the kth index in a distribution in which difference of adjacent elements is less than 1 and total sum of distribution is m . ; variable to store final answer ; variables for binary search ; binary search ; variable for binary search ; variable to store total sum of array ; number of indices on the left excluding the kth index ; number of indices on the left excluding the kth index ; add mid to final sum ; distribution on left side is possible ; sum of distribution on the left side ; sum of distribution on the left side with ( l - mid ) 1 s ; distribution on right side is possible ; sum of distribution on the right side ; sum of distribution on the left side with ( r - mid ) 1 s ; distribution is valid ; return answer ; 
def calculateMax(N, M, K):
    ans = -1
    low = 0
    high = M
    while (low <= high):
        mid = (low + high) / 2
        val = 0
        L = K - 1
        R = N - K
        val += mid
        if (mid >= L):
            val += (L) * (2 * mid - L - 1) / 2
        else:
            val += mid * (mid - 1) / 2 + (L - mid)
        if (mid >= R):
            val += (R) * (2 * mid - R - 1) / 2
        else:
            val += mid * (mid - 1) / 2 + (R - mid)
        if (val <= M):
            ans = max(ans, mid)
            low = mid + 1
        else:
            high = mid - 1
    return int(ans)


N = 7
M = 100
K = 6
print(calculateMax(N, M, K))

# Expected output:
16