giulio98/xlcost-single-prompt huggingface dataset:
# smallest value of x satisfying the condition x % a [ i ] = b [ i ] for two given arrays | python3 program for the above approach ; function to calculate modulo inverse of a w . r . t m using extended euclid algorithm ; base case ; perform extended euclid algorithm ; q is quotient ; m is remainder now , process same as euclid 's algorithm ; if x1 is negative ; make x1 positive ; function to implement chinese remainder theorem to find x ; stores the product of array elements ; traverse the array ; update product ; initialize the result ; apply the above formula ; function to calculate the product of all elements of the array a [ ] ; stores product of all array elements ; traverse the array ; return the product ; function to find the value of x that satisfies the given condition ; stores the required smallest value using chinese remainder theorem ; stores the product of all array elements ; the equation is y + k * m >= p therefore , calculate k = ceil ( ( p - y ) / m ) ; so , x = y + k * m ; print the resultant value of x ; 

import math


def inv(a, m):
    m0 = m
    x0 = 0
    x1 = 1
    if (m == 1):
        return 0
    while (a > 1):
        q = a // m
        t = m
        m = a % m
        a = t
        t = x0
        x0 = x1 - q * x0
        x1 = t
    if (x1 < 0):
        x1 += m0
    return x1


def findMinX(A, B, N):
    prod = 1
    for i in range(N):
        prod *= A[i]
    result = 0
    for i in range(N):
        pp = prod // A[i]
        result += B[i] * inv(pp, A[i]) * pp
    return result % prod


def product(a, n):
    ans = 1
    for i in range(n):
        ans *= a[i]
    return ans


def findSmallestInteger(A, B, P, n):
    Y = findMinX(A, B, n)
    M = product(A, n)
    K = math .ceil((P - Y) / M)
    X = Y + K * M
    print(X)


if __name__ == "__main__":
    A = [3, 4, 5]
    B = [2, 3, 1]
    n = len(A)
    P = 72
    findSmallestInteger(A, B, P, n)

# Expected output:
131
# minimum number of jumps required to sort the given array in ascending order | function to count minimum number of jumps required to sort the array ; stores minimum number of jumps ; stores distances of jumps ; stores the array elements with their starting indices ; push the pairs { arr [ i ] , i + 1 } into the vector of pairs vect ; update vect ; populate the array temp [ ] ; update temp [ arr [ i ] ] ; sort the vector in the ascending order ; jump till the previous index <= current index ; update vect [ i ] ; increment the number of jumps ; print the minimum number of jumps required ; 
def minJumps(arr, jump, N):
    jumps = 0
    temp = [0 for i in range(1000)]
    vect = []
    for i in range(N):
        vect .append([arr[i], i + 1])
    for i in range(N):
        temp[arr[i]] = jump[i]
    vect .sort(reverse=False)
    for i in range(N):
        while (vect[i][1] <= vect[i - 1][1]):
            vect[i] = [vect[i][0], vect[i][1] + temp[vect[i][0]]]
            jumps += 1
    print(jumps)


if __name__ == '__main__':
    arr = [3, 2, 1]
    jump = [1, 1, 1]
    N = len(arr)
    minJumps(arr, jump, N)

# Expected output:
6
# minimum number of basic logic gates required to realize given boolean expression | function to count the total number of gates required to realize the boolean expression s ; length of the string ; stores the count of total gates ; traverse the string ; and , or and not gate ; print the count of gates required ; 
def numberOfGates(s):
    N = len(s)
    ans = 0
    for i in range(len(s)):
        if (s[i] == '.' or s[i] == '+' or s[i] == '1'):
            ans += 1
    print(ans, end="")


if __name__ == "__main__":
    S = "(1-A).B+C"
    numberOfGates(S)

# Expected output:
3
# count pairs ( i , j ) from an array such that | arr [ i ] | and | arr [ j ] | both lies between | arr [ i ] | function to find pairs ( i , j ) such that | arr [ i ] | and | arr [ j ] | lies in between | arr [ i ] - arr [ j ] | and | arr [ i ] + arr [ j ] | ; calculate absolute value of all array elements ; sort the array ; stores the count of pairs ; traverse the array ; increment left ; add to the current count of pairs ; print the answer ; 
def findPairs(arr, N):
    for i in range(N):
        arr[i] = abs(arr[i])
    arr .sort()
    left = 0
    ans = 0
    for right in range(N):
        while (2 * arr[left] < arr[right]):
            left += 1
        ans += (right - left)
    print(ans)


if __name__ == "__main__":
    arr = [1, 3, 5, 7]
    N = len(arr)
    findPairs(arr, N)

# Expected output:
2
# calculate absolute difference between minimum and maximum sum of pairs in an array | python 3 program for the above approach ; function to find the difference between the maximum and minimum sum of a pair ( arr [ i ] , arr [ j ] ) from the array such that i < j and arr [ i ] < arr [ j ] ; stores the maximum from the suffix of the array ; set the last element ; traverse the remaining array ; update the maximum from suffix for the remaining indices ; stores the maximum sum of any pair ; calculate the maximum sum ; stores the maximum sum of any pair ; stores the minimum of suffixes from the given array ; set the last element ; traverse the remaining array ; update the maximum from suffix for the remaining indices ; calculate the minimum sum ; return the resultant difference ; 

import sys


def GetDiff(A, N):
    SuffMaxArr = [0 for i in range(N)]
    SuffMaxArr[N - 1] = A[N - 1]
    i = N - 2
    while (i >= 0):
        SuffMaxArr[i] = max(SuffMaxArr[i + 1], A[i + 1])
        i -= 1
    MaximumSum = -sys .maxsize - 1
    for i in range(N - 1):
        if (A[i] < SuffMaxArr[i]):
            MaximumSum = max(MaximumSum, A[i] + SuffMaxArr[i])
    MinimumSum = sys .maxsize
    SuffMinArr = [0 for i in range(N)]
    SuffMinArr[N - 1] = sys .maxsize
    i = N - 2
    while (i >= 0):
        SuffMinArr[i] = min(SuffMinArr[i + 1], A[i + 1])
        i -= 1
    for i in range(N - 1):
        if (A[i] < SuffMinArr[i]):
            MinimumSum = min(MinimumSum, A[i] + SuffMinArr[i])
    return abs(MaximumSum - MinimumSum)


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

# Expected output:
7
# minimum number of swaps required to make parity of array elements same as their indices | function to count the minimum number of swaps required to make the parity of array elements same as their indices ; stores count of even and odd array elements ; traverse the array ; check if indices and array elements are not of the same parity ; if index is even ; update even ; update odd ; condition for not possible ; otherwise ; 
def minimumSwaps(arr, N):
    even, odd = 0, 0
    for i in range(N):
        if (arr[i] % 2 != i % 2):
            if (i % 2 == 0):
                even += 1
            else:
                odd += 1
    if (even != odd):
        print(-1)
    else:
        print(even)


if __name__ == '__main__':
    arr = [3, 2, 7, 6]
    N = len(arr)
    minimumSwaps(arr, N)

# Expected output:
2
# smallest substring occurring only once in a given string | python3 program of the above approach ; function to find the smallest substring occurring only once ; stores all occurences ; generate all the substrings ; avoid multiple occurences ; append all substrings ; take into account all the substrings ; iterate over all unique substrings ; if frequency is 1 ; append into fresh list ; initialize a dictionary ; append the keys ; traverse the dictionary ; print the minimum of dictionary ; 

from collections import Counter


def smallestSubstring(a):
    a1 = []
    for i in range(len(a)):
        for j in range(i + 1, len(a)):
            if i != j:
                a1 .append(a[i:j + 1])
    a2 = Counter(a1)
    freshlist = []
    for i in a2:
        if a2[i] == 1:
            freshlist .append(i)
    dictionary = dict()
    for i in range(len(freshlist)):
        dictionary[freshlist[i]] = len(freshlist[i])
    newlist = []
    for i in dictionary:
        newlist .append(dictionary[i])
    return (min(newlist))


S = "ababaabba"
print(smallestSubstring(S))

# Expected output:
2
# minimize insertions required to make ratio of maximum and minimum of all pairs of adjacent array elements at most k | function to count the minimum number of insertions required ; stores the number of insertions required ; traverse the array ; store the minimum array element ; store the maximum array element ; checking condition ; increase current count ; return the count of insertions ; 
def mininsert(arr, K, N):
    ans = 0
    for i in range(N - 1):
        a = min(arr[i], arr[i + 1])
        b = max(arr[i], arr[i + 1])
        while (K * a < b):
            a *= K
            ans += 1
    return ans


arr = [2, 10, 25, 21]
K = 2
N = len(arr)
print(mininsert(arr, K, N))

# Expected output:
3
# sum of numbers formed by consecutive digits present in a given string | function to calculate the sum of numbers formed by consecutive sequences of digits present in the string ; stores consecutive digits present in the string ; stores the sum ; iterate over characters of the input string ; if current character is a digit ; append current digit to curr ; add curr to sum ; reset curr ; 
def sumOfDigits(s):
    curr = 0
    ret = 0
    for ch in s:
        if (ord(ch) >= 48 and ord(ch) <= 57):
            curr = curr * 10 + ord(ch) - ord('0')
        else:
            ret += curr
            curr = 0
    ret += curr
    return ret


S = "11aa32bbb5"
print(sumOfDigits(S))

# Expected output:
48
# find a triplet ( i , j , k ) from an array such that i < j < k and arr [ i ] < arr [ j ] > arr [ k ] | function to find a triplet such that i < j < k and arr [ i ] < arr [ j ] and arr [ j ] > arr [ k ] ; traverse the array ; condition to satisfy for the resultant triplet ; otherwise , triplet doesn 't exist ; 
def print_triplet(arr, n):
    for i in range(1, n - 1):
        if (arr[i - 1] < arr[i] and arr[i] > arr[i + 1]):
            print(i - 1, i, i + 1)
            return
    print(-1)


if __name__ == "__main__":
    arr = [4, 3, 5, 2, 1, 6]
    N = len(arr)
    print_triplet(arr, N)

# Expected output:
1 2 3
# check if an array element is concatenation of two elements from another array | python3 program for the above approach ; function to find elements present in the array b [ ] which are concatenation of any pair of elements in the array a [ ] ; stores if there doesn 't any such  element in the array brr[] ; stored the size of both the arrays ; store the presence of an element of array a [ ] ; traverse the array a [ ] ; traverse the array b [ ] ; traverse over all possible concatenations of b [ i ] ; update right and left parts ; check if both left and right parts are present in a [ ] ; 

from collections import defaultdict


def findConcatenatedNumbers(a, b):
    ans = True
    n1 = len(a)
    n2 = len(b)
    cnt = defaultdict(int)
    for i in range(n1):
        cnt[a[i]] = 1
    for i in range(n2):
        left = b[i]
        right = 0
        mul = 1
        while (left > 9):
            right += (left % 10) * mul
            left //= 10
            mul *= 10
            if (cnt[left] == 1 and cnt[right] == 1):
                ans = False
                print(b[i], end=" ")
    if (ans):
        print("-1")


if __name__ == "__main__":
    a = [2, 34, 4, 5]
    b = [26, 24, 345, 4, 22]
    findConcatenatedNumbers(a, b)

# Expected output:
24 345 22
# number of subarrays having even product | function to count subarrays with even product ; stores count of subarrays with even product ; traverse the array ; initialize product ; update product of the subarray ; print total count of subarrays ; 
def evenproduct(arr, length):
    count = 0
    for i in range(length + 1):
        product = 1
        for j in range(i, length + 1):
            product *= arr[j]
            if (product % 2 == 0):
                count += 1
    print(count)


if __name__ == "__main__":
    arr = [7, 5, 4, 9]
    length = len(arr) - 1
    evenproduct(arr, length)

# Expected output:
6
# count pairs of nodes having minimum distance between them equal to the difference of their distances from root | stores the count of pairs ; store the adjacency list of the connecting vertex ; function for theto perform dfs traversal of the given tree ; traverse the adjacency list of the current node u ; if the current node is the parent node ; add number of ancestors , which is same as depth of the node ; function for dfs traversal of the given tree ; print result ; function to find the count of pairs such that the minimum distance between them is equal to the difference between distance of the nodes from root node ; add edges to adj [ ] ; 

ans = 0
adj = [[]for i in range(10 ** 5 + 1)]


def dfsUtil(u, par, depth):
    global adj, ans
    for it in adj[u]:
        if (it != par):
            dfsUtil(it, u, depth + 1)
    ans += depth


def dfs(u, par, depth):
    global ans
    dfsUtil(u, par, depth)
    print(ans)


def countPairs(edges):
    global adj
    for i in range(len(edges)):
        u = edges[i][0]
        v = edges[i][1]
        adj[u].append(v)
        adj[v].append(u)
    dfs(1, 1, 1)


if __name__ == '__main__':
    edges = [[1, 2], [1, 3], [2, 4]]
    countPairs(edges)

# Expected output:
8
# number from a given range that requires kth smallest number of steps to get reduced to 1 | python3 program for the above approach ; function to count the number of steps required to reduce val to 1 by the given operations ; base case ; if val is even , divide by 2 ; otherwise , multiply it by 3 and increment by 1 ; function to find kth smallest count of steps required for numbers from the range [ l , r ] ; stores numbers and their respective count of steps ; count the number of steps for anumbers from the range [ l , r ] ; insert in the vector ; sort the vector in ascending order w . r . t . to power value ; print the k - th smallest number ; 

v = [-1] * (1000000)


def power_value(val):
    if (val == 1):
        return 0
    if (val % 2 == 0):
        v[val] = power_value(val // 2) + 1
        return v[val]
    else:
        temp = val * 3
        temp += 1
        v[val] = power_value(temp) + 1
        return v[val]


def getKthNumber(l, r, k):
    ans = []
    for i in range(l, r + 1):
        if (v[i] == -1):
            power_value(i)
    j = 0
    for i in range(l, r + 1):
        ans .append([v[i], i])
        j += 1
    ans = sorted(ans)
    print(ans[k - 1][1])


if __name__ == '__main__':
    L, R, K = 7, 10, 4
    getKthNumber(L, R, K)

# Expected output:
9
# sum of decimal equivalents of binary node values in each level of a binary tree | structure of a tree node ; function to convert binary number to its equivalent decimal value ; function to calculate sum of decimal equivalent of binary numbers of node values present at each level ; push root node into queue ; connect nodes at the same level to form a binary number ; stores the front element of the queue ; append the value of the current node to eachlvl ; insert the left child to queue , if its not null ; insert the right child to queue , if its not null ; decrement length by one ; add decimal equivalent of the binary number formed on the current level to ans ; finally print ans ; 

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


def convertBinaryToDecimal(arr):
    ans = 0
    for i in arr:
        ans = (ans << 1) | i
    return ans


def decimalEquilvalentAtEachLevel(root):
    ans = 0
    que = [root]
    while True:
        length = len(que)
        if not length:
            break
        eachLvl = []
        while length:
            temp = que .pop(0)
            eachLvl .append(temp .val)
            if temp .left:
                que .append(temp .left)
            if temp .right:
                que .append(temp .right)
            length -= 1
        ans += convertBinaryToDecimal(eachLvl)
    print(ans)


root = TreeNode(0)
root .left = TreeNode(1)
root .right = TreeNode(0)
root .left .left = TreeNode(0)
root .left .right = TreeNode(1)
root .right .left = TreeNode(1)
root .right .right = TreeNode(1)
decimalEquilvalentAtEachLevel(root)

# Expected output:
9
# minimize increments required to make differences between all pairs of array elements even | function to find the minimum increments required to difference between all pairs of array elements even ; store the count of odd and even numbers ; traverse the array ; increment evencnt by 1 ; increment evecnt by 1 ; prthe minimum of oddcnt and evecnt ; 
def minimumOperations(arr, N):
    oddCnt = 0
    evenCnt = 0
    for i in range(N):
        if (arr[i] % 2 == 0):
            evenCnt += 1
        else:
            oddCnt += 1
    print(min(oddCnt, evenCnt))


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

# Expected output:
1
# minimum increments required to make array elements alternately even and odd | function to find the minimum number of increments required to make the array even - odd alternately or vice - versa ; store the minimum number of increments required ; traverse the array arr [ ] ; increment foreven if even element is present at an odd index ; increment foreven if odd element is present at an even index ; return the minimum number of increments ; 
def minIncr(arr):
    forEven = 0
    for i in range(len(arr)):
        if i % 2:
            if not arr[i] % 2:
                forEven += 1
        else:
            if arr[i] % 2:
                forEven += 1
    return min(forEven, len(arr) - forEven)


arr = [1, 4, 6, 8, 9, 5]
print(minIncr(arr))

# Expected output:
2
# queries to find the minimum array sum possible by removing elements from either end | function to find the minimum sum for each query after removing element from either ends till each value q [ i ] ; stores the prefix sum from both the ends of the array ; traverse the array from front ; insert it into the map m1 ; traverse the array in reverse ; insert it into the map m2 ; traverse the query array ; print the minimum of the two values as the answer ; 
def minOperations(arr, N, Q, M):
    m1 = {}
    m2 = {}
    front = 0
    rear = 0
    for i in range(N):
        front += arr[i]
        m1[arr[i]] = front
    for i in range(N - 1, -1, -1):
        rear += arr[i]
        m2[arr[i]] = rear
    for i in range(M):
        print(min(m1[Q[i]], m2[Q[i]]), end=" ")


arr = [2, 3, 6, 7, 4, 5, 1]
N = len(arr)
Q = [7, 6]
M = len(Q)
minOperations(arr, N, Q, M)

# Expected output:
17 11
# check if a string contains an anagram of another string as its substring | function to check if string s2 contains anagram of the string s1 as its substring ; stores frequencies of characters in substrings of s2 ; stores frequencies of characters in s1 ; if length of s2 exceeds length of s1 ; store frequencies of characters in first substring of length s1len in string s2 ; perform sliding window technique ; if hashmaps are found to be identical for any substring ; 
def checkAnagram(s1, s2):
    s2hash = [0 for i in range(26)]
    s1hash = [0 for i in range(26)]
    s1len = len(s1)
    s2len = len(s2)
    if (s1len > s2len):
        return False
    left = 0
    right = 0
    while (right < s1len):
        s1hash[ord(s1[right]) - 97] += 1
        s2hash[ord(s2[right]) - 97] += 1
        right += 1
    right -= 1
    while (right < s2len):
        if (s1hash == s2hash):
            return True
        right += 1
        if (right != s2len):
            s2hash[ord(s2[right]) - 97] += 1
        s2hash[ord(s2[left]) - 97] -= 1
        left += 1
    return False


if __name__ == '__main__':
    s1 = "ab"
    s2 = "bbpobac"
    if (checkAnagram(s1, s2)):
        print("YES")
    else:
        print("No")

# Expected output:
YES
# maximum number of intervals that an interval can intersect | function to count the maximum number of intervals that an interval can intersect ; store the required answer ; traverse all the intervals ; store the number of intersecting intervals ; iterate in the range [ 0 , n - 1 ] ; check if jth interval lies outside the ith interval ; update the overall maximum ; print the answer ; 
def findMaxIntervals(v, n):
    maxi = 0
    for i in range(n):
        c = n
        for j in range(n):
            if (v[i][1] < v[j][0] or v[i][0] > v[j][1]):
                c -= 1
        maxi = max(c, maxi)
    print(maxi)


arr = []
arr .append((1, 2))
arr .append((3, 4))
arr .append((2, 5))
N = len(arr)
findMaxIntervals(arr, N)

# Expected output:
3
# check if all disks can be placed at a single rod based on given conditions | function to check if it is possible to move all disks to a single rod ; stores if it is possible to move all disks to a single rod ; traverse the array ; if i - th element is smaller than both its adjacent elements ; if flag is true ; otherwise ; 
def check(a, n):
    flag = 0
    for i in range(1, n - 1):
        if (a[i + 1] > a[i] and a[i] < a[i - 1]):
            flag = 1
    if (flag != 0):
        return False
    else:
        return True


arr = [1, 3, 5, 2]
N = len(arr)
if (check(arr, N) != 0):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# smallest positive integer that does not divide any elements of the given array | function to find the smallest number which doesn 't divides any integer in the given array arr[] ; traverse the array arr [ ] ; maximum array element ; initialize variable ; traverse from 2 to max ; stores if any such integer is found or not ; if any array element is divisible by j ; smallest integer ; prthe answer ; 
def smallestNumber(arr, lenn):
    maxi = 0
    for i in range(lenn):
        maxi = max(maxi, arr[i])
    ans = -1
    for i in range(2, maxi + 2):
        flag = True
        for j in range(lenn):
            if (arr[j] % i == 0):
                flag = False
                break
        if (flag):
            ans = i
            break
    print(ans)


if __name__ == '__main__':
    arr = [3, 2, 6, 9, 2]
    N = len(arr)
    smallestNumber(arr, N)

# Expected output:
4
# find the duplicate characters in a string in o ( 1 ) space | function to find duplicate characters in str1ing without using any additional data str1ucture ; check if ( i + ' a ' ) is present in str1 at least once or not . ; check if ( i + ' a ' ) is present in str1 at least twice or not . ; iterate over the characters of the str1ing str1 ; if str1 [ i ] has already occurred in str1 ; set ( str1 [ i ] - ' a ' ) - th bit of second ; set ( str1 [ i ] - ' a ' ) - th bit of second ; iterate over the range [ 0 , 25 ] ; if i - th bit of both first and second is set ; 
def findDuplicate(str1, N):
    first = 0
    second = 0
    for i in range(N):
        if (first & (1 << (ord(str1[i]) - 97))):
            second = second | (1 << (ord(str1[i]) - 97))
        else:
            first = first | (1 << (ord(str1[i]) - 97))
    for i in range(26):
        if ((first & (1 << i)) and (second & (1 << i))):
            print(chr(i + 97), end=" ")


if __name__ == '__main__':
    str1 = "geeksforgeeks"
    N = len(str1)
    findDuplicate(str1, N)

# Expected output:
e g k s
# minimize insertions required to make all characters of a given string equal | function to calculate the minimum number of operations required to make all characters of the string same ; stores count of operations ; traverse the string ; check if adjacent characters are same or not ; increment count ; prthe count obtained ; 
def minOperations(S):
    count = 0
    for i in range(1, len(S)):
        if (S[i] != S[i - 1]):
            count += 1
    print(count)


if __name__ == '__main__':
    S = "0101010101"
    minOperations(S)

# Expected output:
9