giulio98/xlcost-single-prompt huggingface dataset:
# minimum numbers with one 's place as 9 to be added to get n | function to find minimum count of numbers ( with one 's digit 9) that sum up to n ; fetch one 's digit ; apply cases mentioned in approach ; if no possible answer exists ; 
def findMin(N: int):
    digit = N % 10
    if digit == 0 and N >= 90:
        return 10
    elif digit == 1 and N >= 81:
        return 9
    elif digit == 2 and N >= 72:
        return 8
    elif digit == 3 and N >= 63:
        return 7
    elif digit == 4 and N >= 54:
        return 6
    elif digit == 5 and N >= 45:
        return 5
    elif digit == 6 and N >= 36:
        return 4
    elif digit == 7 and N >= 27:
        return 3
    elif digit == 8 and N >= 18:
        return 2
    elif digit == 9 and N >= 9:
        return 1
    return -1


if __name__ == "__main__":
    N = 27
    print(findMin(N))

# Expected output:
3
# maximum string partition | return the count of string ; p will store the answer ; current will store current string previous will store the previous that has been taken already ; add a character to current string ; here we will create a partition and update the previous with current string ; now we will clear the current string ; increment the count of partition . ; 
def maxPartition(s):
    n = len(s)
    P = 0
    current = ""
    previous = ""
    for i in range(n):
        current += s[i]
        if (current != previous):
            previous = current
            current = ""
            P += 1
    return P


s = "geeksforgeeks"
ans = maxPartition(s)
print(ans)

# Expected output:
11
# find the smallest positive number missing from an unsorted array | set 3 | function to find the smallest positive missing number ; default smallest positive integer ; store values in set which are greater than variable m ; store value when m is less than current index of given array ; increment m when it is equal to current element ; increment m when it is one of the element of the set ; return the required answer ; 
def findMissingPositive(arr, n):
    m = 1
    x = []
    for i in range(n):
        if (m < arr[i]):
            x .append(arr[i])
        elif (m == arr[i]):
            m = m + 1
            while (x .count(m)):
                x .remove(m)
                m = m + 1
    return m


if __name__ == '__main__':
    arr = [2, 3, -7, 6, 8, 1, -10, 15]
    n = len(arr)
    print(findMissingPositive(arr, n))

# Expected output:
4
# sum of all second largest divisors after splitting a number into one or more parts | python 3 program to find sum of all second largest divisor after splitting a number into one or more parts ; function to find a number is prime or not ; if there is any divisor ; function to find the sum of all second largest divisor after splitting a number into one or more parts ; if number is prime ; if n is even ; if the number is odd ; if n - 2 is prime ; there exists 3 primes x1 , x2 , x3 such that x1 + x2 + x3 = n ; 

from math import sqrt


def prime(n):
    if (n == 1):
        return False
    for i in range(2, int(sqrt(n)) + 1, 1):
        if (n % i == 0):
            return False
    return True


def Min_Sum(n):
    if (prime(n)):
        return 1
    if (n % 2 == 0):
        return 2
    else:
        if (prime(n - 2)):
            return 2
        else:
            return 3


if __name__ == '__main__':
    n = 27
    print(Min_Sum(n))

# Expected output:
3
# count pairs of strings that satisfy the given conditions | function that returns true if c is vowel ; function to return the count of required pairs ; for every of the array ; vector to store the vowels of the current string ; if current character is a vowel ; if current contains vowels ; create tuple ( first vowel , last vowel , total vowels ) ; v stores the indices for which the given condition satisfies total valid pairs will be half the size ; 
def is_vowel(c):
    return (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u')


def count(s, n):
    map = dict()
    for i in range(n):
        vowel = []
        for j in range(len(s[i])):
            if (is_vowel(s[i][j])):
                vowel .append(s[i][j])
        if (len(vowel) > 0):
            Len = len(vowel)
            if (vowel[0], vowel[Len - 1], Len) in map .keys():
                map[(vowel[0], vowel[Len - 1], Len)].append(i)
            else:
                map[(vowel[0], vowel[Len - 1], Len)] = [i, ]
    count = 0
    for i in map:
        v = map[i]
        count += len(v) // 2
    return count


s = ["geeks", "for", "geeks"]
n = len(s)
print(count(s, n))

# Expected output:
1
# find maximum value of the last element after reducing the array with given operations | function to return the maximized value ; overall minimum absolute value of some element from the array ; add all absolute values ; count positive and negative elements ; both positive and negative values are present ; only positive or negative values are present ; 
def find_maximum_value(a, n):
    sum = 0
    minimum = 10 ** 9
    pos = 0
    neg = 0
    for i in range(n):
        minimum = min(minimum, abs(a[i]))
        sum += abs(a[i])
        if (a[i] >= 0):
            pos += 1
        else:
            neg += 1
    if (pos > 0 and neg > 0):
        return sum
    return (sum - 2 * minimum)


a = [5, 4, 6, 2]
n = len(a)
print(find_maximum_value(a, n))

# Expected output:
13
# find nth smallest number that is divisible by 100 exactly k times | function to find the nth smallest number ; if n is divisible by 100 then we multiply n + 1 otherwise , it will be divisible by 100 more than k times ; convert integer to string ; if n is not divisible by 100 ; convert integer to string ; add 2 * k 0 's at the end to be divisible  by 100 exactly k times ; 
def find_number(N, K):
    r = ""
    if (N % 100 == 0):
        N += 1
        r = str(N)
    else:
        r = str(N)
    for i in range(1, K + 1):
        r += "00"
    return r


N = 1000
K = 2
ans = find_number(N, K)
print(ans)

# Expected output:
10010000
# count of adjacent vowel consonant pairs | function to count the adjacent pairs of consonant and vowels in the string ; using a set to store the vowels so that checking each character becomes easier ; variable to store number of consonant - vowel pairs ; if the ith character is not found in the set , means it is a consonant and if the ( i + 1 ) th character is found in the set , means it is a vowel we increment the count of such pairs ; 
def countPairs(s):
    st = set()
    st .add('a')
    st .add('e')
    st .add('i')
    st .add('o')
    st .add('u')
    count = 0
    n = len(s)
    for i in range(n - 1):
        if (s[i]not in st and s[i + 1] in st):
            count += 1
    return count


if __name__ == "__main__":
    s = "geeksforgeeks"
    print(countPairs(s))

# Expected output:
3
# find the largest interval that contains exactly one of the given n integers . | function to return the maximum size of the required interval ; insert the borders for array ; sort the elements in ascending order ; to store the maximum size ; to store the range [ l , r ] such that only v [ i ] lies within the range ; total integers in the range ; 
def maxSize(v, n):
    v .append(0)
    v .append(100001)
    n += 2
    v = sorted(v)
    mx = 0
    for i in range(1, n - 1):
        L = v[i - 1] + 1
        R = v[i + 1] - 1
        cnt = R - L + 1
        mx = max(mx, cnt)
    return mx


v = [200, 10, 5]
n = len(v)
print(maxSize(v, n))

# Expected output:
99990
# maximum length of subarray such that sum of the subarray is even | function to find length of the longest subarray such that sum of the subarray is even ; check if sum of complete array is even ; if ( sum % 2 == 0 ) : total sum is already even ; find an index i such the a [ i ] is odd and compare length of both halfs excluding a [ i ] to find max length subarray ; 
def maxLength(a, n):
    Sum = 0
    Len = 0
    for i in range(n):
        Sum += a[i]
        return n
    for i in range(n):
        if (a[i] % 2 == 1):
            Len = max(Len, max(n - i - 1, i))
    return Len


a = [1, 2, 3, 2]
n = len(a)
print(maxLength(a, n))

# Expected output:
4
# find a symmetric matrix of order n that contain integers from 0 to n | function to generate the required matrix ; form cyclic array of elements 1 to n - 1 ; store initial array into final array ; fill the last row and column with 0 's ; swap 0 and the number present at the current indexed row ; also make changes in the last row with the number we swapped ; print the final array ; 
def solve(n):
    initial_array = [[0 for i in range(n - 1)]for j in range(n - 1)]
    final_array = [[0 for i in range(n)]for j in range(n)]
    for i in range(n - 1):
        initial_array[0][i] = i + 1
    for i in range(1, n - 1):
        for j in range(n - 1):
            initial_array[i][j] = initial_array[i - 1][(j + 1) % (n - 1)]
    for i in range(n - 1):
        for j in range(n - 1):
            final_array[i][j] = initial_array[i][j]
    for i in range(n):
        final_array[i][n - 1] = final_array[n - 1][i] = 0
    for i in range(n):
        t0 = final_array[i][i]
        t1 = final_array[i][n - 1]
        temp = final_array[i][i]
        final_array[i][i] = final_array[i][n - 1]
        final_array[i][n - 1] = temp
        final_array[n - 1][i] = t0
    for i in range(n):
        for j in range(n):
            print(final_array[i][j], end=" ")
        print("", end="")


if __name__ == '__main__':
    n = 5
    solve(n)

# Expected output:
0 2 3 4 1 2 0 4 1 3 3 4 0 2 1 4 1 2 0 3 1 3 1 3 0
# generate original array from difference between every two consecutive elements | function to print the required permutation ; take x = 0 for simplicity ; calculate athe differences and store it in a vector ; preserve the original array ; check if athe consecutive elements have difference = 1 ; if consecutive elements don 't have  difference 1 at any position then  the answer is impossible ; else store the indices and values at those indices in a map and finainty print them ; 
def findPerm(n, differences):
    ans = []
    ans .append(0)
    x = 0
    for i in range(n - 1):
        diff = differences[i]
        x = x + diff
        ans .append(x)
    anss = ans
    ans = sorted(ans)
    flag = -1
    for i in range(1, n):
        res = ans[i] - ans[i - 1]
        if (res != 1):
            flag = 0
    if (flag == 0):
        print("-1")
        return
    else:
        mpp = dict()
        j = 1
        value_at_index = []
        for x in ans:
            mpp[x] = j
            j += 1
        for x in anss:
            value_at_index .append(mpp[x])
        for x in value_at_index:
            print(x, end=" ")
        print()


differences = []
differences .append(2)
differences .append(-3)
differences .append(2)
n = len(differences) + 1
findPerm(n, differences)

# Expected output:
2 4 1 3
# find smallest number k such that k % p = 0 and q % k = 0 | function to return the minimum value k such that k % p = 0 and q % k = 0 ; if k is possible ; no such k is possible ; 
def getMinVal(p, q):
    if q % p == 0:
        return p
    return -1


p = 24
q = 48
print(getMinVal(p, q))

# Expected output:
24
# sort the numbers according to their sum of digits | function to return the sum of the digits of n ; function to sort the array according to the sum of the digits of elements ; vector to store digit sum with respective element ; inserting digit sum with element in the vector pair ; quick sort the vector , this will sort the pair according to sum of the digits of elements ; print the sorted vector content ; 
def sumOfDigit(n):
    sum = 0
    while (n > 0):
        sum += n % 10
        n = n // 10
    return sum


def sortArr(arr, n):
    vp = []
    for i in range(n):
        vp .append([sumOfDigit(arr[i]), arr[i]])
    vp .sort()
    for i in range(len(vp)):
        print(vp[i][1], end=" ")


if __name__ == "__main__":
    arr = [14, 1101, 10, 35, 0]
    n = len(arr)
    sortArr(arr, n)

# Expected output:
0 10 1101 14 35
# count all prime length palindromic substrings | python3 implementation of the approach ; function that returns true if sub - str1ing starting at i and ending at j in str1 is a palindrome ; function to count all palindromic substr1ing whose lwngth is a prime number ; 0 and 1 are non - primes ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; to store the required number of sub - str1ings ; starting from the smallest prime till the largest length of the sub - str1ing possible ; if j is prime ; check all the sub - str1ings of length j ; if current sub - str1ing is a palindrome ; 

import math as mt


def isPalindrome(str1, i, j):
    while (i < j):
        if (str1[i] != str1[j]):
            return False
        i += 1
        j -= 1
    return True


def countPrimePalindrome(str1, Len):
    prime = [True for i in range(Len + 1)]
    prime[0], prime[1] = False, False
    for p in range(2, mt .ceil(mt .sqrt(Len + 1))):
        if (prime[p]):
            for i in range(2 * p, Len + 1, p):
                prime[i] = False
    count = 0
    for j in range(2, Len + 1):
        if (prime[j]):
            for i in range(Len + 1 - j):
                if (isPalindrome(str1, i, i + j - 1)):
                    count += 1
    return count


s = "geeksforgeeks"
Len = len(s)
print(countPrimePalindrome(s, Len))

# Expected output:
2
# minimum operations of the given type required to make a complete graph | python 3 implementation of the approach ; function to return the minimum number of steps required ; 

from math import log2, ceil


def minOperations(N):
    x = log2(N)
    ans = ceil(x)
    return ans


if __name__ == '__main__':
    N = 10
    print(minOperations(N))

# Expected output:
4
# greatest divisor which divides all natural number in range [ l , r ] | function to return the greatest divisor that divides all the natural numbers in the range [ l , r ] ; 
def find_greatest_divisor(l, r):
    if (l == r):
        return l
    return 1


l = 2
r = 12
print(find_greatest_divisor(l, r))

# Expected output:
1
# probability of getting two consecutive heads after choosing a random coin among two different types of coins | function to return the probability of getting two consecutive heads ; formula derived from bayes 's theorem ; 
def getProbability(p, q):
    p /= 100
    q /= 100
    probability = (p * p + q * q) / (p + q)
    return probability


if __name__ == "__main__":
    p = 80
    q = 40
    print(getProbability(p, q))

# Expected output:
0.6666666666666667
# check whether bitwise or of n numbers is even or odd | function to check if bitwise or of n numbers is even or odd ; if at least one odd number is found , then the bitwise or of all numbers will be odd ; bitwise or is an odd number ; 
def check(arr, n):
    for i in range(n):
        if arr[i] & 1:
            return True
    return False


if __name__ == '__main__':
    arr = [3, 9, 12, 13, 15]
    n = len(arr)
    if check(arr, n):
        print("Odd Bit-wise OR")
    else:
        print("Even Bit-wise OR")

# Expected output:
Odd Bit-wise OR
# iterated logarithm log * ( n ) | recursive python3 program to find value of iterated logarithm ; 

import math


def _log(x, base):
    return (int)(math .log(x) / math .log(base))


def recursiveLogStar(n, b):
    if (n > 1.0):
        return 1.0 + recursiveLogStar(_log(n, b), b)
    else:
        return 0


if __name__ == '__main__':
    n = 100
    base = 5
    print("Log*(", n, ") = ", recursiveLogStar(n, base))

# Expected output:
Log*( 100 ) =  2.0
# find the maximum among the count of positive or negative integers in the array | function to find the maximum of the count of positive or negative elements ; initialize the pointers ; find the value of mid ; if element is negative then ignore the left half ; if element is positive then ignore the right half ; return maximum among the count of positive & negative element ; 
def findMaximum(arr, size):
    i = 0
    j = size - 1
    while (i <= j):
        mid = i + (j - i) // 2
        if (arr[mid] < 0):
            i = mid + 1
        elif (arr[mid] > 0):
            j = mid - 1
    return max(i, size - i)


if __name__ == "__main__":
    arr = [-9, -7, -4, 1, 5, 8, 9]
    N = len(arr)
    print(findMaximum(arr, N))

# Expected output:
4
# perform given queries on queue according to the given rules | function to perform all the queries operations on the given queue ; stores the count query of type 1 ; event e1 : increase counte1 ; event e2 : add the x in set ; event e3 : find position of x ; initial position is ( position - counte1 ) ; if x is already removed or popped out ; finding the position of x in queue ; traverse set to decrease position of x for all the number removed in front ; print the position of x ; 
def solve(n, m, queries):
    countE1 = 0
    removed = set()
    for i in range(0, m):
        if (queries[i][0] == 1):
            countE1 += 1
        elif (queries[i][0] == 2):
            removed .add(queries[i][1])
        else:
            position = queries[i][1] - countE1
            if (queries[i][1] in removed or position <= 0):
                print("-1")
            else:
                for it in removed:
                    if (it > queries[i][1]):
                        break
                    position -= 1
                print(position)


if __name__ == "__main__":
    N = 5
    Q = 3
    queries = [[0 for _ in range(2)]for _ in range(Q)]
    queries[0][0] = 1
    queries[0][1] = 0
    queries[1][0] = 3
    queries[1][1] = 3
    queries[2][0] = 2
    queries[2][1] = 2
    solve(N, Q, queries)

# Expected output:
2
# maximum index a pointer can reach in n steps by avoiding a given index b | python 3 program for the above approach ; function to find the maximum index reachable ; store the answer ; store the maximum index possible i . e , n * ( n - 1 ) ; add bthe previous elements ; run a loop ; binary search ; 

from bisect import bisect_left


def maxIndex(N, B):
    maximumIndexReached = 0
    Ans = []
    for i in range(1, N + 1):
        maximumIndexReached += i
        Ans .append(i)
    Ans .reverse()
    for i in range(len(Ans)):
        Ans[i] += Ans[i - 1]
    while (maximumIndexReached):
        it = bisect_left(Ans, maximumIndexReached - B)
        if (it not in Ans):
            break
        if (it == maximumIndexReached - B):
            maximumIndexReached -= 1
        else:
            break
    return maximumIndexReached


if __name__ == "__main__":
    N = 3
    B = 2
    print(maxIndex(N, B))

# Expected output:
6
# maximize kth largest element after splitting the given array at most c times | function to find the k - th maximum element after upto c operations ; check for the base case ; stores the count iterations of bs ; create the left and right bounds of binary search ; perform binary search ; find the value of mid ; traverse the array ; update the ranges ; return the maximum value obtained ; 
def maxKth(arr, N, C, K):
    if (N + C < K):
        return -1
    iter = 300
    l = 0
    r = 1000000000.0
    while (iter):
        iter = iter - 1
        mid = (l + r) * 0.5
        a = 0
        b = 0
        for i in range(N):
            a += arr[i] // mid
            if (arr[i] >= mid):
                b += 1
        if (a >= K and b + C >= K):
            l = mid
        else:
            r = mid
    return int(l)


arr = [5, 8]
K = 1
C = 1
N = len(arr)
print(maxKth(arr, N, C, K))

# Expected output:
8
# maximize the minimum difference between any element pair by selecting k elements from given array | to check if selection of k elements is possible such that difference between them is greater than dif ; selecting first element in the sorted array ; prev is the previously selected element initially at index 0 as first element is already selected ; check if selection of k - 1 elements from array with a minimum difference of dif is possible ; if the current element is atleast dif difference apart from the previously selected element then select the current element and increase the count ; if selection of k elements with a min difference of dif is possible then return true ; prev will become current element for the next iteration ; if selection of k elements with minimum difference of dif is not possible then return false ; minimum largest difference possible is 1 ; check if selection of k elements is possible with a minimum difference of dif ; if dif is greater than previous ans we update ans ; continue to search for better answer . try finding greater dif ; k elements cannot be selected ; 
def isPossibleToSelect(arr, N, dif, K):
    count = 1
    prev = arr[0]
    for i in range(1, N):
        if (arr[i] >= (prev + dif)):
            count += 1
            if (count == K):
                return True
            prev = arr[i]
    return False


def binarySearch(arr, left, right, K, N):
    ans = 1
    while (left <= right):
        dif = left + (right - left) // 2
        if (isPossibleToSelect(arr, N, dif, K)):
            ans = max(ans, dif)
            left = dif + 1
        else:
            right = dif - 1
    return ans


if __name__ == "__main__":
    N = 7
    K = 4
    arr = sorted([1, 4, 9, 0, 2, 13, 3])
    print(binarySearch(arr, 0, arr[N - 1], K, N))

# Expected output:
4
# find maximum height to cut all chocolates horizontally such that at least k amount remains | function to find the sum of remaining chocolate after making the horizontal cut at height mid ; stores the sum of chocolates ; traverse the array arr [ ] ; if the height is at least mid ; return the possible sum ; function to find the maximum horizontal cut made to all the chocolates such that the sum of the remaining element is at least k ; ranges of binary search ; perform the binary search ; find the sum of removed after making cut at height mid ; if the chocolate removed is same as the chocolate needed then return the height ; if the chocolate removed is less than chocolate needed then shift to the left range ; otherwise , shift to the right range ; return the possible cut ; 
def cal(arr, mid):
    chocolate = 0
    for i in arr:
        if i >= mid:
            chocolate += i - mid
    return chocolate


def maximumCut(arr, K):
    low = 0
    high = max(arr)
    while low <= high:
        mid = (low + high) // 2
        chocolate = cal(arr, mid)
        if chocolate == K:
            return mid
        elif chocolate < K:
            high = mid - 1
        else:
            low = mid + 1
            if mid > high:
                high = mid
    return high


N, K = 4, 7
arr = [15, 20, 8, 17]
print(maximumCut(arr, K))

# Expected output:
15
# koko eating bananas | python implementation for the above approach ; to get the ceil value ; in case of odd number ; in case of even number ; check if time is less than or equals to given hour ; as minimum speed of eating must be 1 ; maximum speed of eating is the maximum bananas in given piles ; check if the mid ( hours ) is valid ; if valid continue to search lower speed ; if cant finish bananas in given hours , then increase the speed ; 
def check(bananas, mid_val, H):
    time = 0
    for i in range(len(bananas)):
        if (bananas[i] % mid_val != 0):
            time += bananas[i] // mid_val + 1
        else:
            time += bananas[i] // mid_val
    if (time <= H):
        return True
    else:
        return False


def minEatingSpeed(piles, H):
    start = 1
    end = sorted(piles .copy(), reverse=True)[0]
    while (start < end):
        mid = start + (end - start) // 2
        if (check(piles, mid, H)):
            end = mid
        else:
            start = mid + 1
    return end


piles = [30, 11, 23, 4, 20]
H = 6
print(minEatingSpeed(piles, H))

# Expected output:
23