giulio98/xlcost-single-prompt huggingface dataset:
# get level of a node in binary tree | iterative approach | python3 program to find closest value in binary search tree ; helper function that allocates a new node with the given data and none left and right poers . ; utility function to return level of given node ; extra none is appended to keep track of all the nodes to be appended before level is incremented by 1 ; 

_MIN = -2147483648
_MAX = 2147483648


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


def getlevel(root, data):
    q = []
    level = 1
    q .append(root)
    q .append(None)
    while (len(q)):
        temp = q[0]
        q .pop(0)
        if (temp is None):
            if len(q) == 0:
                return 0
            if (q[0] is not None):
                q .append(None)
            level += 1
        else:
            if (temp .data == data):
                return level
            if (temp .left):
                q .append(temp .left)
            if (temp .right):
                q .append(temp .right)
    return 0


if __name__ == '__main__':
    root = getnode(20)
    root .left = getnode(10)
    root .right = getnode(30)
    root .left .left = getnode(5)
    root .left .right = getnode(15)
    root .left .right .left = getnode(12)
    root .right .left = getnode(25)
    root .right .right = getnode(40)
    level = getlevel(root, 30)
    if level != 0:
        print("level of node 30 is", level)
    else:
        print("node 30 not found")
    level = getlevel(root, 12)
    if level != 0:
        print("level of node 12 is", level)
    else:
        print("node 12 not found")
    level = getlevel(root, 25)
    if level != 0:
        print("level of node 25 is", level)
    else:
        print("node 25 not found")
    level = getlevel(root, 27)
    if level != 0:
        print("level of node 27 is", level)
    else:
        print("node 27 not found")

# Expected output:
level of node 30 is 2
level of node 12 is 4
level of node 25 is 3
node 27 not found
# lexicographically smallest palindromic path in a binary tree | struct binary tree node ; function to check if the is palindrome or not ; function to find the lexicographically smallest palindromic path in the binary tree ; base case ; append current node 's  data to the string ; check if a node is leaf or not ; check for the 1 st palindromic path ; store lexicographically the smallest palindromic path ; recursively traverse left subtree ; recursively traverse right subtree ; function to get smallest lexographical palindromic path ; variable which stores the final result ; function call to compute lexicographically smallest palindromic path ; 

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


def checkPalindrome(s):
    low, high = 0, len(s) - 1
    while (low < high):
        if (s[low] != s[high]):
            return False
        low += 1
        high -= 1
    return True


def lexicographicallySmall(root, s):
    global finalAns
    if (root is None):
        return
    s += root .data
    if (not root .left and not root .right):
        if (checkPalindrome(s)):
            if (finalAns == "$"):
                finalAns = s
            else:
                finalAns = min(finalAns, s)
        return
    lexicographicallySmall(root .left, s)
    lexicographicallySmall(root .right, s)


def getPalindromePath(root):
    global finalAns
    finalAns = "$"
    lexicographicallySmall(root, "")
    if (finalAns == "$"):
        print("No Palindromic Path exists")
    else:
        print(finalAns)


if __name__ == '__main__':
    finalAns = ""
    root = Node('a')
    root .left = Node('c')
    root .left .left = Node('a')
    root .left .right = Node('g')
    root .right = Node('b')
    root .right .left = Node('b')
    root .right .right = Node('x')
    root .right .left .right = Node('a')
    getPalindromePath(root)

# Expected output:
abba
# find mirror of a given node in binary tree | python3 program to find the mirror node in binary tree ; a binary tree node has data , reference to left child and a reference to right child ; recursive function to find mirror ; if any of the node is none then node itself and decendent have no mirror , so return none , no need to further explore ! ; if left node is target node , then return right 's key (that is mirror) and vice versa ; first recur external nodes ; if no mirror found , recur internal nodes ; interface for mirror search ; 

class Node:
    def __init__(self, key, lchild=None, rchild=None):
        self .key = key
        self .lchild = None
        self .rchild = None


def findMirrorRec(target, left, right):
    if left is None or right is None:
        return None
    if left .key == target:
        return right .key
    if right .key == target:
        return left .key
    mirror_val = findMirrorRec(target, left .lchild, right .rchild)
    if mirror_val is not None:
        return mirror_val
    findMirrorRec(target, left .rchild, right .lchild)


def findMirror(root, target):
    if root is None:
        return None
    if root .key == target:
        return target
    return findMirrorRec(target, root .lchild, root .rchild)


def main():
    root = Node(1)
    n1 = Node(2)
    n2 = Node(3)
    root .lchild = n1
    root .rchild = n2
    n3 = Node(4)
    n4 = Node(5)
    n5 = Node(6)
    n1 .lchild = n3
    n2 .lchild = n4
    n2 .rchild = n5
    n6 = Node(7)
    n7 = Node(8)
    n8 = Node(9)
    n3 .rchild = n6
    n4 .lchild = n7
    n4 .rchild = n8
    target = n3 .key
    mirror = findMirror(root, target)
    print("Mirror of node {} is node {}".format(target, mirror))


if __name__ == '__main__':
    main()

# Expected output:
Mirror of node 4 is node 6
# smallest substring with each letter occurring both in uppercase and lowercase | python 3 program for the above approach ; function to check if the current string is balanced or not ; for every character , check if there exists uppercase as well as lowercase characters ; function to find smallest length substring in the given string which is balanced ; store frequency of lowercase characters ; stores frequency of uppercase characters ; count frequency of characters ; mark those characters which are not present in both lowercase and uppercase ; initialize the frequencies back to 0 ; marks the start and end of current substring ; marks the start and end of required substring ; stores the length of smallest balanced substring ; remove all characters obtained so far ; remove extra characters from front of the current substring ; if substring ( st , i ) is balanced ; no balanced substring ; store answer string ; 

import sys


def balanced(small, caps):
    for i in range(26):
        if (small[i] != 0 and (caps[i] == 0)):
            return 0
        elif ((small[i] == 0) and (caps[i] != 0)):
            return 0
    return 1


def smallestBalancedSubstring(s):
    small = [0 for i in range(26)]
    caps = [0 for i in range(26)]
    for i in range(len(s)):
        if (ord(s[i]) >= 65 and ord(s[i]) <= 90):
            caps[ord(s[i]) - 65] += 1
        else:
            small[ord(s[i]) - 97] += 1
    mp = {}
    for i in range(26):
        if (small[i] and caps[i] == 0):
            mp[chr(i + 97)] = 1
        elif (caps[i] and small[i] == 0):
            mp[chr(i + 65)] = 1
    for i in range(len(small)):
        small[i] = 0
        caps[i] = 0
    i = 0
    st = 0
    start = -1
    end = -1
    minm = sys .maxsize
    while (i < len(s)):
        if (s[i] in mp):
            while (st < i):
                if (ord(s[st]) >= 65 and ord(s[st]) <= 90):
                    caps[ord(s[st]) - 65] -= 1
                else:
                    small[ord(s[st]) - 97] -= 1
                st += 1
            i += 1
            st = i
        else:
            if (ord(s[i]) >= 65 and ord(s[i]) <= 90):
                caps[ord(s[i]) - 65] += 1
            else:
                small[ord(s[i]) - 97] += 1
            while (1):
                if (ord(s[st]) >= 65 and ord(s[st]) <=
                        90 and caps[ord(s[st]) - 65] > 1):
                    caps[ord(s[st]) - 65] -= 1
                    st += 1
                elif (ord(s[st]) >= 97 and ord(s[st]) <= 122 and small[ord(s[st]) - 97] > 1):
                    small[ord(s[st]) - 97] -= 1
                    st += 1
                else:
                    break
            if (balanced(small, caps)):
                if (minm > (i - st + 1)):
                    minm = i - st + 1
                    start = st
                    end = i
            i += 1
    if (start == -1 or end == -1):
        print(-1)
    else:
        ans = ""
        for i in range(start, end + 1, 1):
            ans += s[i]
        print(ans)


if __name__ == '__main__':
    s = "azABaabba"
    smallestBalancedSubstring(s)

# Expected output:
ABaab
# convert given string to another by minimum replacements of subsequences by its smallest character | function to return the minimum number of operation ; storing data ; initialize both arrays ; stores the index of character ; filling str1array , convchar and hashmap convertmap . ; not possible to convert ; calculate result initializing return values ; iterating the character from the end ; increment the number of operations ; not possible to convert ; to check whether the final element has been added in set s or not . ; check if v1 [ j ] is present in hashmap or not ; already converted then then continue ; not possible to convert ; print the result ; 
def transformString(str1, str2):
    N = len(str1)
    convChar = []
    str1array = []
    for i in range(26):
        convChar .append([])
        str1array .append([])
    convertMap = {}
    for i in range(N):
        str1array[ord(str1[i]) - ord('a')].append(i)
    for i in range(N):
        if (str1[i] < str2[i]):
            print(-1)
            return
        elif (str1[i] == str2[i]):
            continue
        else:
            convChar[ord(str2[i]) - ord('a')].append(i)
            convertMap[i] = str2[i]
    ret = 0
    retv = []
    for i in range(25, -1, -1):
        v = convChar[i]
        if (len(v) == 0):
            continue
        ret += 1
        v1 = str1array[i]
        if (len(v1) == 0):
            print(-1)
            return
        isScompleted = False
        for j in range(len(v1)):
            if (v1[j] in convertMap):
                a = v1[j]
                if (a > i + ord('a')):
                    continue
                else:
                    v .append(v1[j])
                    isScompleted = True
                    retv .append(v)
                    break
            else:
                v .append(v1[j])
                isScompleted = True
                retv .append(v)
                break
        if (isScompleted == False):
            print(-1)
            return
    print(ret)


A = "abcab"
B = "aabab"
transformString(A, B)

# Expected output:
2
# smallest number containing all possible n length permutations using digits 0 to d | initialize set to see if all the possible permutations are present in the min length string ; to keep min length string ; generate the required string ; iterate over all possible character ; append to make a new string ; if the new string is not visited ; add in set ; call the dfs function on the last d characters ; base case ; append '0' n - 1 times ; call the dfs function ; 

visited = set()
ans = []


def dfs(curr, D):
    for c in range(D):
        c = str(c)
        neighbour = curr + c
        if neighbour not in visited:
            visited .add(neighbour)
            dfs(neighbour[1:], D)
            ans .append(c)


def reqString(N, D):
    if (N == 1 and D == 1):
        return "0"
    start = ''.join(['0'] * (N - 1))
    dfs(start, D)
    ans .extend(['0'] * (N - 1))
    return ''.join(ans)


if __name__ == '__main__':
    N, D = 2, 2
    print(reqString(N, D))

# Expected output:
01100
# check if a string is a scrambled form of another string | python3 program to check if a given string is a scrambled form of another string ; strings of non - equal length cant ' be scramble strings ; empty strings are scramble strings ; equal strings are scramble strings ; check for the condition of anagram ; check if s2 [ 0. . . i ] is a scrambled string of s1 [ 0. . . i ] and if s2 [ i + 1. . . n ] is a scrambled string of s1 [ i + 1. . . n ] ; check if s2 [ 0. . . i ] is a scrambled string of s1 [ n - i ... n ] and s2 [ i + 1. . . n ] is a scramble string of s1 [ 0. . . n - i - 1 ] ; if none of the above conditions are satisfied ; 
def isScramble(S1: str, S2: str):
    if len(S1) != len(S2):
        return False
    n = len(S1)
    if not n:
        return True
    if S1 == S2:
        return True
    if sorted(S1) != sorted(S2):
        return False
    for i in range(1, n):
        if (isScramble(S1[:i], S2[:i]) and isScramble(S1[i:], S2[i:])):
            return True
        if (isScramble(S1[-i:], S2[:i]) and isScramble(S1[:-i], S2[i:])):
            return True
    return False


if __name__ == "__main__":
    S1 = "coder"
    S2 = "ocred"
    if (isScramble(S1, S2)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# smallest number possible by swapping adjacent even odd pairs | function to return the smallest number possible ; arrays to store odd and even digits in the order of their appearance in the given string ; insert the odd and even digits ; pointer to odd digit ; pointer to even digit ; in case number of even and odd digits are not equal if odd digits are remaining ; if even digits are remaining ; removal of leading 0 's  ; 
def findAns(s):
    odd = []
    even = []
    for c in s:
        digit = int(c)
        if (digit & 1):
            odd .append(digit)
        else:
            even .append(digit)
    i = 0
    j = 0
    ans = ""
    while (i < len(odd) and j < len(even)):
        if (odd[i] < even[j]):
            ans += str(odd[i])
            i = i + 1
        else:
            ans += str(even[j])
            j = j + 1
    while (i < len(odd)):
        ans += str(odd[i])
        i = i + 1
    while (j < len(even)):
        ans += str(even[j])
        j = j + 1
    while (ans[0] == '0'):
        ans = ans[1:]
    return ans


s = "894687536"
print(findAns(s))

# Expected output:
846869753
# program to convert bcd number into decimal number | function to convert bcd to decimal ; iterating through the bits backwards ; forming the equivalent digit ( 0 to 9 ) from the group of 4. ; reinitialize all variables and compute the number ; update the answer ; reverse the number formed . ; 
def bcdToDecimal(s):
    length = len(s)
    check = 0
    check0 = 0
    num = 0
    sum = 0
    mul = 1
    rev = 0
    for i in range(length - 1, -1, -1):
        sum += (ord(s[i]) - ord('0')) * mul
        mul *= 2
        check += 1
        if (check == 4 or i == 0):
            if (sum == 0 and check0 == 0):
                num = 1
                check0 = 1
            else:
                num = num * 10 + sum
            check = 0
            sum = 0
            mul = 1
    while (num > 0):
        rev = rev * 10 + (num % 10)
        num //= 10
    if (check0 == 1):
        return rev - 1
    return rev


if __name__ == "__main__":
    s = "100000101000"
    print(bcdToDecimal(s))

# Expected output:
828
# find count of single valued subtrees | utility function to create a new node ; this function increments count by number of single valued subtrees under root . it returns true if subtree under root is singly , else false . ; return false to indicate none ; recursively count in left and right subtress also ; if any of the subtress is not singly , then this cannot be singly ; if left subtree is singly and non - empty , but data doesn 't match ; same for right subtree ; if none of the above conditions is true , then tree rooted under root is single valued , increment count and return true ; this function mainly calss countsinglerec ( ) after initializing count as 0 ; 

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


def countSingleRec(root, count):
    if root is None:
        return True
    left = countSingleRec(root .left, count)
    right = countSingleRec(root .right, count)
    if left == False or right == False:
        return False
    if root .left and root .data != root .left .data:
        return False
    if root .right and root .data != root .right .data:
        return False
    count[0] += 1
    return True


def countSingle(root):
    count = [0]
    countSingleRec(root, count)
    return count[0]


root = Node(5)
root .left = Node(4)
root .right = Node(5)
root .left .left = Node(4)
root .left .right = Node(4)
root .right .right = Node(5)
countSingle(root)
print("Count of Single Valued Subtress is", countSingle(root))

# Expected output:
Count of Single Valued Subtress is 5
# bitwise xor of a binary array | function to return the bitwise xor of all the binary strings ; get max size and reverse each string since we have to perform xor operation on bits from right to left reversing the string will make it easier to perform operation from left to right ; add 0 s to the end of strings if needed ; perform xor operation on each bit ; reverse the resultant string to get the final string ; return the final string ; 

import sys


def strBitwiseXOR(arr, n):
    result = ""
    max_len = -1
    for i in range(n):
        max_len = max(max_len, len(arr[i]))
        arr[i] = arr[i][::-1]
    for i in range(n):
        s = ""
        for j in range(max_len - len(arr[i])):
            s += "0"
        arr[i] = arr[i] + s
    for i in range(max_len):
        pres_bit = 0
        for j in range(n):
            pres_bit = pres_bit ^ (ord(arr[j][i]) - ord('0'))
        result += chr((pres_bit) + ord('0'))
    result = result[::-1]
    print(result)


if (__name__ == "__main__"):
    arr = ["1000", "10001", "0011"]
    n = len(arr)
    strBitwiseXOR(arr, n)

# Expected output:
11010
# count of sticks required to represent the given string | stick [ ] stores the count of matchsticks required to represent the alphabets ; number [ ] stores the count of matchsticks required to represent the numerals ; function that return the count of sticks required to represent the given string ; for every char of the given string ; add the count of sticks required to represent the current character ; 

sticks = [6, 7, 4, 6, 5, 4, 6, 5, 2, 4, 4, 3,
          6, 6, 6, 5, 7, 6, 5, 3, 5, 4, 6, 4, 3, 4]
number = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]


def countSticks(string):
    cnt = 0
    for i in range(len(string)):
        ch = string[i]
        if (ch >= 'A' and ch <= 'Z'):
            cnt += sticks[ord(ch) - ord('A')]
        else:
            cnt += number[ord(ch) - ord('0')]
    return cnt


if __name__ == "__main__":
    string = "GEEKSFORGEEKS"
    print(countSticks(string))

# Expected output:
66
# find the last remaining character in the binary string according to the given conditions | python3 implementation of the above approach ; converting string to array ; delete counters for each to count the deletes ; counters to keep track of characters left from each type ; queue to simulate the process ; initializing the queue ; looping till at least 1 digit is left from both the type ; if there is a floating delete for current character we will delete it and move forward otherwise we will increase delete counter for opposite digit ; if 0 are left then answer is 0 else answer is 1 ; 

from collections import deque


def remainingDigit(S, N):
    c = [i for i in S]
    de = [0, 0]
    count = [0, 0]
    q = deque()
    for i in c:
        x = 0
        if i == '1':
            x = 1
        count[x] += 1
        q .append(x)
    while (count[0] > 0 and count[1] > 0):
        t = q .popleft()
        if (de[t] > 0):
            de[t] -= 1
            count[t] -= 1
        else:
            de[t ^ 1] += 1
            q .append(t)
    if (count[0] > 0):
        return "0"
    return "1"


if __name__ == '__main__':
    S = "1010100100000"
    N = len(S)
    print(remainingDigit(S, N))

# Expected output:
0
# find the closest leaf in a binary tree | python program to find closest leaf of a given key in binary tree ; a binary tree node ; a utility function to find distance of closest leaf of the tree rooted under given root ; base case ; return minum of left and right plus one ; returns destance of the closes leaf to a given key k the array ancestors us used to keep track of ancestors of current node and ' index ' is used to keep track of current index in 'ancestors[i]   ; base case ; if key found ; find closest leaf under the subtree rooted with 

INT_MAX = 2 ** 32


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


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


def findClosestUtil(root, k, ancestors, index):
    if root is None:
        return INT_MAX
    if root .key == k:
        res = closestDown(root)
        for i in reversed(range(0, index)):
            res = min(res, index - i + closestDown(ancestors[i]))
        return res
    ancestors[index] = root
    return min(
        findClosestUtil(
            root .left,
            k,
            ancestors,
            index + 1),
        findClosestUtil(
            root .right,
            k,
            ancestors,
            index + 1))


def findClosest(root, k):
    ancestors = [None for i in range(100)]
    return findClosestUtil(root, k, ancestors, 0)


root = Node('A')
root .left = Node('B')
root .right = Node('C')
root .right .left = Node('E')
root .right .right = Node('F')
root .right .left .left = Node('G')
root .right .left .left .left = Node('I')
root .right .left .left .right = Node('J')
root .right .right .right = Node('H')
root .right .right .right .left = Node('K')
k = 'H'
print("Distance of the closest key from " + k + " is")
print(findClosest(root, k))
k = 'C'
print("Distance of the closest key from " + k + " is")
print(findClosest(root, k))
k = 'E'
print("Distance of the closest key from " + k + " is")
print(findClosest(root, k))
k = 'B'
print("Distance of the closest key from " + k + " is")
print(findClosest(root, k))

# Expected output:
Distance of the closest key from H is
1
Distance of the closest key from C is
2
Distance of the closest key from E is
2
Distance of the closest key from B is
0
# find the time which is palindromic and comes after the given time | function to return the required time ; to store the resultant time ; hours are stored in h as integer ; minutes are stored in m as integer ; reverse of h ; reverse of h as a string ; if mm < reverse of ( hh ) ; 0 is added if hh < 10 ; 0 is added if rev_h < 10 ; increment hours ; reverse of the hour after incrementing 1 ; 0 is added if hh < 10 ; 0 is added if rev_h < 10 ; 
def getTime(s, n):
    res = ""
    h = int(s[0:2])
    m = int(s[3:5])
    rev_h = (h % 10) * 10 + ((h % 100) - (h % 10)) // 10
    rev_hs = str(rev_h)
    temp = ""
    if (h == 23 and m >= 32):
        res = "-1"
    elif (m < rev_h):
        if (h < 10):
            temp = "0"
        temp = temp + str(h)
        if (rev_h < 10):
            res = res + temp + ":0" + rev_hs
        else:
            res = res + temp + ":" + rev_hs
    else:
        h += 1
        rev_h = (h % 10) * 10 + ((h % 100) - (h % 10)) // 10
        rev_hs = str(rev_h)
        if (h < 10):
            temp = "0"
        temp = temp + str(h)
        if (rev_h < 10):
            res = res + temp + ":0" + rev_hs
        else:
            res = res + temp + ":" + rev_hs
    return res


if __name__ == "__main__":
    s = "21:12"
    n = len(s)
    print(getTime(s, n))

# Expected output:
22:22