giulio98/xlcost-single-prompt huggingface dataset:
# queries to find the minimum index in a range [ l , r ] having at least value x with updates | python 3 program for the above approach ; stores nodes value of the tree ; function to build segment tree ; base case ; find the value of mid ; update for left subtree ; update for right subtree ; update the value at the current index ; function for finding the index of the first element at least x ; if current range does not lie in query range ; if current range is inside of query range ; maximum value in this range is less than x ; finding index of first value in this range ; update the value of the minimum index ; find mid of the current range ; left subtree ; if it does not lie in left subtree ; function for updating segment tree ; update the value , we reached leaf node ; find the mid ; if pos lies in the left subtree ; pos lies in the right subtree ; update the maximum value in the range ; function to print the answer for the given queries ; build segment tree ; find index of first value atleast 2 in range [ 0 , n - 1 ] ; update value at index 2 to 5 ; find index of first value atleast 4 in range [ 0 , n - 1 ] ; find index of first value atleast 0 in range [ 0 , n - 1 ] ; 

maxN = 100
Tree = [0 for i in range(4 * maxN)]


def build(arr, index, s, e):
    global Tree
    global max
    if (s == e):
        Tree[index] = arr[s]
    else:
        m = (s + e) // 2
        build(arr, 2 * index, s, m)
        build(arr, 2 * index + 1, m + 1, e)
        Tree[index] = max(Tree[2 * index], Tree[2 * index + 1])


def atleast_x(index, s, e, ql, qr, x):
    global Tree
    global max
    if (ql > e or qr < s):
        return -1
    if (s <= ql and e <= qr):
        if (Tree[index] < x):
            return -1
        while (s != e):
            m = (s + e) // 2
            if (Tree[2 * index] >= x):
                e = m
                index = 2 * index
            else:
                s = m + 1
                index = 2 * index + 1
        return s
    m = (s + e) // 2
    val = atleast_x(2 * index, s, m, ql, qr, x)
    if (val != -1):
        return val
    return atleast_x(2 * index + 1, m + 1, e, ql, qr, x)


def update(index, s, e, new_val, pos):
    global Tree
    global max
    if (s == e):
        Tree[index] = new_val
    else:
        m = (s + e) // 2
        if (pos <= m):
            update(2 * index, s, m, new_val, pos)
        else:
            update(2 * index + 1, m + 1, e, new_val, pos)
        Tree[index] = max(Tree[2 * index], Tree[2 * index + 1])


def printAnswer(arr, n):
    global Tree
    global max
    build(arr, 1, 0, n - 1)
    print(atleast_x(1, 0, n - 1, 0, n - 1, 2))
    arr[2] = 5
    update(1, 0, n - 1, 5, 2)
    print(atleast_x(1, 0, n - 1, 0, n - 1, 4))
    print(atleast_x(1, 0, n - 1, 0, n - 1, 0))


if __name__ == '__main__':
    arr = [1, 3, 2, 4, 6]
    N = len(arr)
    printAnswer(arr, N)

# Expected output:
1
2
0
# smallest subtree with all the deepest nodes | structure of a node ; function to return depth of the tree from root ; if current node is a leaf node ; function to find the root of the smallest subtree consisting of all deepest nodes ; stores height of left subtree ; stores height of right subtree ; if height of left subtree exceeds that of the right subtree ; traverse left subtree ; if height of right subtree exceeds that of the left subtree ; otherwise ; return current node ; 

class TreeNode:
    def __init__(self, x):
        self .val = x
        self .left = None
        self .right = None


def find_ht(root):
    if (not root):
        return 0
    if (root .left is None and root .right is None):
        return 1
    return max(find_ht(root .left), find_ht(root .right)) + 1


def find_node(root):
    global req_node
    if (not root):
        return
    left_ht = find_ht(root .left)
    right_ht = find_ht(root .right)
    if (left_ht > right_ht):
        find_node(root .left)
    elif (right_ht > left_ht):
        find_node(root .right)
    else:
        req_node = root
        return


if __name__ == '__main__':
    root = TreeNode(1)
    root .left = TreeNode(2)
    root .right = TreeNode(3)
    req_node = None
    find_node(root)
    print(req_node .val)

# Expected output:
1
# maximum even numbers present in any subarray of size k | function to find the maximum count of even numbers from all the subarrays of size k ; stores the maximum count of even numbers from all the subarrays of size k ; generate all subarrays of size k ; store count of even numbers in current subarray of size k ; traverse the current subarray ; if current element is an even number ; update the answer ; return answer ; 
def maxEvenIntegers(arr, N, K):
    ans = 0
    for i in range(N - K + 1):
        cnt = 0
        for j in range(0, K):
            if arr[i + j] % 2 == 0:
                cnt += 1
        ans = max(cnt, ans)
    return ans


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

# Expected output:
2
# count maximum concatenation of pairs from given array that are divisible by 3 | function to count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; stores count of array elements whose remainder is 0 by taking modulo by 3 ; stores count of array elements whose remainder is 1 by taking modulo by 3 ; stores count of array elements whose remainder is 2 by taking modulo by 3 ; traverse the array ; stores sum of digits of arr [ i ] ; update digitsum ; if remainder of digitsum by by taking modulo 3 is 0 ; update rem0 ; if remainder of digitsum by by taking modulo 3 is 1 ; update rem1 ; update rem2 ; 
def countDiv(arr):
    rem0 = 0
    rem1 = 0
    rem2 = 0
    for i in arr:
        digitSum = 0
        for digit in str(i):
            digitSum += int(digit)
        if digitSum % 3 == 0:
            rem0 += 1
        elif digitSum % 3 == 1:
            rem1 += 1
        else:
            rem2 += 1
    return (rem0 // 2 + min(rem1, rem2))


arr = [5, 3, 2, 8, 7]
print(countDiv(arr))

# Expected output:
1
# maximum sum subsequence | function to print the maximum non - emepty subsequence sum ; stores the maximum non - emepty subsequence sum in an array ; stores the largest element in the array ; traverse the array ; if a [ i ] is greater than 0 ; update sum ; 
def MaxNonEmpSubSeq(a, n):
    sum = 0
    maxm = max(a)
    if (maxm <= 0):
        return maxm
    for i in range(n):
        if (a[i] > 0):
            sum += a[i]
    return sum


if __name__ == '__main__':
    arr = [-2, 11, -4, 2, -3, -10]
    N = len(arr)
    print(MaxNonEmpSubSeq(arr, N))

# Expected output:
13
# count numbers up to n having kth bit set | function to return the count of number of 1 's at ith bit in a range [1, n - 1] ; store count till nearest power of 2 less than n ; if k - th bit is set in n ; add to result the nearest power of 2 less than n ; return result ; 
def getcount(n, k):
    res = (n >> (k + 1)) << k
    if ((n >> k) & 1):
        res += n & ((1 << k) - 1)
    return res


if __name__ == '__main__':
    N = 14
    K = 2
    print(getcount(N + 1, K))

# Expected output:
7
# check if a string can be split into two substrings such that one substring is a substring of the other | function to check if a can be divided into two substrings such that one subis subof the other ; store the last character of s ; traverse the characters at indices [ 0 , n - 2 ] ; check if the current character is equal to the last character ; if true , set f = 1 ; break out of the loop ; 
def splitString(S, N):
    c = S[N - 1]
    f = 0
    for i in range(N - 1):
        if (S[i] == c):
            f = 1
            break
    if (f):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    S = "abcdab"
    N = len(S)
    splitString(S, N)

# Expected output:
Yes
# find the light bulb with maximum glowing time | python3 program for the above approach ; function to find the bulb having maximum glow ; initialize variables ; traverse the array consisting of glowing time of the bulbs ; for 1 st bulb ; calculate the glowing time ; update the maximum glow ; find lexicographically largest bulb ; bulb with maximum time ; return the resultant bulb ; 

import sys
INT_MIN = (sys .maxsize - 1)


def longestLastingBulb(onTime, s):
    n = len(onTime)
    maxDur = INT_MIN
    maxPos = INT_MIN
    currentDiff = 0
    for i in range(n):
        if (i == 0):
            currentDiff = onTime[i]
            maxDur = currentDiff
            maxPos = i
        else:
            currentDiff = onTime[i] - onTime[i - 1]
            if (maxDur < currentDiff):
                maxDur = currentDiff
                maxPos = i
            else:
                if (maxDur == currentDiff):
                    one = s[i]
                    two = s[maxPos]
                    if (one > two):
                        maxDur = currentDiff
                        maxPos = i
    ans = s[maxPos]
    return ans


if __name__ == "__main__":
    S = "spuda"
    arr = [12, 23, 36, 46, 62]
    print(longestLastingBulb(arr, S))

# Expected output:
a
# find a pair of intersecting ranges from a given array | function to find a pair of intersecting ranges ; stores ending po of every range ; stores the maximum ending poobtained ; iterate from 0 to n - 1 ; starting point of the current range ; end point of the current range ; push pairs into tup ; sort the tup vector ; iterate over the ranges ; if starting points are equal ; prthe indices of the intersecting ranges ; if no such pair of segments exist ; 
def findIntersectingRange(tup, N, ranges):
    curr = 0
    currPos = 0
    for i in range(N):
        x = ranges[i][0]
        y = ranges[i][1]
        tup .append([[x, y], i + 1])
    tup = sorted(tup)
    curr = tup[0][0][1]
    currPos = tup[0][1]
    for i in range(1, N):
        Q = tup[i - 1][0][0]
        R = tup[i][0][0]
        if (Q == R):
            if (tup[i - 1][0][1] < tup[i][0][1]):
                print(tup[i - 1][1], tup[i][1])
            else:
                print(tup[i][1], tup[i - 1][1])
            return
        T = tup[i][0][1]
        if (T <= curr):
            print(tup[i][1], currPos)
            return
        else:
            curr = T
            currPos = tup[i][1]
    print("-1 -1")


if __name__ == '__main__':
    N = 5
    ranges = [[1, 5], [2, 10], [3, 10], [2, 2], [2, 15]]
    findIntersectingRange([], N, ranges)

# Expected output:
4 1
# find the next greater element in a circular array | set 2 | function to find the nge for the given circular array arr [ ] ; create stack list ; initialize nge [ ] array to - 1 ; traverse the array ; if stack is not empty and current element is greater than top element of the stack ; assign next greater element for the top element of the stack ; pop the top element of the stack ; print the nge [ ] array ; 
def printNGE(arr, n):
    s = []
    nge = [-1] * n
    i = 0
    while (i < 2 * n):
        while (len(s) != 0 and arr[i % n] > arr[s[-1]]):
            nge[s[-1]] = arr[i % n]
            s .pop()
        s .append(i % n)
        i += 1
    for i in range(n):
        print(nge[i], end=" ")


if __name__ == "__main__":
    arr = [4, -2, 5, 8]
    N = len(arr)
    printNGE(arr, N)

# Expected output:
5 5 8 -1
# count array elements whose product of digits is a composite number | python3 program for the above approach ; function to generate prime numbers using sieve of eratosthenes ; set 0 and 1 as non - prime ; if p is a prime ; set all multiples of p as non - prime ; function to calculate the product of digits of the given number ; stores the product of digits ; extract digits and add to the sum ; return the product of its digits ; function to print number of distinct values with digit product as composite ; initialize set ; initialize boolean array ; pre - compute primes ; traverse array ; of the current array element ; if product of digits is less than or equal to 1 ; if product of digits is not a prime ; print the answer ; 

from math import sqrt
N = 100005


def SieveOfEratosthenes(prime, p_size):
    prime[0] = False
    prime[1] = False
    for p in range(2, int(sqrt(p_size)), 1):
        if (prime[p]):
            for i in range(p * 2, p_size + 1, p):
                prime[i] = False


def digitProduct(number):
    res = 1
    while (number > 0):
        res *= (number % 10)
        number //= 10
    return res


def DistinctCompositeDigitProduct(arr, n):
    output = set()
    prime = [True for i in range(N + 1)]
    SieveOfEratosthenes(prime, N)
    for i in range(n):
        ans = digitProduct(arr[i])
        if (ans <= 1):
            continue
        if (prime[ans] == False):
            output .add(ans)
    print(len(output))


if __name__ == '__main__':
    arr = [13, 55, 7, 13, 11, 71, 233, 233, 144, 89]
    n = len(arr)
    DistinctCompositeDigitProduct(arr, n)

# Expected output:
4
# count pairs from a given range whose sum is a prime number in that range | python program to implement the above approach ; function to find all prime numbers in range [ 1 , lmt ] using sieve of eratosthenes ; segmentedsieve [ i ] : stores if i is a prime number ( true ) or not ( false ) ; set 0 and 1 as non - prime ; iterate over the range [ 2 , lmt ] ; if i is a prime number ; append i into prime ; set all multiple of i non - prime ; update sieve [ j ] ; function to find all the prime numbers in the range [ low , high ] ; stores square root of high + 1 ; stores all the prime numbers in the range [ 1 , lmt ] ; find all the prime numbers in the range [ 1 , lmt ] ; stores count of elements in the range [ low , high ] ; segmentedsieve [ i ] : check if ( i - low ) is a prime number or not ; traverse the array prime [ ] ; store smallest multiple of prime [ i ] in the range [ low , high ] ; if lowlim is less than low ; update lowlim ; iterate over all multiples of prime [ i ] ; if j not equal to prime [ i ] ; update segmentedsieve [ j - low ] ; function to count the number of pairs in the range [ l , r ] whose sum is a prime number in the range [ l , r ] ; segmentedsieve [ i ] : check if ( i - l ) is a prime number or not ; stores count of pairs whose sum of elements is a prime and in range [ l , r ] ; iterate over [ l , r ] ; if ( i - l ) is a prime ; update cntpairs ; 

import math


def simpleSieve(lmt, prime):
    Sieve = [True] * (lmt + 1)
    Sieve[0] = Sieve[1] = False
    for i in range(2, lmt + 1):
        if (Sieve[i]):
            prime .append(i)
            for j in range(i * i, int(math .sqrt(lmt)) + 1, i):
                Sieve[j] = false
    return prime


def SegmentedSieveFn(low, high):
    lmt = int(math .sqrt(high)) + 1
    prime = []
    prime = simpleSieve(lmt, prime)
    n = high - low + 1
    segmentedSieve = [True] * (n + 1)
    for i in range(0, len(prime)):
        lowLim = int(low // prime[i]) * prime[i]
        if (lowLim < low):
            lowLim += prime[i]
            for j in range(lowLim, high + 1, prime[i]):
                if (j != prime[i]):
                    segmentedSieve[j - low] = False
    return segmentedSieve


def countPairsWhoseSumPrimeL_R(L, R):
    segmentedSieve = SegmentedSieveFn(L, R)
    cntPairs = 0
    for i in range(L, R + 1):
        if (segmentedSieve[i - L]):
            cntPairs += i / 2
    return cntPairs


if __name__ == '__main__':
    L = 1
    R = 5
    print(countPairsWhoseSumPrimeL_R(L, R))

# Expected output:
5.5
# lexicographically smallest permutation of a string that can be reduced to length k by removing k | function to count the number of zeroes present in the string ; traverse the string ; return the count ; function to rearrange the string s . t the string can be reduced to a length k as per the given rules ; distribute the count of 0 s and 1 s in segment of length 2 k ; store string that are initially have formed lexicographically smallest 2 k length substring ; store the lexicographically smallest string of length n that satisfy the condition ; insert temp_str into final_str ( n / 2 k ) times and add ( n % 2 k ) characters of temp_str at end ; return the final string ; function to reduce the string to length k that follows the given conditions ; if the string contains either 0 s or 1 s then it always be reduced into a k length string ; if the string contains only 0 s 1 s then it always reduces to a k length string ; if k = 1 ; check whether the given string is k reducing string or not ; otherwise recursively find the string ; 
def count_zeroes(n, str):
    cnt = 0
    for i in range(0, len(str)):
        if (str[i] == '0'):
            cnt += 1
    return cnt


def kReducingStringUtil(n, k, str, no_of_zeroes):
    zeroes_in_2k = (((no_of_zeroes) * (2 * k)) // n)
    ones_in_2k = 2 * k - zeroes_in_2k
    temp_str = ""
    for i in range(0, (zeroes_in_2k) // 2):
        temp_str += '0'
    for i in range(0, (ones_in_2k)):
        temp_str += '1'
    for i in range(0, (zeroes_in_2k) // 2):
        temp_str += '0'
    final_str = ""
    for i in range(0, n // (2 * k)):
        final_str += (temp_str)
    for i in range(0, n % (2 * k)):
        final_str += (temp_str[i])
    return final_str


def kReducingString(n, k, str):
    no_of_zeroes = count_zeroes(n, str)
    no_of_ones = n - no_of_zeroes
    if (no_of_zeroes == 0 or no_of_zeroes == n):
        return str
    if (k == 1):
        if (no_of_zeroes == 0 or no_of_zeroes == n):
            return str
        else:
            return "Not Possible"
    check = 0
    for i in range((n // k), n, (n // k)):
        if (no_of_zeroes == i or no_of_ones == i):
            check = 1
            break
    if (check == 0):
        return "Not Possible"
    return kReducingStringUtil(n, k, str, no_of_zeroes)


if __name__ == '__main__':
    str = "0000100001100001"
    K = 4
    N = len(str)
    print(kReducingString(N, K, str))

# Expected output:
0001100000011000
# count quadruplets with sum k from given array | python3 program for the above approach ; function to return the number of quadruplets having the given sum ; initialize answer ; store the frequency of sum of first two elements ; traverse from 0 to n - 1 , where arr [ i ] is the 3 rd element ; all possible 4 th elements ; sum of last two element ; frequency of sum of first two elements ; store frequency of all possible sums of first two elements ; return the answer ; 

from collections import defaultdict


def countSum(a, n, sum):
    count = 0
    m = defaultdict(int)
    for i in range(n - 1):
        for j in range(i + 1, n):
            temp = a[i] + a[j]
            if (temp < sum):
                count += m[sum - temp]
        for j in range(i):
            temp = a[i] + a[j]
            if (temp < sum):
                m[temp] += 1
    return count


if __name__ == "__main__":
    arr = [4, 5, 3, 1, 2, 4]
    S = 13
    N = len(arr)
    print(countSum(arr, N, S))

# Expected output:
3
# count pairs whose product modulo 10 ^ 9 + 7 is equal to 1 | python3 program to implement the above approach ; iterative function to calculate ( x ^ y ) % mod ; initialize result ; update x if it exceeds mod ; if x is divisible by mod ; if y is odd ; multiply x with res ; y must be even now ; function to count number of pairs whose product modulo 1000000007 is 1 ; stores the count of desired pairs ; stores the frequencies of each array element ; traverse the array and update frequencies in hash ; calculate modular inverse of arr [ i ] under modulo 1000000007 ; update desired count of pairs ; if arr [ i ] and its modular inverse is equal under modulo mod ; updating count of desired pairs ; return the final count ; 

from collections import defaultdict
MOD = 1000000007


def modPower(x, y):
    res = 1
    x = x % MOD
    if (x == 0):
        return 0
    while (y > 0):
        if (y & 1):
            res = (res * x) % MOD
        y = y // 2
        x = (x * x) % MOD
    return res


def countPairs(arr, N):
    pairCount = 0
    hash1 = defaultdict(int)
    for i in range(N):
        hash1[arr[i]] += 1
    for i in range(N):
        modularInverse = modPower(arr[i], MOD - 2)
        pairCount += hash1[modularInverse]
        if (arr[i] == modularInverse):
            pairCount -= 1
    return pairCount // 2


if __name__ == "__main__":
    arr = [2, 236426, 280311812, 500000004]
    N = len(arr)
    print(countPairs(arr, N))

# Expected output:
2
# check if all subarrays contains at least one unique element | python3 program for the above approach ; function to check if all subarrays of array have at least one unique element ; stores frequency of subarray elements ; generate all subarrays ; insert first element in map ; update frequency of current subarray in the hashmap ; check if at least one element occurs once in current subarray ; if any subarray doesn 't  have unique element ; clear map for next subarray ; return yes if all subarray having at least 1 unique element ; 

from collections import defaultdict


def check(arr, n):
    hm = defaultdict(int)
    for i in range(n):
        hm[arr[i]] += 1
        for j in range(i + 1, n):
            hm[arr[j]] += 1
            flag = False
            for k in hm .values():
                if (k == 1):
                    flag = True
                    break
            if (not flag):
                return "No"
        hm .clear()
    return "Yes"


if __name__ == "__main__":
    arr = [1, 2, 1]
    N = len(arr)
    print(check(arr, N))

# Expected output:
Yes
# search insert position of k in a sorted array | function to find insert position of k ; lower and upper bounds ; traverse the search space ; if k is found ; return the insert position ; 
def find_index(arr, n, B):
    start = 0
    end = n - 1
    while start <= end:
        mid = (start + end) // 2
        if arr[mid] == K:
            return mid
        elif arr[mid] < K:
            start = mid + 1
        else:
            end = mid - 1
    return end + 1


arr = [1, 3, 5, 6]
n = len(arr)
K = 2
print(find_index(arr, n, K))

# Expected output:
1
# queries to find minimum swaps required to sort given array with updates | function to return the position of the given value using binary search ; return 0 if every value is greater than the given value ; return n - 1 if every value is smaller than the given value ; perform binary search ; iterate till start < end ; find the mid ; update start and end ; return the position of the given value ; function to return the number of make the array sorted ; index x to update ; increment value by y ; set newelement equals to x + y ; compute the new index ; print the minimum number of swaps ; 
def computePos(arr, n, value):
    if (value < arr[0]):
        return 0
    if (value > arr[n - 1]):
        return n - 1
    start = 0
    end = n - 1
    while (start < end):
        mid = (start + end + 1) // 2
        if (arr[mid] >= value):
            end = mid - 1
        else:
            start = mid
    return start


def countShift(arr, n, queries):
    for q in queries:
        index = q[0]
        update = q[1]
        newElement = arr[index] + update
        newIndex = computePos(arr, n, newElement)
        print(abs(newIndex - index), end=" ")


if __name__ == '__main__':
    arr = [2, 3, 4, 5, 6]
    N = len(arr)
    queries = [[0, -1], [4, -11]]
    countShift(arr, N, queries)

# Expected output:
0 4