giulio98/xlcost-single-prompt huggingface dataset:
# count pairs whose products exist in array | returns count of pairs whose product exists in arr [ ] ; find product in an array ; if product found increment counter ; return count of all pair whose product exist in array ; 
def countPairs(arr, n):
    result = 0
    for i in range(0, n):
        for j in range(i + 1, n):
            product = arr[i] * arr[j]
            for k in range(0, n):
                if (arr[k] == product):
                    result = result + 1
                    break
    return result


arr = [6, 2, 4, 12, 5, 3]
n = len(arr)
print(countPairs(arr, n))

# Expected output:
3
# count pairs whose products exist in array | returns count of pairs whose product exists in arr [ ] ; create an empty hash - set that store all array element ; insert all array element into set ; generate all pairs and check is exist in ' hash ' or not ; if product exists in set then we increment count by 1 ; return count of pairs whose product exist in array ; 
def countPairs(arr, n):
    result = 0
    Hash = set()
    for i in range(n):
        Hash .add(arr[i])
    for i in range(n):
        for j in range(i + 1, n):
            product = arr[i] * arr[j]
            if product in (Hash):
                result += 1
    return result


if __name__ == '__main__':
    arr = [6, 2, 4, 12, 5, 3]
    n = len(arr)
    print(countPairs(arr, n))

# Expected output:
3
# master theorem for subtract and conquer recurrences | ''python3 code for the above approach ; ''
def fib(n):
    if (n <= 1):
        return n
    return fib(n - 1) + fib(n - 2)


n = 9
print(fib(n))

# Expected output:
34
# tail recursion | ''a tail recursive function to calculate factorial ; ''
def fact(n, a=1):
    if (n == 1):
        return a
    return fact(n - 1, n * a)


print(fact(5))

# Expected output:
120
# minimum and maximum count of elements at d distance from arr [ i ] in either direction | ''function to find the minimum and maximum number of points included in a range of distance d ; '' stores the minimum and maximum  number of points that lies  over the distance of d ; '' iterate the array ; '' count of elements included  to left of point at index i ; '' update the minimum number  of points ; '' update the maximum number  of points ; '' count of elements included  to right of point at index i ; '' update the minimum number  of points ; '' update the maximum number  of points ; '' return the array ; ''function to perform the binary search to the left of arr[i] over the given range ; '' base case ; '' binary search for index to left ; '' update index ; '' return the number of elements  by subtracting indices ; ''function to perform the binary search to the right of arr[i] over the given range ; '' base case ; '' binary search for index to right ; '' update the index ; '' return the number of elements  by subtracting indices ; ''
def leftSearch(arr, val, i):
    if (i == 0):
        return 1
    left = 0
    right = i - 1
    ind = -1
    while (left <= right):
        mid = (left + right) // 2
        if (arr[mid] < val):
            left = mid + 1
        else:
            right = mid - 1
            ind = mid
    return i - ind + 1 if ind != -1 else 1


def rightSearch(arr, val, i):
    if (i == len(arr) - 1):
        return 1
    left = i + 1
    right = len(arr) - 1
    ind = -1
    while (left <= right):
        mid = (left + right) // 2
        if (arr[mid] > val):
            right = mid - 1
        else:
            left = mid + 1
            ind = mid
    return ind - i + 1 if ind != -1 else 1


def minMaxRange(arr, D, N):
    Max = 1
    Min = N
    for i in range(N):
        dist = leftSearch(arr, arr[i] - D, i)
        Min = min(Min, dist)
        Max = max(Max, dist)
        dist = rightSearch(arr, arr[i] + D, i)
        Min = min(Min, dist)
        Max = max(Max, dist)
    return [Min, Max]

arr = [1, 3, 5, 9, 14]
N = len(arr)
D = 4
minMax = minMaxRange(arr, D, N)
print(minMax[0], minMax[1])

# Expected output:
1 3
# given two unsorted arrays , find all pairs whose sum is x | function to print all pairs in both arrays whose sum is equal to given value x ; 
def findPairs(arr1, arr2, n, m, x):
    for i in range(0, n):
        for j in range(0, m):
            if (arr1[i] + arr2[j] == x):
                print(arr1[i], arr2[j])


arr1 = [1, 2, 3, 7, 5, 4]
arr2 = [0, 7, 4, 3, 2, 1]
n = len(arr1)
m = len(arr2)
x = 8
findPairs(arr1, arr2, n, m, x)

# Expected output:
1 7
7 1
5 3
4 4
# smallest possible integer k such that ceil of each array element when divided by k is at most m | ''python program for the above approach ; ''function to check if the sum of ceil values of the arr[] for the k value is at most m or not ; '' stores the sum of ceil values ; '' update the sum ; '' return true if sum is less than  or equal to m, false otherwise ; ''function to find the smallest possible integer k such that ceil(arr[0]/k) + ceil(arr[1]/k) +....+ ceil(arr[n-1]/k) is less than or equal to m ; '' stores the low value ; '' stores the high value ; '' stores the middle value ; '' update the mid value ; '' check if the mid value is k ; '' update the low value ; '' update the high value ; '' check if low is k or high is k  and return it ; ''

import math


def isvalid(arr, K, N, M):
    sum = 0
    for i in range(0, N):
        sum += math .ceil(arr[i] * 1.0 / K)
    return sum <= M


def smallestValueForK(arr, N, M):
    low = 1
    high = arr[0]
    for i in range(1, len(arr)):
        high = max(high, arr[i])
    mid = 0
    while (high - low > 1):
        mid = (high + low) // 2
        if (not isvalid(arr, mid, N, M)):
            low = mid + 1
        else:
            high = mid
    if (isvalid(arr, low, N, M)):
        return low
    else:
        return high


if __name__ == "__main__":
    arr = [4, 3, 2, 7]
    N = len(arr)
    M = 5
    print(smallestValueForK(arr, N, M))

# Expected output:
4
# given two unsorted arrays , find all pairs whose sum is x | function to find all pairs in both arrays whose sum is equal to given value x ; insert all elements of first array in a hash ; subtract sum from second array elements one by one and check it 's present in  array first or not ; 
def findPairs(arr1, arr2, n, m, x):
    s = set()
    for i in range(0, n):
        s .add(arr1[i])
    for j in range(0, m):
        if ((x - arr2[j]) in s):
            print((x - arr2[j]), '', arr2[j])


arr1 = [1, 0, -4, 7, 6, 4]
arr2 = [0, 2, 4, -3, 2, 1]
x = 8
n = len(arr1)
m = len(arr2)
findPairs(arr1, arr2, n, m, x)

# Expected output:
6  2
4  4
6  2
7  1
# maximum fixed point ( value equal to index ) in a given array | ''python implementation of the above approach function to find the maximum index i such that arr[i] is equal to i ; '' traversing the array from  backwards ; '' if arr[i] is equal to i ; '' if there is no such index ; 
def findLargestIndex(arr, n):
    for i in range(n):
        if (arr[i] == i):
            print(i)
            return
    print(-1)


arr = [-10, -5, 0, 3, 7]
n = len(arr)
findLargestIndex(arr, n)

# Expected output:
3
# cumulative frequency of count of each element in an unsorted array | function to print the cumulative frequency according to the order given ; insert elements and their frequencies in hash map . ; traverse in the array ; add the frequencies ; if the element has not been visited previously ; mark the hash 0 as the element 's cumulative  frequency has been printed ; 
def countFreq(a, n):
    hm = dict()
    for i in range(n):
        hm[a[i]] = hm .get(a[i], 0) + 1
    cumul = 0
    for i in range(n):
        cumul += hm[a[i]]
        if (hm[a[i]] > 0):
            print(a[i], "->", cumul)
        hm[a[i]] = 0


a = [1, 3, 2, 4, 2, 1]
n = len(a)
countFreq(a, n)

# Expected output:
1 -> 2
3 -> 3
2 -> 5
4 -> 6
# find pairs in array whose sums already exist in array | function to find pair whose sum exists in arr [ ] ; 
def findPair(arr, n):
    found = False
    for i in range(0, n):
        for j in range(i + 1, n):
            for k in range(0, n):
                if (arr[i] + arr[j] == arr[k]):
                    print(arr[i], arr[j])
                    found = True
    if (found == False):
        print("Not exist")


if __name__ == '__main__':
    arr = [10, 4, 8, 13, 5]
    n = len(arr)
    findPair(arr, n)

# Expected output:
8 5
# maximum number of mangoes that can be bought | ''function to check if mid number of mangoes can be bought ; '' store the coins ; '' if watermelons needed are greater  than given watermelons ; '' store remaining watermelons if vl  watermelons are used to buy mangoes ; '' store the value of coins if these  watermelon get sold ; '' increment coins by ex ; '' number of mangoes that can be buyed  if only x coins needed for one mango ; '' if the condition is satisfied,  return true ; '' otherwise return false ; ''function to find the maximum number of mangoes that can be bought by selling watermelons ; '' initialize the boundary values ; '' store the required result ; '' binary search ; '' store the mid value ; '' check if it is possible to  buy mid number of mangoes ; '' otherwise, update r to mid -1 ; '' return the result ; ''
def check(n, m, x, y, vl):
    temp = m
    if (vl > n):
        return False
    ex = n - vl
    ex *= y
    temp += ex
    cr = temp // x
    if (cr >= vl):
        return True
    return False


def maximizeMangoes(n, m, x, y):
    l = 0
    r = n
    ans = 0
    while (l <= r):
        mid = l + (r - l) // 2
        if (check(n, m, x, y, mid)):
            ans = mid
            l = mid + 1
        else:
            r = mid - 1
    return ans


if __name__ == '__main__':
    W = 4
    C = 8
    x = 4
    y = 4
    print(maximizeMangoes(W, C, x, y))

# Expected output:
3
# kth smallest element in a sorted array formed by reversing subarrays from a random index | ''function to find the kth element in a sorted and rotated array at random point ; '' set the boundaries for binary search ; '' apply binary search to find r ; '' initialize the middle element ; '' check in the right side of mid ; '' else check in the left side ; '' random point either l or h ; '' return the kth smallest element ; ''
def findkthElement(arr, n, K):
    l = 0
    h = n - 1
    while l + 1 < h:
        mid = (l + h) // 2
        if arr[l] >= arr[mid]:
            l = mid
        else:
            h = mid
    if arr[l] < arr[h]:
        r = l
    else:
        r = h
    if K <= r + 1:
        return arr[r + 1 - K]
    else:
        return arr[n - (K - (r + 1))]


if __name__ == "__main__":
    arr = [10, 8, 6, 5, 2, 1, 13, 12]
    n = len(arr)
    K = 3
    print(findkthElement(arr, n, K))

# Expected output:
5
# find all pairs ( a , b ) in an array such that a % b = k | function to find pair such that ( a % b = k ) ; consider each and every pair ; print if their modulo equals to k ; 
def printPairs(arr, n, k):
    isPairFound = True
    for i in range(0, n):
        for j in range(0, n):
            if (i != j and arr[i] % arr[j] == k):
                print("(", arr[i], ", ", arr[j], ")", sep="", end=" ")
                isPairFound = True
    return isPairFound


arr = [2, 3, 5, 4, 7]
n = len(arr)
k = 3
if (printPairs(arr, n, k) == False):
    print("No such pair exists")

# Expected output:
(3, 5) (3, 4) (3, 7) (7, 4)
# find all pairs ( a , b ) in an array such that a % b = k | utiltity function to find the divisors of n and store in vector v [ ] ; vector is used to store the divisors ; if n is a square number , push only one occurrence ; function to find pairs such that ( a % b = k ) ; store all the elements in the map to use map as hash for finding elements in o ( 1 ) time . ; print all the pairs with ( a , b ) as ( k , numbers greater than k ) as k % ( num ( > k ) ) = k i . e . 2 % 4 = 2 ; now check for the current element as ' a ' how many b exists such that a % b = k ; find all the divisors of ( arr [ i ] - k ) ; check for each divisor i . e . arr [ i ] % b = k or not , if yes then prthat pair . ; clear vector ; 

import math as mt


def findDivisors(n):
    v = []
    for i in range(1, mt .floor(n ** (.5)) + 1):
        if (n % i == 0):
            if (n / i == i):
                v .append(i)
            else:
                v .append(i)
                v .append(n // i)
    return v


def printPairs(arr, n, k):
    occ = dict()
    for i in range(n):
        occ[arr[i]] = True
    isPairFound = False
    for i in range(n):
        if (occ[k] and k < arr[i]):
            print("(", k, ",", arr[i], ")", end=" ")
            isPairFound = True
        if (arr[i] >= k):
            v = findDivisors(arr[i] - k)
            for j in range(len(v)):
                if (arr[i] % v[j] == k and arr[i] != v[j] and occ[v[j]]):
                    print("(", arr[i], ",", v[j], ")", end=" ")
                    isPairFound = True
    return isPairFound


arr = [3, 1, 2, 5, 4]
n = len(arr)
k = 2
if (printPairs(arr, n, k) == False):
    print("No such pair exists")

# Expected output:
( 2 , 3 ) ( 2 , 5 ) ( 5 , 3 ) ( 2 , 4 )
# return maximum occurring character in an input string | python program to return the maximum occurring character in the input string ; create array to keep the count of individual characters initialize the count array to zero ; construct character count array from the input string . ; initialize max count ; initialize result ; traversing through the string and maintaining the count of each character ; 

ASCII_SIZE = 256


def getMaxOccuringChar(str):
    count = [0] * ASCII_SIZE
    for i in str:
        count[ord(i)] += 1
    max = -1
    c = ''
    for i in str:
        if max < count[ord(i)]:
            max = count[ord(i)]
            c = i
    return c


str = "sample string"
print("Max occurring character is " + getMaxOccuringChar(str))

# Expected output:
Max occurring character is s
# queries to count sum of rows and columns of a matrix present in given ranges | ''python3 program for the above approach ; ''function to preprocess the matrix to execute the queries ; '' stores the sum of each row ; '' stores the sum of each col ; '' traverse the matrix and calculate  sum of each row and column ; '' insert all row sums in sum_list ; '' insert all column sums in sum_list ; '' sort the array in ascending order ; '' traverse the array queries[][] ; '' search the leftmost index of l ; '' search the rightmost index of r ; ''function to search for the leftmost index of given number ; '' initialize low, high and ans ; '' stores mid ; '' if a[mid] >= num ; ''function to search for the rightmost index of given number ; '' initialise low, high and ans ; '' stores mid ; '' if a[mid] <= num ; '' update ans ; '' update mid ; '' update high ; ''

from collections import deque
from bisect import bisect_left, bisect_right


def left_search(A, num):
    low, high = 0, len(A) - 1
    ans = 0
    while (low <= high):
        mid = low + (high - low) // 2
        if (A[mid] >= num):
            ans = mid
            high = mid - 1
        else:
            low = mid + 1
    return ans


def right_search(A, num):
    low, high = 0, len(A) - 1
    ans = high
    while (low <= high):
        mid = low + (high - low) // 2
        if (A[mid] <= num):
            ans = mid
            low = mid + 1
        else:
            high = mid - 1
    return ans

def totalCount(A, N, M, queries, Q):
    row_sum = [0] * N
    col_sum = [0] * M
    for i in range(N):
        for j in range(M):
            row_sum[i] += A[i][j]
            col_sum[j] += A[i][j]
    sum_list = []
    for i in range(N):
        sum_list .append(row_sum[i])
    for i in range(M):
        sum_list .append(col_sum[i])
    sum_list = sorted(sum_list)
    for i in range(Q):
        L = queries[i][0]
        R = queries[i][1]
        l = left_search(sum_list, L)
        r = right_search(sum_list, R)
        print(r - l + 1, end=" ")


if __name__ == '__main__':
    N, M = 3, 2
    A = [[13, 3], [9, 4], [6, 10]]
    Q = 2
    queries = [[10, 20], [25, 35]]
    totalCount(A, N, M, queries, Q)

# Expected output:
4 1
# smallest element repeated exactly ‘ k ’ times ( not limited to small range ) | python program to find the smallest element with frequency exactly k . ; map is used to store the count of elements present in the array ; traverse the map and find minimum element with frequency k . ; 

from collections import defaultdict
import sys


def smallestKFreq(arr, n, k):
    mp = defaultdict(lambda: 0)
    for i in range(n):
        mp[arr[i]] += 1
    res = sys .maxsize
    res1 = sys .maxsize
    for key, values in mp .items():
        if values == k:
            res = min(res, key)
    return res if res != res1 else -1


arr = [2, 2, 1, 3, 1]
k = 2
n = len(arr)
print(smallestKFreq(arr, n, k))

# Expected output:
1
# maximize profit that can be earned by selling an item among n buyers |  ; ''function to find the maximum profit earned by selling an item among n buyers ; '' stores the maximum profit ; '' stores the price of the item ; '' traverse the array ; '' count of buyers with  budget >= arr[i] ; '' increment count ; '' update the maximum profit ; '' return the maximum possible  price ; ''

import sys


def maximumProfit(arr, n):
    ans = -sys .maxsize - 1
    price = 0
    for i in range(n):
        count = 0
        for j in range(n):
            if (arr[i] <= arr[j]):
                count += 1
        if (ans < count * arr[i]):
            price = arr[i]
            ans = count * arr[i]
    return price


if __name__ == '__main__':
    arr = [22, 87, 9, 50, 56, 43]
    print(maximumProfit(arr, 6))

# Expected output:
43
# lexicographically smallest permutation of the array possible by at most one swap | ''function to print the elements of the array arr[] ; '' traverse the array arr[] ; ''function to convert given array to lexicographically smallest permutation possible by swapping at most one pair ; '' stores the index of the first  element which is not at its  correct position ; '' checks if any such array  element exists or not ; '' traverse the given array ; '' if element is found at i ; '' if the first array is  not in correct position ; '' store the index of  the first elements ; '' store the index of  the first element ; '' swap the pairs ; '' print the array ; ''
def printt(arr, N):
    for i in range(N):
        print(arr[i], end=" ")


def makeLexicographically(arr, N):
    index = 0
    temp = 0
    check = 0
    condition = 0
    element = 0
    for i in range(N):
        if (element == arr[i]):
            check = i
            break
        elif (arr[i] != i + 1 and check == 0):
            index = i
            check = 1
            condition = -1
            element = i + 1
    if (condition == -1):
        temp = arr[index]
        arr[index] = arr[check]
        arr[check] = temp
    printt(arr, N)


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

# Expected output:
1 2 3 4
# check if uppercase characters in a string are used correctly or not | ''function to check if the character c is in lowercase or not ; ''function to check if the character c is in uppercase or not ; ''utility function to check if uppercase characters are used correctly or not ; '' length of string ; '' if the first character is in lowercase ; '' otherwise ; '' check if all characters  are in uppercase or not ; '' if all characters are  in uppercase ; '' check if all characters except  the first are in lowercase ; ''function to check if uppercase characters are used correctly or not ; '' stores whether the use of uppercase  characters are correct or not ; '' if correct ; '' otherwise ; ''
def isLower(c):
    return ord(c) >= ord('a') and ord(c) <= ord('z')


def isUpper(c):
    return ord(c) >= ord('A') and ord(c) <= ord('Z')


def detectUppercaseUseUtil(S):
    N = len(S)
    i = 0
    if (isLower(S[0])):
        i = 1
        while (S[i] and isLower(S[i])):
            i += 1
        return True if (i == N)else False
    else:
        i = 1
        while (S[i] and isUpper(S[i])):
            i += 1
        if (i == N):
            return True
        elif (i > 1):
            return False
        while (S[i] and isLower(S[i])):
            i += 1
        return True if (i == N)else False


def detectUppercaseUse(S):
    check = detectUppercaseUseUtil(S)
    if (check):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    S = "GeeKs"
    detectUppercaseUse(S)

# Expected output:
No
# queries to count array elements from a 
def check(N):
    if (N == 0):
        return 0
    return ((N & (N - 1)) == 0)


def build_seg_tree(ss, se, si, tree, arr):
    if (ss == se):
        tree[si] = check(arr[ss])
        return
    mid = (ss + se) // 2
    build_seg_tree(ss, mid, 2 * si + 1, tree, arr)
    build_seg_tree(mid + 1, se, 2 * si + 2, tree, arr)
    tree[si] = tree[2 * si + 1] + tree[2 * si + 2]


def update(ss, se, si, X, V, tree, arr):
    if (ss == se):
        if (ss == X):
            arr[X] = V
            tree[si] = check(V)
        return
    mid = (ss + se) // 2
    if (X <= mid):
        update(ss, mid, 2 * si + 1, X, V, tree, arr)
    else:
        update(mid + 1, se, 2 * si + 2, X, V, tree, arr)
    tree[si] = tree[2 * si + 1] + tree[2 * si + 2]


def query(l, r, ss, se, si, tree):
    if (r < ss or l > se):
        return 0
    if (l <= ss and r >= se):
        return tree[si]
    mid = (ss + se) // 2
    return (query(l, r, ss, mid, 2 * si + 1, tree) +
            query(l, r, mid + 1, se, 2 * si + 2, tree))


def Query(arr, N, Q):
    tree = [0] * (4 * N)
    build_seg_tree(0, N - 1, 0, tree, arr)
    for i in range(len(Q)):
        if (Q[i][0] == 1):
            print(query(Q[i][1], Q[i][2], 0, N - 1, 0, tree), end=" ")
        else:
            update(0, N - 1, 0, Q[i][1], Q[i][2], tree, arr)


arr = [12, 11, 16, 2, 32]
Q = [[1, 0, 2], [2, 4, 24], [1, 1, 4]]
N = len(arr)
Query(arr, N, Q)

# Expected output:
1 2
# find the smallest value of n such that sum of first n natural numbers is â ‰¥ x | ''function to check if sum of first n natural numbers is >= x ; ''finds minimum value of n such that sum of first n natural number >= x ; '' binary search ; ' ' ▁ checks ▁ if ▁ sum ▁ of ▁ first ▁ ' mid ' natural  numbers is greater than equal to x ; '' update res ; '' update high ; '' update low ; ''
def isGreaterEqual(N, X):
    return (N * (N + 1) // 2) >= X


def minimumPossible(X):
    low = 1
    high = X
    res = -1
    while (low <= high):
        mid = low + (high - low) // 2
        if (isGreaterEqual(mid, X)):
            res = mid
            high = mid - 1
        else:
            low = mid + 1
    return res


if __name__ == "__main__":
    X = 14
    print(minimumPossible(X))

# Expected output:
5