giulio98/xlcost-single-prompt huggingface dataset:
# queries for counts of array elements with values in given range | function to count elements within given range ; initialize result ; check if element is in range ; 
def countInRange(arr, n, x, y):
    count = 0
    for i in range(n):
        if (arr[i] >= x and arr[i] <= y):
            count += 1
    return count


arr = [1, 3, 4, 9, 10, 3]
n = len(arr)
i = 1
j = 4
print(countInRange(arr, n, i, j))
i = 9
j = 12
print(countInRange(arr, n, i, j))

# Expected output:
4
2
# path with smallest product of edges with weight >= 1 | function to return the smallest product of edges ; if the source is equal to the destination ; initialise the priority queue ; visited array ; while the priority - queue is not empty ; current node ; current product of distance ; popping the top - most element ; if already visited continue ; marking the node as visited ; if it is a destination node ; traversing the current node ; if no path exists ; 
def dijkstra(s, d, gr):
    if (s == d):
        return 0
    pq = []
    pq .append((1, s))
    v = [0] * (len(gr) + 1)
    while (len(pq) != 0):
        curr = pq[0][1]
        dist = pq[0][0]
        pq .pop()
        if (v[curr]):
            continue
        v[curr] = 1
        if (curr == d):
            return dist
        for it in gr[curr]:
            if it not in pq:
                pq .insert(0, (dist * it[1], it[0]))
    return -1


if __name__ == "__main__":
    n = 3
    gr = {}
    gr[1] = [(3, 9)]
    gr[2] = [(3, 1)]
    gr[1].append((2, 5))
    gr[3] = []
    s = 1
    d = 3
    print(dijkstra(s, d, gr))

# Expected output:
5
# queries for counts of array elements with values in given range | function to find first index >= x ; function to find last index <= x ; function to count elements within given range ; initialize result ; 
def lowerIndex(arr, n, x):
    l = 0
    h = n - 1
    while (l <= h):
        mid = int((l + h) / 2)
        if (arr[mid] >= x):
            h = mid - 1
        else:
            l = mid + 1
    return l


def upperIndex(arr, n, x):
    l = 0
    h = n - 1
    while (l <= h):
        mid = int((l + h) / 2)
        if (arr[mid] <= x):
            l = mid + 1
        else:
            h = mid - 1
    return h


def countInRange(arr, n, x, y):
    count = 0
    count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1
    return count


arr = [1, 3, 4, 9, 10, 3]
n = len(arr)
arr .sort()
i = 1
j = 4
print(countInRange(arr, n, i, j))
i = 9
j = 12
print(countInRange(arr, n, i, j))

# Expected output:
4
2
# count elements which divide all numbers in range l | function to count element time complexity o ( n ^ 2 ) worst case ; answer for query ; 0 based index ; iterate for all elements ; check if the element divides all numbers in range ; no of elements ; if all elements are divisible by a [ i ] ; answer for every query ; 
def answerQuery(a, n, l, r):
    count = 0
    l = l - 1
    for i in range(l, r, 1):
        element = a[i]
        divisors = 0
        for j in range(l, r, 1):
            if (a[j] % a[i] == 0):
                divisors += 1
            else:
                break
        if (divisors == (r - l)):
            count += 1
    return count


if __name__ == '__main__':
    a = [1, 2, 3, 5]
    n = len(a)
    l = 1
    r = 4
    print(answerQuery(a, n, l, r))
    l = 2
    r = 4
    print(answerQuery(a, n, l, r))

# Expected output:
1
0
# minimum number of binary strings to represent a number | function to find the minimum number of binary strings to represent a number ; storing digits in correct order ; find the maximum digit in the array ; traverse for all the binary strings ; if digit at jth position is greater than 0 then substitute 1 ; 
def minBinary(n):
    digit = [0 for i in range(3)]
    len = 0
    while (n > 0):
        digit[len] = n % 10
        len += 1
        n //= 10
    digit = digit[::-1]
    ans = 0
    for i in range(len):
        ans = max(ans, digit[i])
    print("Minimum Number of binary strings needed:", ans)
    for i in range(1, ans + 1, 1):
        num = 0
        for j in range(0, len, 1):
            if (digit[j] > 0):
                num = num * 10 + 1
                digit[j] -= 1
            else:
                num *= 10
        print(num, end=" ")


if __name__ == '__main__':
    n = 564
    minBinary(n)

# Expected output:
Minimum Number of binary strings needed: 6
111 111 111 111 110 10
# array range queries over range queries | function to create the record array ; 
def record_sum(record, l, r, n, adder):
    for i in range(l, r + 1):
        record[i] += adder


n = 5
m = 5
arr = [0] * n
query = [[1, 1, 2], [1, 4, 5], [2, 1, 2], [2, 1, 3], [2, 3, 4]]
record = [0] * m
for i in range(m - 1, -1, -1):
    if (query[i][0] == 2):
        record_sum(record, query[i][1] - 1, query[i][2] - 1, m, record[i] + 1)
    else:
        record_sum(record, i, i, m, 1)
for i in range(m):
    if (query[i][0] == 1):
        record_sum(arr, query[i][1] - 1, query[i][2] - 1, n, record[i])
for i in range(n):
    print(arr[i], end=' ')

# Expected output:
7 7 0 7 7
# count of pairs from 1 to a and 1 to b whose sum is divisible by n | function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; iterate over 1 to a to find distinct pairs ; for each integer from 1 to a b / n integers exists such that pair / sum is divisible by n ; if ( i % n + b % n ) >= n one more pair is possible ; return answer ; 
def findCountOfPairs(a, b, n):
    ans = 0
    for i in range(1, a + 1):
        ans += b // n
        ans += 1 if (i % n + b % n) >= n else 0
    return ans


a = 5
b = 13
n = 3
print(findCountOfPairs(a, b, n))

# Expected output:
22
# count of pairs from 1 to a and 1 to b whose sum is divisible by n | function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; if first element is bigger then swap ; count is store the number of pair . ; we use temp for breaking a loop . ; count when a is greater . ; count when a is smaller but b is greater ; count when a and b both are smaller ; for storing the pair in count . ; return the number of pairs . ; 
def findCountOfPairs(a, b, n):
    if (a > b):
        a, b = b, a
    temp = 1
    count = 0
    i = n
    while (temp > 0):
        if (a >= i):
            temp = i - 1
        elif (b >= i):
            temp = a
        elif (i > b):
            temp = a - (i - b) + 1
        if (temp > 0):
            count += temp
        i += n
    return count


a = 5
b = 13
n = 3
print(findCountOfPairs(a, b, n))

# Expected output:
22
# array range queries for elements with frequency same as value | python 3 program to answer q queries to find number of times an element x appears x times in a query subarray ; returns the count of number x with frequency x in the subarray from start to end ; map for frequency of elements ; store frequency of each element in arr [ start end ] ; count elements with same frequency as value ; 

import math as mt


def solveQuery(start, end, arr):
    frequency = dict()
    for i in range(start, end + 1):
        if arr[i] in frequency .keys():
            frequency[arr[i]] += 1
        else:
            frequency[arr[i]] = 1
    count = 0
    for x in frequency:
        if x == frequency[x]:
            count += 1
    return count


A = [1, 2, 2, 3, 3, 3]
n = len(A)
queries = [[0, 1], [1, 1], [0, 2], [1, 3], [3, 5], [0, 5]]
q = len(queries)
for i in range(q):
    start = queries[i][0]
    end = queries[i][1]
    print("Answer for Query ", (i + 1), " = ", solveQuery(start, end, A))

# Expected output:
Answer for Query  1  =  1
Answer for Query  2  =  0
Answer for Query  3  =  2
Answer for Query  4  =  1
Answer for Query  5  =  1
Answer for Query  6  =  3
# buy minimum items without change and given coins | python3 implementation of above approach ; see if we can buy less than 10 items using 10 rs coins and one r rs coin ; we can always buy 10 items ; 
def minItems(k, r):
    for i in range(1, 10):
        if ((i * k - r) % 10 == 0 or (i * k) % 10 == 0):
            return i
    return 10


if __name__ == "__main__":
    k, r = 15, 2
    print(minItems(k, r))

# Expected output:
2
# number of indexes with equal elements in given range | function that answers every query in o ( r - l ) ; traverse from l to r and count the required indexes ; 
def answer_query(a, n, l, r):
    count = 0
    for i in range(l, r):
        if (a[i] == a[i + 1]):
            count += 1
    return count


a = [1, 2, 2, 2, 3, 3, 4, 4, 4]
n = len(a)
L = 1
R = 8
print(answer_query(a, n, L, R))
L = 0
R = 4
print(answer_query(a, n, L, R))

# Expected output:
5
2
# diagonal sum of a binary tree | python3 program calculate the sum of diagonal nodes . ; a binary tree node structure ; to map the node with level - index ; recursvise function to calculate sum of elements where level - index is same ; if there is no child then return ; add the element in the group of node whose level - index is equal ; left child call ; right child call ; function call ; for different values of level - index add te sum of those node to answer ; 

from collections import deque


class Node:
    def __init__(self, key):
        self .data = key
        self .left = None
        self .right = None


grid = {}


def addConsideringGrid(root, level, index):
    global grid
    if (root is None):
        return
    grid[level - index] = (grid .get(level - index, 0) + root .data)
    addConsideringGrid(root .left, level + 1, index - 1)
    addConsideringGrid(root .right, level + 1, index + 1)


def diagonalSum(root):
    addConsideringGrid(root, 0, 0)
    ans = []
    for x in grid:
        ans .append(grid[x])
    return ans


if __name__ == '__main__':
    root = Node(1)
    root .left = Node(2)
    root .right = Node(3)
    root .left .left = Node(9)
    root .left .right = Node(6)
    root .right .left = Node(4)
    root .right .right = Node(5)
    root .right .left .right = Node(7)
    root .right .left .left = Node(12)
    root .left .right .left = Node(11)
    root .left .left .right = Node(10)
    v = diagonalSum(root)
    for i in v:
        print(i, end=" ")

# Expected output:
9 19 42
# count subarrays with prime sum | function to count subarrays with prime sum ; use sieve to find all prime numbers less than or equal to max_val create a boolean array " prime [ 0 . . n ] " . a value in prime [ i ] will finally be false if i is not a prime , else true . ; remaining part of sieve ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p ; initialize result ; traverse through the array ; return answer ; 
def primeSubarrays(A, n):
    max_val = 10 ** 7
    prime = [True] * (max_val + 1)
    prime[0] = False
    prime[1] = False
    for p in range(2, int(max_val ** (0.5)) + 1):
        if prime[p]:
            for i in range(2 * p, max_val + 1, p):
                prime[i] = False
    cnt = 0
    for i in range(0, n - 1):
        val = A[i]
        for j in range(i + 1, n):
            val += A[j]
            if prime[val]:
                cnt += 1
    return cnt


if __name__ == "__main__":
    A = [1, 2, 3, 4, 5]
    n = len(A)
    print(primeSubarrays(A, n))

# Expected output:
3
# total numbers with no repeated digits in a range | function to check if the given number has repeated digit or not ; traversing through each digit ; if the digit is present more than once in the number ; return 0 if the number has repeated digit ; return 1 if the number has no repeated digit ; function to find total number in the given range which has no repeated digit ; traversing through the range ; add 1 to the answer if i has no repeated digit else 0 ; 
def repeated_digit(n):
    a = []
    while n != 0:
        d = n % 10
        if d in a:
            return 0
        a .append(d)
        n = n // 10
    return 1


def calculate(L, R):
    answer = 0
    for i in range(L, R + 1):
        answer = answer + repeated_digit(i)
    return answer


L = 1
R = 100
print(calculate(L, R))

# Expected output:
90
# minimum swaps required to make a binary string alternating | returns the minimum number of swaps of a binary string passed as the argument to make it alternating ; counts number of zeroes at odd and even positions ; counts number of ones at odd and even positions ; alternating string starts with 0 ; alternating string starts with 1 ; calculates the minimum number of swaps ; 
def countMinSwaps(st):
    min_swaps = 0
    odd_0, even_0 = 0, 0
    odd_1, even_1 = 0, 0
    n = len(st)
    for i in range(0, n):
        if i % 2 == 0:
            if st[i] == "1":
                even_1 += 1
            else:
                even_0 += 1
        else:
            if st[i] == "1":
                odd_1 += 1
            else:
                odd_0 += 1
    cnt_swaps_1 = min(even_0, odd_1)
    cnt_swaps_2 = min(even_1, odd_0)
    return min(cnt_swaps_1, cnt_swaps_2)


if __name__ == "__main__":
    st = "000111"
    print(countMinSwaps(st))

# Expected output:
1
# largest sum contiguous subarray | python program to find maximum contiguous subarray function to find the maximum contiguous subarray ; 

from sys import maxsize


def maxSubArraySum(a, size):
    max_so_far = -maxsize - 1
    max_ending_here = 0
    for i in range(0, size):
        max_ending_here = max_ending_here + a[i]
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here
        if max_ending_here < 0:
            max_ending_here = 0
    return max_so_far


a = [-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7]
print("Maximum contiguous sum is", maxSubArraySum(a, len(a)))

# Expected output:
Maximum contiguous sum is -3
# minimum rooms for m events of n batches with given schedule | returns minimum number of rooms required to perform classes of n groups in m slots with given schedule . ; store count of classes happening in every slot . ; initialize all values to zero ; number of rooms required is equal to maximum classes happening in a particular slot . ; 
def findMinRooms(slots, n, m):
    counts = [0] * m
    for i in range(n):
        for j in range(m):
            if (slots[i][j] == '1'):
                counts[j] += 1
    return max(counts)


n = 3
m = 7
slots = ["0101011", "0011001", "0110111"]
print(findMinRooms(slots, n, m))

# Expected output:
3
# largest sum contiguous subarray | python program to find maximum contiguous subarray ; 
def maxSubArraySum(a, size):
    max_so_far = a[0]
    curr_max = a[0]
    for i in range(1, size):
        curr_max = max(a[i], curr_max + a[i])
        max_so_far = max(max_so_far, curr_max)
    return max_so_far


a = [-2, -3, 4, -1, -2, 1, 5, -3]
print("Maximum contiguous sum is", maxSubArraySum(a, len(a)))

# Expected output:
Maximum contiguous sum is 7
# largest sum contiguous subarray | function to find the maximum contiguous subarray and print its starting and end index ; 

from sys import maxsize


def maxSubArraySum(a, size):
    max_so_far = -maxsize - 1
    max_ending_here = 0
    start = 0
    end = 0
    s = 0
    for i in range(0, size):
        max_ending_here += a[i]
        if max_so_far < max_ending_here:
            max_so_far = max_ending_here
            start = s
            end = i
        if max_ending_here < 0:
            max_ending_here = 0
            s = i + 1
    print("Maximum contiguous sum is %d" % (max_so_far))
    print("Starting Index %d" % (start))
    print("Ending Index %d" % (end))


a = [-2, -3, 4, -1, -2, 1, 5, -3]
maxSubArraySum(a, len(a))

# Expected output:
Maximum contiguous sum is 7
Starting Index 2
Ending Index 6
# minimum sum by choosing minimum of pairs from array | returns minimum possible sum in array b [ ] ; 
def minSum(A):
    min_val = min(A)
    return min_val * (len(A) - 1)


A = [7, 2, 3, 4, 5, 6]
print(minSum(A))

# Expected output:
10
# program for next fit algorithm in memory management | function to allocate memory to blocks as per next fit algorithm ; initially no block is assigned to any process ; pick each process and find suitable blocks according to its size ad assign to it ; do not start from beginning ; allocate block j to p [ i ] process ; reduce available memory in this block . ; mod m will help in traversing the blocks from starting block after we reach the end . ; 
def NextFit(blockSize, m, processSize, n):
    allocation = [-1] * n
    j = 0
    for i in range(n):
        while j < m:
            if blockSize[j] >= processSize[i]:
                allocation[i] = j
                blockSize[j] -= processSize[i]
                break
            j = (j + 1) % m
    print("Process No. Process Size Block no.")
    for i in range(n):
        print(i + 1, " ", processSize[i], end=" ")
        if allocation[i] != -1:
            print(allocation[i] + 1)
        else:
            print("Not Allocated")


if __name__ == '__main__':
    blockSize = [5, 10, 20]
    processSize = [10, 20, 5]
    m = len(blockSize)
    n = len(processSize)
    NextFit(blockSize, m, processSize, n)

# Expected output:
Process No. Process Size Block no.
1   10 2
2   20 3
3   5 1
# find if there is a pair in root to a leaf path with sum equals to root 's data | utility that allocates a new node with the given data and none left and right pointers . ; function to prroot to leaf path which satisfies the condition ; base condition ; check if current node makes a pair with any of the existing elements in set . ; insert current node in set ; if result returned by either left or right child is true , return true . ; remove current node from hash table ; a wrapper over printpathutil ( ) ; create an empty hash table ; recursively check in left and right subtrees . ; 

class newnode:
    def __init__(self, data):
        self .data = data
        self .left = self .right = None


def printPathUtil(node, s, root_data):
    if (node is None):
        return False
    rem = root_data - node .data
    if rem in s:
        return True
    s .add(node .data)
    res = printPathUtil(
        node .left, s, root_data) or printPathUtil(
        node .right, s, root_data)
    s .remove(node .data)
    return res


def isPathSum(root):
    s = set()
    return printPathUtil(
        root .left, s, root .data) or printPathUtil(
        root .right, s, root .data)


if __name__ == '__main__':
    root = newnode(8)
    root .left = newnode(5)
    root .right = newnode(4)
    root .left .left = newnode(9)
    root .left .right = newnode(7)
    root .left .right .left = newnode(1)
    root .left .right .right = newnode(12)
    root .left .right .right .right = newnode(2)
    root .right .right = newnode(11)
    root .right .right .left = newnode(3)
    print("Yes")if (isPathSum(root))else print("No")

# Expected output:
Yes
# find the subarray with least average | prints beginning and ending indexes of subarray of size k with minimum average ; k must be smaller than or equal to n ; initialize beginning index of result ; compute sum of first subarray of size k ; initialize minimum sum as current sum ; traverse from ( k + 1 ) ' th ▁ ▁ element ▁ to ▁ n ' th element ; add current item and remove first item of previous subarray ; update result if needed ; 
def findMinAvgSubarray(arr, n, k):
    if (n < k):
        return 0
    res_index = 0
    curr_sum = 0
    for i in range(k):
        curr_sum += arr[i]
    min_sum = curr_sum
    for i in range(k, n):
        curr_sum += arr[i] - arr[i - k]
        if (curr_sum < min_sum):
            min_sum = curr_sum
            res_index = (i - k + 1)
    print(
        "Subarray between [",
        res_index,
        ", ",
        (res_index + k - 1),
        "] has minimum average")


arr = [3, 7, 90, 20, 10, 50, 40]
k = 3
n = len(arr)
findMinAvgSubarray(arr, n, k)

# Expected output:
Subarray between [ 3 ,  5 ] has minimum average
# find the largest number with given number of digits and sum of digits | prints the smalles possible number with digit sum ' s ' and ' m ' number of digits . ; if sum of digits is 0 , then a number is possible only if number of digits is 1. ; sum greater than the maximum possible sum . ; create an array to store digits of result ; fill from most significant digit to least significant digit . ; fill 9 first to make the number largest ; if remaining sum becomes less than 9 , then fill the remaining sum ; 
def findLargest(m, s):
    if (s == 0):
        if (m == 1):
            print("Largest number is ", "0", end="")
        else:
            print("Not possible", end="")
        return
    if (s > 9 * m):
        print("Not possible", end="")
        return
    res = [0] * m
    for i in range(0, m):
        if (s >= 9):
            res[i] = 9
            s = s - 9
        else:
            res[i] = s
            s = 0
    print("Largest number is ", end="")
    for i in range(0, m):
        print(res[i], end="")


s = 9
m = 2
findLargest(m, s)

# Expected output:
Largest number is 90
# minimum number of jumps to reach end | returns minimum number of jumps to reach arr [ h ] from arr [ l ] ; base case : when source and destination are same ; when nothing is reachable from the given source ; traverse through all the points reachable from arr [ l ] . recursively get the minimum number of jumps needed to reach arr [ h ] from these reachable points . ; 
def minJumps(arr, l, h):
    if (h == l):
        return 0
    if (arr[l] == 0):
        return float('inf')
    min = float('inf')
    for i in range(l + 1, h + 1):
        if (i < l + arr[l] + 1):
            jumps = minJumps(arr, i, h)
            if (jumps != float('inf') and jumps + 1 < min):
                min = jumps + 1
    return min


arr = [1, 3, 6, 3, 2, 3, 6, 8, 9, 5]
n = len(arr)
print('Minimum number of jumps to reach', 'end is', minJumps(arr, 0, n - 1))

# Expected output:
Minimum number of jumps to reach end is 4
# count of valid arrays of size p with elements in range [ 1 , n ] having duplicates at least m distance apart | function to calculate the total number of arrays ; if the size of the array is p ; check if all elements are used atlease once ; check if this state is already calculated ; initialize the result ; use a number from the list of unused numbers ; there are ' unused ' number of favourable choices ; use a number from already present number atlease m distance back ; there are ' used ▁ - ▁ m ' number of favourable choices ; store the result ; function to solve the problem ; initialize dp table : dp [ i ] [ j ] [ j ] i : current position / index j : number of used elements k : number of unused elements ; 
def calculate(position, used, unused, P, M, dp):
    if (position == P):
        if unused == 0:
            return 1
        else:
            return 0
    if (dp[position][used][unused] != -1):
        return dp[position][used][unused]
    result = 0
    if (unused > 0):
        result += calculate(position + 1, used + 1,
                            unused - 1, P, M, dp) * unused
    if (used > M):
        result += calculate(position + 1, used, unused, P, M, dp) * (used - M)
    dp[position][used][unused] = result
    return dp[position][used][unused]


def solve(N, P, M):
    dp = [[[-1 for i in range(101)]for i in range(101)]for j in range(101)]
    return calculate(0, 0, N, P, M, dp)


if __name__ == '__main__':
    N = 2
    M = 0
    P = 3
    print(solve(N, P, M))

# Expected output:
6