giulio98/xlcost-single-prompt huggingface dataset:
# two clique problem ( check if graph can be divided in two cliques ) | python3 program to find out whether a given graph can be converted to two cliques or not . ; this function returns true if subgraph reachable from src is bipartite or not . ; create a queue ( fifo ) of vertex numbers and enqueue source vertex for bfs traversal ; run while there are vertices in queue ( similar to bfs ) ; dequeue a vertex from queue ; find all non - colored adjacent vertices ; an edge from u to v exists and destination v is not colored ; assign alternate color to this adjacent v of u ; an edge from u to v exists and destination v is colored with same color as u ; if we reach here , then all adjacent vertices can be colored with alternate color ; returns true if a graph g [ ] [ ] is bipartite or not . note that g may not be connected . ; create a color array to store colors assigned to all veritces . vertex number is used as index in this array . the value ' - 1' of colorarr [ i ] is used to indicate that no color is assigned to vertex ' i ' . the value 1 is used to indicate first color is assigned and value 0 indicates second color is assigned . ; one by one check all not yet colored vertices . ; returns true if g can be divided into two cliques , else false . ; find complement of g [ ] [ ] all values are complemented except diagonal ones ; return true if complement is bipartite else false . ; 

from queue import Queue


def isBipartiteUtil(G, src, colorArr):
    global V
    colorArr[src] = 1
    q = Queue()
    q .put(src)
    while (not q .empty()):
        u = q .get()
        for v in range(V):
            if (G[u][v] and colorArr[v] == -1):
                colorArr[v] = 1 - colorArr[u]
                q .put(v)
            elif (G[u][v] and colorArr[v] == colorArr[u]):
                return False
    return True


def isBipartite(G):
    global V
    colorArr = [-1] * V
    for i in range(V):
        if (colorArr[i] == -1):
            if (isBipartiteUtil(G, i, colorArr) == False):
                return False
    return True


def canBeDividedinTwoCliques(G):
    global V
    GC = [[None] * V for i in range(V)]
    for i in range(V):
        for j in range(V):
            GC[i][j] = not G[i][j]if i != j else 0
    return isBipartite(GC)


V = 5
G = [[0, 1, 1, 1, 0], [1, 0, 1, 0, 0], [
    1, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 0, 0, 1, 0]]
if canBeDividedinTwoCliques(G):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check whether 
def check(degree, n):
    deg_sum = sum(degree)
    if (2 * (n - 1) == deg_sum):
        return True
    else:
        return False


n = 5
degree = [2, 3, 1, 1, 1]
if (check(degree, n)):
    print("Tree")
else:
    print("Graph")

# Expected output:
Tree
# iterative preorder traversal | a binary tree node ; an iterative process to print preorder traveral of bt ; base case ; create an empty stack and push root to it ; pop all items one by one . do following for every popped item a ) print it b ) push its right child c ) push its left child note that right child is pushed first so that left is processed first ; pop the top item from stack and print it ; push right and left children of the popped node to stack ; 

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


def iterativePreorder(root):
    if root is None:
        return
    nodeStack = []
    nodeStack .append(root)
    while (len(nodeStack) > 0):
        node = nodeStack .pop()
        print(node .data, end=" ")
        if node .right is not None:
            nodeStack .append(node .right)
        if node .left is not None:
            nodeStack .append(node .left)


root = Node(10)
root .left = Node(8)
root .right = Node(2)
root .left .left = Node(3)
root .left .right = Node(5)
root .right .left = Node(2)
iterativePreorder(root)

# Expected output:
10 8 3 5 2 2
# iterative preorder traversal | tree node ; iterative function to do preorder traversal of the tree ; start from root node ( set current node to root node ) ; run till stack is not empty or current is not null ; print left children while exist and keep appending right into the stack . ; we reach when curr is null , so we take out a right child from stack ; 

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


def preorderIterative(root):
    if (root is None):
        return
    st = []
    curr = root
    while (len(st) or curr is not None):
        while (curr is not None):
            print(curr .data, end=" ")
            if (curr .right is not None):
                st .append(curr .right)
            curr = curr .left
        if (len(st) > 0):
            curr = st[-1]
            st .pop()


root = Node(10)
root .left = Node(20)
root .right = Node(30)
root .left .left = Node(40)
root .left .left .left = Node(70)
root .left .right = Node(50)
root .right .left = Node(60)
root .left .left .right = Node(80)
preorderIterative(root)

# Expected output:
10 20 40 70 80 50 30 60
# josephus circle implementation using stl list | structure for a node in circular linked list ; function to find the only person left after one in every m - th node is killed in a circle of n nodes ; create a circular linked list of size n . ; connect last node to first ; while only one node is left in the linked list ; find m - th node ; remove the m - th node ; 

class Node:
    def __init__(self, x):
        self .data = x
        self .next = None


def getJosephusPosition(m, n):
    head = Node(1)
    prev = head
    for i in range(2, n + 1):
        prev .next = Node(i)
        prev = prev .next
        prev .next = head
    ptr1 = head
    ptr2 = head
    while (ptr1 .next != ptr1):
        count = 1
        while (count != m):
            ptr2 = ptr1
            ptr1 = ptr1 .next
            count += 1
        ptr2 .next = ptr1 .next
        ptr1 = ptr2 .next
    print("Last person left standing (Josephus Position) is ", ptr1 .data)


if __name__ == '__main__':
    n = 14
    m = 2
    getJosephusPosition(m, n)

# Expected output:
Last person left standing (Josephus Position) is  13
# diagonal traversal of binary tree | a binary tree node ; root - root of the binary tree d - distance of current line from rightmost - topmost slope . diagonalprint - multimap to store diagonal elements ( passed by reference ) ; base case ; store all nodes of same line together as a vector ; increase the vertical distance if left child ; vertical distance remains same for right child ; print diagonal traversal of given binary tree ; create a dict to store diagnoal elements ; 

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


def diagonalPrintUtil(root, d, diagonalPrintMap):
    if root is None:
        return
    try:
        diagonalPrintMap[d].append(root .data)
    except KeyError:
        diagonalPrintMap[d] = [root .data]
    diagonalPrintUtil(root .left, d + 1, diagonalPrintMap)
    diagonalPrintUtil(root .right, d, diagonalPrintMap)


def diagonalPrint(root):
    diagonalPrintMap = dict()
    diagonalPrintUtil(root, 0, diagonalPrintMap)
    print("Diagonal Traversal of binary tree : ")
    for i in diagonalPrintMap:
        for j in diagonalPrintMap[i]:
            print(j,)
        print("")


root = Node(8)
root .left = Node(3)
root .right = Node(10)
root .left .left = Node(1)
root .left .right = Node(6)
root .right .right = Node(14)
root .right .right .left = Node(13)
root .left .right .left = Node(4)
root .left .right .right = Node(7)
diagonalPrint(root)

# Expected output:
Diagonal Traversal of binary tree : 
8
10
14

3
6
7
13

1
4
# iterative diagonal traversal of binary tree | a binary tree node has data , pointer to left child and a pointer to right child ; function to print diagonal view ; base case ; queue of treenode ; append root ; append delimiter ; if current is delimiter then insert another for next diagonal and cout nextline ; if queue is empty then return ; print output on nextline ; append delimiter again ; if left child is present append into queue ; current equals to right child ; 

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


def diagonalprint(root):
    if root is None:
        return
    q = []
    q .append(root)
    q .append(None)
    while len(q) > 0:
        temp = q .pop(0)
        if not temp:
            if len(q) == 0:
                return
            print(' ')
            q .append(None)
        else:
            while temp:
                print(temp .val, end=' ')
                if temp .left:
                    q .append(temp .left)
                temp = temp .right


root = Node(8)
root .left = Node(3)
root .right = Node(10)
root .left .left = Node(1)
root .left .right = Node(6)
root .right .right = Node(14)
root .right .right .left = Node(13)
root .left .right .left = Node(4)
root .left .right .right = Node(7)
diagonalprint(root)

# Expected output:
8 10 14  
3 6 7 13  
1 4
# boundary traversal of binary tree | a binary tree node ; a simple function to print leaf nodes of a binary tree ; print it if it is a leaf node ; a function to print all left boundary nodes , except a leaf node . print the nodes in top down manner ; to ensure top down order , print the node before calling itself for left subtree ; a function to print all right boundary nodes , except a leaf node . print the nodes in bottom up manner ; to ensure bottom up order , first call for right subtree , then print this node ; a function to do boundary traversal of a given binary tree ; print the left boundary in top - down manner ; print all leaf nodes ; print the right boundary in bottom - up manner ; 

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


def printLeaves(root):
    if (root):
        printLeaves(root .left)
        if root .left is None and root .right is None:
            print(root .data),
        printLeaves(root .right)


def printBoundaryLeft(root):
    if (root):
        if (root .left):
            print(root .data)
            printBoundaryLeft(root .left)
        elif (root .right):
            print(root .data)
            printBoundaryLeft(root .right)


def printBoundaryRight(root):
    if (root):
        if (root .right):
            printBoundaryRight(root .right)
            print(root .data)
        elif (root .left):
            printBoundaryRight(root .left)
            print(root .data)


def printBoundary(root):
    if (root):
        print(root .data)
        printBoundaryLeft(root .left)
        printLeaves(root .left)
        printLeaves(root .right)
        printBoundaryRight(root .right)


root = Node(20)
root .left = Node(8)
root .left .left = Node(4)
root .left .right = Node(12)
root .left .right .left = Node(10)
root .left .right .right = Node(14)
root .right = Node(22)
root .right .right = Node(25)
printBoundary(root)

# Expected output:
20
8
4
10
14
25
22
# check given array of size n can represent bst of n levels or not | a binary tree node has data , left child and right child ; to create a tree with n levels . we always insert new node to left if it is less than previous value . ; please refer below post for details of this function . www . geeksforgeeks . org / a - program - to - check - if - a - binary - tree - is - bst - or - not / https : ; allow only distinct values ; returns tree if given array of size n can represent a bst of n levels . ; 

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


def createNLevelTree(arr, n):
    root = newNode(arr[0])
    temp = root
    for i in range(1, n):
        if (temp .key > arr[i]):
            temp .left = newNode(arr[i])
            temp = temp .left
        else:
            temp .right = newNode(arr[i])
            temp = temp .right
    return root


def isBST(root, min, max):
    if (root is None):
        return True
    if (root .key < min or root .key > max):
        return False
    return (
        isBST(
            root .left,
            min,
            (root .key) -
            1) and isBST(
            root .right,
            (root .key) +
            1,
            max))


def canRepresentNLevelBST(arr, n):
    root = createNLevelTree(arr, n)
    return isBST(root, 0, 2 ** 32)


arr = [512, 330, 78, 11, 8]
n = len(arr)
if (canRepresentNLevelBST(arr, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check if the given array can represent level order traversal of binary search tree | to store details of a node like node ' s ▁ ▁ data , ▁ ' min ' ▁ and ▁ ' max ' ▁ to ▁ obtain ▁ the ▁ ▁ range ▁ of ▁ values ▁ where ▁ node ' s left and right child 's should lie  ; function to check if the given array can represent level order traversal of binary search tree ; if tree is empty ; queue to store nodedetails ; index variable to access array elements ; node details for the root of the bst ; until there are no more elements in arr [ ] or queue is not empty ; extracting nodedetails of a node from the queue ; check whether there are more elements in the arr [ ] and arr [ i ] can be left child of ' temp . data ' or not ; create nodedetails for newnode / and add it to the queue ; check whether there are more elements in the arr [ ] and arr [ i ] can be right child of ' temp . data ' or not ; create nodedetails for newnode / and add it to the queue ; given array represents level order traversal of bst ; given array do not represent level order traversal of bst ; 

INT_MIN, INT_MAX = float('-inf'), float('inf')


class NodeDetails:
    def __init__(self, data, min, max):
        self .data = data
        self .min = min
        self .max = max


def levelOrderIsOfBST(arr, n):
    if n == 0:
        return True
    q = []
    i = 0
    newNode = NodeDetails(arr[i], INT_MIN, INT_MAX)
    i += 1
    q .append(newNode)
    while i != n and len(q) != 0:
        temp = q .pop(0)
        if i < n and (arr[i] < temp .data and arr[i] > temp .min):
            newNode = NodeDetails(arr[i], temp .min, temp .data)
            i += 1
            q .append(newNode)
        if i < n and (arr[i] > temp .data and arr[i] < temp .max):
            newNode = NodeDetails(arr[i], temp .data, temp .max)
            i += 1
            q .append(newNode)
    if i == n:
        return True
    return False


if __name__ == "__main__":
    arr = [7, 4, 12, 3, 6, 8, 1, 5, 10]
    n = len(arr)
    if levelOrderIsOfBST(arr, n):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# Lowest Common Ancestor in a Binary Search Tree . | A recursive python program to find LCA of two nodes n1 and n2 A Binary tree node ; Function to find LCA of n1 and n2 . The function assumes that both n1 and n2 are present in BST ; If both n1 and n2 are smaller than root , then LCA lies in left ; If both n1 and n2 are greater than root , then LCA lies in right ; Let us construct the BST shown in the figure

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


def lca(root, n1, n2):
    while root:
        if root .data > n1 and root .data > n2:
            root = root .left
        elif root .data < n1 and root .data < n2:
            root = root .right
        else:
            break
    return root


root = Node(20)
root .left = Node(8)
root .right = Node(22)
root .left .left = Node(4)
root .left .right = Node(12)
root .left .right .left = Node(10)
root .left .right .right = Node(14)
n1 = 10
n2 = 14
t = lca(root, n1, n2)
print("LCA of %d and %d is %d" % (n1, n2, t .data))
n1 = 14
n2 = 8
t = lca(root, n1, n2)
print("LCA of %d and %d is %d" % (n1, n2, t .data))
n1 = 10
n2 = 22
t = lca(root, n1, n2)
print("LCA of %d and %d is %d" % (n1, n2, t .data))

# Expected output:
LCA of 10 and 14 is 12
LCA of 14 and 8 is 8
LCA of 10 and 22 is 20
# a program to check if a binary tree is bst or not | python3 program to check if a given tree is bst . ; a binary tree node has data , pointer to left child and a pointer to right child ; traverse the tree in inorder fashion and keep track of prev node ; allows only distinct valued nodes ; 

import math


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


def isBSTUtil(root, prev):
    if (root is not None):
        if (isBSTUtil(root .left, prev)):
            return False
        if (prev is not None and root .data <= prev .data):
            return False
        prev = root
        return isBSTUtil(root .right, prev)
    return True


def isBST(root):
    prev = None
    return isBSTUtil(root, prev)


if __name__ == '__main__':
    root = Node(3)
    root .left = Node(2)
    root .right = Node(5)
    root .right .left = Node(1)
    root .right .right = Node(4)
    if (isBST(root) is None):
        print("Is BST")
    else:
        print("Not a BST")

# Expected output:
Not a BST
# check if each internal node of a bst has exactly one child | check if each internal node of bst has only one child ; 
def hasOnlyOneChild(pre, size):
    nextDiff = 0
    lastDiff = 0
    for i in range(size - 1):
        nextDiff = pre[i] - pre[i + 1]
        lastDiff = pre[i] - pre[size - 1]
        if nextDiff * lastDiff < 0:
            return False
    return True


if __name__ == "__main__":
    pre = [8, 3, 5, 7, 6]
    size = len(pre)
    if (hasOnlyOneChild(pre, size)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check if each internal node of a bst has exactly one child | check if each internal node of bst has only one child approach 2 ; initialize min and max using last two elements ; every element must be either smaller than min or greater than max ; 
def hasOnlyOneChild(pre, size):
    min = 0
    max = 0
    if pre[size - 1] > pre[size - 2]:
        max = pre[size - 1]
        min = pre[size - 2]
    else:
        max = pre[size - 2]
        min = pre[size - 1]
    for i in range(size - 3, 0, -1):
        if pre[i] < min:
            min = pre[i]
        elif pre[i] > max:
            max = pre[i]
        else:
            return False
    return True


if __name__ == "__main__":
    pre = [8, 3, 5, 7, 6]
    size = len(pre)
    if (hasOnlyOneChild(pre, size)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check if an array represents inorder of binary search tree or not | function that returns true if array is inorder traversal of any binary search tree or not . ; array has one or no element ; unsorted pair found ; no unsorted pair found ; 
def isInorder(arr, n):
    if (n == 0 or n == 1):
        return True
    for i in range(1, n, 1):
        if (arr[i - 1] > arr[i]):
            return False
    return True


if __name__ == '__main__':
    arr = [19, 23, 25, 30, 45]
    n = len(arr)
    if (isInorder(arr, n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# inorder predecessor and successor for a given key in bst | a binary tree node utility function to create a new tree node ; since inorder traversal results in ascendingorder visit to node , we can store the values of the largest o which is smaller than a ( predecessor ) and smallest no which is large than a ( successor ) using inorder traversal ; if root is none return ; traverse the left subtree ; root data is greater than a ; q stores the node whose data is greater than a and is smaller than the previously stored data in * q which is successor ; if the root data is smaller than store it in p which is predecessor ; traverse the right subtree ; 

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


def find_p_s(root, a, p, q):
    if (not root):
        return
    find_p_s(root .left, a, p, q)
    if (root and root .data > a):
        if ((not q[0]) or q[0] and q[0].data > root .data):
            q[0] = root
    elif (root and root .data < a):
        p[0] = root
    find_p_s(root .right, a, p, q)


if __name__ == '__main__':
    root1 = getnode(50)
    root1 .left = getnode(20)
    root1 .right = getnode(60)
    root1 .left .left = getnode(10)
    root1 .left .right = getnode(30)
    root1 .right .left = getnode(55)
    root1 .right .right = getnode(70)
    p = [None]
    q = [None]
    find_p_s(root1, 55, p, q)
    if (p[0]):
        print(p[0].data, end="")
    if (q[0]):
        print("", q[0].data)

# Expected output:
50 60
# sorted order printing of a given array that represents a bst | python3 code for sorted order printing of a given array that represents a bst ; print left subtree ; print root ; print right subtree ; 
def printSorted(arr, start, end):
    if start > end:
        return
    printSorted(arr, start * 2 + 1, end)
    print(arr[start], end=" ")
    printSorted(arr, start * 2 + 2, end)


if __name__ == '__main__':
    arr = [4, 2, 5, 1, 3]
    arr_size = len(arr)
    printSorted(arr, 0, arr_size - 1)

# Expected output:
1 2 3 4 5
# floor and ceil from a bst | a binary tree node ; function to find ceil of a given input in bst . if input is more than the max key in bst , return - 1 ; base case ; we found equal key ; if root 's key is smaller, ceil must be in right subtree ; else , either left subtre or root has the ceil value ; 

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


def ceil(root, inp):
    if root is None:
        return -1
    if root .key == inp:
        return root .key
    if root .key < inp:
        return ceil(root .right, inp)
    val = ceil(root .left, inp)
    return val if val >= inp else root .key


root = Node(8)
root .left = Node(4)
root .right = Node(12)
root .left .left = Node(2)
root .left .right = Node(6)
root .right .left = Node(10)
root .right .right = Node(14)
for i in range(16):
    print("% d % d" % (i, ceil(root, i)))

# Expected output:
 0  2
 1  2
 2  2
 3  4
 4  4
 5  6
 6  6
 7  8
 8  8
 9  10
 10  10
 11  12
 12  12
 13  14
 14  14
 15 -1
# floor and ceil from a bst | a binary tree node has key , . left child and right child ; helper function to find floor and ceil of a given key in bst ; display the floor and ceil of a given key in bst . if key is less than the min key in bst , floor will be - 1 ; if key is more than the max key in bst , ceil will be - 1 ; ; variables ' floor ' and ' ceil ' are passed by reference ; 

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


def floorCeilBSTHelper(root, key):
    global floor, ceil
    while (root):
        if (root .data == key):
            ceil = root .data
            floor = root .data
            return
        if (key > root .data):
            floor = root .data
            root = root .right
        else:
            ceil = root .data
            root = root .left


def floorCeilBST(root, key):
    global floor, ceil
    floor = -1
    ceil = -1
    floorCeilBSTHelper(root, key)
    print(key, floor, ceil)


if __name__ == '__main__':
    floor, ceil = -1, -1
    root = Node(8)
    root .left = Node(4)
    root .right = Node(12)
    root .left .left = Node(2)
    root .left .right = Node(6)
    root .right .left = Node(10)
    root .right .right = Node(14)
    for i in range(16):
        floorCeilBST(root, i)

# Expected output:
0 -1 2
1 -1 2
2 2 2
3 2 4
4 4 4
5 4 6
6 6 6
7 6 8
8 8 8
9 8 10
10 10 10
11 10 12
12 12 12
13 12 14
14 14 14
15 14 -1