giulio98/xlcost-single-prompt huggingface dataset:
# minimum and maximum node that lies in the path connecting two nodes in a binary tree | python3 implementation of the approach ; function to store the path from root node to given node of the tree in path vector and then returns true if the path exists otherwise false ; function to print the minimum and the maximum value present in the path connecting the given two nodes of the given binary tree ; to store the path from the root node to a ; to store the path from the root node to b ; to store the minimum and the maximum value in the path from lca to a ; to store the minimum and the maximum value in the path from lca to b ; if both a and b are present in the tree ; compare the paths to get the first different value ; find minimum and maximum value in the path from lca to a ; find minimum and maximum value in the path from lca to b ; minimum of min values in first path and second path ; maximum of max values in first path and second path ; if no path exists ; 

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


def FindPath(root, path, key):
    if root is None:
        return False
    path .append(root .data)
    if root .data == key:
        return True
    if (FindPath(root .left, path, key) or FindPath(root .right, path, key)):
        return True
    path .pop()
    return False


def minMaxNodeInPath(root, a, b):
    Path1 = []
    Path2 = []
    min1, max1 = float('inf'), float('-inf')
    min2, max2 = float('inf'), float('-inf')
    i, j = 0, 0
    if (FindPath(root, Path1, a) and FindPath(root, Path2, b)):
        while i < len(Path1) and i < len(Path2):
            if Path1[i] != Path2[i]:
                break
            i += 1
        i -= 1
        j = i
        while i < len(Path1):
            if min1 > Path1[i]:
                min1 = Path1[i]
            if max1 < Path1[i]:
                max1 = Path1[i]
            i += 1
        while j < len(Path2):
            if min2 > Path2[j]:
                min2 = Path2[j]
            if max2 < Path2[j]:
                max2 = Path2[j]
            j += 1
        print("Min =", min(min1, min2))
        print("Max =", max(max1, max2))
    else:
        print("Min=-1Max=-1")


if __name__ == "__main__":
    root = Node(20)
    root .left = Node(8)
    root .right = Node(22)
    root .left .left = Node(5)
    root .left .right = Node(3)
    root .right .left = Node(4)
    root .right .right = Node(25)
    root .left .right .left = Node(10)
    root .left .right .right = Node(14)
    a, b = 5, 14
    minMaxNodeInPath(root, a, b)

# Expected output:
Min = 3
Max = 14
# time complexity and space complexity | function to find a pair in the given array whose sum is equal to z ; iterate through all the pairs ; check if the sum of the pair ( a [ i ] , a [ j ] ) is equal to z ; 
def findPair(a, n, z):
    for i in range(n):
        for j in range(n):
            if (i != j and a[i] + a[j] == z):
                return True
    return False


a = [1, -2, 1, 0, 5]
z = 0
n = len(a)
if (findPair(a, n, z)):
    print("True")
else:
    print("False")

# Expected output:
False
# analysis of algorithms | big | function to print all possible pairs ; 
def printt(a, n):
    for i in range(n):
        for j in range(n):
            if (i != j):
                print(a[i], "", a[j])


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

# Expected output:
1  2
1  3
2  1
2  3
3  1
3  2
# maximum sum obtained by dividing array into several subarrays as per 
def maximumSum(arr, N):
    Sum = 0
    for i in range(1, N):
        if (arr[i] > arr[i - 1]):
            Sum += (arr[i] - arr[i - 1])
    return Sum


arr = [1, 5, 3]
N = len(arr)
print(maximumSum(arr, N))

# Expected output:
4
# the slowest sorting algorithms | function to implement stooge sort ; base case ; if first element is smaller than last element , swap them ; if there are more than 2 elements in the array ; recursively sort the first 2 / 3 elements ; recursively sort the last 2 / 3 elements ; recursively sort the first 2 / 3 elements again ; 
def stoogesort(arr, l, h):
    if (l >= h):
        return
    if (arr[l] > arr[h]):
        temp = arr[l]
        arr[l] = arr[h]
        arr[h] = temp
    if (h - l + 1 > 2):
        t = (h - l + 1) // 3
        stoogesort(arr, l, h - t)
        stoogesort(arr, l + t, h)
        stoogesort(arr, l, h - t)


arr = [2, 4, 5, 3, 1]
N = len(arr)
stoogesort(arr, 0, N - 1)
for i in range(N):
    print(arr[i], end=" ")

# Expected output:
1 2 3 4 5
# determine winner of the game by arranging balls in a row | function to find the winner of the game by arranging the balls in a row ; check if small balls are greater or equal to the large ones ; x can place balls therefore scores n - 1 ; condition if large balls are greater than small ; x can have m - 1 as a score since greater number of balls can only be adjacent ; compare the score ; 
def findWinner(n, m):
    X = 0
    Y = 0
    if (n >= m):
        X = n - 1
        Y = m
    else:
        X = m - 1
        Y = n
    if (X > Y):
        print("X")
    elif (Y > X):
        print("Y")
    else:
        print("-1")


if __name__ == '__main__':
    n = 3
    m = 1
    findWinner(n, m)

# Expected output:
X
# check if pascal 's triangle is possible with a complete layer by using numbers upto n | python3 program for the above approach ; function to check if pascaltriangle can be made by n integers ; find x ; if x is integer ; 

import math


def checkPascaltriangle(N):
    x = (math .sqrt(8 * N + 1) - 1) / 2
    if (math .ceil(x) - x == 0):
        print("Yes")
    else:
        print("No")


N = 10
checkPascaltriangle(N)

# Expected output:
Yes
# count subarrays having sum of elements at even and odd positions equal | function to count subarrays in which sum of elements at even and odd positions are equal ; initialize variables ; iterate over the array ; check if position is even then add to sum hen add it to sum ; else subtract it to sum ; increment the count if the sum equals 0 ; print the count of subarrays ; 
def countSubarrays(arr, n):
    count = 0
    for i in range(n):
        sum = 0
        for j in range(i, n):
            if ((j - i) % 2 == 0):
                sum += arr[j]
            else:
                sum -= arr[j]
            if (sum == 0):
                count += 1
    print(count)


if __name__ == '__main__':
    arr = [2, 4, 6, 4, 2]
    n = len(arr)
    countSubarrays(arr, n)

# Expected output:
2
# find position of non | function to find the count of placing non - attacking rooks on the n x n chessboard ; count of the non - attacking rooks ; printing lexographically smallest configuration ; 
def findCountRooks(row, col, n, k):
    res = n - k
    print(res)
    ri = 0
    ci = 0
    while (res > 0):
        while (ri < k and row[ri] == 1):
            ri += 1
        while (ci < k and col[ci] == 1):
            ci += 1
        print((ri + 1), "", (ci + 1))
        ri += 1
        ci += 1
        res -= 1


n = 4
k = 2
row = [1, 2]
col = [4, 2]
findCountRooks(row, col, n, k)

# Expected output:
2
2  1
3  2
# check if a large number is divisible by a number which is a power of 2 | python3 program for the above approach ; function to check divisibility ; calculate the number of digits in num ; check if the length of the string is less than the powerof2 then return false ; check if the powerof2 is 0 that means the given number is 1 and as every number is divisible by 1 so return true ; find the number which is formed by the last n digits of the string where n = powerof2 ; check if the number formed is divisible by input num or not ; 

from math import log2


def checkIfDivisible(string, num):
    powerOf2 = int(log2(num))
    if (len(string) < powerOf2):
        return False
    if (powerOf2 == 0):
        return True
    number = 0
    length = len(string)
    for i in range(length - powerOf2, length):
        number += ((ord(string[i]) - ord('0')) * (10 ** (powerOf2 - 1)))
        powerOf2 -= 1
    if (number % num):
        return False
    else:
        return True


if __name__ == "__main__":
    string = "213467756564"
    num = 4
    if (checkIfDivisible(string, num)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check if given permutation of 1 to n can be counted in clockwise or anticlockwise direction | python3 program to check clockwise or counterclockwise order in an array ; comparing the first and last value of array ; if the count is greater than 1 then it can 't be  represented in required order ; 
def check_order(arr):
    cnt = 0
    for i in range(len(arr) - 1):
        if (abs(arr[i + 1] - arr[i]) > 1):
            cnt += 1
    if (abs(arr[0] - arr[len(arr) - 1]) > 1):
        cnt += 1
    if (cnt > 1):
        return False
    return True


arr = [2, 3, 4, 5, 1]
if (check_order(arr)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# largest number m less than n such that xor of m and n is even | function to find the maximum possible value of m ; edge case ; m = n - 2 is maximum possible value ; 
def getM(n):
    if (n == 1):
        return -1
    else:
        return n - 2


n = 10
print(getM(n))

# Expected output:
8
# maximize profit in buying and selling stocks with rest condition | python3 program for the above problem ; if there is only one day for buying and selling no profit can be made ; array to store maxprofit by resting on given day ; array to store maxprofit by buying or resting on the given day ; array to store maxprofit by selling on given day ; initially there will 0 profit ; buying on 1 st day results in negative profit ; zero profit since selling before buying isn 't possible ; max of profit on ( i - 1 ) th day by resting and profit on ( i - 1 ) th day by selling . ; max of profit by resting on ith day and buying on ith day . ; max of profit by selling on ith day ; maxprofit ; 
def maxProfit(prices, n):
    if (n <= 1):
        return 0
    rest = [0] * n
    hold = [0] * n
    sold = [0] * n
    rest[0] = 0
    hold[0] = -prices[0]
    sold[0] = 0
    for i in range(1, n):
        rest[i] = max(rest[i - 1], sold[i - 1])
        hold[i] = max(hold[i - 1], rest[i - 1] - prices[i])
        sold[i] = hold[i - 1] + prices[i]
    return max(rest[n - 1], sold[n - 1])


price = [2, 4, 5, 0, 2]
n = len(price)
print(maxProfit(price, n))

# Expected output:
4
# count of subarrays of size k having at least one pair with absolute difference divisible by k | function to return the required number of subarrays ; return number of possible subarrays of length k ; 
def findSubarrays(arr, N, K):
    return N - K + 1


if __name__ == '__main__':
    arr = [1, 5, 3, 2, 17, 18]
    K = 4
    N = len(arr)
    print(findSubarrays(arr, N, K))

# Expected output:
3
# maximum length of subarray such that all elements are equal in the subarray | function to find the longest subarray with same element ; check if the elements are same then we can increment the length ; reinitialize j ; compare the maximum length e with j ; return max length ; 
def longest_subarray(arr, d):
    (i, j, e) = (0, 1, 0)
    for i in range(d - 1):
        if arr[i] == arr[i + 1]:
            j += 1
        else:
            j = 1
        if e < j:
            e = j
    return e


arr = [1, 2, 3, 4]
N = len(arr)
print(longest_subarray(arr, N))

# Expected output:
1
# print all strong numbers less than or equal to n | store the factorial of all the digits from [ 0 , 9 ] ; function to return true if number is strong or not ; converting n to string so that can easily access all it 's digit ; sum will store summation of factorial of all digits of a number n ; returns true of n is strong number ; function to print all strong number till n ; iterating from 1 to n ; checking if a number is strong then print it ; 

factorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]


def isStrong(N):
    num = str(N)
    sum = 0
    for i in range(len(num)):
        sum += factorial[ord(num[i]) - ord('0')]
    if sum == N:
        return True
    else:
        return False


def printStrongNumbers(N):
    for i in range(1, N + 1):
        if (isStrong(i)):
            print(i, end=" ")


if __name__ == "__main__":
    N = 1000
    printStrongNumbers(N)

# Expected output:
1 2 145
# count of pairs in a given range with sum of their product and sum equal to their concatenated number | function for counting pairs ; count possible values of y ; 
def countPairs(A, B):
    countY = 0
    countX = (B - A) + 1
    next_val = 9
    while (next_val <= B):
        if (next_val >= A):
            countY += 1
        next_val = next_val * 10 + 9
    return (countX * countY)


if __name__ == '__main__':
    A = 1
    B = 16
    print(countPairs(A, B))

# Expected output:
16
# minimum sprinklers required to water a rectangular park | function to find the minimum number sprinklers required to water the park . ; general requirements of sprinklers ; if m is odd then add one additional sprinklers ; 
def solve(N, M):
    ans = int((N) * int(M / 2))
    if (M % 2 == 1):
        ans += int((N + 1) / 2)
    print(ans)


N = 5
M = 3
solve(N, M)

# Expected output:
8
# queries to find frequencies of a string within specified substrings | python3 program to find frequency of a string k in a substring [ l , r ] in s ; store the frequency of string for each index ; compute and store frequencies for every index ; 

max_len = 100005
cnt = [0] * max_len


def precompute(s, K):
    n = len(s)
    for i in range(n - 1):
        cnt[i + 1] = cnt[i]
        if s[i:len(K) + i] == K:
            cnt[i + 1] += 1


if __name__ == "__main__":
    s = "ABCABCABABC"
    K = "ABC"
    precompute(s, K)
    Q = [[1, 6], [5, 11]]
    for it in Q:
        print(cnt[it[1] - 1] - cnt[it[0] - 1])

# Expected output:
2
1
# count of double prime numbers in a given range l to r | array to make sieve where arr [ i ] = 0 indicates non prime and arr [ i ] = 1 indicates prime ; array to find double prime ; function to find the number double prime numbers in range ; assume all numbers as prime ; check if the number is prime ; check for multiples of i ; make all multiples of ith prime as non - prime ; check if number at ith position is prime then increment count ; indicates count of numbers from 1 to i that are also prime and hence double prime ; if number is not a double prime ; finding cumulative sum ; 

arr = [0] * 1000001
dp = [0] * 1000001


def count():
    maxN = 1000000
    for i in range(0, maxN):
        arr[i] = 1
    arr[0] = 0
    arr[1] = 0
    i = 2
    while (i * i <= maxN):
        if (arr[i] == 1):
            for j in range(2 * i, maxN + 1, i):
                arr[j] = 0
        i += 1
    cnt = 0
    for i in range(0, maxN + 1):
        if (arr[i] == 1):
            cnt += 1
        if (arr[cnt] == 1):
            dp[i] = 1
        else:
            dp[i] = 0
    for i in range(0, maxN + 1):
        dp[i] += dp[i - 1]


L = 4
R = 12
count()
print(dp[R] - dp[L - 1])

# Expected output:
5
# count of ungrouped characters after dividing a string into k groups of distinct characters | python3 code to implement the above approach ; create array where index represents alphabets ; fill count of every alphabet to corresponding array index ; count for every element how much is exceeding from no . of groups then sum them ; print answer ; 
def findUngroupedElement(s, k):
    n = len(s)
    b = [0] * 26
    for i in range(n):
        p = s[i]
        b[ord(p) - ord('a')] += 1
    sum = 0
    for i in range(26):
        if (b[i] > k):
            sum += b[i] - k
    print(sum)


s = "stayinghomesaveslife"
k = 1
findUngroupedElement(s, k)

# Expected output:
6
# generate an array of given size with equal count and sum of odd and even numbers | function to find the array such that the array contains the same count of even and odd elements with equal sum of even and odd elements ; length of array which is not divisible by 4 is unable to form such array ; loop to find the resulted array containing the same count of even and odd elements ; find the total sum of even elements ; find the total sum of odd elements ; find the difference between the total sum of even and odd elements ; the difference will be added in the last odd element ; 
def findSolution(N):
    if (N % 4 != 0):
        print(-1)
    else:
        temp = 0
        sum_odd = 0
        sum_even = 0
        result = [0] * N
        for i in range(0, N, 2):
            temp += 2
            result[i + 1] = temp
            sum_even += result[i + 1]
            result[i] = temp - 1
            sum_odd += result[i]
        diff = sum_even - sum_odd
        result[N - 2] += diff
        for i in range(N):
            print(result[i], end=" ")
        print()


N = 8
findSolution(N)

# Expected output:
1 2 3 4 5 6 11 8
# number of ways to place two queens on a n * n chess | python3 implementation to find the number of ways to place two queens on the n * n chess board ; function to find number of valid positions for two queens in the n * n chess board ; 

import math


def possiblePositions(n):
    term1 = pow(n, 4)
    term2 = pow(n, 3)
    term3 = pow(n, 2)
    term4 = n / 3
    ans = ((math .ceil(term1)) / 2 - (math .ceil(5 * term2)) /
           3 + (math .ceil(3 * term3)) / 2 - term4)
    return ans


if __name__ == '__main__':
    n = 3
    ans = possiblePositions(n)
    print(int(ans))

# Expected output:
8
# group all co | function to group the mutually co - prime numbers into one group ; loop for the numbers less than the 4 ; integers 1 , 2 and 3 can be grouped into one group ; consecutive even and odd numbers ; 
def mutually_coprime(n):
    if (n <= 3):
        for j in range(1, n + 1):
            print(j, end=" ")
        print()
    else:
        print(1, 2, 3)
        for j in range(4, n, 2):
            print(j, (j + 1))
        if (n % 2 == 0):
            print(n)


if __name__ == "__main__":
    n = 9
    mutually_coprime(n)

# Expected output:
1 2 3
4 5
6 7
8 9
# maximum sum subset having equal number of positive and negative elements | function to find maximum sum subset with equal number of positive and negative elements ; loop to store the positive and negative elements in two different array ; sort both the array ; pointers starting from the highest elements ; find pairs having sum greater than zero ; 
def findMaxSum(arr, n):
    a = []
    b = []
    for i in range(n):
        if (arr[i] > 0):
            a .append(arr[i])
        elif (arr[i] < 0):
            b .append(arr[i])
    a .sort()
    b .sort()
    p = len(a) - 1
    q = len(b) - 1
    s = 0
    while (p >= 0 and q >= 0):
        if (a[p] + b[q] > 0):
            s = s + a[p] + b[q]
        else:
            break
        p = p - 1
        q = q - 1
    return s


arr1 = [1, -2, 3, 4, -5, 8]
n1 = len(arr1)
print(findMaxSum(arr1, n1))

# Expected output:
6
# print the nodes with a prime degree in given prufer sequence of a tree | function to create sieve to check primes ; false here indicates that it is not prime ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p , set them to non - prime ; function to print the nodes with prime degree in the tree whose prufer sequence is given ; hash - table to mark the degree of every node ; initially let all the degrees be 1 ; increase the count of the degree ; print the nodes with prime degree ; 
def SieveOfEratosthenes(prime, p_size):
    prime[0] = False
    prime[1] = False
    p = 2
    while (p * p <= p_size):
        if (prime[p]):
            for i in range(p * 2, p_size + 1, p):
                prime[i] = False
        p += 1


def PrimeDegreeNodes(prufer, n):
    nodes = n + 2
    prime = [True] * (nodes + 1)
    SieveOfEratosthenes(prime, nodes + 1)
    degree = [0] * (n + 2 + 1)
    for i in range(1, nodes + 1):
        degree[i] = 1
    for i in range(0, n):
        degree[prufer[i]] += 1
    for i in range(1, nodes + 1):
        if prime[degree[i]]:
            print(i, end=' ')


if __name__ == '__main__':
    a = [4, 1, 3, 4]
    n = len(a)
    PrimeDegreeNodes(a, n)

# Expected output:
1 3 4
# find k 'th smallest number such that a + b = a | b | function to find k 'th smallest number such that a + b = a | b ; res will store final answer ; skip when j ' th ▁ position ▁ ▁ has ▁ 1 ▁ in ▁ binary ▁ representation ▁ ▁ as ▁ in ▁ res , ▁ j ' th position will be 0. ; j 'th bit is set ; if i ' th ▁ bit ▁ of ▁ k ▁ is ▁ 1 ▁ ▁ and ▁ i ' th bit of j is 0 then set i 'th bit in res. ; proceed to next bit ; 
def kthSmallest(a, k):
    res = 0
    j = 0
    for i in range(32):
        while (j < 32 and (a & (1 << j))):
            j += 1
        if (k & (1 << i)):
            res |= (1 << j)
        j += 1
    return res


a = 5
k = 3
print(kthSmallest(a, k))

# Expected output:
10
# nodes with prime degree in an undirected graph | python3 implementation of the above approach ; to store prime numbers ; function to find the prime numbers till 10 ^ 5 ; traverse all multiple of i and make it false ; function to print the nodes having prime degree ; to store adjacency list of a graph ; make adjacency list ; to precompute prime numbers till 10 ^ 5 ; traverse each vertex ; find size of adjacency list ; if length of adj [ i ] is prime then print it ; 

n = 10005
Prime = [True for i in range(n + 1)]


def SieveOfEratosthenes():
    i = 2
    Prime[0] = Prime[1] = False
    while i * i <= 10005:
        if (Prime[i]):
            for j in range(2 * i, 10005):
                Prime[j] = False
        i += 1


def primeDegreeNodes(N, M, edges):
    Adj = [[]for i in range(N + 1)]
    for i in range(M):
        x = edges[i][0]
        y = edges[i][1]
        Adj[x].append(y)
        Adj[y].append(x)
    SieveOfEratosthenes()
    for i in range(N + 1):
        x = len(Adj[i])
        if (Prime[x]):
            print(i, end=' ')


if __name__ == "__main__":
    N = 4
    M = 6
    edges = [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
    primeDegreeNodes(N, M, edges)

# Expected output:
1 2 3 4
# number of ways to color n | python3 program for the above approach ; recursive function to count the ways ; base case ; initialise answer to 0 ; color each uncolored block according to the given condition ; if any block is uncolored ; check if adjacent blocks are colored or not ; color the block ; recursively iterate for next uncolored block ; uncolored for the next recursive call ; return the final count ; function to count the ways to color block ; mark which blocks are colored in each recursive step ; function call to count the ways ; 

mod = 1000000007


def countWays(colored, count, n):
    if (count == n):
        return 1
    answer = 0
    for i in range(1, n + 1):
        if (colored[i] == 0):
            if (colored[i - 1] == 1 or colored[i + 1] == 1):
                colored[i] = 1
                answer = ((answer + countWays(colored, count + 1, n)) % mod)
                colored[i] = 0
    return answer


def waysToColor(arr, n, k):
    colored = [0] * (n + 2)
    for i in range(k):
        colored[arr[i]] = 1
    return countWays(colored, k, n)


if __name__ == "__main__":
    N = 6
    K = 3
    arr = [1, 2, 6]
    print(waysToColor(arr, N, K))

# Expected output:
4
# shortest palindromic substring | function return the shortest palindromic substring ; finding the smallest character present in the string ; 
def ShortestPalindrome(s):
    n = len(s)
    ans = s[0]
    for i in range(1, n):
        ans = min(ans, s[i])
    return ans


s = "geeksforgeeks"
print(ShortestPalindrome(s))

# Expected output:
e