giulio98/xlcost-single-prompt huggingface dataset:
# divide array into two parts with equal sum according to the given constraints | function that checks if the given conditions are satisfied ; to store the prefix sum of the array elements ; sort the array ; compute the prefix sum array ; maximum element in the array ; variable to check if there exists any number ; stores the index of the largest number present in the array smaller than i ; stores the index of the smallest number present in the array greater than i ; find index of smallest number greater than i ; find index of smallest number greater than i ; if there exists a number ; if no such number exists print no ; 
def IfExists(arr, n):
    sum = [0] * n
    arr .sort()
    sum[0] = arr[0]
    for i in range(1, n):
        sum[i] = sum[i - 1] + arr[i]
    max = arr[n - 1]
    flag = False
    for i in range(1, max + 1):
        findex = 0
        lindex = 0
        l = 0
        r = n - 1
        while (l <= r):
            m = (l + r) // 2
            if (arr[m] < i):
                findex = m
                l = m + 1
            else:
                r = m - 1
        l = 1
        r = n
        flag = False
        while (l <= r):
            m = (r + l) // 2
            if (arr[m] > i):
                lindex = m
                r = m - 1
            else:
                l = m + 1
        if (sum[findex] == sum[n - 1] - sum[lindex - 1]):
            flag = True
            break
    if (flag):
        print("Yes")
    else:
        print("No")


if __name__ == "__main__":
    arr = [1, 2, 2, 5]
    n = len(arr)
    IfExists(arr, n)

# Expected output:
Yes
# find missing element in a sorted array of consecutive numbers | function to return the missing element ; check if middle element is consistent ; no inconsistency till middle elements when missing element is just after the middle element ; move right ; inconsistency found when missing element is just before the middle element ; move left ; no missing element found ; 
def findMissing(arr, n):
    l, h = 0, n - 1
    mid = 0
    while (h > l):
        mid = l + (h - l) // 2
        if (arr[mid] - mid == arr[0]):
            if (arr[mid + 1] - arr[mid] > 1):
                return arr[mid] + 1
            else:
                l = mid + 1
        else:
            if (arr[mid] - arr[mid - 1] > 1):
                return arr[mid] - 1
            else:
                h = mid - 1
    return -1


arr = [-9, -8, -7, -5, -4, -3, -2, -1, 0]
n = len(arr)
print(findMissing(arr, n))

# Expected output:
-6
# find maximum sum taking every kth element in the array | python 3 implementation of the approach ; function to return the maximum sum for every possible sequence such that a [ i ] + a [ i + k ] + a [ i + 2 k ] + ... + a [ i + qk ] is maximized ; initialize the maximum with the smallest value ; find maximum from all sequences ; sum of the sequence starting from index i ; update maximum ; 

import sys


def maxSum(arr, n, K):
    maximum = -sys .maxsize - 1
    for i in range(n):
        sumk = 0
        for j in range(i, n, K):
            sumk = sumk + arr[j]
        maximum = max(maximum, sumk)
    return maximum


if __name__ == '__main__':
    arr = [3, 6, 4, 7, 2]
    n = len(arr)
    K = 2
    print(maxSum(arr, n, K))

# Expected output:
13
# find the number of elements greater than k in a sorted array | function to return the count of elements from the array which are greater than k ; stores the index of the left most element from the array which is greater than k ; finds number of elements greater than k ; if mid element is greater than k update leftgreater and r ; if mid element is less than or equal to k update l ; return the count of elements greater than k ; 
def countGreater(arr, n, k):
    l = 0
    r = n - 1
    leftGreater = n
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] > k):
            leftGreater = m
            r = m - 1
        else:
            l = m + 1
    return (n - leftGreater)


if __name__ == '__main__':
    arr = [3, 3, 4, 7, 7, 7, 11, 13, 13]
    n = len(arr)
    k = 7
    print(countGreater(arr, n, k))

# Expected output:
3
# count the number of operations required to reduce the given number | python3 implementation of the approach ; to store the normalized value of all the operations ; minimum possible value for a series of operations ; if k can be reduced with first ( i + 1 ) operations ; impossible to reduce k ; number of times all the operations can be performed on k without reducing it to <= 0 ; perform operations ; final check ; 
def operations(op, n, k):
    i, count = 0, 0
    nVal = 0
    minimum = 10 ** 9
    for i in range(n):
        nVal += op[i]
        minimum = min(minimum, nVal)
        if ((k + nVal) <= 0):
            return (i + 1)
    if (nVal >= 0):
        return -1
    times = (k - abs(minimum)) // abs(nVal)
    k = (k - (times * abs(nVal)))
    count = (times * n)
    while (k > 0):
        for i in range(n):
            k = k + op[i]
            count += 1
            if (k <= 0):
                break
    return count


op = [-60, 65, -1, 14, -25]
n = len(op)
k = 100000
print(operations(op, n, k))

# Expected output:
71391
# find the smallest number x such that x ! contains at least y trailing zeros . | function to count the number of factors p in x ! ; function to find the smallest x such that x ! contains y trailing zeros ; 
def countFactor(P, X):
    if (X < P):
        return 0
    return (X // P + countFactor(P, X // P))


def findSmallestX(Y):
    low = 0
    high = 5 * Y
    N = 0
    while (low <= high):
        mid = (high + low) // 2
        if (countFactor(5, mid) < Y):
            low = mid + 1
        else:
            N = mid
            high = mid - 1
    return N


Y = 10
print(findSmallestX(Y))

# Expected output:
45
# find maximum n such that the sum of square of first n natural numbers is not more than x | function to return the sum of the squares of first n natural numbers ; function to return the maximum n such that the sum of the squares of first n natural numbers is not more than x ; 
def squareSum(N):
    Sum = (N * (N + 1) * (2 * N + 1)) // 6
    return Sum


def findMaxN(X):
    low, high, N = 1, 100000, 0
    while low <= high:
        mid = (high + low) // 2
        if squareSum(mid) <= X:
            N = mid
            low = mid + 1
        else:
            high = mid - 1
    return N


if __name__ == "__main__":
    X = 25
    print(findMaxN(X))

# Expected output:
3
# search an element in given n ranges | function to return the index of the range in which k lies and uses linear search ; iterate and find the element ; if k lies in the current range ; k doesn 't lie in any of the  given ranges ; 
def findNumber(a, n, K):
    for i in range(0, n, 1):
        if (K >= a[i][0] and K <= a[i][1]):
            return i
    return -1


if __name__ == '__main__':
    a = [[1, 3], [4, 7], [8, 11]]
    n = len(a)
    k = 6
    index = findNumber(a, n, k)
    if (index != -1):
        print(index, end="")
    else:
        print(-1, end="")

# Expected output:
1
# search an element in given n ranges | function to return the index of the range in which k lies and uses binary search ; binary search ; find the mid element ; if element is found ; check in first half ; check in second half ; not found ; 
def findNumber(a, n, K):
    low = 0
    high = n - 1
    while (low <= high):
        mid = (low + high) >> 1
        if (K >= a[mid][0] and K <= a[mid][1]):
            return mid
        elif (K < a[mid][0]):
            high = mid - 1
        else:
            low = mid + 1
    return -1


a = [[1, 3], [4, 7], [8, 11]]
n = len(a)
k = 6
index = findNumber(a, n, k)
if (index != -1):
    print(index)
else:
    print(-1)

# Expected output:
1
# cost to make a string panagram | set 2 | function to return the cost to make string a panagram ; count the occurrences of each lowercase character ; to store the total gain ; if some character is missing , it has to be added at twice the cost ; if some character appears more than once all of its occurrences except 1 can be traded for some gain ; if gain is more than the cost ; return the total cost if gain < 0 ; 
def costToPanagram(string, cost):
    n = len(string)
    occurrences = [0] * 26
    for i in range(n):
        occurrences[ord(string[i]) - ord('a')] += 1
    gain = 0
    for i in range(26):
        if occurrences[i] == 0:
            gain -= 2 * cost[i]
        elif occurrences[i] > 1:
            gain += cost[i] * (occurrences[i] - 1)
    if gain >= 0:
        return 0
    return gain * -1


if __name__ == "__main__":
    cost = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    string = "geeksforgeeks"
    print(costToPanagram(string, cost))

# Expected output:
32
# weighted sum of the characters of a string in an array | set 2 | function to return the required string score ; create a hash map of strings in str ; store every string in the map along with its position in the array ; if given string is not present in str [ ] ; multiply sum of alphabets with position ; 
def strScore(string, s, n):
    m = {}
    for i in range(n):
        m[string[i]] = i + 1
    if s not in m .keys():
        return 0
    score = 0
    for i in range(len(s)):
        score += ord(s[i]) - ord('a') + 1
    score = score * m[s]
    return score


if __name__ == "__main__":
    string = ["geeksforgeeks", "algorithms", "stack"]
    s = "algorithms"
    n = len(string)
    score = strScore(string, s, n)
    print(score)

# Expected output:
244
# number of subarrays have bitwise or >= k | function to return the count of required sub - arrays ; traverse sub - array [ i . . j ] ; 
def countSubArrays(arr, n, K):
    count = 0
    for i in range(n):
        for j in range(i, n):
            bitwise_or = 0
            for k in range(i, j + 1):
                bitwise_or = bitwise_or | arr[k]
            if (bitwise_or >= K):
                count += 1
    return count


if __name__ == "__main__":
    arr = [3, 4, 5]
    n = len(arr)
    k = 6
    print(countSubArrays(arr, n, k))

# Expected output:
2
# number of subarrays have bitwise or >= k | python implementation of the approach ; function to build the segment tree ; function to return the bitwise or of segment [ l . . r ] ; function to return the count of required sub - arrays ; build segment tree ; query segment tree for bitwise or of sub - array [ i . . j ] ; 

N = 100002
tree = [0] * (4 * N)


def build(arr, node, start, end):
    if start == end:
        tree[node] = arr[start]
        return
    mid = (start + end) >> 1
    build(arr, 2 * node, start, mid)
    build(arr, 2 * node + 1, mid + 1, end)
    tree[node] = tree[2 * node] | tree[2 * node + 1]


def query(node, start, end, l, r):
    if start > end or start > r or end < l:
        return 0
    if start >= l and end <= r:
        return tree[node]
    mid = (start + end) >> 1
    q1 = query(2 * node, start, mid, l, r)
    q2 = query(2 * node + 1, mid + 1, end, l, r)
    return q1 or q2


def countSubArrays(arr, n, K):
    build(arr, 1, 0, n - 1)
    count = 0
    for i in range(n):
        for j in range(n):
            bitwise_or = query(1, 0, n - 1, i, j)
            if bitwise_or >= K:
                count += 1
    return count


arr = [3, 4, 5]
n = len(arr)
k = 6
print(countSubArrays(arr, n, k))

# Expected output:
2
# occurrences of a pattern in binary representation of a number | function to return the count of occurrence of pat in binary representation of n ; to store decimal value of the pattern ; to store a number that has all ones in its binary representation and length of ones equal to length of the pattern ; find values of pattern_int and all_ones ; if the pattern occurs in the last digits of n ; right shift n by 1 bit ; 
def countPattern(n, pat):
    pattern_int = 0
    power_two = 1
    all_ones = 0
    i = len(pat) - 1
    while (i >= 0):
        current_bit = ord(pat[i]) - ord('0')
        pattern_int += (power_two * current_bit)
        all_ones = all_ones + power_two
        power_two = power_two * 2
        i -= 1
    count = 0
    while (n != 0 and n >= pattern_int):
        if ((n & all_ones) == pattern_int):
            count += 1
        n = n >> 1
    return count


if __name__ == '__main__':
    n = 500
    pat = "10"
    print(countPattern(n, pat))

# Expected output:
2
# pairs with same manhattan and euclidean distance | python3 implementation of the above approach ; function to return the number of non coincident pairs of points with manhattan distance equal to euclidean distance ; to store frequency of all distinct xi ; to store frequency of all distinct yi ; to store frequency of all distinct points ( xi , yi ) ; hash xi coordinate ; hash yi coordinate ; hash the point ( xi , yi ) ; find pairs with same xi ; calculate ( ( xfrequency ) c2 ) ; find pairs with same yi ; calculate ( ( yfrequency ) c2 ) ; find pairs with same ( xi , yi ) ; calculate ( ( xyfrequency ) c2 ) ; 

from collections import defaultdict


def findManhattanEuclidPair(arr, n):
    X = defaultdict(lambda: 0)
    Y = defaultdict(lambda: 0)
    XY = defaultdict(lambda: 0)
    for i in range(0, n):
        xi = arr[i][0]
        yi = arr[i][1]
        X[xi] += 1
        Y[yi] += 1
        XY[tuple(arr[i])] += 1
    xAns, yAns, xyAns = 0, 0, 0
    for xCoordinatePair in X:
        xFrequency = X[xCoordinatePair]
        sameXPairs = (xFrequency * (xFrequency - 1)) // 2
        xAns += sameXPairs
    for yCoordinatePair in Y:
        yFrequency = Y[yCoordinatePair]
        sameYPairs = (yFrequency * (yFrequency - 1)) // 2
        yAns += sameYPairs
    for XYPair in XY:
        xyFrequency = XY[XYPair]
        samePointPairs = (xyFrequency * (xyFrequency - 1)) // 2
        xyAns += samePointPairs
    return (xAns + yAns - xyAns)


if __name__ == "__main__":
    arr = [[1, 2], [2, 3], [1, 3]]
    n = len(arr)
    print(findManhattanEuclidPair(arr, n))

# Expected output:
2
# remove exactly one element from the array such that max | function to calculate max - min ; 
def max_min(a, n):
    a .sort()
    return min(a[n - 2] - a[0], a[n - 1] - a[1])


a = [1, 3, 3, 7]
n = len(a)
print(max_min(a, n))

# Expected output:
2
# count numbers < = n whose difference with the count of primes upto them is > = k | python3 implementation of the above approach ; primeupto [ i ] denotes count of prime numbers upto i ; function to compute all prime numbers and update primeupto array ; 0 and 1 are not primes ; if i is prime ; set all multiples of i as non - prime ; compute primeupto array ; function to return the count of valid numbers ; compute primeupto array ; check if the number is valid , try to reduce it ; ans is the minimum valid number ; 

MAX = 1000001
MAX_sqrt = MAX ** (0.5)
primeUpto = [0] * (MAX)


def SieveOfEratosthenes():
    isPrime = [1] * (MAX)
    isPrime[0], isPrime[1] = 0, 0
    for i in range(2, int(MAX_sqrt)):
        if isPrime[i] == 1:
            for j in range(i * 2, MAX, i):
                isPrime[j] = 0
    for i in range(1, MAX):
        primeUpto[i] = primeUpto[i - 1]
        if isPrime[i] == 1:
            primeUpto[i] += 1


def countOfNumbers(N, K):
    SieveOfEratosthenes()
    low, high, ans = 1, N, 0
    while low <= high:
        mid = (low + high) >> 1
        if mid - primeUpto[mid] >= K:
            ans = mid
            high = mid - 1
        else:
            low = mid + 1
    return (N - ans + 1)if ans else 0


if __name__ == "__main__":
    N, K = 10, 3
    print(countOfNumbers(N, K))

# Expected output:
5
# find the element whose multiplication with | function to find minimum index such that sum becomes 0 when the element is multiplied by - 1 ; find array sum ; find element with value equal to sum / 2 ; when sum is equal to 2 * element then this is our required element ; 
def minIndex(arr, n):
    sum = 0
    for i in range(0, n):
        sum += arr[i]
    for i in range(0, n):
        if (2 * arr[i] == sum):
            return (i + 1)
    return -1


arr = [1, 3, -5, 3, 4]
n = len(arr)
print(minIndex(arr, n))

# Expected output:
2
# ceiling of every element in same array | python implementation of efficient algorithm to find floor of every element ; prints greater elements on left side of every element ; create a sorted copy of arr [ ] ; traverse through arr [ ] and do binary search for every element ; find the location of first element that is greater than the given element ; since arr [ i ] also exists in array , v [ it - 1 ] will be same as arr [ i ] . let us check v [ it - 2 ] is also same as arr [ i ] . if true , then arr [ i ] exists twice in array , so ceiling is same same as arr [ i ] ; if next element is also same , then there are multiple occurrences , so print it ; 

import bisect


def printPrevGreater(arr, n):
    if n == 1:
        print("-1")
        return
    v = list(arr)
    v .sort()
    for i in range(n):
        it = bisect .bisect_right(v, arr[i])
        if (it - 1) != 0 and v[it - 2] == arr[i]:
            print(arr[i], end=" ")
        elif it <= n - 1:
            print(v[it], end=" ")
        else:
            print(-1, end=" ")


if __name__ == "__main__":
    arr = [10, 5, 11, 10, 20, 12]
    n = len(arr)
    printPrevGreater(arr, n)

# Expected output:
10 10 12 10 -1 20
# floor of every element in same array | prints greater elements on left side of every element ; create a sorted copy of arr ; traverse through arr [ ] and do binary search for every element . ; floor of first element is - 1 if there is only one occurrence of it . ; find the first element that is greater than or or equal to given element ; if next element is also same , then there are multiple occurrences , so print it ; otherwise print previous element ; 
def printPrevGreater(arr, n):
    v = arr .copy()
    v .sort()
    for i in range(n):
        if (arr[i] == v[0]):
            if (arr[i] == v[1]):
                print(arr[i], end=" ")
            else:
                print(-1, end=" ")
            continue
        if v .count(arr[i]) > 0:
            it = v[v .index(arr[i])]
        else:
            it = v[n - 1]
        if (it != v[n - 1] and v[v .index(it) + 1] == arr[i]):
            print(arr[i], end=" ")
        else:
            print(v[v .index(it) - 1], end=" ")


if __name__ == "__main__":
    arr = [6, 11, 7, 8, 20, 12]
    n = len(arr)
    printPrevGreater(arr, n)

# Expected output:
-1 8 6 7 12 11
# find smallest and largest element from square matrix diagonals | python3 program to find smallest and largest elements of both diagonals ; function to find smallest and largest element from principal and secondary diagonal ; take length of matrix ; declare and initialize variables with appropriate value ; take new smallest value ; take new largest value ; condition for secondary diagonal is mat [ n - 1 - i ] [ i ] take new smallest value ; take new largest value ; declare and 

n = 5


def diagonalsMinMax(mat):
    if (n == 0):
        return
    principalMin = mat[0][0]
    principalMax = mat[0][0]
    secondaryMin = mat[n - 1][0]
    secondaryMax = mat[n - 1][0]
    for i in range(n):
        if (mat[i][i] < principalMin):
            principalMin = mat[i][i]
        if (mat[i][i] > principalMax):
            principalMax = mat[i][i]
        if (mat[n - 1 - i][i] < secondaryMin):
            secondaryMin = mat[n - 1 - i][i]
        if (mat[n - 1 - i][i] > secondaryMax):
            secondaryMax = mat[n - 1 - i][i]
    print("Principal Diagonal Smallest Element: ", principalMin)
    print("Principal Diagonal Greatest Element : ", principalMax)
    print("Secondary Diagonal Smallest Element: ", secondaryMin)
    print("Secondary Diagonal Greatest Element: ", secondaryMax)


matrix = [[1, 2, 3, 4, -10], [5, 6, 7, 8, 6],
          [1, 2, 11, 3, 4], [5, 6, 70, 5, 8], [4, 9, 7, 1, -5]]
diagonalsMinMax(matrix)

# Expected output:
Principal Diagonal Smallest Element:  -5
Principal Diagonal Greatest Element :  11
Secondary Diagonal Smallest Element:  -10
Secondary Diagonal Greatest Element:  11
# check if array can be sorted with one swap | a linear python 3 program to check if array becomes sorted after one swap ; find counts and positions of elements that are out of order . ; if there are more than two elements which are out of order . ; if all elements are sorted already ; cases like { 1 , 5 , 3 , 4 , 2 } we swap 5 and 2. ; cases like { 1 , 2 , 4 , 3 , 5 } ; now check if array becomes sorted for cases like { 4 , 1 , 2 , 3 } ; 
def checkSorted(n, arr):
    first, second = 0, 0
    count = 0
    for i in range(1, n):
        if arr[i] < arr[i - 1]:
            count += 1
            if first == 0:
                first = i
            else:
                second = i
    if count > 2:
        return False
    if count == 0:
        return True
    if count == 2:
        (arr[first - 1], arr[second]) = (arr[second], arr[first - 1])
    elif count == 1:
        (arr[first - 1], arr[first]) = (arr[first], arr[first - 1])
    for i in range(1, n):
        if arr[i] < arr[i - 1]:
            return False
    return True


if __name__ == '__main__':
    arr = [1, 4, 3, 2]
    n = len(arr)
    if checkSorted(n, arr):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# find the intersection of two matrices | python 3 program to find intersection of two matrices ; function to print the resultant matrix ; print element value for equal elements else * ; 

N, M = 4, 4


def printIntersection(A, B):
    for i in range(M):
        for j in range(N):
            if (A[i][j] == B[i][j]):
                print(A[i][j], end=" ")
            else:
                print("* ", end=" ")
        print()


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

# Expected output:
2 *  6 8 
1 3 5 *  
8 *  4 2 
*  5 *  1
# count triplets such that one of the numbers can be written as sum of the other two | python3 program to count triplets such that at least one of the numbers can be written as sum of the other two ; function to count the number of ways to choose the triples ; compute the max value in the array and create frequency array of size max_val + 1. we can also use hashmap to store frequencies . we have used an array to keep remaining code simple . ; case 1 : 0 , 0 , 0 ; case 2 : 0 , x , x ; case 3 : x , x , 2 * x ; case 4 : x , y , x + y iterate through all pairs ( x , y ) ; 

import math as mt


def countWays(arr, n):
    max_val = 0
    for i in range(n):
        max_val = max(max_val, arr[i])

    freq = [0 for i in range(max_val + 1)]

    for i in range(n):
        freq[arr[i]] += 1

    ans = 0
    ans += (freq[0] * (freq[0] - 1) *
            (freq[0] - 2) // 6)
    for i in range(1, max_val + 1):
        ans += (freq[0] * freq[i] *
                (freq[i] - 1) // 2)
    for i in range(1, (max_val + 1) // 2):
        ans += (freq[i] *
                (freq[i] - 1) // 2 * freq[2 * i])
    for i in range(1, max_val + 1):
        for j in range(i + 1, max_val - i + 1):
            ans += freq[i] * freq[j] * freq[i + j]

    return ans


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

# Expected output:
4
# count pairs from two arrays having sum equal to k | function to return the count of pairs having sum equal to k ; initialize pairs to 0 ; create dictionary of elements of array a1 ; count total pairs ; every element can be part of at most one pair ; return total pairs ; 
def countPairs(A1, A2, n1, n2, K):
    res = 0
    m = dict()
    for i in range(0, n1):
        if A1[i]not in m .keys():
            m[A1[i]] = 1
        else:
            m[A1[i]] = m[A1[i]] + 1
    for i in range(0, n2):
        temp = K - A2[i]
        if temp in m .keys():
            res = res + 1
            m[temp] = m[temp] - 1
    return res


A1 = [1, 1, 3, 4, 5, 6, 6]
A2 = [1, 4, 4, 5, 7]
K = 10
n1 = len(A1)
n2 = len(A2)
print(countPairs(A1, A2, n1, n2, K))

# Expected output:
4