giulio98/xlcost-single-prompt huggingface dataset:
# count of root to leaf paths consisting of at most m consecutive nodes having value k | initialize the adjacency list and visited array ; function to find the number of root to leaf paths that contain atmost m consecutive nodes with value k ; mark the current node as visited ; if value at current node is k ; increment counter ; if count is greater than m return from that path ; path is allowed if size of present node becomes 0 i . e it has no child root and no more than m consecutive 1 's ; 

adj = [[]for i in range(100005)]
visited = [0 for i in range(100005)]
ans = 0


def dfs(node, count, m, arr, k):
    global ans
    visited[node] = 1
    if (arr[node - 1] == k):
        count += 1
    else:
        count = 0
    if (count > m):
        return
    if (len(adj[node]) == 1 and node != 1):
        ans += 1
    for x in adj[node]:
        if (not visited[x]):
            dfs(x, count, m, arr, k)


if __name__ == "__main__":
    arr = [2, 1, 3, 2, 1, 2, 1]
    N = 7
    K = 2
    M = 2
    adj[1].append(2)
    adj[2].append(1)
    adj[1].append(3)
    adj[3].append(1)
    adj[2].append(4)
    adj[4].append(2)
    adj[2].append(5)
    adj[5].append(2)
    adj[3].append(6)
    adj[6].append(3)
    adj[3].append(7)
    adj[7].append(3)
    counter = 0
    dfs(1, counter, M, arr, K)
    print(ans)

# Expected output:
4
# count of n | function to calculate and return the reverse of the number ; function to calculate the total count of n - digit numbers satisfying the necessary conditions ; initialize two variables ; calculate the sum of odd and even positions ; check for divisibility ; return the answer ; 
def reverse(num):
    rev = 0
    while (num > 0):
        r = int(num % 10)
        rev = rev * 10 + r
        num = num // 10
    return rev


def count(N, A, B):
    l = int(pow(10, N - 1))
    r = int(pow(10, N) - 1)
    if (l == 1):
        l = 0
    ans = 0
    for i in range(l, r + 1):
        even_sum = 0
        odd_sum = 0
        itr = 0
        num = reverse(i)
        while (num > 0):
            if (itr % 2 == 0):
                odd_sum += num % 10
            else:
                even_sum += num % 10
            num = num // 10
            itr += 1
        if (even_sum % A == 0 and odd_sum % B == 0):
            ans += 1
    return ans


if __name__ == '__main__':
    N = 2
    A = 5
    B = 3
    print(count(N, A, B))

# Expected output:
6
# distance traveled by two trains together in the same direction | function to find the distance traveled together ; stores distance travelled by a ; stpres distance travelled by b ; stores the total distance travelled together ; sum of distance travelled ; condition for traveling together ; 
def calc_distance(A, B, n):
    distance_traveled_A = 0
    distance_traveled_B = 0
    answer = 0
    for i in range(5):
        distance_traveled_A += A[i]
        distance_traveled_B += B[i]
        if ((distance_traveled_A == distance_traveled_B) and (A[i] == B[i])):
            answer += A[i]
    return answer


A = [1, 2, 3, 2, 4]
B = [2, 1, 3, 1, 4]
N = len(A)
print(calc_distance(A, B, N))

# Expected output:
3
# find a pair in array with second largest product | function to find second largest product pair in arr [ 0. . n - 1 ] ; no pair exits ; initialize max product pair ; traverse through every possible pair and keep track of largest product ; if pair is largest ; second largest ; if pair dose not largest but larger then second largest ; print the pairs ; 
def maxProduct(arr, N):
    if (N < 3):
        return
    a = arr[0]
    b = arr[1]
    c = 0
    d = 0
    for i in range(0, N, 1):
        for j in range(i + 1, N - 1, 1):
            if (arr[i] * arr[j] > a * b):
                c = a
                d = b
                a = arr[i]
                b = arr[j]
            if (arr[i] * arr[j] < a * b and arr[i] * arr[j] > c * d):
                c = arr[i]
            d = arr[j]
    print(c, " ", d)


if __name__ == '__main__':
    arr = [5, 2, 67, 45, 160, 78]
    N = len(arr)
    maxProduct(arr, N)

# Expected output:
67   160
# count of substrings consisting of even number of vowels | utility function to check if a character is a vowel ; function to calculate and return the count of substrings with even number of vowels ; stores the count of substrings ; if the current character is a vowel ; increase count ; if substring contains even number of vowels ; increase the answer ; prthe final answer ; 
def isVowel(c):
    if (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u'):
        return True
    return False


def countSubstrings(s, n):
    result = 0
    for i in range(n):
        count = 0
        for j in range(i, n):
            if (isVowel(s[j])):
                count += 1
            if (count % 2 == 0):
                result += 1
    print(result)


if __name__ == '__main__':
    n = 5
    s = "abcde"
    countSubstrings(s, n)

# Expected output:
7
# count of substrings consisting of even number of vowels | utility function to check if a character is a vowel ; function to calculate and return the count of substrings with even number of vowels ; stores the count of substrings with even and odd number of vowels respectively ; update count of vowels modulo 2 in sum to obtain even or odd ; increment even / odd count ; count substrings with even number of vowels using handshaking lemma ; 
def isVowel(c):
    if (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u'):
        return True
    return False


def countSubstrings(s, n):
    temp = [1, 0]
    result = 0
    sum = 0
    for i in range(0, n):
        sum += (1 if isVowel(s[i])else 0)
        sum %= 2
        temp[sum] += 1
    result += ((temp[0] * (temp[0] - 1)) // 2)
    result += ((temp[1] * (temp[1] - 1)) // 2)
    print(result)


if __name__ == '__main__':
    n = 5
    s = "abcde"
    countSubstrings(s, n)

# Expected output:
7
# find the level of a binary tree with width k | python3 program to implement the above approach ; structure of a tree node ; function to create new node ; function returns required level of width k , if found else - 1 ; to store the node and the label and perform traversal ; taking the last label of each level of the tree ; check width of current level ; if the width is equal to k then return that level ; taking the first label of each level of the tree ; if any level does not has width equal to k , return - 1 ; 

from collections import deque


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


def findLevel(root: Node, k: int, level: int) -> int:
    qt = deque()
    qt .append([root, 0])
    count = 1
    b = 0
    a = 0
    while qt:
        temp = qt .popleft()
        if (count == 1):
            b = temp[1]
        if (temp[0].left):
            qt .append([temp[0].left, 2 * temp[1]])
        if (temp[0].right):
            qt .append([temp[0].right, 2 * temp[1] + 1])
        count -= 1
        if (count == 0):
            if (b - a + 1 == k):
                return level
            secondLabel = qt[0]
            a = secondLabel[1]
            level += 1
            count = len(qt)
    return -1


if __name__ == "__main__":
    root = Node(5)
    root .left = Node(6)
    root .right = Node(2)
    root .right .right = Node(8)
    root .left .left = Node(7)
    root .left .left .left = Node(5)
    root .left .right = Node(3)
    root .left .right .right = Node(4)
    k = 4
    print(findLevel(root, k, 1))

# Expected output:
3
# maximize median after doing k addition operation on the array | function to check operation can be perform or not ; number of operation to perform s . t . mid is median ; if mid is median of the array ; function to find max median of the array ; lowest possible median ; highest possible median ; checking for mid is possible for the median of array after doing at most k operation ; return the max possible ans ; 
def possible(arr, N, mid, K):
    add = 0
    for i in range(N // 2 - (N + 1) % 2, N):
        if (mid - arr[i] > 0):
            add += (mid - arr[i])
            if (add > K):
                return False
    if (add <= K):
        return True
    else:
        return False


def findMaxMedian(arr, N, K):
    low = 1
    mx = 0
    for i in range(N):
        mx = max(mx, arr[i])
    high = K + mx
    while (low <= high):
        mid = (high + low) // 2
        if (possible(arr, N, mid, K)):
            low = mid + 1
        else:
            high = mid - 1
    if (N % 2 == 0):
        if (low - 1 < arr[N // 2]):
            return (arr[N // 2] + low - 1) // 2
    return low - 1


if __name__ == '__main__':
    arr = [1, 3, 6]
    K = 10
    N = len(arr)
    arr = sorted(arr)
    print(findMaxMedian(arr, N, K))

# Expected output:
9
# kth smallest element of a matrix of given dimensions filled with product of indices | function that returns true if the count of elements is less than mid ; to store count of elements less than mid ; loop through each row ; count elements less than mid in the ith row ; function that returns the kth smallest element in the nxm matrix after sorting in an array ; initialize low and high ; perform binary search ; find the mid ; check if the count of elements is less than mid ; return kth smallest element of the matrix ; 
def countLessThanMid(mid, N, M, K):
    count = 0
    for i in range(1, min(N, mid) + 1):
        count = count + min(mid // i, M)
    if (count >= K):
        return False
    else:
        return True


def findKthElement(N, M, K):
    low = 1
    high = N * M
    while (low <= high):
        mid = low + (high - low) // 2
        if (countLessThanMid(mid, N, M, K)):
            low = mid + 1
        else:
            high = mid - 1
    return high + 1


if __name__ == "__main__":
    N = 2
    M = 3
    K = 5
    print(findKthElement(N, M, K))

# Expected output:
4
# count of substrings containing only the given character | function that finds the count of substrings containing only character c in the s ; to store total count of substrings ; to store count of consecutive c 's ; loop through the string ; increase the consecutive count of c 's ; add count of sub - strings from consecutive strings ; reset the consecutive count of c 's ; add count of sub - strings from consecutive strings ; print the count of sub - strings containing only c ; 
def countSubString(S, C):
    count = 0
    conCount = 0
    for ch in S:
        if (ch == C):
            conCount += 1
        else:
            count += ((conCount * (conCount + 1)) // 2)
            conCount = 0
    count += ((conCount * (conCount + 1)) // 2)
    print(count)


if __name__ == '__main__':
    S = "geeksforgeeks"
    C = 'e'
    countSubString(S, C)

# Expected output:
6
# check if both halves of a string are palindrome or not | function to check if both halves of a string are palindrome or not ; length of string ; initialize both part as true ; if first half is not palindrome ; if second half is not palindrome ; if both halves are palindrome ; 
def checkPalindrome(S):
    n = len(S)
    first_half = True
    second_half = True
    cnt = (n // 2) - 1
    for i in range(0, int((n / 2) / 2)):
        if (S[i] != S[cnt]):
            first_half = False
            break
        if (S[n // 2 + i] != S[n // 2 + cnt]):
            second_half = False
            break
        cnt -= 1
    if (first_half and second_half):
        print('Yes', end='')
    else:
        print('No', end='')


if __name__ == '__main__':
    S = 'momdad'
    checkPalindrome(S)

# Expected output:
Yes
# count of pairs of strings whose concatenation forms a palindromic string | python3 program to find palindromic string ; stores frequency array and its count ; total number of pairs ; initializing array of size 26 to store count of character ; counting occurrence of each character of current string ; convert each count to parity ( 0 or 1 ) on the basis of its frequency ; adding to answer ; frequency of single character can be possibly changed , so change its parity ; 

from collections import defaultdict


def getCount(N, s):
    mp = defaultdict(lambda: 0)
    ans = 0
    for i in range(N):
        a = [0] * 26
        for j in range(len(s[i])):
            a[ord(s[i][j]) - ord('a')] += 1
        for j in range(26):
            a[j] = a[j] % 2
        ans += mp[tuple(a)]
        for j in range(26):
            changedCount = a[:]
            if (a[j] == 0):
                changedCount[j] = 1
            else:
                changedCount[j] = 0
            ans += mp[tuple(changedCount)]
        mp[tuple(a)] += 1
    return ans


if __name__ == '__main__':
    N = 6
    A = ["aab", "abcac", "dffe", "ed", "aa", "aade"]
    print(getCount(N, A))

# Expected output:
6
# check if given binary string follows then given condition or not | function to check if the string follows rules or not ; check for the first condition ; check for the third condition ; check for the second condition ; 
def checkrules(s):
    if len(s) == 0:
        return True
    if s[0] != '1':
        return False
    if len(s) > 2:
        if s[1] == '0' and s[2] == '0':
            return checkrules(s[3:])
    return checkrules(s[1:])


if __name__ == '__main__':
    s = '1111'
    if checkrules(s):
        print('valid string')
    else:
        print('invalid string')

# Expected output:
valid string
# length of longest subsequence in an array having all elements as nude numbers | function to check if the number is a nude number ; variable initialization ; integer ' copy ' is converted to a string ; total digits in the number ; loop through all digits and check if every digit divides n or not ; flag is used to keep check ; return true or false as per the condition ; function to find the longest subsequence which contain all nude numbers ; find the length of longest nude number subsequence ; 
def isNudeNum(n):
    flag = 0
    copy = n
    temp = str(copy)
    length = len(temp)
    for i in range(length):
        num = ord(temp[i]) - ord('0')
        if ((num == 0) or (n % num != 0)):
            flag = 1
    if (flag == 1):
        return False
    else:
        return True


def longestNudeSubseq(arr, n):
    answer = 0
    for i in range(n):
        if (isNudeNum(arr[i])):
            answer += 1
    return answer


arr = [34, 34, 2, 2, 3, 333, 221, 32]
n = len(arr)
print(longestNudeSubseq(arr, n))

# Expected output:
4
# longest subarray with difference exactly k between any two distinct values | function to return the length of the longest sub - array ; initialize set ; store 1 st element of sub - array into set ; check absolute difference between two elements ; if the new element is not present in the set ; if the set contains two elements ; otherwise ; update the maximum length ; remove the set elements ; 
def longestSubarray(arr, n, k):
    Max = 1
    s = set()
    for i in range(n - 1):
        s .add(arr[i])
        for j in range(i + 1, n):
            if (abs(arr[i] - arr[j]) == 0 or abs(arr[i] - arr[j]) == k):
                if (not arr[j] in s):
                    if (len(s) == 2):
                        break
                    else:
                        s .add(arr[j])
            else:
                break
        if (len(s) == 2):
            Max = max(Max, j - i)
            s .clear()
        else:
            s .clear()
    return Max


if __name__ == '__main__':
    arr = [1, 0, 2, 2, 5, 5, 5]
    N = len(arr)
    K = 1
    length = longestSubarray(arr, N, K)
    if (length == 1):
        print("-1")
    else:
        print(length)

# Expected output:
2
# longest subarray of non | function to find the maximum length of a subarray of 1 s after removing at most one 0 ; stores the count of consecutive 1 's from left ; stores the count of consecutive 1 's from right ; traverse left to right ; if cell is non - empty ; increase count ; if cell is empty ; store the count of consecutive 1 's  till (i - 1)-th index ; traverse from right to left ; store the count of consecutive 1 s till ( i + 1 ) - th index ; stores the length of longest subarray ; store the maximum ; if array a contains only 1 s return n else return ans ; 
def longestSubarray(a, n):
    l = [0] * (n)
    r = [0] * (n)
    count = 0
    for i in range(n):
        if (a[i] == 1):
            count += 1
        else:
            l[i] = count
            count = 0
    count = 0
    for i in range(n - 1, -1, -1):
        if (a[i] == 1):
            count += 1
        else:
            r[i] = count
            count = 0
    ans = -1
    for i in range(n):
        if (a[i] == 0):
            ans = max(ans, l[i] + r[i])
    return ans < 0 and n or ans


arr = [0, 1, 1, 1, 0, 1, 0, 1, 1]
n = len(arr)
print(longestSubarray(arr, n))

# Expected output:
4
# find largest factor of n such that n / f is less than k | function to find the value of x ; loop to check all the numbers divisible by n that yield minimum n / i value ; prthe value of packages ; 
def findMaxValue(N, K):
    packages = 0
    maxi = 1
    for i in range(1, K + 1):
        if (N % i == 0):
            maxi = max(maxi, i)
    packages = N // maxi
    print(packages)


if __name__ == '__main__':
    N = 8
    K = 7
    findMaxValue(N, K)

# Expected output:
2
# largest square which can be formed using given rectangular blocks | function to find maximum side length of square ; sort array in asc order ; traverse array in desc order ; 
def maxSide(a, n):
    sideLength = 0
    a .sort
    for i in range(n - 1, -1, -1):
        if (a[i] > sideLength):
            sideLength += 1
        else:
            break
    print(sideLength)


N = 6
arr = [3, 2, 1, 5, 2, 4]
maxSide(arr, N)

# Expected output:
3
# count of subtrees from an n | function to implement dfs traversal ; mark node v as visited ; traverse adj_list of node v ; if current node is not visited ; dfs call for current node ; count the total red and blue nodes of children of its subtree ; count the no . of red and blue nodes in the subtree ; if subtree contains all red node & no blue node ; if subtree contains all blue node & no red node ; function to count the number of nodes with red color ; function to count the number of nodes with blue color ; function to create a tree with given vertices ; traverse the edge [ ] array ; create adjacency list ; function to count the number of subtree with the given condition ; for creating adjacency list ; to store the count of subtree with only blue and red color ; visited array for dfs traversal ; count the number of red node in the tree ; count the number of blue node in the tree ; function call to build tree ; dfs traversal ; print the final count ; 
def Solution_dfs(v, color, red, blue, sub_red, sub_blue, vis, adj, ans):
    vis[v] = 1
    for i in range(len(adj[v])):
        if (vis[adj[v][i]] == 0):
            ans = Solution_dfs(
                adj[v][i],
                color,
                red,
                blue,
                sub_red,
                sub_blue,
                vis,
                adj,
                ans)
            sub_red[v] += sub_red[adj[v][i]]
            sub_blue[v] += sub_blue[adj[v][i]]
    if (color[v] == 1):
        sub_red[v] += 1
    if (color[v] == 2):
        sub_blue[v] += 1
    if (sub_red[v] == red and sub_blue[v] == 0):
        (ans) += 1
    if (sub_red[v] == 0 and sub_blue[v] == blue):
        (ans) += 1
    return ans


def countRed(color, n):
    red = 0
    for i in range(n):
        if (color[i] == 1):
            red += 1
    return red


def countBlue(color, n):
    blue = 0
    for i in range(n):
        if (color[i] == 2):
            blue += 1
    return blue


def buildTree(edge, m, n):
    u, v, i = 0, 0, 0
    for i in range(n - 1):
        u = edge[i][0] - 1
        v = edge[i][1] - 1
        if u not in m:
            m[u] = []
        if v not in m:
            m[v] = []
        m[u].append(v)
        m[v].append(u)


def countSubtree(color, n, edge):
    adj = dict()
    ans = 0
    sub_red = [0 for i in range(n + 3)]
    sub_blue = [0 for i in range(n + 3)]
    vis = [0 for i in range(n + 3)]
    red = countRed(color, n)
    blue = countBlue(color, n)
    buildTree(edge, adj, n)
    ans = Solution_dfs(0, color, red, blue, sub_red, sub_blue, vis, adj, ans)
    print(ans, end='')


if __name__ == '__main__':
    N = 5
    color = [1, 0, 0, 0, 2]
    edge = [[1, 2], [2, 3], [3, 4], [4, 5]]
    countSubtree(color, N, edge)

# Expected output:
4
# minimize difference after changing all odd elements to even | function to minimize the difference between two elements of array ; find all the element which are possible by multiplying 2 to odd numbers ; sort the array ; find the minimum difference iterate and find which adjacent elements have the minimum difference ; print the minimum difference ; 
def minDiff(a, n):
    for i in range(n):
        if (a[i] % 2 == 1):
            a .append(a[i] * 2)
    a = sorted(a)
    mindifference = a[1] - a[0]
    for i in range(1, len(a)):
        mindifference = min(mindifference, a[i] - a[i - 1])
    print(mindifference)


if __name__ == '__main__':
    arr = [3, 8, 13, 30, 50]
    n = len(arr)
    minDiff(arr, n)

# Expected output:
2
# longest subarray having sum k | set 2 | to store the prefix sum1 array ; function for searching the lower bound of the subarray ; iterate until low less than equal to high ; for each mid finding sum1 of sub array less than or equal to k ; return the final answer ; function to find the length of subarray with sum1 k ; initialize sum1 to 0 ; push the prefix sum1 of the array arr [ ] in prefix [ ] ; search r for each i ; update ans ; print the length of subarray found in the array ; 

v = []


def bin1(val, k, n):
    global v
    lo = 0
    hi = n
    mid = 0
    ans = -1
    while (lo <= hi):
        mid = lo + ((hi - lo) // 2)
        if (v[mid] - val <= k):
            lo = mid + 1
            ans = mid
        else:
            hi = mid - 1
    return ans


def findSubarraysum1K(arr, N, K):
    global v
    sum1 = 0
    v .append(0)
    for i in range(N):
        sum1 += arr[i]
        v .append(sum1)
    l = 0
    ans = 0
    r = 0
    for i in range(len(v)):
        r = bin1(v[i], K, N)
        ans = max(ans, r - i)
    print(ans)


if __name__ == '__main__':
    arr = [6, 8, 14, 9, 4, 11, 10]
    N = len(arr)
    K = 13
    findSubarraysum1K(arr, N, K)

# Expected output:
2
# minimum number of reversals to reach node 0 from every other node | function to find minimum reversals ; add all adjacent nodes to the node in the graph ; insert edges in the graph ; insert edges in the reversed graph ; create array visited to mark all the visited nodes ; stores the number of edges to be reversed ; bfs traversal ; pop the current node from the queue ; mark the current node visited ; intitialize count of edges need to be reversed to 0 ; push adjacent nodes in the reversed graph to the queue , if not visited ; push adjacent nodes in graph to the queue , if not visited count the number of nodes added to the queue ; update the reverse edge to the final count ; return the result ; 
def minRev(edges, n):
    graph = dict()
    graph_rev = dict()
    for i in range(len(edges)):
        x = edges[i][0]
        y = edges[i][1]
        if x not in graph:
            graph[x] = []
        graph[x].append(y)
        if y not in graph_rev:
            graph_rev[y] = []
        graph_rev[y].append(x)
    q = []
    visited = [0 for i in range(n)]
    q .append(0)
    ans = 0
    while (len(q) != 0):
        curr = q[0]
        visited[curr] = 1
        count = 0
        q .pop(0)
        if curr in graph_rev:
            for i in range(len(graph_rev[curr])):
                if (not visited[graph_rev[curr][i]]):
                    q .append(graph_rev[curr][i])
        if curr in graph:
            for i in range(len(graph[curr])):
                if (not visited[graph[curr][i]]):
                    q .append(graph[curr][i])
                    count += 1
        ans += count
    return ans


if __name__ == '__main__':
    edges = []
    edges = [[0, 1], [1, 3], [2, 3], [4, 0], [4, 5]]
    n = 6
    print(minRev(edges, n))

# Expected output:
3