giulio98/xlcost-single-prompt huggingface dataset:
# find closest number in array | returns element closest to target in arr [ ] ; corner cases ; doing binary search ; if target is less than array element , then search in left ; if target is greater than previous to mid , return closest of two ; repeat for left half ; if target is greater than mid ; update i ; only single element left after search ; method to compare which one is the more close . we find the closest by taking the difference between the target and both values . it assumes that val2 is greater than val1 and target lies between these two . ; 
def getClosest(val1, val2, target):
    if (target - val1 >= val2 - target):
        return val2
    else:
        return val1


def findClosest(arr, n, target):
    if (target <= arr[0]):
        return arr[0]
    if (target >= arr[n - 1]):
        return arr[n - 1]
    i = 0
    j = n
    mid = 0
    while (i < j):
        mid = (i + j) // 2
        if (arr[mid] == target):
            return arr[mid]
        if (target < arr[mid]):
            if (mid > 0 and target > arr[mid - 1]):
                return getClosest(arr[mid - 1], arr[mid], target)
            j = mid
        else:
            if (mid < n - 1 and target < arr[mid + 1]):
                return getClosest(arr[mid], arr[mid + 1], target)
            i = mid + 1
    return arr[mid]


arr = [1, 2, 4, 5, 6, 6, 8, 9]
n = len(arr)
target = 11
print(findClosest(arr, n, target))

# Expected output:
9
# number of pairs with maximum sum | python program to count pairs with maximum sum ; traverse through all the pairs ; traverse through all pairs and keep a count of the number of maximum pairs ; 
def _sum(a, n):
    maxSum = -9999999
    for i in range(n):
        for j in range(n):
            maxSum = max(maxSum, a[i] + a[j])
    c = 0
    for i in range(n):
        for j in range(i + 1, n):
            if a[i] + a[j] == maxSum:
                c += 1
    return c


array = [1, 1, 1, 2, 2, 2]
n = len(array)
print(_sum(array, n))

# Expected output:
3
# number of pairs with maximum sum | python 3 program to count pairs with maximum sum . ; function to find the number of maximum pair sums ; find maximum and second maximum elements . also find their counts . ; if maximum element appears more than once . ; if maximum element appears only once . ; 

import sys


def sum(a, n):
    maxVal = a[0]
    maxCount = 1
    secondMax = sys .maxsize
    for i in range(1, n):
        if (a[i] == maxVal):
            maxCount += 1
        elif (a[i] > maxVal):
            secondMax = maxVal
            secondMaxCount = maxCount
            maxVal = a[i]
            maxCount = 1
        elif (a[i] == secondMax):
            secondMax = a[i]
            secondMaxCount += 1
        elif (a[i] > secondMax):
            secondMax = a[i]
            secondMaxCount = 1
    if (maxCount > 1):
        return maxCount * (maxCount - 1) / 2
    return secondMaxCount


array = [1, 1, 1, 2, 2, 2, 3]
n = len(array)
print(sum(array, n))

# Expected output:
3
# find first k natural numbers missing in given array | prints first k natural numbers in arr [ 0. . n - 1 ] ; find first positive number ; now find missing numbers between array elements ; find missing numbers after maximum . ; 
def printKMissing(arr, n, k):
    arr .sort()
    i = 0
    while (i < n and arr[i] <= 0):
        i = i + 1
    count = 0
    curr = 1
    while (count < k and i < n):
        if (arr[i] != curr):
            print(str(curr) + " ", end='')
            count = count + 1
        else:
            i = i + 1
        curr = curr + 1
    while (count < k):
        print(str(curr) + " ", end='')
        curr = curr + 1
        count = count + 1


arr = [2, 3, 4]
n = len(arr)
k = 3
printKMissing(arr, n, k)

# Expected output:
1 5 6
# find first k natural numbers missing in given array | program to print first k missing number ; creating a hashmap ; iterate over array ; iterate to find missing element ; 
def printmissingk(arr, n, k):
    d = {}
    for i in range(len(arr)):
        d[arr[i]] = arr[i]
    cnt = 1
    fl = 0
    for i in range(n + k):
        if cnt not in d:
            fl += 1
            print(cnt, end=" ")
            if fl == k:
                break
        cnt += 1
    print()


arr = [1, 4, 3]
n = len(arr)
k = 3
printmissingk(arr, n, k)

# Expected output:
2 5 6
# noble integers in an array ( count of greater elements is equal to value ) | returns a noble integer if present , else returns - 1. ; if count of greater elements is equal to arr [ i ] ; 
def nobleInteger(arr, size):
    for i in range(0, size):
        count = 0
        for j in range(0, size):
            if (arr[i] < arr[j]):
                count += 1
        if (count == arr[i]):
            return arr[i]
    return -1


arr = [10, 3, 20, 40, 2]
size = len(arr)
res = nobleInteger(arr, size)
if (res != -1):
    print("The noble integer is ", res)
else:
    print("No Noble Integer Found")

# Expected output:
The noble integer is  3
# noble integers in an array ( count of greater elements is equal to value ) | python3 code to find noble elements in an array ; return a noble element if present before last ; in case of duplicates we reach last occurrence here ; 
def nobleInteger(arr):
    arr .sort()
    n = len(arr)
    for i in range(n - 1):
        if arr[i] == arr[i + 1]:
            continue
        if arr[i] == n - i - 1:
            return arr[i]
    if arr[n - 1] == 0:
        return arr[n - 1]
    return -1


arr = [10, 3, 20, 40, 2]
res = nobleInteger(arr)
if res != -1:
    print("The noble integer is", res)
else:
    print("No Noble Integer Found")

# Expected output:
The noble integer is 3
# Minimum sum of absolute difference of pairs of two arrays | Python3 program to find minimum sum of absolute differences of two arrays . ; Sort both arrays ; Find sum of absolute differences ; Both a [ ] and b [ ] must be of same size .
def findMinSum(a, b, n):
    a .sort()
    b .sort()
    sum = 0
    for i in range(n):
        sum = sum + abs(a[i] - b[i])
    return sum


a = [4, 1, 8, 7]
b = [2, 3, 6, 5]
n = len(a)
print(findMinSum(a, b, n))

# Expected output:
6
# minimum product subset of an array | def to find maximum product of a subset ; find count of negative numbers , count of zeros , maximum valued negative number , minimum valued positive number and product of non - zero numbers ; if number is 0 , we don 't  multiply it with product. ; count negatives and keep track of maximum valued negative . ; track minimum positive number of array ; if there are all zeros or no negative number present ; if there are all positive ; if there are even number of negative numbers and count_neg not 0 ; otherwise result is product of all non - zeros divided by maximum valued negative . ; 
def minProductSubset(a, n):
    if (n == 1):
        return a[0]
    max_neg = float('-inf')
    min_pos = float('inf')
    count_neg = 0
    count_zero = 0
    prod = 1
    for i in range(0, n):
        if (a[i] == 0):
            count_zero = count_zero + 1
            continue
        if (a[i] < 0):
            count_neg = count_neg + 1
            max_neg = max(max_neg, a[i])
        if (a[i] > 0):
            min_pos = min(min_pos, a[i])
        prod = prod * a[i]
    if (count_zero == n or (count_neg == 0 and count_zero > 0)):
        return 0
    if (count_neg == 0):
        return min_pos
    if ((count_neg & 1) == 0 and count_neg != 0):
        prod = int(prod / max_neg)
    return prod


a = [-1, -1, -2, 4, 3]
n = len(a)
print(minProductSubset(a, n))

# Expected output:
-24
# repeatedly search an element by doubling it after every successful search | python program to repeatedly search an element by doubling it after every successful search ; sort the given array so that binary search can be applied on it ; maximum array element ; search for the element b present or not in array ; 
def binary_search(a, x, lo=0, hi=None):
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        midval = a[mid]
        if midval < x:
            lo = mid + 1
        elif midval > x:
            hi = mid
        else:
            return mid
    return -1


def findElement(a, n, b):
    a .sort()
    mx = a[n - 1]
    while (b < mx):
        if (binary_search(a, b, 0, n) != -1):
            b *= 2
        else:
            return b
    return b


a = [1, 2, 3]
n = len(a)
b = 1
print(findElement(a, n, b))

# Expected output:
4
# maximum sum of pairwise product in an array with negative allowed | python3 code for above implementation ; function to find the maximum sum ; sort the array first ; first multiply negative numbers pairwise and sum up from starting as to get maximum sum . ; second multiply positive numbers pairwise and summed up from the last as to get maximum sum . ; to handle case if positive and negative numbers both are odd in counts . ; if one of them occurs odd times ; 

Mod = 1000000007


def findSum(arr, n):
    sum = 0
    arr .sort()
    i = 0
    while i < n and arr[i] < 0:
        if i != n - 1 and arr[i + 1] <= 0:
            sum = (sum + (arr[i] * arr[i + 1]) % Mod) % Mod
            i += 2
        else:
            break
    j = n - 1
    while j >= 0 and arr[j] > 0:
        if j != 0 and arr[j - 1] > 0:
            sum = (sum + (arr[j] * arr[j - 1]) % Mod) % Mod
            j -= 2
        else:
            break
    if j > i:
        sum = (sum + (arr[i] * arr[j]) % Mod) % Mod
    elif i == j:
        sum = (sum + arr[i]) % Mod
    return sum


arr = [-1, 9, 4, 5, -4, 7]
n = len(arr)
print(findSum(arr, n))

# Expected output:
87
# print nodes between two given level numbers of a binary tree | a binary tree node ; given a binary tree , print nodes form level number ' low ' to level number 'high   ; marker node to indicate end of level ; initialize level number ; enqueue the only first level node and marker node for end of level ; print q simple level order traversal loop ; remove the front item from queue ; print q check if end of level is reached ; print a new line and increment level number ; check if marker node was last node in queue or level nubmer is beyond the given upper limit ; enqueue the marker for end of next level ; if this is marker , then we don 't need print it  and enqueue its children ; if level is equal to or greater than given lower level , print it ; enqueue children of non - marker node ; 

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


def printLevels(root, low, high):
    Q = []
    marker = Node(11114)
    level = 1
    Q .append(root)
    Q .append(marker)
    while (len(Q) > 0):
        n = Q[0]
        Q .pop(0)
        if n == marker:
            print
            level += 1
            if len(Q) == 0 or level > high:
                break
            Q .append(marker)
            continue
        if level >= low:
            print(n .key,)
        if n .left is not None:
            Q .append(n .left)
            Q .append(n .right)


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)
print("Level Order Traversal between given two levels is",)
printLevels(root, 2, 3)

# Expected output:
Level Order Traversal between given two levels is
8
22
4
12
# Print nodes at k distance from root | A Binary tree node ; Constructed binary tree is 1 / \ 2 3 / \ / 4 5 8

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


def printKDistant(root, k):
    if root is None:
        return
    if k == 0:
        print(root .data,)
    else:
        printKDistant(root .left, k - 1)
        printKDistant(root .right, k - 1)


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
root .right .left = Node(8)
printKDistant(root, 2)

# Expected output:
4
5
8
# print all leaf nodes of a binary tree from left to right | binary tree node ; function to print leaf nodes from left to right ; if node is null , return ; if node is leaf node , print its data ; if left child exists , check for leaf recursively ; if right child exists , check for leaf recursively ; 

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


def printLeafNodes(root: Node) -> None:
    if (not root):
        return
    if (not root .left and not root .right):
        print(root .data, end=" ")
        return
    if root .left:
        printLeafNodes(root .left)
    if root .right:
        printLeafNodes(root .right)


if __name__ == "__main__":
    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(8)
    root .right .left .left = Node(6)
    root .right .left .right = Node(7)
    root .right .right .left = Node(9)
    root .right .right .right = Node(10)
    printLeafNodes(root)

# Expected output:
4 6 7 9 10
# print all nodes at distance k from a given node | a binary tree node ; recursive function to print all the nodes at distance k int the tree ( or subtree ) rooted with given root . see ; base case ; if we reach a k distant node , print it ; recur for left and right subtee ; prints all nodes at distance k from a 

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


def printkDistanceNodeDown(root, k):
    if root is None or k < 0:
        return
    if k == 0:
        print(root .data)
        return
    printkDistanceNodeDown(root .left, k - 1)
    printkDistanceNodeDown(root .right, k - 1)


def printkDistanceNode(root, target, k):
    if root is None:
        return -1
    if root == target:
        printkDistanceNodeDown(root, k)
        return 0
    dl = printkDistanceNode(root .left, target, k)
    if dl != -1:
        if dl + 1 == k:
            print(root .data)
        else:
            printkDistanceNodeDown(root .right, k - dl - 2)
        return 1 + dl
    dr = printkDistanceNode(root .right, target, k)
    if dr != -1:
        if (dr + 1 == k):
            print(root .data)
        else:
            printkDistanceNodeDown(root .left, k - dr - 2)
        return 1 + dr
    return -1


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)
target = root .left .right
printkDistanceNode(root, target, 2)

# Expected output:
4
20
# print all nodes that don 't have sibling | a binary tree node ; function to print all non - root nodes that don 't have a sibling ; base case ; if this is an internal node , recur for left and right subtrees ; if left child is null , and right is not , print right child and recur for right child ; if right child is null and left is not , print left child and recur for left child ; let us create binary tree 

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


def printSingles(root):
    if root is None:
        return
    if root .left is not None and root .right is not None:
        printSingles(root .left)
        printSingles(root .right)
    elif root .right is not None:
        print(root .right .key,)
        printSingles(root .right)
    elif root .left is not None:
        print(root .left .key,)
        printSingles(root .left)


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .right = Node(4)
root .right .left = Node(5)
root .right .left .left = Node(6)
printSingles(root)

# Expected output:
4
5
6
# print leftmost and rightmost nodes of a binary tree | python3 program to print corner node at each level of binary tree ; a binary tree node has key , pointer to left child and a pointer to right child ; function to print corner node at each level ; if the root is null then simply return ; star node is for keeping track of levels ; pushing root node and star node ; do level order traversal using a single queue ; n denotes the size of the current level in the queue ; if it is leftmost corner value or rightmost corner value then print it ; push the left and right children of the temp node ; 

from collections import deque


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


def printCorner(root: Node):
    if root is None:
        return
    q = deque()
    q .append(root)
    while q:
        n = len(q)
        for i in range(n):
            temp = q[0]
            q .popleft()
            if i == 0 or i == n - 1:
                print(temp .key, end=" ")
            if temp .left:
                q .append(temp .left)
            if temp .right:
                q .append(temp .right)


if __name__ == "__main__":
    root = Node(15)
    root .left = Node(10)
    root .right = Node(20)
    root .left .left = Node(8)
    root .left .right = Node(12)
    root .right .left = Node(16)
    root .right .right = Node(25)
    printCorner(root)

# Expected output:
15 10 20 8 25
# print left view of a binary tree | a binary tree node ; recursive function pritn left view of a binary tree ; base case ; if this is the first node of its level ; recur for left and right subtree ; a wrapper over leftviewutil ( ) ; 

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


def leftViewUtil(root, level, max_level):
    if root is None:
        return
    if (max_level[0] < level):
        print("% dTABSYMBOL" % (root .data),)
        max_level[0] = level
    leftViewUtil(root .left, level + 1, max_level)
    leftViewUtil(root .right, level + 1, max_level)


def leftView(root):
    max_level = [0]
    leftViewUtil(root, 1, max_level)


root = Node(12)
root .left = Node(10)
root .right = Node(20)
root .right .left = Node(25)
root .right .right = Node(40)
leftView(root)

# Expected output:
 12TABSYMBOL
 10TABSYMBOL
 25TABSYMBOL
# reduce the given array of [ 1 , n ] by rotating left or right based on given conditions | function to find the last element left after performing n - 1 queries of type x ; stores the next power of 2 ; iterate until nextpower is at most n ; if x is equal to 1 ; stores the power of 2 less than or equal to n ; return the final value ; 
def rotate(arr, N, X):
    nextPower = 1
    while (nextPower <= N):
        nextPower *= 2
    if (X == 1):
        ans = nextPower - N
        return ans
    prevPower = nextPower // 2
    return 2 * (N - prevPower) + 1


arr = [1, 2, 3, 4, 5]
X = 1
N = len(arr)
print(rotate(arr, N, X))

# Expected output:
3
# maximum number of 0 s placed consecutively at the start and end in any rotation of a binary string | function to find the maximum sum of consecutive 0 s present at the start and end of a string present in any of the rotations of the given string ; check if all the characters in the string are 0 ; iterate over characters of the string ; if the frequency of '1' is 0 ; print n as the result ; concatenate the string with itself ; stores the required result ; generate all rotations of the string ; store the number of consecutive 0 s at the start and end of the string ; count 0 s present at the start ; count 0 s present at the end ; calculate the sum ; update the overall maximum sum ; print the result ; 
def findMaximumZeros(st, n):
    c0 = 0
    for i in range(n):
        if (st[i] == '0'):
            c0 += 1
    if (c0 == n):
        print(n)
        return
    s = st + st
    mx = 0
    for i in range(n):
        cs = 0
        ce = 0
        for j in range(i, i + n):
            if (s[j] == '0'):
                cs += 1
            else:
                break
        for j in range(i + n - 1, i - 1, -1):
            if (s[j] == '0'):
                ce += 1
            else:
                break
        val = cs + ce
        mx = max(val, mx)
    print(mx)


if __name__ == "__main__":
    s = "1001"
    n = len(s)
    findMaximumZeros(s, n)

# Expected output:
2
# maximum number of 0 s placed consecutively at the start and end in any rotation of a binary string | function to find the maximum sum of consecutive 0 s present at the start and end of any rotation of the string str ; stores the count of 0 s ; if the frequency of '1' is 0 ; print n as the result ; stores the required sum ; find the maximum consecutive length of 0 s present in the string ; update the overall maximum sum ; find the number of 0 s present at the start and end of the string ; update the count of 0 s at the start ; update the count of 0 s at the end ; update the maximum sum ; print the result ; 
def findMaximumZeros(string, n):
    c0 = 0
    for i in range(n):
        if (string[i] == '0'):
            c0 += 1
    if (c0 == n):
        print(n, end="")
        return
    mx = 0
    cnt = 0
    for i in range(n):
        if (string[i] == '0'):
            cnt += 1
        else:
            mx = max(mx, cnt)
            cnt = 0
    mx = max(mx, cnt)
    start = 0
    end = n - 1
    cnt = 0
    while (string[start] != '1' and start < n):
        cnt += 1
        start += 1
    while (string[end] != '1' and end >= 0):
        cnt += 1
        end -= 1
    mx = max(mx, cnt)
    print(mx, end="")


if __name__ == "__main__":
    s = "1001"
    n = len(s)
    findMaximumZeros(s, n)

# Expected output:
2
# modify a matrix by rotating ith row exactly i times in clockwise direction | function to rotate every i - th row of the matrix i times ; traverse the matrix row - wise ; reverse the current row ; reverse the first i elements ; reverse the last ( n - i ) elements ; increment count ; print final matrix ; 
def rotateMatrix(mat):
    i = 0
    mat1 = []
    for it in mat:
        it .reverse()
        it1 = it[:i]
        it1 .reverse()
        it2 = it[i:]
        it2 .reverse()
        i += 1
        mat1 .append(it1 + it2)
    for rows in mat1:
        for cols in rows:
            print(cols, end=" ")
        print()


if __name__ == "__main__":
    mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    rotateMatrix(mat)

# Expected output:
1 2 3 
6 4 5 
8 9 7
# modify given array to a non | function to check if a non - decreasing array can be obtained by rotating the original array ; stores copy of original array ; sort the given vector ; traverse the array ; rotate the array by 1 ; if array is sorted ; if it is not possible to sort the array ; 
def rotateArray(arr, N):
    v = arr
    v .sort(reverse=False)
    for i in range(1, N + 1, 1):
        x = arr[N - 1]
        i = N - 1
        while (i > 0):
            arr[i] = arr[i - 1]
            arr[0] = x
            i -= 1
        if (arr == v):
            print("YES")
            return
    print("NO")


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

# Expected output:
YES
# maximum value possible by rotating digits of a given number | function to find the maximum value possible by rotations of digits of n ; store the required result ; store the number of digits ; iterate over the range [ 1 , len - 1 ] ; store the unit 's digit ; store the remaining number ; find the next rotation ; if the current rotation is greater than the overall answer , then update answer ; print the result ; 
def findLargestRotation(num):
    ans = num
    length = len(str(num))
    x = 10 ** (length - 1)
    for i in range(1, length):
        lastDigit = num % 10
        num = num // 10
        num += (lastDigit * x)
        if (num > ans):
            ans = num
    print(ans)


N = 657
findLargestRotation(N)

# Expected output:
765