giulio98/xlcost-single-prompt huggingface dataset:
# m | function to find the next higher number with same number of set bits as in 'x ; the approach is same as discussed in ; function to find the mth smallest number having k number of set bits ; smallest number having ' k ' number of set bits ; finding the mth smallest number having k set bits ; required number ; 
def nxtHighWithNumOfSetBits(x):
    rightOne = 0
    nextHigherOneBit = 0
    rightOnesPattern = 0
    next = 0
    if (x):
        rightOne = x & (-x)
        nextHigherOneBit = x+rightOne
        rightOnesPattern = x ^ nextHigherOneBit
        rightOnesPattern = (rightOnesPattern)//rightOne
        rightOnesPattern >>= 2
        next = nextHigherOneBit | rightOnesPattern
    return next


def mthSmallestWithKSetBits(m, k):
    num = (1 << k)-1
    for i in range(1, m):
        num = nxtHighWithNumOfSetBits(num)
    return num


if __name__ == '__main__':
    m = 6
    k = 4
    print(mthSmallestWithKSetBits(m, k))

# Expected output:
39
# count unset bits of a number | an optimized python program to count unset bits in an integer . ; this makes sure two bits ( from msb and including msb ) are set ; this makes sure 4 bits ( from msb and including msb ) are set ; count set bits in toggled number ; 

import math


def countUnsetBits(n):
    x = n
    n |= n >> 1
    n |= n >> 2
    n |= n >> 4
    n |= n >> 8
    n |= n >> 16
    t = math .log(x ^ n, 2)
    return math .floor(t)


n = 17
print(countUnsetBits(n))

# Expected output:
3
# count total bits in a number | function to get no of bits in binary representation of positive integer ; 
def countBits(n):
    count = 0
    while (n):
        count += 1
        n >>= 1
    return count


i = 65
print(countBits(i))

# Expected output:
7
# toggle all bits after most significant bit | function to toggle bits starting from msb ; temporary variable to use xor with one of a n ; run loop until the only set bit in temp crosses mst of n . ; toggle bit of n corresponding to current set bit in temp . ; move set bit to next higher position . ; 
def toggle(n):
    temp = 1
    while (temp <= n):
        n = n ^ temp
        temp = temp << 1
    return n


n = 10
n = toggle(n)
print(n)

# Expected output:
5
# find the n | python 3 program to find n - th number whose binary representation is palindrome . ; finds if the kth bit is set in the binary representation ; returns the position of leftmost set bit in the binary representation ; finds whether the integer in binary representation is palindrome or not ; one by one compare bits ; compare left and right bits and converge ; start from 1 , traverse through all the integers ; if we reach n , break the loop ; 

INT_MAX = 2147483647


def isKthBitSet(x, k):
    return 1 if (x & (1 << (k - 1)))else 0


def leftmostSetBit(x):
    count = 0
    while (x):
        count += 1
        x = x >> 1
    return count


def isBinPalindrome(x):
    l = leftmostSetBit(x)
    r = 1
    while (l > r):
        if (isKthBitSet(x, l) != isKthBitSet(x, r)):
            return 0
        l -= 1
        r += 1
    return 1


def findNthPalindrome(n):
    pal_count = 0
    i = 0
    for i in range(1, INT_MAX + 1):
        if (isBinPalindrome(i)):
            pal_count += 1
        if (pal_count == n):
            break
    return i


if __name__ == "__main__":
    n = 9
    print(findNthPalindrome(n))

# Expected output:
27
# print ' k ' th least significant bit of a number | function returns 1 if set , 0 if not ; 
def LSB(num, K):
    return bool(num & (1 << (K - 1)))


num, k = 10, 4
res = LSB(num, k)
if res:
    print(1)
else:
    print(0)

# Expected output:
1
# check if two numbers are equal without using comparison operators | finds if a and b are same ; 
def areSame(a, b):
    if (not (a - b)):
        print("Same")
    else:
        print("Not Same")


areSame(10, 20)

# Expected output:
Not Same
# toggle bits in the given range | function to toggle bits in the given range ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; toggle bits in the range l to r in ' n ' besides this , we can calculate num as : num = ( 1 << r ) - l . ; 
def toggleBitsFromLToR(n, l, r):
    num = ((1 << r) - 1) ^ ((1 << (l - 1)) - 1)
    return (n ^ num)


n = 50
l = 2
r = 5
print(toggleBitsFromLToR(n, l, r))

# Expected output:
44
# position of rightmost different bit | python implementation to find the position of rightmost different bit ; function to find the position of rightmost set bit in 'n ; to handle edge case when n = 0. ; function to find the position of rightmost different bit in the binary representations of ' m ' and 'n ; position of rightmost different bit ; 

import math


def getRightMostSetBit(n):
    if (n == 0):
        return 0
    return math.log2(n & -n)+1


def posOfRightMostDiffBit(m, n):
    return getRightMostSetBit(m ^ n)


m = 52
n = 4
print("position = ", int(posOfRightMostDiffBit(m, n)))

# Expected output:
position =  5
# closest ( or next ) smaller and greater numbers with same number of set bits | main function to find next smallest number bigger than n ; compute c0 and c1 ; if there is no bigger number with the same no . of 1 's ; 
def getNext(n):
    c = n
    c0 = 0
    c1 = 0
    while (((c & 1) == 0) and (c != 0)):
        c0 = c0 + 1
        c >>= 1
    while ((c & 1) == 1):
        c1 = c1 + 1
        c >>= 1
    if (c0 + c1 == 31 or c0 + c1 == 0):
        return -1
    return n + (1 << c0) + (1 << (c1 - 1)) - 1


if __name__ == '__main__':
    n = 5
    print(getNext(n))
    n = 8
    print(getNext(n))

# Expected output:
6
16
# Count minimum bits to flip such that XOR of A and B equal to C | Python code to find minimum bits to be flip ; If both A [ i ] and B [ i ] are equal ; if A [ i ] and B [ i ] are unequal ; N represent total count of Bits
def totalFlips(A, B, C, N):
    count = 0
    for i in range(N):
        if A[i] == B[i] and C[i] == '1':
            count = count + 1
        elif A[i] != B[i] and C[i] == '0':
            count = count + 1
    return count


N = 5
a = "10100"
b = "00010"
c = "10011"
print(totalFlips(a, b, c, N))

# Expected output:
2
# swap three variables without using temporary variable | assign c ' s ▁ value ▁ to ▁ a , ▁ a ' s value to b and b 's value to c. ; store xor of all in a ; after this , b has value of a [ 0 ] ; after this , c has value of b ; after this , a [ 0 ] has value of c ; 
def swapThree(a, b, c):
    a[0] = a[0] ^ b[0] ^ c[0]
    b[0] = a[0] ^ b[0] ^ c[0]
    c[0] = a[0] ^ b[0] ^ c[0]
    a[0] = a[0] ^ b[0] ^ c[0]


a, b, c = [10], [20], [30]
print("Before swapping a = ", a[0], ", b = ", b[0], ", c = ", c[0])
swapThree(a, b, c)
print("After swapping a = ", a[0], ", b = ", b[0], ", c = ", c[0])

# Expected output:
Before swapping a =  10 , b =  20 , c =  30
After swapping a =  30 , b =  10 , c =  20
# find two missing numbers | set 2 ( xor based solution ) | function to find two missing numbers in range [ 1 , n ] . this function assumes that size of array is n - 2 and all array elements are distinct ; get the xor of all elements in arr [ ] and { 1 , 2 . . n } ; get a set bit of xor ( we get the rightmost set bit ) ; now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element . ; xor of first set in arr [ ] ; xor of second set in arr [ ] ; xor of first set in arr [ ] and { 1 , 2 , ... n } ; xor of second set in arr [ ] and { 1 , 2 , ... n } ; 
def findTwoMissingNumbers(arr, n):
    XOR = arr[0]
    for i in range(1, n - 2):
        XOR ^= arr[i]
    for i in range(1, n + 1):
        XOR ^= i
    set_bit_no = XOR & ~(XOR - 1)
    x = 0
    y = 0
    for i in range(0, n - 2):
        if arr[i] & set_bit_no:
            x = x ^ arr[i]
        else:
            y = y ^ arr[i]
    for i in range(1, n + 1):
        if i & set_bit_no:
            x = x ^ i
        else:
            y = y ^ i
    print("TwoMissingNumbersare%d%d" % (x, y))


arr = [1, 3, 5, 6]
n = 2 + len(arr)
findTwoMissingNumbers(arr, n)

# Expected output:
TwoMissingNumbersare24
# find xor of two number without using xor operator | returns xor of x and y ; 
def myXOR(x, y):
    return (x & (~y)) | ((~x) & y)


x = 3
y = 5
print("XOR is", myXOR(x, y))

# Expected output:
XOR is 6
# convert a given temperature to another system based on given boiling and freezing points | function to return temperature in the second thermometer ; calculate the temperature ; 
def temp_convert(F1, B1, F2, B2, T):
    t2 = F2 + ((float)(B2 - F2) / (B1 - F1) * (T - F1))
    return t2


F1 = 0
B1 = 100
F2 = 32
B2 = 212
T = 37
print(temp_convert(F1, B1, F2, B2, T))

# Expected output:
98.60000000000001
# maximum possible elements which are divisible by 2 | function to find maximum possible elements which divisible by 2 ; to store count of even numbers ; all even numbers and half of odd numbers ; 
def Divisible(arr, n):
    count_even = 0
    for i in range(n):
        if (arr[i] % 2 == 0):
            count_even += 1
    return count_even + (n - count_even) // 2


arr = [1, 2, 3, 4, 5]
n = len(arr)
print(Divisible(arr, n))

# Expected output:
3
# write a program to find the maximum depth or height of a tree | a binary tree node ; compute the " maxdepth " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node ; compute the depth of each subtree ; use the larger one ; 

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


def maxDepth(node):
    if node is None:
        return 0
    else:
        lDepth = maxDepth(node .left)
        rDepth = maxDepth(node .right)
        if (lDepth > rDepth):
            return lDepth + 1
        else:
            return rDepth + 1


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
print("Height of tree is %d" % (maxDepth(root)))

# Expected output:
Height of tree is 3
# find postorder traversal of bst from preorder traversal | python3 program for finding postorder traversal of bst from preorder traversal ; function to find postorder traversal from preorder traversal . ; if entire preorder array is traversed then return as no more element is left to be added to post order array . ; if array element does not lie in range specified , then it is not part of current subtree . ; store current value , to be printed later , after printing left and right subtrees . increment preindex to find left and right subtrees , and pass this updated value to recursive calls . ; all elements with value between minval and val lie in left subtree . ; all elements with value between val and maxval lie in right subtree . ; function to find postorder traversal . ; to store index of element to be traversed next in preorder array . this is passed by reference to utility function . ; 

INT_MIN = -2 ** 31
INT_MAX = 2 ** 31


def findPostOrderUtil(pre, n, minval, maxval, preIndex):
    if (preIndex[0] == n):
        return
    if (pre[preIndex[0]] < minval or pre[preIndex[0]] > maxval):
        return
    val = pre[preIndex[0]]
    preIndex[0] += 1
    findPostOrderUtil(pre, n, minval, val, preIndex)
    findPostOrderUtil(pre, n, val, maxval, preIndex)
    print(val, end=" ")


def findPostOrder(pre, n):
    preIndex = [0]
    findPostOrderUtil(pre, n, INT_MIN, INT_MAX, preIndex)


if __name__ == '__main__':
    pre = [40, 30, 35, 80, 100]
    n = len(pre)
    findPostOrder(pre, n)

# Expected output:
35 30 100 80 40
# find height of binary tree represented by parent array | this functio fills depth of i 'th element in parent[] the depth is filled in depth[i] ; if depth [ i ] is already filled ; if node at index i is root ; if depth of parent is not evaluated before , then evaluate depth of parent first ; depth of this node is depth of parent plus 1 ; this function reutns height of binary tree represented by parent array ; create an array to store depth of all nodes and 
def fillDepth(parent, i, depth):
    if depth[i] != 0:
        return
    if parent[i] == -1:
        depth[i] = 1
        return
    if depth[parent[i]] == 0:
        fillDepth(parent, parent[i], depth)
    depth[i] = depth[parent[i]] + 1


def findHeight(parent):
    n = len(parent)
    depth = [0 for i in range(n)]
    for i in range(n):
        fillDepth(parent, i, depth)
    ht = depth[0]
    for i in range(1, n):
        ht = max(ht, depth[i])
    return ht


parent = [-1, 0, 0, 1, 1, 3, 5]
print("Height is %d" % (findHeight(parent)))

# Expected output:
Height is 5
# how to determine if a binary tree is height | a binary tree node ; function to check if tree is height - balanced or not ; base condition ; for left and right subtree height allowed values for ( lh - rh ) are 1 , - 1 , 0 ; if we reach here means tree is not height - balanced tree ; function to find height of binary tree ; base condition when binary tree is empty ; if tree is not empty then height = 1 + max of left height and right heights ; 

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


def height(root):
    if root is None:
        return 0
    return max(height(root .left), height(root .right)) + 1


def isBalanced(root):
    if root is None:
        return True
    lh = height(root .left)
    rh = height(root .right)
    if (abs(lh - rh) <=
            1) and isBalanced(root .left) is True and isBalanced(root .right) is True:
        return True
    return False


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
root .left .left .left = Node(8)
if isBalanced(root):
    print("Tree is balanced")
else:
    print("Tree is not balanced")

# Expected output:
Tree is not balanced
# diameter of a binary tree | a binary tree node ; the function compute the " height " of a tree . height is the number of nodes along the longest path from the root node down to the farthest leaf node . ; base case : tree is empty ; if tree is not empty then height = 1 + max of left height and right heights ; function to get the diameter of a binary tree ; base case when tree is empty ; get the height of left and right sub - trees ; get the diameter of left and right sub - trees ; return max of the following tree : 1 ) diameter of left subtree 2 ) diameter of right subtree 3 ) height of left subtree + height of right subtree + 1 ; constructed binary tree is 1 / \ 2 3 / \ 4 5 ; 

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


def height(node):
    if node is None:
        return 0
    return 1 + max(height(node .left), height(node .right))


def diameter(root):
    if root is None:
        return 0
    lheight = height(root .left)
    rheight = height(root .right)
    ldiameter = diameter(root .left)
    rdiameter = diameter(root .right)
    return max(lheight + rheight + 1, max(ldiameter, rdiameter))


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

# Expected output:
4
# find if possible to visit every nodes in given graph exactly once based on given conditions | function to find print path ; if a [ 0 ] is 1 ; printing path ; seeking for a [ i ] = 0 and a [ i + 1 ] = 1 ; printing path ; if a [ n - 1 ] = 0 ; 
def findpath(N, a):
    if (a[0]):
        print(N + 1)
        for i in range(1, N + 1, 1):
            print(i, end=" ")
        return
    for i in range(N - 1):
        if (a[i] == 0 and a[i + 1]):
            for j in range(1, i + 1, 1):
                print(j, end=" ")
            print(N + 1, end=" ")
            for j in range(i + 1, N + 1, 1):
                print(j, end=" ")
            return
    for i in range(1, N + 1, 1):
        print(i, end=" ")
    print(N + 1, end=" ")


if __name__ == '__main__':
    N = 3
    arr = [0, 1, 0]
    findpath(N, arr)

# Expected output:
4 1 2 3
# modify a numeric string to a balanced parentheses by replacements | function to check if the given string can be converted to a balanced bracket sequence or not ; check if the first and last characters are equal ; initialize two variables to store the count of open and closed brackets ; if the current character is same as the first character ; if the current character is same as the last character ; if count of open brackets becomes less than 0 ; print the new string ; if the current character is same as the first character ; if bracket sequence is not balanced ; check for unbalanced bracket sequence ; print the sequence ; 
def balBracketSequence(str):
    n = len(str)
    if (str[0] == str[n - 1]):
        print("No", end="")
    else:
        cntForOpen = 0
        cntForClose = 0
        check = 1
        for i in range(n):
            if (str[i] == str[0]):
                cntForOpen += 1
            elif str[i] == str[n - 1]:
                cntForOpen -= 1
            else:
                cntForOpen += 1
            if (cntForOpen < 0):
                check = 0
                break
        if (check and cntForOpen == 0):
            print("Yes, ", end="")
            for i in range(n):
                if (str[i] == str[n - 1]):
                    print(')', end="")
                else:
                    print('(', end="")
            return
        else:
            for i in range(n):
                if (str[i] == str[0]):
                    cntForClose += 1
                else:
                    cntForClose -= 1
                if (cntForClose < 0):
                    check = 0
                    break
            if (check and cntForClose == 0):
                print("Yes, ", end="")
                for i in range(n):
                    if (str[i] == str[0]):
                        print('(', end="")
                    else:
                        print(')', end="")
                return
        print("NO", end="")


str = "123122"
balBracketSequence(str)

# Expected output:
Yes, ()(())
# diameter of a binary tree | a binary tree node ; utility class to pass height object ; optimised recursive function to find diameter of binary tree ; to store height of left and right subtree ; base condition - when binary tree is empty ; diameter is also 0 ; ldiameter -- > diameter of left subtree rdiamter -- > diameter of right subtree height of left subtree and right subtree is obtained from lh and rh and returned value of function is stored in ldiameter and rdiameter ; height of tree will be max of left subtree height and right subtree height plus1 ; function to calculate diameter of binary tree ; constructed binary tree is 1 / \ 2 3 / \ 4 5 ; 

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


class Height:
    def __init(self):
        self .h = 0


def diameterOpt(root, height):
    lh = Height()
    rh = Height()
    if root is None:
        height .h = 0
        return 0
    ldiameter = diameterOpt(root .left, lh)
    rdiameter = diameterOpt(root .right, rh)
    height .h = max(lh .h, rh .h) + 1
    return max(lh .h + rh .h + 1, max(ldiameter, rdiameter))


def diameter(root):
    height = Height()
    return diameterOpt(root, height)


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

# Expected output:
4
# count substrings made up of a single distinct character | function to count the number of substrings made up of a single distinct character ; stores the required count ; stores the count of substrings possible by using current character ; stores the previous character ; traverse the string ; if current character is same as the previous character ; increase count of substrings possible with current character ; reset count of substrings possible with current character ; update count of substrings ; update previous character ; 
def countSubstrings(s):
    ans = 0
    subs = 1
    pre = ''
    for i in s:
        if pre == i:
            subs += 1
        else:
            subs = 1
        ans += subs
        pre = i
    print(ans)


s = 'geeksforgeeks'
countSubstrings(s)

# Expected output:
15
# generate an array from given pairs of adjacent elements | utility function to find original array ; map to store all neighbors for each element ; vector to store original elements ; stotrs which array elements are visited ; a djacency list to store neighbors of each array element ; find the first corner element ; stores first element of the original array ; push it into the original array ; mark as visited ; traversing the neighbors and check if the elements are visited or not ; traverse adjacent elements ; if element is not visited ; push it into res ; mark as visited ; update the next adjacent ; print original array ; 
def find_original_array(A):
    mp = [[]for i in range(6)]
    res = []
    visited = {}
    for it in A:
        mp[it[0]].append(it[1])
        mp[it[1]].append(it[0])
    start = 0
    for it in range(6):
        if (len(mp[it]) == 1):
            start = it + 3
            break
    adjacent = start
    res .append(start)
    visited[start] = True
    while (len(res) != len(A) + 1):
        for elements in mp[adjacent]:
            if (elements not in visited):
                res .append(elements)
                visited[elements] = True
                adjacent = elements
    print(*res)


if __name__ == '__main__':
    A = [[5, 1], [3, 4], [3, 5]]
    find_original_array(A)

# Expected output:
4 3 5 1
# possible edges of a tree for given diameter , height and vertices | function to construct the tree ; special case when d == 2 , only one edge ; tree is not possible ; satisfy the height condition by add edges up to h ; add d - h edges from 1 to satisfy diameter condition ; remaining edges at vertex 1 or 2 ( d == h ) ; 
def constructTree(n, d, h):
    if d == 1:
        if n == 2 and h == 1:
            print("1 2")
            return 0
        print("-1")
        return 0
    if d > 2 * h:
        print("-1")
        return 0
    for i in range(1, h + 1):
        print(i, " ", i + 1)
    if d > h:
        print(1, " ", h + 2)
        for i in range(h + 2, d + 1):
            print(i, " ", i + 1)
    for i in range(d + 1, n):
        k = 1
        if d == h:
            k = 2
        print(k, " ", i + 1)


n = 5
d = 3
h = 2
constructTree(n, d, h)

# Expected output:
1   2
2   3
1   4
1   5
# smallest element present in every subarray of all possible lengths | function to add count of numbers in the map for a subarray of length k ; set to store unique elements ; add elements to the set ; adding count in map ; function to check if there is any number which repeats itself in every subarray of length k ; check all number starting from 1 ; check if i occurred n - k + 1 times ; print the smallest number ; print - 1 , if no such number found ; function to count frequency of each number in each subarray of length k ; traverse all subarrays of length k ; check and print the smallest number present in every subarray and print it ; function to generate the value of k ; function call ; 
def uniqueElements(arr, start, K, mp):
    st = set()
    for i in range(K):
        st .add(arr[start + i])
    for itr in st:
        if itr in mp:
            mp[itr] += 1
        else:
            mp[itr] = 1


def checkAnswer(mp, N, K):
    for i in range(1, N + 1):
        if i in mp:
            if (mp[i] == (N - K + 1)):
                print(i, end=" ")
                return
    print(-1, end=" ")


def smallestPresentNumber(arr, N, K):
    mp = {}
    for i in range(N - K + 1):
        uniqueElements(arr, i, K, mp)
    checkAnswer(mp, N, K)


def generateK(arr, N):
    for k in range(1, N + 1):
        smallestPresentNumber(arr, N, k)


if __name__ == "__main__":
    arr = [2, 3, 5, 3, 2, 3, 1, 3, 2, 7]
    N = len(arr)
    generateK(arr, N)

# Expected output:
-1 -1 3 2 2 2 1 1 1 1