giulio98/xlcost-single-prompt huggingface dataset:
# find a partition point in array to maximize its xor sum | function to calculate prefix xor array ; calculating prefix xor ; function to find partition point in array to maximize xor sum ; to store prefix xor ; compute the prefix xor ; to store sum and index ; calculate the maximum sum that can be obtained splitting the array at some index i ; prefixxor [ i ] = xor of all arr elements till i ' th ▁ index ▁ prefixxor [ n - 1 ] ▁ ▁ ^ ▁ prefixxor [ i ] ▁ = ▁ xor ▁ of ▁ all ▁ elements ▁ ▁ from ▁ i + 1' th index to n - 1 'th index ; return the index ; 
def ComputePrefixXor(arr, PrefixXor, n):
    PrefixXor[0] = arr[0]
    for i in range(1, n):
        PrefixXor[i] = PrefixXor[i - 1] ^ arr[i]


def Xor_Sum(arr, n):
    PrefixXor = [0] * n
    ComputePrefixXor(arr, PrefixXor, n)
    sum, index = 0, 0
    for i in range(n):
        if (PrefixXor[i] + (PrefixXor[n - 1] ^ PrefixXor[i]) > sum):
            sum = PrefixXor[i] + (PrefixXor[n - 1] ^ PrefixXor[i])
            index = i
    return index + 1


arr = [1, 4, 6, 3, 8, 13, 34, 2, 21, 10]
n = len(arr)
print(Xor_Sum(arr, n))

# Expected output:
2
# count of strings in the first array which are smaller than every string in the second array | python3 implementation of the approach ; function to count the number of smaller strings in a for every in b ; count the frequency of all characters ; iterate for all possible strings in a ; increase the frequency of every character ; check for the smallest character 's frequency ; get the smallest character frequency ; insert it in the vector ; sort the count of all the frequency of the smallest character in every string ; iterate for every in b ; hash set every frequency 0 ; count the frequency of every character ; find the frequency of the smallest character ; count the number of strings in a which has the frequency of the smaller character less than the frequency of the smaller character of the in b ; store the answer ; function to print the answer ; get the answer ; print the number of strings for every answer ; 

from bisect import bisect_left as lower_bound
MAX = 26


def findCount(a, b, n, m):
    freq = [0 for i in range(MAX)]
    smallestFreq = []
    for i in range(n):
        s = a[i]
        for i in range(MAX):
            freq[i] = 0
        for j in range(len(s)):
            freq[ord(s[j]) - ord('a')] += 1
        for j in range(MAX):
            if (freq[j]):
                smallestFreq .append(freq[j])
                break
    smallestFreq = sorted(smallestFreq)
    ans = []
    for i in range(m):
        s = b[i]
        for i in range(MAX):
            freq[i] = 0
        for j in range(len(s)):
            freq[ord(s[j]) - ord('a')] += 1
        frequency = 0
        for j in range(MAX):
            if (freq[j]):
                frequency = freq[j]
                break
        ind = lower_bound(smallestFreq, frequency)
        ans .append(ind)
    return ans


def printAnswer(a, b, n, m):
    ans = findCount(a, b, n, m)
    for it in ans:
        print(it, end=" ")


A = ["aaa", "aa", "bdc"]
B = ["cccch", "cccd"]
n = len(A)
m = len(B)
printAnswer(A, B, n, m)

# Expected output:
3 2
# find leftmost and rightmost node of bst from its given preorder traversal | function to return the leftmost and rightmost nodes of the bst whose preorder traversal is given ; variables for finding minimum and maximum values of the array ; update the minimum ; update the maximum ; print the values ; 
def LeftRightNode(preorder, n):
    min = 10 ** 9
    max = -10 ** 9
    for i in range(n):
        if (min > preorder[i]):
            min = preorder[i]
        if (max < preorder[i]):
            max = preorder[i]
    print("Leftmost node is ", min)
    print("Rightmost node is ", max)


preorder = [3, 2, 1, 5, 4]
n = len(preorder)
LeftRightNode(preorder, n)

# Expected output:
Leftmost node is  1
Rightmost node is  5
# find the position of the given row in a 2 | python3 implementation of the approach ; function that compares both the arrays and returns - 1 , 0 and 1 accordingly ; return 1 if mid row is less than arr [ ] ; return 1 if mid row is greater than arr [ ] ; both the arrays are equal ; function to find a row in the given matrix using binary search ; if current row is equal to the given array then return the row number ; if arr [ ] is greater , ignore left half ; if arr [ ] is smaller , ignore right half ; no valid row found ; 

m = 6
n = 4


def compareRow(a1, a2):
    for i in range(n):
        if (a1[i] < a2[i]):
            return 1
        elif (a1[i] > a2[i]):
            return -1
    return 0


def binaryCheck(ar, arr):
    l = 0
    r = m - 1
    while (l <= r):
        mid = (l + r) // 2
        temp = compareRow(ar[mid], arr)
        if (temp == 0):
            return mid + 1
        elif (temp == 1):
            l = mid + 1
        else:
            r = mid - 1
    return -1


if __name__ == "__main__":
    mat = [[0, 0, 1, 0], [10, 9, 22, 23], [40, 40, 40, 40], [
        43, 44, 55, 68], [81, 73, 100, 132], [100, 75, 125, 133]]
    row = [10, 9, 22, 23]
    print(binaryCheck(mat, row))

# Expected output:
2
# number of subarrays having absolute sum greater than k | set | python3 implementation of the above approach ; function to find required value ; variable to store final answer ; loop to find prefix - sum ; sorting prefix - sum array ; loop to find upper_bound for each element ; returning final answer ; 

from bisect import bisect as upper_bound
maxLen = 30


def findCnt(arr, n, k):
    ans = 0
    for i in range(1, n):
        arr[i] += arr[i - 1]
        if (arr[i] > k or arr[i] < -1 * k):
            ans += 1
    if (arr[0] > k or arr[0] < -1 * k):
        ans += 1
    arr = sorted(arr)
    for i in range(n):
        ans += n - upper_bound(arr, arr[i] + k)
    return ans


arr = [-1, 4, -5, 6]
n = len(arr)
k = 0
print(findCnt(arr, n, k))

# Expected output:
10
# number of intersections between two ranges | python3 implementation of above approach ; function to return total number of intersections ; maximum possible number of intersections ; store all starting points of type1 ranges ; store all endpoints of type1 ranges ; starting point of type2 ranges ; ending point of type2 ranges ; subtract those ranges which are starting after r ; subtract those ranges which are ending before l ; 

from bisect import bisect as upper_bound


def FindIntersection(type1, n, type2, m):
    ans = n * m
    start = []
    end = []
    for i in range(n):
        start .append(type1[i][0])
        end .append(type1[i][1])
    start = sorted(start)
    start = sorted(end)
    for i in range(m):
        L = type2[i][0]
        R = type2[i][1]
        ans -= (len(start) - upper_bound(start, R))
        ans -= (upper_bound(end, L - 1))
    return ans


type1 = [[1, 2], [2, 3], [4, 5], [6, 7]]
type2 = [[1, 5], [2, 3], [4, 7], [5, 7]]
n = len(type1)
m = len(type2)
print(FindIntersection(type1, n, type2, m))

# Expected output:
9
# find the nth term divisible by a or b or c | function to return gcd of a and b ; function to return the lcm of a and b ; function to return the count of numbers from 1 to num which are divisible by a , b or c ; calculate number of terms divisible by a and by b and by c then , remove the terms which is are divisible by both a and b , both b and c , both c and a and then add which are divisible by a and b and c ; function to find the nth term divisible by a , b or c by using binary search ; set low to 1 and high to max ( a , b , c ) * n ; if the current term is less than n then we need to increase low to mid + 1 ; if current term is greater than equal to n then high = mid ; 
def gcd(a, b):
    if (a == 0):
        return b
    return gcd(b % a, a)


def lcm(a, b):
    return ((a * b) // gcd(a, b))


def divTermCount(a, b, c, num):
    return ((num // a) + (num // b) + (num // c) - (num // lcm(a, b)) -
            (num // lcm(b, c)) - (num // lcm(a, c)) + (num // lcm(a, lcm(b, c))))


def findNthTerm(a, b, c, n):
    low = 1
    high = 10 ** 9
    mid = 0
    while (low < high):
        mid = low + (high - low) // 2
        if (divTermCount(a, b, c, mid) < n):
            low = mid + 1
        else:
            high = mid
    return low


a = 2
b = 3
c = 5
n = 10
print(findNthTerm(a, b, c, n))

# Expected output:
14
# split the given array into k sub | function to check if mid can be maximum sub - arrays sum ; if individual element is greater maximum possible sum ; increase sum of current sub - array ; if the sum is greater than mid increase count ; check condition ; function to find maximum subarray sum which is minimum ; start = max ( array ) max subarray sum , considering subarray of length 1 ; answer stores possible maximum sub array sum ; if mid is possible solution put answer = mid ; ; 
def check(mid, array, n, K):
    count = 0
    sum = 0
    for i in range(n):
        if (array[i] > mid):
            return False
        sum += array[i]
        if (sum > mid):
            count += 1
            sum = array[i]
    count += 1
    if (count <= K):
        return True
    return False


def solve(array, n, K):

    start = max(array)
    end = 0

    for i in range(n):
        end += array[i]
    answer = 0
    while (start <= end):
        mid = (start + end) // 2
        if (check(mid, array, n, K)):
            answer = mid
            end = mid - 1
        else:
            start = mid + 1

    return answer


if __name__ == '__main__':
    array = [1, 2, 3, 4]
    n = len(array)
    K = 3
    print(solve(array, n, K))

# Expected output:
4
# count number of common elements between two arrays by using bitset and bitwise operation | python3 implementation of the approach ; function to return the count of common elements ; traverse the first array ; set 1 at ( index ) position a [ i ] ; traverse the second array ; set 1 at ( index ) position b [ i ] ; bitwise and of both the bitsets ; find the count of 1 's  ; 

MAX = 100000
bit1, bit2, bit3 = 0, 0, 0


def count_common(a, n, b, m):
    for i in range(n):
        global bit1, bit2, bit3
        bit1 = bit1 | (1 << a[i])
    for i in range(m):
        bit2 = bit2 | (1 << b[i])
    bit3 = bit1 & bit2
    count = bin(bit3).count('1')
    return count


if __name__ == "__main__":
    a = [1, 4, 7, 2, 3]
    b = [2, 11, 7, 4, 15, 20, 24]
    n = len(a)
    m = len(b)
    print(count_common(a, n, b, m))

# Expected output:
3
# create a sorted array using binary search | function to create a new sorted array using binary search ; auxiliary array ; if b is empty any element can be at first place ; perform binary search to find the correct position of current element in the new array ; let the element should be at first index ; if a [ j ] is already present in the new array ; add a [ j ] at mid + 1. you can add it at mid ; if a [ j ] is lesser than b [ mid ] go right side ; means pos should be between start and mid - 1 ; else pos should be between mid + 1 and end ; if a [ j ] is the largest push it at last ; here max ( 0 , pos ) is used because sometimes pos can be negative as smallest duplicates can be present in the array ; print the new generated sorted array ; 
def createSorted(a: list, n: int):
    b = []
    for j in range(n):
        if len(b) == 0:
            b .append(a[j])
        else:
            start = 0
            end = len(b) - 1
            pos = 0
            while start <= end:
                mid = start + (end - start) // 2
                if b[mid] == a[j]:
                    b .insert(max(0, mid + 1), a[j])
                    break
                elif b[mid] > a[j]:
                    pos = end = mid - 1
                else:
                    pos = start = mid + 1
                if start > end:
                    pos = start
                    b .insert(max(0, pos), a[j])
                    break
    for i in range(n):
        print(b[i], end=" ")


if __name__ == "__main__":
    a = [2, 5, 4, 9, 8]
    n = len(a)
    createSorted(a, n)

# Expected output:
2 4 5 8 9
# largest sub | python3 implementation of the approach ; function that return true if frequency of all the present characters is at least k ; if the character is present and its frequency is less than k ; function to set every frequency to zero ; function to return the length of the longest sub - string such that it contains every character at least k times ; to store the required maximum length ; starting index of the sub - string ; ending index of the sub - string ; if the frequency of every character of the current sub - string is at least k ; update the maximum possible length ; 

MAX = 26


def atLeastK(freq, k):
    for i in range(MAX):
        if (freq[i] != 0 and freq[i] < k):
            return False
    return True


def setZero(freq):
    for i in range(MAX):
        freq[i] = 0


def findlength(string, n, k):
    maxLen = 0
    freq = [0] * MAX
    for i in range(n):
        setZero(freq)
        for j in range(i, n):
            freq[ord(string[j]) - ord('a')] += 1
            if (atLeastK(freq, k)):
                maxLen = max(maxLen, j - i + 1)
    return maxLen


if __name__ == "__main__":
    string = "xyxyyz"
    n = len(string)
    k = 2
    print(findlength(string, n, k))

# Expected output:
5
# minimum increments to convert to an array of consecutive integers | function that return true if the required array can be generated with m as the last element ; build the desired array ; check if the given array can be converted to the desired array with the given operation ; function to return the minimum number of operations required to convert the given array to an increasing ap series with common difference as 1 ; apply binary search ; if array can be generated with mid as the last element ; current ans is mid ; check whether the same can be achieved with even less operations ; build the desired array ; calculate the number of operations required ; return the number of operations required ; 
def check(m, n, arr):
    desired = [0] * n
    for i in range(n - 1, -1, -1):
        desired[i] = m
        m -= 1
    for i in range(n):
        if (arr[i] > desired[i] or desired[i] < 1):
            return False
    return True


def minOperations(arr, n):
    start = arr[n - 1]
    end = max(arr) + n
    max_arr = 0
    while (start <= end):
        mid = (start + end) // 2
        if (check(mid, n, arr)):
            max_arr = mid
            end = mid - 1
        else:
            start = mid + 1
    desired = [0] * n
    for i in range(n - 1, -1, -1):
        desired[i] = max_arr
        max_arr -= 1
    operations = 0
    for i in range(n):
        operations += (desired[i] - arr[i])
    return operations


if __name__ == "__main__":
    arr = [4, 4, 5, 5, 7]
    n = len(arr)
    print(minOperations(arr, n))

# Expected output:
5
# minimize the number of steps required to reach the end of the array | set 2 | function to return the minimum steps required to reach the end of the given array ; array to determine whether a cell has been visited before ; queue for bfs ; push the source i . e . index 0 ; variable to store the depth of search ; bfs algorithm ; current queue size ; top - most element of queue ; base case ; if we reach the destination i . e . index ( n - 1 ) ; marking the cell visited ; pushing the adjacent nodes i . e . indices reachable from the current index ; 
def minSteps(arr, n):
    v = [0 for i in range(n)]
    q = []
    q .append(0)
    depth = 0
    while (len(q) != 0):
        x = len(q)
        while (x >= 1):
            i = q[0]
            q .remove(i)
            x -= 1
            if (v[i]):
                continue
            if (i == n - 1):
                return depth
            v[i] = 1
            if (i + arr[i] < n):
                q .append(i + arr[i])
            if (i - arr[i] >= 0):
                q .append(i - arr[i])
        depth += 1
    return -1


if __name__ == '__main__':
    arr = [1, 1, 1, 1, 1, 1]
    n = len(arr)
    print(minSteps(arr, n))

# Expected output:
5
# find the winner of the game based on greater number of divisors | python3 implementation of the approach ; function to return the count of divisors of elem ; function to return the winner of the game ; convert every element of a [ ] to their divisor count ; convert every element of b [ ] to their divisor count ; sort both the arrays ; for every element of a [ ] apply binary search to find number of pairs where a wins ; b wins if a doesnot win ; 

from math import *


def divisorcount(elem):
    ans = 0
    for i in range(1, int(sqrt(elem)) + 1):
        if (elem % i == 0):
            if (i * i == elem):
                ans += 1
            else:
                ans += 2
    return ans


def findwinner(A, B, N, M):
    for i in range(N):
        A[i] = divisorcount(A[i])
    for i in range(M):
        B[i] = divisorcount(B[i])
    A .sort()
    B .sort()
    winA = 0
    for i in range(N):
        val = A[i]
        start = 0
        end = M - 1
        index = -1
        while (start <= end):
            mid = (start + end) // 2
            if (B[mid] <= val):
                index = mid
                start = mid + 1
            else:
                end = mid - 1
        winA += (index + 1)
    winB = N * M - winA
    if (winA > winB):
        return "A"
    elif (winB > winA):
        return "B"
    return "Draw"


if __name__ == '__main__':
    A = [4, 12, 24]
    N = len(A)
    B = [25, 28, 13, 45]
    M = len(B)
    print(findwinner(A, B, N, M))

# Expected output:
A
# minimum time required to transport all the boxes from source to the destination under the given constraints | function that returns true if it is possible to transport all the boxes in the given amount of time ; if all the boxes can be transported in the given time ; if all the boxes can 't be  transported in the given time ; function to return the minimum time required ; sort the two arrays ; stores minimum time in which all the boxes can be transported ; check for the minimum time in which all the boxes can be transported ; if it is possible to transport all the boxes in mid amount of time ; 
def isPossible(box, truck, n, m, min_time):
    temp = 0
    count = 0
    while (count < m):
        j = 0
        while (j < min_time and temp < n and truck[count] >= box[temp]):
            temp += 1
            j += 2
        count += 1
    if (temp == n):
        return True
    return False


def minTime(box, truck, n, m):
    box .sort()
    truck .sort()
    l = 0
    h = 2 * n
    min_time = 0
    while (l <= h):
        mid = (l + h) // 2
        if (isPossible(box, truck, n, m, mid)):
            min_time = mid
            h = mid - 1
        else:
            l = mid + 1
    return min_time


if __name__ == "__main__":
    box = [10, 2, 16, 19]
    truck = [29, 25]
    n = len(box)
    m = len(truck)
    print(minTime(box, truck, n, m))

# Expected output:
3
# maximum points covered after removing an interval | function to find the required interval ; total count of covered numbers ; array to store numbers that occur exactly in one interval till ith interval ; calculate new count by removing all numbers in range [ l , r ] occurring exactly once ; 
def solve(interval, N, Q):
    Mark = [0 for i in range(Q)]
    for i in range(N):
        l = interval[i][0] - 1
        r = interval[i][1] - 1
        for j in range(l, r + 1):
            Mark[j] += 1
    count = 0
    for i in range(Q):
        if (Mark[i]):
            count += 1
    count1 = [0 for i in range(Q)]
    if (Mark[0] == 1):
        count1[0] = 1
    for i in range(1, Q):
        if (Mark[i] == 1):
            count1[i] = count1[i - 1] + 1
        else:
            count1[i] = count1[i - 1]
    maxindex = 0
    maxcoverage = 0
    for i in range(N):
        l = interval[i][0] - 1
        r = interval[i][1] - 1
        elem1 = 0
        if (l != 0):
            elem1 = count1[r] - count1[l - 1]
        else:
            elem1 = count1[r]
        if (count - elem1 >= maxcoverage):
            maxcoverage = count - elem1
            maxindex = i
    print(
        "Maximum Coverage is",
        maxcoverage,
        "after removing interval at index",
        maxindex)


interval = [[1, 4], [4, 5], [5, 6], [6, 7], [3, 5]]
N = len(interval)
Q = 7
solve(interval, N, Q)

# Expected output:
Maximum Coverage is 7 after removing interval at index 4
# find the minimum of maximum length of a jump required to reach the last island in exactly k jumps | function that returns true if it is possible to reach end of the array in exactly k jumps ; variable to store the number of steps required to reach the end ; if it is possible to reach the end in exactly k jumps ; returns the minimum maximum distance required to reach the end of the array in exactly k jumps ; stores the answer ; binary search to calculate the result ; 
def isPossible(arr, n, dist, k):
    req = 0
    curr = 0
    prev = 0
    for i in range(0, n):
        while (curr != n and (arr[curr] - arr[prev]) <= dist):
            curr = curr + 1
        req = req + 1
        if (curr == n):
            break
        prev = curr - 1
    if (curr != n):
        return False
    if (req <= k):
        return True
    return False


def minDistance(arr, n, k):
    l = 0
    h = arr[n - 1]
    ans = 0
    while (l <= h):
        m = (l + h) // 2
        if (isPossible(arr, n, m, k)):
            ans = m
            h = m - 1
        else:
            l = m + 1
    return ans


arr = [2, 15, 36, 43]
n = len(arr)
k = 2
print(minDistance(arr, n, k))

# Expected output:
28
# find the kth element in the series generated by the given n ranges | function to return the kth element of the required series ; to store the number of integers that lie upto the ith index ; compute the number of integers ; stores the index , lying from 1 to n , ; using binary search , find the index in which the kth element will lie ; find the position of the kth element in the interval in which it lies ; 
def getKthElement(n, k, L, R):
    l = 1
    h = n
    total = [0 for i in range(n + 1)]
    total[0] = 0
    for i in range(n):
        total[i + 1] = total[i] + (R[i] - L[i]) + 1
    index = -1
    while (l <= h):
        m = (l + h) // 2
        if (total[m] > k):
            index = m
            h = m - 1
        elif (total[m] < k):
            l = m + 1
        else:
            index = m
            break
    l = L[index - 1]
    h = R[index - 1]
    x = k - total[index - 1]
    while (l <= h):
        m = (l + h) // 2
        if ((m - L[index - 1]) + 1 == x):
            return m
        elif ((m - L[index - 1]) + 1 > x):
            h = m - 1
        else:
            l = m + 1


L = [1, 8, 21]
R = [4, 10, 23]
n = len(L)
k = 6
print(getKthElement(n, k, L, R))

# Expected output:
9
# find minimum positive integer x such that a ( x ^ 2 ) + b ( x ) + c >= k | function to return the minimum positive integer satisfying the given equation ; binary search to find the value of x ; return the answer ; 
def MinimumX(a, b, c, k):
    x = 10 ** 9
    if (k <= c):
        return 0
    h = k - c
    l = 0
    while (l <= h):
        m = (l + h) // 2
        if ((a * m * m) + (b * m) > (k - c)):
            x = min(x, m)
            h = m - 1
        elif ((a * m * m) + (b * m) < (k - c)):
            l = m + 1
        else:
            return m
    return x


a, b, c, k = 3, 2, 4, 15
print(MinimumX(a, b, c, k))

# Expected output:
2