giulio98/xlcost-single-prompt huggingface dataset:
# count nodes having smallest value in the path from root to itself in a binary tree | python3 program for the above approach ; class of a tree node ; function to create new tree node ; function to find the total number of required nodes ; if current node is null then return to the parent node ; check if current node value is less than or equal to minnodeval ; update the value of minnodeval ; update the count ; go to the left subtree ; go to the right subtree ; 

import sys
ans = 0


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


def countReqNodes(root, minNodeVal):
    global ans
    if root is None:
        return
    if root .key <= minNodeVal:
        minNodeVal = root .key
        ans += 1
    countReqNodes(root .left, minNodeVal)
    countReqNodes(root .right, minNodeVal)


if __name__ == '__main__':
    root = Node(8)
    root .left = Node(6)
    root .right = Node(5)
    root .left .left = Node(6)
    root .left .right = Node(7)
    root .right .left = Node(3)
    root .right .right = Node(9)
    minNodeVal = sys .maxsize
    countReqNodes(root, minNodeVal)
    print(ans)

# Expected output:
5
# check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings | function to check if a string is palindrome or not ; start and end of the string ; iterate the string until i > j ; if there is a mismatch ; increment first pointer and decrement the other ; given string is a palindrome ; function two check if the strings can be combined to form a palindrome ; initialize array of characters ; stores character of string in the character array ; find left and right parts of strings a and b ; substring a [ j ... i - 1 ] ; substring b [ j ... i - 1 ] ; substring a [ i ... n ] ; substring b [ i ... n ] ; check is left part of a + right part of b or vice versa is a palindrome ; print the result ; otherwise ; 
def isPalindrome(st):
    i = 0
    j = len(st) - 1
    while (i < j):
        if (st[i] != st[j]):
            return False
        i += 1
        j -= 1
    return True


def formPalindrome(a, b, n):
    aa = [' '] * (n + 2)
    bb = [' '] * (n + 2)
    for i in range(1, n + 1):
        aa[i] = a[i - 1]
        bb[i] = b[i - 1]
    ok = False
    for i in range(n + 2):
        la = ""
        ra = ""
        lb = ""
        rb = ""
        for j in range(1, i):
            if (aa[j] == ' '):
                la += ""
            else:
                la += aa[j]
            if (bb[j] == ' '):
                lb += ""
            else:
                lb += bb[j]
        for j in range(i, n + 2):
            if (aa[j] == ' '):
                ra += ""
            else:
                ra += aa[j]
            if (bb[j] == ' '):
                rb += ""
            else:
                rb += bb[j]
        if (isPalindrome(str(la) + str(rb)) or isPalindrome(str(lb) + str(ra))):
            ok = True
            break
    if (ok):
        print("Yes")
    else:
        print("No")


if __name__ == "__main__":
    A = "bdea"
    B = "abbb"
    N = 4
    formPalindrome(A, B, N)

# Expected output:
Yes
# minimize elements to be added to a given array such that it contains another given array as its subsequence | set 2 | function to return minimum element to be added in array b so that array a become subsequence of array b ; stores indices of the array elements ; iterate over the array ; store the indices of the array elements ; stores the lis ; check if element b [ i ] is in array a [ ] ; perform binary search ; find the value of mid m ; update l and r ; if found better element ' e ' for pos r + 1 ; otherwise , extend the current subsequence ; return the answer ; 
def minElements(A, B, N, M):
    map = {}
    for i in range(len(A)):
        map[A[i]] = i
    subseq = []
    l = 0
    r = -1
    for i in range(M):
        if B[i] in map:
            e = map[B[i]]
            while (l <= r):
                m = l + (r - l) // 2
                if (subseq[m] < e):
                    l = m + 1
                else:
                    r = m - 1
            if (r + 1 < len(subseq)):
                subseq[r + 1] = e
            else:
                subseq .append(e)
            l = 0
            r = len(subseq) - 1
    return N - len(subseq)


if __name__ == '__main__':
    A = [1, 2, 3, 4, 5]
    B = [2, 5, 6, 4, 9, 12]
    M = len(A)
    N = len(B)
    print(minElements(A, B, M, N))

# Expected output:
3
# detect a negative cycle in a graph using shortest path faster algorithm | python3 program for the above approach ; stores the adjacency list of the given graph ; create adjacency list ; stores the distance of all reachable vertex from source ; check if vertex is present in queue or not ; counts the relaxation for each vertex ; distance from src to src is 0 ; create a queue ; push source in the queue ; mark source as visited ; front vertex of queue ; relaxing all edges of vertex from the queue ; update the dist [ v ] to minimum distance ; if vertex v is in queue ; negative cycle ; no cycle found ; 

import sys


def sfpa(V, src, Edges, M):
    g = [[]for i in range(V)]
    for i in range(M):
        u = Edges[i][0]
        v = Edges[i][1]
        w = Edges[i][2]
        g[u].append([v, w])
    dist = [sys .maxsize for i in range(V)]
    inQueue = [False for i in range(V)]
    cnt = [0 for i in range(V)]
    dist[src] = 0
    q = []
    q .append(src)
    inQueue[src] = True
    while (len(q)):
        u = q[0]
        q .remove(q[0])
        inQueue[u] = False
        for x in g[u]:
            v = x[0]
            cost = x[1]
            if (dist[v] > dist[u] + cost):
                dist[v] = dist[u] + cost
                if (inQueue[v] == False):
                    q .append(v)
                    inQueue[v] = True
                    cnt[v] += 1
                    if (cnt[v] >= V):
                        return True
    return False


if __name__ == '__main__':
    N = 4
    src = 0
    M = 4
    Edges = [[0, 1, 1], [1, 2, -1], [2, 3, -1], [3, 0, -1]]
    if (sfpa(N, src, Edges, M)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# sum of all pair shortest paths in a tree | python3 program for the above approach ; function that performs the floyd warshall to find all shortest paths ; initialize the distance matrix ; pick all vertices as source one by one ; pick all vertices as destination for the above picked source ; if vertex k is on the shortest path from i to j then update dist [ i ] [ j ] ; sum the upper diagonal of the shortest distance matrix ; traverse the given dist [ ] [ ] ; add the distance ; return the final sum ; function to generate the tree ; add edges ; get source and destination with weight ; add the edges ; perform floyd warshal algorithm ; 

INF = 99999


def floyd_warshall(graph, V):
    dist = [[0 for i in range(V)]for i in range(V)]
    for i in range(V):
        for j in range(V):
            dist[i][j] = graph[i][j]
    for k in range(V):
        for i in range(V):
            for j in range(V):
                if (dist[i][k] + dist[k][j] < dist[i][j]):
                    dist[i][j] = dist[i][k] + dist[k][j]
    sum = 0
    for i in range(V):
        for j in range(i + 1, V):
            sum += dist[i][j]
    return sum


def sumOfshortestPath(N, E, edges):
    g = [[INF for i in range(N)]for i in range(N)]
    for i in range(E):
        u = edges[i][0]
        v = edges[i][1]
        w = edges[i][2]
        g[u][v] = w
        g[v][u] = w
    return floyd_warshall(g, N)


if __name__ == '__main__':
    N = 4
    E = 3
    Edges = [[0, 1, 1], [1, 2, 2], [2, 3, 3]]
    print(sumOfshortestPath(N, E, Edges))

# Expected output:
20
# kth space | function to prkth integer in a given string ; size of the string ; if space char found decrement k ; if k becomes 1 , the next string is the required one ; print required number ; 
def print_kth_string(s, K):
    N = len(s)
    for i in range(0, N, 1):
        if (s[i] == ' '):
            K -= 1
        if (K == 1):
            break
    while (i < N):
        if (s[i] != ' '):
            print(s[i], end="")
        i += 1


if __name__ == '__main__':
    s = "10 20 30 40"
    K = 4
    print_kth_string(s, K)

# Expected output:
40
# minimum peak elements from an array by their repeated removal at every iteration of the array | python3 program for the above approach ; function to return the list of minimum peak elements ; length of original list ; initialize resultant list ; traverse each element of list ; length of original list after removing the peak element ; traverse new list after removal of previous min peak element ; update min and index , if first element of list > next element ; update min and index , if last element of list > previous one ; update min and index , if list has single element ; update min and index , if current element > adjacent elements ; remove current min peak element from list ; insert min peak into resultant list ; print resultant list ; 

import sys


def minPeaks(list1):
    n = len(list1)
    result = []
    for i in range(n):
        min = sys .maxsize
        index = -1
        size = len(list1)
        for j in range(size):
            if (j == 0 and j + 1 < size):
                if (list1[j] > list1[j + 1] and min > list1[j]):
                    min = list1[j]
                    index = j
            elif (j == size - 1 and j - 1 >= 0):
                if (list1[j] > list1[j - 1] and min > list1[j]):
                    min = list1[j]
                    index = j
            elif (size == 1):
                min = list1[j]
                index = j
            elif (list1[j] > list1[j - 1] and list1[j] > list1[j + 1] and min > list1[j]):
                min = list1[j]
                index = j
        list1 .pop(index)
        result .append(min)
    print(result)


if __name__ == "__main__":
    arr = [1, 9, 7, 8, 2, 6]
    minPeaks(arr)

# Expected output:
[6, 8, 9, 7, 2, 1]
# search an element in a reverse sorted array | function to search if element x is present in reverse sorted array ; store the first index of the subarray in which x lies ; store the last index of the subarray in which x lies ; store the middle index of the subarray ; check if value at middle index of the subarray equal to x ; element is found ; if x is smaller than the value at middle index of the subarray ; search in right half of subarray ; search in left half of subarray ; if x not found ; 
def binarySearch(arr, N, X):
    start = 0
    end = N
    while (start <= end):
        mid = start + (end - start) // 2
        if (X == arr[mid]):
            return mid
        elif (X < arr[mid]):
            start = mid + 1
        else:
            end = mid - 1
    return -1


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

# Expected output:
0
# construct an ap series consisting of a and b having minimum possible nth term | python3 program for the above approach ; function to check if both a and b are present in the ap series or not ; iterate over the array arr [ ] ; if a is present ; if b is present ; if both are present ; otherwise ; function to print all the elements of the arithmetic progression ; function to construct ap series consisting of a and b with minimum nth term ; stores the resultant series ; initialise ans [ i ] as int_max ; maintain a smaller than b ; swap a and b ; difference between a and b ; check for all possible combination of start and common difference d ; initialise arr [ 0 ] as start ; check if both a and b are present or not and the nth term is the minimum or not ; update the answer ; print the resultant array ; 

import sys


def check_both_present(arr, N, a, b):
    f1 = False
    f2 = False
    for i in range(0, N):
        if arr[i] == a:
            f1 = True
        if arr[i] == b:
            f2 = True
    if f1 and f2:
        return True
    else:
        return False


def print_array(ans, N):
    for i in range(0, N):
        print(ans[i], end=" ")


def build_AP(N, a, b):
    INT_MAX = sys .maxsize
    arr = [None for i in range(N)]
    ans = [INT_MAX for i in range(N)]
    flag = 0
    if a > b:
        a, b = b, a
    diff = b - a
    for start in range(1, a + 1):
        for d in range(1, diff + 1):
            arr[0] = start
            for i in range(1, N):
                arr[i] = arr[i - 1] + d
            if ((check_both_present(arr, N, a, b)
                    and arr[N - 1] < ans[N - 1])):
                for i in range(0, N):
                    ans[i] = arr[i]
    print_array(ans, N)


if __name__ == "__main__":
    N = 5
    A = 20
    B = 50
    build_AP(N, A, B)

# Expected output:
10 20 30 40 50
# find the word from a given sentence having given word as prefix | function to find the position of the string having word as prefix ; initialize an list ; extract words from the sentence ; traverse each word ; traverse the characters of word ; if prefix does not match ; otherwise ; return the word ; return - 1 if not present ; 
def isPrefixOfWord(sentence, word):
    a = sentence .split(" ")
    v = []
    for i in a:
        v .append(i)
    for i in range(len(v)):
        for j in range(len(v[i])):
            if (v[i][j] != word[j]):
                break
            elif (j == len(word) - 1):
                return v[i]
    return -1


s = "Welcome to Geeksforgeeks"
word = "Gee"
print(isPrefixOfWord(s, word))

# Expected output:
Geeksforgeeks
# paths requiring minimum number of jumps to reach end of array | python3 program to implement the above approach ; pair class instance ; stores the current index ; stores the path travelled so far ; stores the minimum jumps required to reach the last index from current index ; constructor ; minimum jumps required to reach end of the array ; stores the maximum number of steps that can be taken from the current index ; checking if index stays within bounds ; stores the minimum number of jumps required to jump from ( i + j ) - th index ; function to find all possible paths to reach end of array requiring minimum number of steps ; storing the neighbours of current index element ; function to find the minimum steps and corresponding paths to reach end of an array ; stores the minimum jumps from each position to last position ; 

from queue import Queue
import sys


class Pair (object):
    idx = 0
    psf = ""
    jmps = 0

    def __init__(self, idx, psf, jmps):
        self .idx = idx
        self .psf = psf
        self .jmps = jmps


def minJumps(arr):
    MAX_VALUE = sys .maxsize
    dp = [MAX_VALUE for i in range(len(arr))]
    n = len(dp)
    dp[n - 1] = 0
    for i in range(n - 2, -1, -1):
        steps = arr[i]
        minimum = MAX_VALUE
        for j in range(1, steps + 1, 1):
            if i + j >= n:
                break
            if ((dp[i + j] != MAX_VALUE) and (dp[i + j] < minimum)):
                minimum = dp[i + j]
        if minimum != MAX_VALUE:
            dp[i] = minimum + 1
    return dp


def possiblePath(arr, dp):
    queue = Queue(maxsize=0)
    p1 = Pair(0, "0", dp[0])
    queue .put(p1)
    while queue .qsize() > 0:
        tmp = queue .get()
        if tmp .jmps == 0:
            print(tmp .psf)
            continue
        for step in range(1, arr[tmp .idx] + 1, 1):
            if ((tmp .idx + step < len(arr))
                    and (tmp .jmps - 1 == dp[tmp .idx + step])):
                p2 = Pair(tmp .idx + step, tmp .psf + " -> " +
                          str((tmp .idx + step)), tmp .jmps - 1)
                queue .put(p2)


def Solution(arr):
    dp = minJumps(arr)
    possiblePath(arr, dp)


if __name__ == "__main__":
    arr = [3, 3, 0, 2, 1, 2, 4, 2, 0, 0]
    size = len(arr)
    Solution(arr)

# Expected output:
0 -> 3 -> 5 -> 6 -> 9
0 -> 3 -> 5 -> 7 -> 9
# length of longest increasing absolute even subsequence | function to find the longest increasing absolute even subsequence ; length of arr ; stores length of required subsequence ; traverse the array ; traverse prefix of current array element ; check if the subsequence is lis and have even absolute difference of adjacent pairs ; update lis [ ] ; stores maximum length ; find the length of longest absolute even subsequence ; return the maximum length of absolute even subsequence ; 
def EvenLIS(arr):
    n = len(arr)
    lis = [1] * n
    for i in range(1, n):
        for j in range(0, i):
            if abs(
                arr[i]) > abs(
                arr[j]) and abs(
                arr[i] %
                2) == 0 and abs(
                    arr[j] %
                    2) == 0 and lis[i] < lis[j] + 1:
                lis[i] = lis[j] + 1
    maxlen = 0
    for i in range(n):
        maxlen = max(maxlen, lis[i])
    print(maxlen)


arr = [11, -22, 43, -54, 66, 5]
EvenLIS(arr)

# Expected output:
3
# Count balanced nodes present in a binary tree | Structure of a Tree Node ; Function to get the sum of left subtree and right subtree ; Base case ; Store the sum of left subtree ; Store the sum of right subtree ; Check if node is balanced or not ; Increase count of balanced nodes ; Return subtree sum ; Insert nodes in tree ; Store the count of balanced nodes

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


def Sum(root):
    global res
    if (root is None):
        return 0
    leftSubSum = Sum(root .left)
    rightSubSum = Sum(root .right)
    if (root .left and root .right and leftSubSum == rightSubSum):
        res += 1
    return (root .data + leftSubSum + rightSubSum)


root = Node(9)
root .left = Node(2)
root .left .left = Node(-1)
root .left .right = Node(3)
root .right = Node(4)
root .right .right = Node(0)
global res
res = 0
Sum(root)
print(res)

# Expected output:
1
# count subarrays for every array element in which they are the minimum | function to required count subarrays ; for storing count of subarrays ; for finding next smaller element left to a element if there is no next smaller element left to it than taking - 1. ; for finding next smaller element right to a element if there is no next smaller element right to it than taking n . ; taking exact boundaries in which arr [ i ] is minimum ; similarly for right side ; 
def countingSubarray(arr, n):
    a = [0 for i in range(n)]
    nsml = [-1 for i in range(n)]
    nsmr = [n for i in range(n)]
    st = []
    for i in range(n - 1, -1, -1):
        while (len(st) > 0 and arr[st[-1]] >= arr[i]):
            del st[-1]
        if (len(st) > 0):
            nsmr[i] = st[-1]
        else:
            nsmr[i] = n
        st .append(i)
    while (len(st) > 0):
        del st[-1]
    for i in range(n):
        while (len(st) > 0 and arr[st[-1]] >= arr[i]):
            del st[-1]
        if (len(st) > 0):
            nsml[i] = st[-1]
        else:
            nsml[i] = -1
        st .append(i)
    for i in range(n):
        nsml[i] += 1
        nsmr[i] -= 1
        r = nsmr[i] - i + 1
        l = i - nsml[i] + 1
        a[i] = r * l
    return a


N = 5
arr = [3, 2, 4, 1, 5]
a = countingSubarray(arr, N)
print(a)

# Expected output:
[1, 4, 1, 8, 1]
# lexicographically smallest permutation of a string that contains all substrings of another string | function to reorder the b to contain all the substrings of a ; find length of strings ; initialize array to count the frequencies of the character ; counting frequencies of character in b ; find remaining character in b ; declare the reordered string ; loop until freq [ j ] > 0 ; decrement the value from freq array ; check if a [ j ] > a [ 0 ] ; check if a [ j ] < a [ 0 ] ; append the remaining characters to the end of the result ; push all the values from frequency array in the answer ; return the answer ; 
def reorderString(A, B):
    size_a = len(A)
    size_b = len(B)
    freq = [0] * 300
    for i in range(size_b):
        freq[ord(B[i])] += 1
    for i in range(size_a):
        freq[ord(A[i])] -= 1
    for j in range(ord('a'), ord('z') + 1):
        if (freq[j] < 0):
            return "-1"
    answer = []
    for j in range(ord('a'), ord(A[0])):
        while (freq[j] > 0):
            answer .append(j)
            freq[j] -= 1
    first = A[0]
    for j in range(size_a):
        if (A[j] > A[0]):
            break
        if (A[j] < A[0]):
            answer += A
            A = ""
            break
    while (freq[ord(first)] > 0):
        answer .append(first)
        freq[ord(first)] -= 1
    answer += A
    for j in range(ord('a'), ord('z') + 1):
        while (freq[j]):
            answer .append(chr(j))
            freq[j] -= 1
    return "".join(answer)


if __name__ == '__main__':
    A = "aa"
    B = "ababab"
    print(reorderString(A, B))

# Expected output:
aaabbb
# number from a range [ l , r ] having kth minimum cost of conversion to 1 by given operations | function to calculate the cost ; base case ; even condition ; odd condition ; return cost ; function to find kth element ; array to store the costs ; sort the array based on cost ; 
def func(n):
    count = 0
    if n == 2 or n == 1:
        return 1
    if n % 2 == 0:
        count = 1 + func(n // 2)
    if n % 2 != 0:
        count = 1 + func(n * 3 + 1)
    return count


def findKthElement(l, r, k):
    arr = list(range(l, r + 1))
    result = []
    for i in arr:
        result .append([i, func(i)])
    result .sort()
    print(result[k - 1][0])


l = 12
r = 15
k = 2
findKthElement(l, r, k)

# Expected output:
13
# check if a string represents a hexadecimal number or not | function to check if the string represents a hexadecimal number ; iterate over string ; check if the character is invalid ; print true if all characters are valid ; 
def checkHex(s):
    for ch in s:
        if ((ch < '0' or ch > '9') and (ch < 'A' or ch > 'F')):
            print("No")
            return
    print("Yes")


s = "BF57C"
checkHex(s)

# Expected output:
Yes
# longest subsequence forming an arithmetic progression ( ap ) | function that finds the longest arithmetic subsequence having the same absolute difference ; stores the length of sequences having same difference ; stores the resultant length ; iterate over the array ; update length of subsequence ; return res ;  ; 
def lenghtOfLongestAP(A, n):
    dp = {}
    res = 2
    for i in range(n):
        for j in range(i + 1, n):
            d = A[j] - A[i]
            if d in dp:
                if i in dp[d]:
                    dp[d][j] = dp[d][i] + 1
                else:
                    dp[d][j] = 2
            else:
                dp[d] = {}
                dp[d][j] = 2
            if d in dp:
                if j in dp[d]:
                    res = max(res, dp[d][j])
    return res


arr = [20, 1, 15, 3, 10, 5, 8]
N = len(arr)
print(lenghtOfLongestAP(arr, N))

# Expected output:
4
# check if a given number can be expressed as pair | python3 program of the above approach ; function to check if the number is pair - sum of sum of first x natural numbers ; check if the given number is sum of pair of special numbers ; x is the sum of first i natural numbers ; t = 2 * y ; condition to check if y is a special number ; 

import math


def checkSumOfNatural(n):
    i = 1
    flag = False
    while i * (i + 1) < n * 2:
        X = i * (i + 1)
        t = n * 2 - X
        k = int(math .sqrt(t))
        if k * (k + 1) == t:
            flag = True
            break
        i += 1
    if flag:
        print('YES')
    else:
        print('NO')


if __name__ == "__main__":
    n = 25
    checkSumOfNatural(n)

# Expected output:
YES