giulio98/xlcost-single-prompt huggingface dataset:
# deepest right leaf node in a binary tree | iterative approach | helper function that allocates a new node with the given data and none left and right poers . ; constructor to create a new node ; utility function to return level of given node ; create a queue for level order traversal ; traverse until the queue is empty ; since we go level by level , the last stored right leaf node is deepest one ; 

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


def getDeepestRightLeafNode(root):
    if (not root):
        return None
    q = []
    q .append(root)
    result = None
    while (len(q)):
        temp = q[0]
        q .pop(0)
        if (temp .left):
            q .append(temp .left)
        if (temp .right):
            q .append(temp .right)
            if (not temp .right .left and not temp .right .right):
                result = temp .right
    return result


if __name__ == '__main__':
    root = newnode(1)
    root .left = newnode(2)
    root .right = newnode(3)
    root .left .right = newnode(4)
    root .right .left = newnode(5)
    root .right .right = newnode(6)
    root .right .left .right = newnode(7)
    root .right .right .right = newnode(8)
    root .right .left .right .left = newnode(9)
    root .right .right .right .right = newnode(10)
    result = getDeepestRightLeafNode(root)
    if result:
        print("Deepest Right Leaf Node ::", result .data)
    else:
        print("No result, right leaf not found")

# Expected output:
Deepest Right Leaf Node :: 10
# check if two strings can be made equal by reversing a substring of one of the strings | function to check if the strings can be made equal or not by reversing a substring of x ; store the first index from the left which contains unequal characters in both the strings ; store the first element from the right which contains unequal characters in both the strings ; checks for the first index from left in which characters in both the strings are unequal ; store the current index ; break out of the loop ; checks for the first index from right in which characters in both the strings are unequal ; store the current index ; break out of the loop ; reverse the substring x [ l , r ] ; if x and y are equal ; otherwise ; 
def checkString(X, Y):
    L = -1
    R = -1
    for i in range(len(X)):
        if (X[i] != Y[i]):
            L = i
            break
    for i in range(len(X) - 1, 0, -1):
        if (X[i] != Y[i]):
            R = i
            break
    X = list(X)
    X = X[:L] + X[R:L - 1:-1] + X[R + 1:]
    if (X == list(Y)):
        print("Yes")
    else:
        print("No")


if __name__ == "__main__":
    X = "adcbef"
    Y = "abcdef"
    checkString(X, Y)

# Expected output:
Yes
# maximum length of same indexed subarrays from two given arrays satisfying the given condition | function to find maximum length of subarray such that sum of maximum element in subarray in brr [ ] and sum of subarray in [ ] arr * k is at most c ; base case ; let maximum length be 0 ; perform binary search ; find mid value ; check if the current mid satisfy the given condition ; if yes , then store length ; otherwise ; return maximum length stored ; function to check if it is possible to have such a subarray of length k ; finds the maximum element in each window of size k ; check for window of size k ; for all possible subarrays of length k ; until deque is empty ; calculate the total cost and check if less than equal to c ; find sum of current subarray and the total cost ; include the new element of current subarray ; discard the element of last subarray ; remove all the elements in the old window ; calculate total cost and check <= c ; if current subarray length satisfies ; if it is not possible ; 
def possible(a, b, n, c, k):
    dq = []
    Sum = 0
    for i in range(k):
        Sum += a[i]
        while (len(dq) > 0 and b[i] > b[dq[len(dq) - 1]]):
            dq .pop(len(dq) - 1)
        dq .append(i)
    total_cost = Sum * k + b[dq[0]]
    if (total_cost <= c):
        return True
    for i in range(k, n):
        Sum += a[i]
        Sum -= a[i - k]
        while (len(dq) > 0 and dq[0] <= i - k):
            dq .pop(0)
        while (len(dq) > 0 and b[i] > b[dq[len(dq) - 1]]):
            dq .pop(len(dq) - 1)
        dq .append(i)
        total_cost = Sum * k + b[dq[0]]
        if (total_cost <= c):
            return True
    return False


def maxLength(a, b, n, c):
    if (n == 0):
        return 0
    max_length = 0
    low = 0
    high = n
    while (low <= high):
        mid = int(low + (high - low) / 2)
        if (possible(a, b, n, c, mid)):
            max_length = mid
            low = mid + 1
        else:
            high = mid - 1
    return max_length


A = [1, 2, 1, 6, 5, 5, 6, 1]
B = [14, 8, 15, 15, 9, 10, 7, 12]
N = len(A)
C = 40
print(maxLength(A, B, N, C))

# Expected output:
3
# program to find the nth natural number with exactly two bits set | set 2 | function to find the nth number with exactly two bits set ; initialize variables ; initialize the range in which the value of ' a ' is present ; perform binary search ; find the mid value ; update the range using the mid value t ; find b value using a and n ; print the value 2 ^ a + 2 ^ b ; 
def findNthNum(N):
    last_num = 0
    left = 1
    right = N
    while (left <= right):
        mid = left + (right - left) // 2
        t = (mid * (mid + 1)) // 2
        if (t < N):
            left = mid + 1
        elif (t == N):
            a = mid
            break
        else:
            a = mid
            right = mid - 1
    t = a - 1
    b = N - (t * (t + 1)) // 2 - 1
    print((1 << a) + (1 << b))


if __name__ == "__main__":
    N = 15
    findNthNum(N)

# Expected output:
48
# longest subsequence having maximum sum | function to find the longest subsequence from the given array with maximum sum ; stores the largest element of the array ; if max is less than 0 ; print the largest element of the array ; traverse the array ; if arr [ i ] is greater than or equal to 0 ; print elements of the subsequence ; 
def longestSubWithMaxSum(arr, N):
    Max = max(arr)
    if (Max < 0):
        print(Max)
        return
    for i in range(N):
        if (arr[i] >= 0):
            print(arr[i], end=" ")


arr = [1, 2, -4, -2, 3, 0]
N = len(arr)
longestSubWithMaxSum(arr, N)

# Expected output:
1 2 3 0
# check if string s2 can be obtained by appending subsequences of string s1 | python3 program to implement the above approach ; function for finding minimum number of operations ; stores the length of strings ; stores frequency of characters in string s ; update frequencies of character in s ; traverse string s1 ; if any character in s1 is not present in s ; stores the indices of each character in s ; traverse string s ; store indices of characters ; stores index of last appended character ; traverse string s1 ; find the index of next character that can be appended ; check if the current character be included in the current subsequence ; otherwise ; start a new subsequence ; update index of last character appended ; 

from bisect import bisect, bisect_left, bisect_right


def findMinimumOperations(s, s1):
    n = len(s)
    m = len(s1)
    frequency = [0] * 26
    for i in range(n):
        frequency[ord(s[i]) - ord('a')] += 1
    for i in range(m):
        if (frequency[ord(s1[i]) - ord('a')] == 0):
            return -1
    indices = [[]for i in range(26)]
    for i in range(n):
        indices[ord(s[i]) - ord('a')].append(i)
    ans = 2
    last = len(indices[ord(s1[0]) - ord('a')]) - 1
    for i in range(1, m):
        ch = ord(s1[i]) - ord('a')
        it = bisect_right(indices[ch], last)
        if (it != len(indices[ch])):
            last = it
        else:
            ans += 1
            last = len(indices[ch])
    return ans


if __name__ == '__main__':
    S1 = "acebcd"
    S2 = "acbcde"
    ans = findMinimumOperations(S1, S2)
    if (ans == -1):
        print("NO")
    else:
        print("YES")
        print(ans)

# Expected output:
YES
2
# print first k distinct moran numbers from a given array |  ; function to calculate the sum of digits of a number ; stores the sum of digits ; add the digit to sum ; remove digit ; returns the sum of digits ; function to check if a number is prime or not ; if r has any divisor ; set r as non - prime ; function to check if a number is moran number ; calculate sum of digits ; check if n is divisible by the sum of digits ; calculate the quotient ; if the quotient is prime ; function to print the first k moran numbers from the array ; sort the given array ; initialise a set ; traverse the array from the end ; if the current array element is a moran number ; insert into the set ; 

import math


def digiSum(a):
    sums = 0
    while (a != 0):
        sums += a % 10
        a = a // 10
    return sums


def isPrime(r):
    s = True
    for i in range(2, int(math .sqrt(r)) + 1):
        if (r % i == 0):
            s = False
            break
    return s


def isMorannumber(n):
    dup = n
    sums = digiSum(dup)
    if (n % sums == 0):
        c = n // sums
        if isPrime(c):
            return True
    return False


def FirstKMorannumber(a, n, k):
    X = k
    a .sort()
    s = set()
    for i in range(n - 1, -1, -1):
        if (k <= 0):
            break
        if (isMorannumber(a[i])):
            s .add(a[i])
            k -= 1
    if (k > 0):
        print(X, end=' Moran numbers are not ' 'present in the array')
        return
    lists = sorted(s)
    for i in lists:
        print(i, end=', ')


if __name__ == '__main__':
    A = [34, 198, 21, 42, 63, 45, 22, 44, 43]
    K = 4
    N = len(A)
    FirstKMorannumber(A, N, K)

# Expected output:
42, 45, 63, 198,
# number of pairs whose sum is a power of 2 | set 2 | python3 program to implement the above approach ; function to count all pairs whose sum is a power of two ; stores the frequency of each element of the array ; update frequency of array elements ; stores count of required pairs ; current power of 2 ; traverse the array ; if pair does not exist ; increment count of pairs ; return the count of pairs ; 

from math import pow


def countPair(arr, n):
    m = {}
    for i in range(n):
        m[arr[i]] = m .get(arr[i], 0) + 1
    ans = 0
    for i in range(31):
        key = int(pow(2, i))
        for j in range(n):
            k = key - arr[j]
            if k not in m:
                continue
            else:
                ans += m .get(k, 0)
            if (k == arr[j]):
                ans += 1
    return ans // 2


if __name__ == '__main__':
    arr = [1, 8, 2, 10, 6]
    n = len(arr)
    print(countPair(arr, n))

# Expected output:
5
# counting rock samples | tcs codevita 2020 | function to find the rock samples in the ranges ; iterate over the ranges ; 
def findRockSample(ranges, n, r, arr):
    a = []
    for i in range(r):
        c = 0
        l, h = ranges[i][0], ranges[i][1]
        for val in arr:
            if l <= val <= h:
                c += 1
        a .append(c)
    return a


if __name__ == "__main__":
    n = 5
    r = 2
    arr = [400, 567, 890, 765, 987]
    ranges = [[300, 380], [800, 1000]]
    print(*findRockSample(ranges, n, r, arr))

# Expected output:
0 2
# n digit numbers having difference between the first and last digits as k | function to store and check the difference of digits ; base case ; last digit of the number to check the difference from the first digit ; condition to avoid repeated values ; update the string pt ; recursive call ; update the string pt ; recursive call ; any number can come in between first and last except the zero ; recursive call ; function to place digit of the number ; when n is 1 and k > 0 , then the single number will be the first and last digit it cannot have difference greater than 0 ; this loop place the digit at the starting ; recursive call ; vector to store results ; generate all the resultant number ; print the result ; 

result = []


def findNumbers(st, prev, n, K):
    global result
    if (len(st) == n):
        result .append(int(st))
        return
    if (len(st) == n - 1):
        if (prev - K >= 0):
            pt = ""
            pt += prev - K + 48
            findNumbers(st + pt, prev - K, n, K)
        if (K != 0 and prev + K < 10):
            pt = ""
            pt += prev + K + 48
            findNumbers(st + pt, prev + K, n, K)
    else:
        for j in range(1, 10, 1):
            pt = ""
            pt += j + 48
            findNumbers(st + pt, prev, n, K)


def numDifference(N, K):
    global result
    st = ""
    if (N == 1 and K == 0):
        result .append(0)
    elif (N == 1 and K > 0):
        return result
    for i in range(1, 10, 1):
        temp = ""
        temp += str(48 + i)
        findNumbers(st + temp, i, N, K)
        st = ""
    return result


def numDifferenceUtil(N, K):
    res = []
    res = numDifference(N, K)
    for i in range(1, len(res)):
        print(res[i] + 40, end=" ")
        break


if __name__ == '__main__':
    N = 2
    K = 9
    numDifferenceUtil(N, K)

# Expected output:
90
# minimum number of bullets required to penetrate all bricks | function to find the minimum number of bullets required to penetrate all bricks ; sort the points in ascending order ; check if there are no points ; iterate through all the points ; increase the count ; return the count ; 
def findMinBulletShots(points):
    for i in range(len(points)):
        points[i] = points[i][::-1]
    points = sorted(points)
    for i in range(len(points)):
        points[i] = points[i][::-1]
    if (len(points) == 0):
        return 0
    cnt = 1
    curr = points[0][1]
    for j in range(1, len(points)):
        if (curr < points[j][0]):
            cnt += 1
            curr = points[j][1]
    return cnt


if __name__ == '__main__':
    bricks = [[5000, 900000], [1, 100], [150, 499]]
    print(findMinBulletShots(bricks))

# Expected output:
3
# count array elements that can be maximized by adding any permutation of first n natural numbers | function to get the count of values that can have the maximum value ; sort array in decreasing order ; stores the answer ; mark stores the maximum value till each index i ; check if arr [ i ] can be maximum ; update the mark ; print the total count ; 
def countMaximum(a, n):
    a .sort(reverse=True)
    count = 0
    mark = 0
    for i in range(n):
        if ((a[i] + n >= mark)):
            count += 1
        mark = max(mark, a[i] + i + 1)
    print(count)


if __name__ == '__main__':
    arr = [8, 9, 6]
    N = len(arr)
    countMaximum(arr, N)

# Expected output:
2
# kth character from the nth string obtained by the given operations | function to return kth character from recursive string ; if n is 1 then return a ; iterate a loop and generate the recursive string ; update current string ; change a to b and b to a ; reverse the previous string ; return the kth character ; 
def findKthChar(n, k):
    prev = "A"
    cur = ""
    if (n == 1):
        return 'A'
    for i in range(2, n + 1):
        cur = prev + "B"
        temp1 = [y for y in prev]
        for i in range(len(prev)):
            if (temp1[i] == 'A'):
                temp1[i] = 'B'
            else:
                temp1[i] = 'A'
        temp1 = temp1[::-1]
        prev = "".join(temp1)
        cur += prev
        prev = cur
    return cur[k - 1]


if __name__ == '__main__':
    N = 4
    K = 3
    print(findKthChar(N, K))

# Expected output:
B
# maximize length of subarray of equal elements by performing at most k increment operations | python3 program for above approach ; function to find the maximum length of subarray of equal elements after performing at most k increments ; length of array ; stores the size of required subarray ; starting po of a window ; stores the sum of window ; iterate over array ; current element ; remove index of minimum elements from deque which are less than the current element ; insert current index in deque ; update current window sum ; calculate required operation to make current window elements equal ; if cost is less than k ; shift window start pointer towards right and update current window sum ; return answer ; 

from collections import deque


def maxSubarray(a, k):
    n = len(a)
    answer = 0
    start = 0
    s = 0
    dq = deque()
    for i in range(n):
        x = a[i]
        while (len(dq) > 0 and a[dq[-1]] <= x):
            dq .popleft()
        dq .append(i)
        s += x
        cost = a[dq[0]] * (answer + 1) - s
        if (cost <= k):
            answer += 1
        else:
            if (dq[0] == start):
                dq .popleft()
            s -= a[start]
            start += 1
    return answer


if __name__ == '__main__':
    a = [2, 2, 4]
    k = 10
    print(maxSubarray(a, k))

# Expected output:
3
# find depth of the deepest odd level leaf node | a binary tree node ; a recursive function to find depth of the deepest odd level leaf node ; base case ; if this node is leaf and its level is odd , return its level ; if not leaf , return the maximum value from left and right subtrees ; main function which calculates the depth of deepest odd level leaf . this function mainly uses depthofoddleafutil ( ) ; 

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


def depthOfOddLeafUtil(root, level):
    if root is None:
        return 0
    if root .left is None and root .right is None and level & 1:
        return level
    return (max(depthOfOddLeafUtil(root .left, level + 1),
            depthOfOddLeafUtil(root .right, level + 1)))


def depthOfOddLeaf(root):
    level = 1
    depth = 0
    return depthOfOddLeafUtil(root, level)


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)
root .right .right .right .right .left = Node(11)
print("%d is the required depth" % (depthOfOddLeaf(root)))

# Expected output:
5 is the required depth
# check if an array can be split into subarrays with gcd exceeding k | function to check if it is possible to split an array into subarrays having gcd at least k ; iterate over the array arr [ ] ; if the current element is less than or equal to k ; if no array element is found to be less than or equal to k ; 
def canSplitArray(arr, n, k):
    for i in range(n):
        if (arr[i] <= k):
            return "No"
    return "Yes"


if __name__ == '__main__':
    arr = [2, 4, 6, 1, 8, 16]
    N = len(arr)
    K = 3
    print(canSplitArray(arr, N, K))

# Expected output:
No
# smallest subarray from a given array with sum greater than or equal to k | set 2 | function to find the smallest subarray sum greater than or equal to target ; base case ; if sum of the array is less than target ; if target is equal to the sum of the array ; required condition ; 
def smallSumSubset(data, target, maxVal):
    if target <= 0:
        return 0
    elif sum(data) < target:
        return maxVal
    elif sum(data) == target:
        return len(data)
    elif data[0] >= target:
        return 1
    elif data[0] < target:
        return min(smallSumSubset(data[1:], target, maxVal), 1 + smallSumSubset(data[1:], target - data[0], maxVal))


data = [3, 1, 7, 1, 2]
target = 11
val = smallSumSubset(data, target, len(data) + 1)
if val > len(data):
    print(-1)
else:
    print(val)

# Expected output:
3
# maximize cost obtained by removal of substrings " pr " or " rp " from a given string | function to maintain the case , x >= y ; to maintain x >= y ; replace ' p ' to 'r ; replace ' r ' to ' p ' . ; function to return the maximum cost ; stores the length of the string ; to maintain x >= y . ; stores the maximum cost ; stores the count of ' p ' after removal of all " pr " substrings up to str [ i ] ; stores the count of ' r ' after removal of all " pr " substrings up to str [ i ] ; stack to maintain the order of characters after removal of substrings ; if substring " pr " is removed ; increase cost by x ; if any substring " rp " left in the stack ; if any substring " rp " left in the stack ; 
def swapXandY(str, X, Y):

    N = len(str)
    X, Y = Y, X

    for i in range(N):
        if (str[i] == 'p'):
            str[i] = 'r'
        elif (str[i] == 'r'):
            str[i] = 'p'


def maxCost(str, X, Y):
    N = len(str)
    if (Y > X):
        swapXandY(str, X, Y)
    res = 0
    countP = 0
    countR = 0
    for i in range(N):
        if (str[i] == 'p'):
            countP += 1

        elif (str[i] == 'r'):
            if (countP > 0):
                countP -= 1
                res += X

            else:
                countR += 1

        else:
            res += min(countP, countR) * Y
            countP = 0
            countR = 0
    res += min(countP, countR) * Y

    return res


str = "abppprrr"
X = 5
Y = 4
print(maxCost(str, X, Y))

# Expected output:
15
# check if an array contains only one distinct element | function to find if the array contains only one distinct element ; assume first element to be the unique element ; traversing the array ; if current element is not equal to x then break the loop and print no ; compare and print the result ; 
def uniqueElement(arr):
    x = arr[0]
    flag = 1
    for i in range(len(arr)):
        if (arr[i] != x):
            flag = 0
            break
    if (flag == 1):
        print("Yes")
    else:
        print("No")


arr = [9, 9, 9, 9, 9, 9, 9]
uniqueElement(arr)

# Expected output:
Yes
# maximum count of pairs having equal sum based on the given conditions | function to find the maximum count of pairs having equal sum ; size of the array ; iterate through evey sum of pairs possible from the given array ; count of pairs with given sum ; check for a possible pair ; update count of possible pair ; update the answer by taking the pair which is maximum for every possible sum ; return the max possible pair ; function to return the count of pairs ; size of the array ; stores the frequencies ; count the frequency ; 
def maxCount(freq, maxi, mini):
    n = len(freq) - 1
    ans = 0
    sum = 2 * mini
    while sum <= 2 * maxi:
        possiblePair = 0
        for firElement in range(1, (sum + 1) // 2):
            if (sum - firElement <= maxi):
                possiblePair += min(freq[firElement], freq[sum - firElement])
        sum += 1
        if (sum % 2 == 0):
            possiblePair += freq[sum // 2] // 2
        ans = max(ans, possiblePair)
    return ans


def countofPairs(a):
    n = len(a)
    freq = [0] * (n + 1)
    maxi = -1
    mini = n + 1
    for i in range(len(a)):
        maxi = max(maxi, a[i])
        mini = min(mini, a[i])
    for i in range(n):
        freq[a[i]] += 1
    return maxCount(freq, maxi, mini)


if __name__ == "__main__":
    a = [1, 2, 4, 3, 3, 5, 6]
    print(countofPairs(a))

# Expected output:
3
# maximum subarray sum possible by replacing an array element by its square | function to find the maximum subarray sum possible ; stores sum without squaring ; stores sum squaring ; stores the maximum subarray sum ; either extend the subarray or start a new subarray ; either extend previous squared subarray or start a new subarray by squaring the current element ; update maximum subarray sum ; return answer ; 
def getMaxSum(a, n):
    dp = [[0 for x in range(2)]for y in range(n)]
    dp[0][0] = a[0]
    dp[0][1] = a[0] * a[0]
    max_sum = max(dp[0][0], dp[0][1])
    for i in range(1, n):
        dp[i][0] = max(a[i], dp[i - 1][0] + a[i])
        dp[i][1] = max(dp[i - 1][1] + a[i], a[i] * a[i])
        dp[i][1] = max(dp[i][1], dp[i - 1][0] + a[i] * a[i])
        max_sum = max(max_sum, dp[i][1])
        max_sum = max(max_sum, dp[i][0])
    return max_sum


n = 5
a = [1, -5, 8, 12, -8]
print(getMaxSum(a, n))

# Expected output:
152