giulio98/xlcost-single-prompt huggingface dataset:
# deepest left leaf node in a binary tree | a binary tree node ; constructor to create a new node ; a utility function to find deepest leaf node . lvl : level of current node . maxlvl : pointer to the deepest left leaf node found so far isleft : a bool indicate that this node is left child of its parent resptr : pointer to the result ; base case ; update result if this node is left leaf and its level is more than the max level of the current result ; recur for left and right subtrees ; a wrapper for left and right subtree ; 

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


def deepestLeftLeafUtil(root, lvl, maxlvl, isLeft):
    if root is None:
        return
    if (isLeft is True):
        if (root .left is None and root .right is None):
            if lvl > maxlvl[0]:
                deepestLeftLeafUtil .resPtr = root
                maxlvl[0] = lvl
                return
    deepestLeftLeafUtil(root .left, lvl + 1, maxlvl, True)
    deepestLeftLeafUtil(root .right, lvl + 1, maxlvl, False)


def deepestLeftLeaf(root):
    maxlvl = [0]
    deepestLeftLeafUtil .resPtr = None
    deepestLeftLeafUtil(root, 0, maxlvl, False)
    return deepestLeftLeafUtil .resPtr


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .right .left = Node(5)
root .right .right = Node(6)
root .right .left .right = Node(7)
root .right .right .right = Node(8)
root .right .left .right .left = Node(9)
root .right .right .right .right = Node(10)
result = deepestLeftLeaf(root)
if result is None:
    print("There is not left leaf in the given tree")
else:
    print("The deepst left child is", result .val)

# Expected output:
The deepst left child is 9
# check if an array contains all elements of a given range | function to check the array for elements in 
def check_elements(arr, n, A, B):
    rangeV = B - A
    for i in range(0, n):
        if (abs(arr[i]) >= A and abs(arr[i]) <= B):
            z = abs(arr[i]) - A
            if (arr[z] > 0):
                arr[z] = arr[z] * -1
    count = 0
    for i in range(0, rangeV + 1):
        if i >= n:
            break
        if (arr[i] > 0):
            return False
        else:
            count = count + 1
    if (count != (rangeV + 1)):
        return False
    return True


arr = [1, 4, 5, 2, 7, 8, 3]
n = len(arr)
A = 2
B = 5
if (check_elements(arr, n, A, B)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# recursive programs to find minimum and maximum elements of array | function to print minimum element using recursion ; if size = 0 means whole array has been traversed ; 
def findMinRec(A, n):
    if (n == 1):
        return A[0]
    return min(A[n - 1], findMinRec(A, n - 1))


if __name__ == '__main__':
    A = [1, 4, 45, 6, -50, 10, 2]
    n = len(A)
    print(findMinRec(A, n))

# Expected output:
-50
# allocate minimum number of pages | utility function to check if current minimum value is feasible or not . ; iterate over all books ; check if current number of pages are greater than curr_min that means we will get the result after mid no . of pages ; count how many students are required to distribute curr_min pages ; increment student count ; update curr_sum ; if students required becomes greater than 
def isPossible(arr, n, m, curr_min):
    studentsRequired = 1
    curr_sum = 0
    for i in range(n):
        if (arr[i] > curr_min):
            return False
        if (curr_sum + arr[i] > curr_min):
            studentsRequired += 1
            curr_sum = arr[i]
            if (studentsRequired > m):
                return False
        else:
            curr_sum += arr[i]
    return True


def findPages(arr, n, m):
    sum = 0
    if (n < m):
        return -1
    for i in range(n):
        sum += arr[i]
    start, end = 0, sum
    result = 10 ** 9
    while (start <= end):
        mid = (start + end) // 2
        if (isPossible(arr, n, m, mid)):
            result = mid
            end = mid - 1
        else:
            start = mid + 1
    return result


arr = [12, 34, 67, 90]
n = len(arr)
m = 2
print("Minimum number of pages = ", findPages(arr, n, m))

# Expected output:
Minimum number of pages =  113
# Find Minimum Depth of a Binary Tree | Tree node ; Function to calculate the minimum depth of the tree ; Corner Case . Should never be hit unless the code is called on root = NULL ; Base Case : Leaf node . This acoounts for height = 1 ; If left subtree is Null , recur for right subtree ; If right subtree is Null , recur for left subtree ; Let us construct the Tree shown in the above figure

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


def minDepth(root):
    if root is None:
        return 0
    if root .left is None and root .right is None:
        return 1
    if root .left is None:
        return minDepth(root .right) + 1
    if root .right is None:
        return minDepth(root .left) + 1
    return min(minDepth(root .left), minDepth(root .right)) + 1


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
print(minDepth(root))

# Expected output:
2
# remove an occurrence of most frequent array element exactly k times | function to print the most frequent array element exactly k times ; stores frequency array element ; count frequency of array element ; maximum array element ; traverse the map ; find the element with maximum frequency ; if the frequency is maximum , store that number in element ; print element as it contains the element having highest frequency ; decrease the frequency of the maximum array element ; reduce the number of operations ; given array ; size of the array ; 
def maxFreqElements(arr, N, K):
    mp = {}
    for i in range(N):
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    while (K > 0):
        Max = 0
        for i in mp:
            if (mp[i] > Max):
                Max = mp[i]
                element = i
        print(element, end=" ")
        if element in mp:
            mp[element] -= 1
        else:
            mp[element] = -1
        K -= 1


arr = [1, 3, 2, 1, 4, 1]
N = len(arr)
K = 2
maxFreqElements(arr, N, K)

# Expected output:
1 1
# maximize difference between maximum and minimum array elements after k operations | function to find the maximum difference between the maximum and minimum in the array after k operations ; stores maximum difference between largest and smallest array element ; sort the array in descending order ; traverse the array arr [ ] ; update maxdiff ; 
def maxDiffLargSmallOper(arr, N, K):
    maxDiff = 0
    arr .sort(reverse=True)
    for i in range(min(K + 1, N)):
        maxDiff += arr[i]
    return maxDiff


if __name__ == "__main__":
    arr = [7, 7, 7, 7]
    N = len(arr)
    K = 1
    print(maxDiffLargSmallOper(arr, N, K))

# Expected output:
14
# minimize cost to convert all characters of a binary string to 0 s | function to get the minimum cost to convert all characters of given string to 0 s ; stores the range of indexes of characters that need to be flipped ; stores the number of times current character is flipped ; stores minimum cost to get the required string ; traverse the given string ; remove all value from pq whose value is less than i ; update flip ; get the current number ; if current character is flipped odd times ; if current character contains non - zero value ; update flip ; update cost ; append r [ i ] into pq ; 
def minCost(s, R, C, N):
    ch = list(s)
    pq = []
    flip = 0
    cost = 0
    for i in range(N):
        while (len(pq) > 0 and pq[0] < i):
            pq .pop(0)
            flip -= 1
        cn = ord(ch[i]) - ord('0')
        if (flip % 2 == 1):
            cn = 1 - cn
        if (cn == 1):
            flip += 1
            cost += C[i]
            pq .append(R[i])
    return cost


N = 4
s = "1010"
R = [1, 2, 2, 3]
C = [3, 1, 2, 3]
print(minCost(s, R, C, N))

# Expected output:
4
# find minimum depth of a binary tree | a binary tree node ; iterative method to find minimum depth of binary tree ; corner case ; create an empty queue for level order traversal ; enqueue root and 

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


def minDepth(root):
    if root is None:
        return 0
    q = []
    q .append({'node': root, 'depth': 1})
    while (len(q) > 0):
        queueItem = q .pop(0)
        node = queueItem['node']
        depth = queueItem['depth']
        if node .left is None and node .right is None:
            return depth
        if node .left is not None:
            q .append({'node': node .left, 'depth': depth + 1})
        if node .right is not None:
            q .append({'node': node .right, 'depth': depth + 1})


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
print(minDepth(root))

# Expected output:
2
# maximum manhattan distance between a distinct pair from n coordinates | function to calculate the maximum manhattan distance ; list to store maximum and minimum of all the four forms ; sorting both the vectors ; 
def MaxDist(A, N):
    V = [0 for i in range(N)]
    V1 = [0 for i in range(N)]
    for i in range(N):
        V[i] = A[i][0] + A[i][1]
        V1[i] = A[i][0] - A[i][1]
    V .sort()
    V1 .sort()
    maximum = max(V[-1] - V[0], V1[-1] - V1[0])
    print(maximum)


if __name__ == "__main__":
    N = 3
    A = [[1, 2], [2, 3], [3, 4]]
    MaxDist(A, N)

# Expected output:
4
# maximum distance between two points in coordinate plane using rotating caliper 's method |  ; function calculates distance between two points ; function to find the maximum distance between any two points ; iterate over all possible pairs ; update maxm ; return actual distance ; 

from math import sqrt


def dist(p1, p2):
    x0 = p1[0] - p2[0]
    y0 = p1[1] - p2[1]
    return x0 * x0 + y0 * y0


def maxDist(p):
    n = len(p)
    maxm = 0
    for i in range(n):
        for j in range(i + 1, n):
            maxm = max(maxm, dist(p[i], p[j]))
    return sqrt(maxm)


if __name__ == '__main__':
    n = 5
    p = []
    p .append([4, 0])
    p .append([0, 2])
    p .append([-1, -7])
    p .append([1, 10])
    p .append([2, -3])
    print(maxDist(p))

# Expected output:
17.11724276862369
# reorder an array such that sum of left half is not equal to sum of right half | function to print the required reordering of the array if possible ; sort the array in increasing order ; if all elements are equal , then it is not possible ; else print the sorted array arr [ ] ; 
def printArr(arr, n):
    arr .sort()
    if (arr[0] == arr[n - 1]):
        print("No")
    else:
        print("Yes")
        for i in range(n):
            print(arr[i], end=" ")
        print()


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

# Expected output:
Yes
1 1 1 2 2 3
# maximize array sum by swapping at most k elements with another array | function to find the maximum sum ; if element of array a is smaller than that of array b , swap them . ; find sum of resultant array ; 
def maximumSum(a, b, k, n):
    a .sort()
    b .sort()
    i = 0
    j = n - 1
    while i < k:
        if (a[i] < b[j]):
            a[i], b[j] = b[j], a[i]
        else:
            break
        i += 1
        j -= 1
    sum = 0
    for i in range(n):
        sum += a[i]
    print(sum)


if __name__ == "__main__":
    K = 1
    A = [2, 3, 4]
    B = [6, 8, 5]
    N = len(A)
    maximumSum(A, B, K, N)

# Expected output:
15
# maximize distinct elements by incrementing / decrementing an element or keeping it same | function that maximize the count of distinct element ; sort thr list ; keeping track of previous change ; decrement is possible ; remain as it is ; increment is possible ; 
def max_dist_ele(arr, n):
    arr .sort()
    ans = 0
    prev = 0
    for i in range(n):
        if prev < (arr[i] - 1):
            ans += 1
            prev = arr[i] - 1
        elif prev < (arr[i]):
            ans += 1
            prev = arr[i]
        elif prev < (arr[i] + 1):
            ans += 1
            prev = arr[i] + 1
    return ans


arr = [1, 1, 1, 8, 8, 8, 9, 9]
n = len(arr)
print(max_dist_ele(arr, n))

# Expected output:
6
# find if array can be sorted by swaps limited to multiples of k | checksort function to check if array can be sorted ; sortarr is sorted array of arr ; if k = 1 then ( always possible to sort ) swapping can easily give sorted array ; comparing sortarray with array ; element at index j must be in j = i + l * k form where i = 0 , 1 , 2 , 3. . . where l = 0 , 1 , 2 , 3 , . . n - 1 ; if element is present then swapped ; if element of sorted array does not found in its sequence then flag remain zero that means arr can not be sort after swapping ; if flag is 0 not possible else possible ; 
def CheckSort(arr, k, n):
    sortarr = sorted(arr)
    if (k == 1):
        print("yes")
    else:
        for i in range(0, n):
            flag = 0
            for j in range(i, n, k):
                if (sortarr[i] == arr[j]):
                    arr[i], arr[j] = arr[j], arr[i]
                    flag = 1
                    break
                if (j + k >= n):
                    break
            if (flag == 0):
                break
        if (flag == 0):
            print("Not possible to sort")
        else:
            print("Possible to sort")


if __name__ == "__main__":
    k = 3
    arr = [1, 5, 6, 9, 2, 3, 5, 9]
    n = len(arr)
    CheckSort(arr, k, n)

# Expected output:
Possible to sort
# check whether an array can be made strictly decreasing by modifying at most one element | function that returns true if the array can be made strictly decreasing with at most one change ; to store the number of modifications required to make the array strictly decreasing ; check whether the last element needs to be modify or not ; check whether the first element needs to be modify or not ; loop from 2 nd element to the 2 nd last element ; check whether arr [ i ] needs to be modified ; modifying arr [ i ] ; check if arr [ i ] is equal to any of arr [ i - 1 ] or arr [ i + 1 ] ; if more than 1 modification is required ; 
def check(arr, n):
    modify = 0
    if (arr[n - 1] >= arr[n - 2]):
        arr[n - 1] = arr[n - 2] - 1
        modify += 1
    if (arr[0] <= arr[1]):
        arr[0] = arr[1] + 1
        modify += 1
    for i in range(n - 2, 0, -1):
        if (arr[i - 1] <= arr[i] and arr[i + 1] <= arr[i]
                ) or (arr[i - 1] >= arr[i] and arr[i + 1] >= arr[i]):
            arr[i] = (arr[i - 1] + arr[i + 1]) // 2
            modify += 1
            if (arr[i] == arr[i - 1] or arr[i] == arr[i + 1]):
                return False
    if (modify > 1):
        return False
    return True


if __name__ == "__main__":
    arr = [10, 5, 11, 3]
    n = len(arr)
    if (check(arr, n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# maximal disjoint intervals | function to find maximal disjoint set ; sort the list of intervals ; first interval will always be included in set ; end point of first interval ; check if given interval overlap with previously included interval , if not then include this interval and update the end point of last added interval ; 
def maxDisjointIntervals(list_):
    list_ .sort(key=lambda x: x[1])
    print("[", list_[0][0], ", ", list_[0][1], "]")
    r1 = list_[0][1]
    for i in range(1, len(list_)):
        l1 = list_[i][0]
        r2 = list_[i][1]
        if l1 > r1:
            print("[", l1, ", ", r2, "]")
            r1 = r2


if __name__ == "__main__":
    N = 4
    intervals = [[1, 4], [2, 3], [4, 6], [8, 9]]
    maxDisjointIntervals(intervals)

# Expected output:
[ 2 ,  3 ]
[ 4 ,  6 ]
[ 8 ,  9 ]
# print k different sorted permutations of a given array | utility function to print the original indices of the elements of the array ; function to print the required permutations ; to keep track of original indices ; sort the array ; count the number of swaps that can be made ; cannot generate 3 permutations ; print the first permutation ; find an index to swap and create second permutation ; print the last permutation ; 
def printIndices(n, a):
    for i in range(n):
        print(a[i][1], end=" ")
    print("",  end="")


def printPermutations(n, a, k):
    arr = [[0, 0]for i in range(n)]
    for i in range(n):
        arr[i][0] = a[i]
        arr[i][1] = i
    arr .sort(reverse=False)
    count = 1
    for i in range(1, n):
        if (arr[i][0] == arr[i - 1][0]):
            count += 1
    if (count < k):
        print("-1", end="")
        return
    next_pos = 1
    for i in range(k - 1):
        printIndices(n, arr)
        for j in range(next_pos, n):
            if (arr[j][0] == arr[j - 1][0]):
                temp = arr[j]
                arr[j] = arr[j - 1]
                arr[j - 1] = temp
                next_pos = j + 1
                break
    printIndices(n, arr)


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

# Expected output:
0 3 1 2 3 0 1 2 3 0 2 1
# maximum width of a binary tree | a binary tree node ; function to get the maximum width of a binary tree ; get width of each level and compare the width with maximum width so far ; get width of a 

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


def getWidth(root, level):
    if root is None:
        return 0
    if level == 1:
        return 1
    elif level > 1:
        return (
            getWidth(
                root .left,
                level -
                1) +
            getWidth(
                root .right,
                level -
                1))


def height(node):
    if node is None:
        return 0
    else:
        lHeight = height(node .left)
        rHeight = height(node .right)
        return (lHeight + 1)if (lHeight > rHeight)else (rHeight + 1)

def getMaxWidth(root):
    maxWidth = 0
    h = height(root)
    for i in range(1, h + 1):
        width = getWidth(root, i)
        if (width > maxWidth):
            maxWidth = width
    return maxWidth


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
root .right .right = Node(8)
root .right .right .left = Node(6)
root .right .right .right = Node(7)
print("Maximum width is %d" % (getMaxWidth(root)))

# Expected output:
Maximum width is 3
# divide n segments into two non | function to print the answer if it exists using the concept of merge overlapping segments ; sort the indices based on their corresponding value in v ; resultant array initialise all the values in resultant array with '2' except the first index of ' indices ' which is initialised as '1' initialise maxr to store the maximum of all right values encountered so far ; if the i - th index has any any point in common with the ( i - 1 ) th index classify it as '1' in resultant array and update maxr if necessary else we have found the breakpoint and we can exit the loop ; 
def printAnswer(v, n):
    indices = list(range(n))
    indices .sort(key=lambda i: v[i])
    res = [2] * n
    res[indices[0]] = 1
    maxR = v[indices[0]][1]
    for i in range(1, n):
        if maxR >= v[indices[i]][0]:
            res[indices[i]] = res[indices[i - 1]]
            maxR = max(maxR, v[indices[i]][1])
        else:
            break
    else:
        print("Not possible")
        return
    print(" ".join(map(str, res)))


if __name__ == "__main__":
    v = [[2, 8], [3, 4], [5, 8], [9, 10]]
    n = len(v)
    printAnswer(v, n)

# Expected output:
1 1 1 2
# count distinct elements in an array | this function prints all distinct elements ; creates an empty hashset ; traverse the input array ; if not present , then put it in hashtable and increment result ; 
def countDistinct(arr, n):
    s = set()
    res = 0
    for i in range(n):
        if (arr[i]not in s):
            s .add(arr[i])
            res += 1
    return res


arr = [6, 10, 5, 4, 9, 120, 4, 6, 10]
n = len(arr)
print(countDistinct(arr, n))

# Expected output:
6
# rearrange an array to maximize i * arr [ i ] | function to calculate the maximum points earned by making an optimal selection on the given array ; sorting the array ; variable to store the total points earned ; 
def findOptimalSolution(a, N):
    a .sort()
    points = 0
    for i in range(0, N):
        points += a[i] * i
    return points


if __name__ == "__main__":
    a = [1, 4, 2, 3, 9]
    N = len(a)
    print(findOptimalSolution(a, N))

# Expected output:
56
# minimum number of towers required such that every house is in the range of at least one tower | function to count the number of tower ; first we sort the house numbers ; for count number of towers ; for iterate all houses ; count number of towers ; find find the middle location ; traverse till middle location ; this is point to middle house where we insert the tower ; now find the last location ; traverse till last house of the range ; return the number of tower ; 
def number_of_tower(house, r, n):
    house .sort()
    numOfTower = 0
    i = 0
    while (i < n):
        numOfTower += 1
        loc = house[i] + r
        while (i < n and house[i] <= loc):
            i += 1
        i -= 1
        loc = house[i] + r
        while (i < n and house[i] <= loc):
            i += 1
    return numOfTower


if __name__ == "__main__":
    house = [7, 2, 4, 6, 5, 9, 12, 11]
    r = 2
    n = len(house)
    print(number_of_tower(house, r, n))

# Expected output:
3
# check if the characters of a given string are in alphabetical order | function that checks whether the string is in alphabetical order or not ; length of the string ; create a character array of the length of the string ; sort the character array ; check if the character array is equal to the string or not ; 
def isAlphabaticOrder(s):
    n = len(s)
    c = [s[i]for i in range(len(s))]
    c .sort(reverse=False)
    for i in range(n):
        if (c[i] != s[i]):
            return False
    return True


if __name__ == '__main__':
    s = "aabbbcc"
    if (isAlphabaticOrder(s)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# Sort first k values in ascending order and remaining n | function to sort the array ; Sort first k elements in ascending order ; Sort remaining n - k elements in descending order ; Our arr contains 8 elements
def printOrder(arr, n, k):
    a = arr[0:k]
    a .sort()
    b = arr[k:n]
    b .sort()
    b .reverse()
    return a + b


arr = [5, 4, 6, 2, 1, 3, 8, 9, -1]
k = 4
n = len(arr)
arr = printOrder(arr, n, k)
for i in range(n):
    print(arr[i], end=" ")

# Expected output:
2 4 5 6 9 8 3 1 -1
# maximum width of a binary tree | a binary tree node ; function to get the maximum width of a binary tree ; base case ; initialize result ; do level order traversal keeping track of number of nodes at every level ; get the size of queue when the level order traversal for one level finishes ; update the maximum node count value ; iterate for all the nodes in the queue currently ; dequeue an node from queue ;  ; 

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


def getMaxWidth(root):
    if root is None:
        return 0
    maxWidth = 0
    q = []
    q .insert(0, root)
    while (q != []):
        count = len(q)
        maxWidth = max(count, maxWidth)
        while (count != 0):
            count = count - 1
            temp = q[-1]
            q .pop()
            if temp .left is not None:
                q .insert(0, temp .left)
            if temp .right is not None:
                q .insert(0, temp .right)
    return maxWidth


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
root .right .right = Node(8)
root .right .right .left = Node(6)
root .right .right .right = Node(7)
print("Maximum width is %d" % (getMaxWidth(root)))

# Expected output:
Maximum width is 3