giulio98/xlcost-single-prompt huggingface dataset:
# sum of minimum and maximum elements of all subarrays of size k . | python3 program to find sum of all minimum and maximum elements of sub - array size k . ; returns sum of min and max element of all subarrays of size k ; initialize result ; the queue will store indexes of useful elements in every window in deque ' g ' we maintain decreasing order of values from front to rear in deque ' s ' we maintain increasing order of values from front to rear ; process first window of size k ; remove all previous greater elements that are useless . ; remove from rear ; remove all previous smaller that are elements are useless . ; remove from rear ; add current element at rear of both deque ; process rest of the array elements ; element at the front of the deque ' g ' & ' s ' is the largest and smallest element of previous window respectively ; remove all elements which are out of this window ; remove all previous greater element that are useless ; remove from rear ; remove all previous smaller that are elements are useless ; remove from rear ; add current element at rear of both deque ; sum of minimum and maximum element of last window ; 

from collections import deque


def SumOfKsubArray(arr, n, k):
    Sum = 0
    S = deque()
    G = deque()
    for i in range(k):
        while (len(S) > 0 and arr[S[-1]] >= arr[i]):
            S .pop()
        while (len(G) > 0 and arr[G[-1]] <= arr[i]):
            G .pop()
        G .append(i)
        S .append(i)
    for i in range(k, n):
        Sum += arr[S[0]] + arr[G[0]]
        while (len(S) > 0 and S[0] <= i - k):
            S .popleft()
        while (len(G) > 0 and G[0] <= i - k):
            G .popleft()
        while (len(S) > 0 and arr[S[-1]] >= arr[i]):
            S .pop()
        while (len(G) > 0 and arr[G[-1]] <= arr[i]):
            G .pop()
        G .append(i)
        S .append(i)
    Sum += arr[S[0]] + arr[G[0]]
    return Sum


arr = [2, 5, -1, 7, -3, -1, -2]
n = len(arr)
k = 3
print(SumOfKsubArray(arr, n, k))

# Expected output:
14
# check if removing an edge can divide a binary tree in two halves | python3 program to check if there exist an edge whose removal creates two trees of same size ; to calculate size of tree with given root ; this function returns size of tree rooted with given root . it also set " res " as true if there is an edge whose removal divides tree in two halves . n is size of tree ; base case ; compute sizes of left and right children ; if required property is true for current node set " res " as true ; return size ; this function mainly uses checkrec ( ) ; count total nodes in given tree ; initialize result and recursively check all nodes bool res = false ; ; 

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


def count(node):
    if (node is None):
        return 0
    return (count(node .left) + count(node .right) + 1)


def checkRec(root, n):
    global res
    if (root is None):
        return 0
    c = (checkRec(root .left, n) + 1 + checkRec(root .right, n))
    if (c == n - c):
        res = True
    return c


def check(root):
    n = count(root)
    checkRec(root, n)


if __name__ == '__main__':
    res = False
    root = Node(5)
    root .left = Node(1)
    root .right = Node(6)
    root .left .left = Node(3)
    root .right .left = Node(7)
    root .right .right = Node(4)
    check(root)
    if res:
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# distance of nearest cell having 1 in a binary matrix | prthe distance of nearest cell having 1 for each cell . ; initialize the answer matrix with int_max . ; for each cell ; traversing the whole matrix to find the minimum distance . ; if cell contain 1 , check for minimum distance . ; printing the answer . ; 
def printDistance(mat):
    global N, M
    ans = [[None] * M for i in range(N)]
    for i in range(N):
        for j in range(M):
            ans[i][j] = 999999999999
    for i in range(N):
        for j in range(M):
            for k in range(N):
                for l in range(M):
                    if (mat[k][l] == 1):
                        ans[i][j] = min(ans[i][j], abs(i - k) + abs(j - l))
    for i in range(N):
        for j in range(M):
            print(ans[i][j], end=" ")
        print()


N = 3
M = 4
mat = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 0]]
printDistance(mat)

# Expected output:
3 2 1 0 
2 1 0 0 
1 0 0 1
# distance of nearest cell having 1 in a binary matrix | python3 program to find distance of nearest cell having 1 in a binary matrix . ; making a class of graph with bfs function . ; function to create graph with n * m nodes considering each cell as a node and each boundary as an edge . ; a number to be assigned to a cell ; if last row , then add edge on right side . ; if not bottom right cell . ; if last column , then add edge toward down . ; else makes an edge in all four directions . ; bfs function to find minimum distance ; printing the solution . ; find minimum distance ; creating a graph with nodes values assigned from 1 to n x m and matrix adjacent . ; to store minimum distance ; to mark each node as visited or not in bfs ; initialising the value of distance and visit . ; inserting nodes whose value in matrix is 1 in the queue . ; calling for bfs with given queue . ; printing the solution . ; 

from collections import deque
MAX = 500
N = 3
M = 4
g = [[]for i in range(MAX)]
n, m = 0, 0


def createGraph():
    global g, n, m
    k = 1
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if (i == n):
                if (j != m):
                    g[k].append(k + 1)
                    g[k + 1].append(k)
            elif (j == m):
                g[k].append(k + m)
                g[k + m].append(k)
            else:
                g[k].append(k + 1)
                g[k + 1].append(k)
                g[k].append(k + m)
                g[k + m].append(k)
            k += 1


def bfs(visit, dist, q):
    global g
    while (len(q) > 0):
        temp = q .popleft()
        for i in g[temp]:
            if (visit[i] != 1):
                dist[i] = min(dist[i], dist[temp] + 1)
                q .append(i)
                visit[i] = 1
    return dist


def prt(dist):
    c = 1
    for i in range(1, n * m + 1):
        print(dist[i], end=" ")
        if (c % m == 0):
            print()
        c += 1


def findMinDistance(mat):
    global g, n, m
    n, m = N, M
    createGraph()
    dist = [0] * MAX
    visit = [0] * MAX
    for i in range(1, M * N + 1):
        dist[i] = 10 ** 9
        visit[i] = 0
    k = 1
    q = deque()
    for i in range(N):
        for j in range(M):
            if (mat[i][j] == 1):
                dist[k] = 0
                visit[k] = 1
                q .append(k)
            k += 1
    dist = bfs(visit, dist, q)
    prt(dist)


if __name__ == '__main__':
    mat = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 0]]
    findMinDistance(mat)

# Expected output:
3 2 1 0 
2 1 0 0 
1 0 0 1
# first negative integer in every window of size k | function to find the first negative integer in every window of size k ; loop for each subarray ( window ) of size k ; traverse through the current window ; if a negative integer is found , then it is the first negative integer for current window . print it , set the flag and break ; if the current window does not contain a negative integer ; 
def printFirstNegativeInteger(arr, n, k):
    for i in range(0, (n - k + 1)):
        flag = False
        for j in range(0, k):
            if (arr[i + j] < 0):
                print(arr[i + j], end=" ")
                flag = True
                break
        if (not (flag)):
            print("0", end=" ")


arr = [12, -1, -7, 8, -15, 30, 16, 28]
n = len(arr)
k = 3
printFirstNegativeInteger(arr, n, k)

# Expected output:
-1 -1 -7 -15 -15 0
# first negative integer in every window of size k | python3 implementation to find the first negative integer in every window of size k import deque ( ) from collections ; function to find the first negative integer in every window of size k ; a double ended queue , di that will store indexes of useful array elements for the current window of size k . the useful elements are all negative integers . ; process first k ( or first window ) elements of array ; add current element at the rear of di if it is a negative integer ; process rest of the elements , i . e . , from arr [ k ] to arr [ n - 1 ] ; if the window does not have a negative integer ; if di is not empty then the element at the front of the queue is the first negative integer of the previous window ; remove the elements which are out of this window ; remove from front of queue ; add current element at the rear of di if it is a negative integer ; print the first negative integer of last window ; 

from collections import deque


def printFirstNegativeInteger(arr, n, k):
    Di = deque()
    for i in range(k):
        if (arr[i] < 0):
            Di .append(i)
    for i in range(k, n):
        if (not Di):
            print(0, end=' ')
        else:
            print(arr[Di[0]], end=' ')
        while Di and Di[0] <= (i - k):
            Di .popleft()
        if (arr[i] < 0):
            Di .append(i)
    if not Di:
        print(0)
    else:
        print(arr[Di[0]], end=" ")


if __name__ == "__main__":
    arr = [12, -1, -7, 8, -15, 30, 16, 28]
    n = len(arr)
    k = 3
    printFirstNegativeInteger(arr, n, k)

# Expected output:
-1 -1 -7 -15 -15 0
# first negative integer in every window of size k | python3 code for first negative integer in every window of size k ; skip out of window and positive elements ; check if a negative element is found , otherwise use 0 ; 
def printFirstNegativeInteger(arr, k):
    firstNegativeIndex = 0
    for i in range(k - 1, len(arr)):
        while firstNegativeIndex < i and (
                firstNegativeIndex <= i -
                k or arr[firstNegativeIndex] > 0):
            firstNegativeIndex += 1
        firstNegativeElement = arr[firstNegativeIndex]if arr[firstNegativeIndex] < 0 else 0
        print(firstNegativeElement, end=' ')


if __name__ == "__main__":
    arr = [12, -1, -7, 8, -15, 30, 16, 28]
    k = 3
    printFirstNegativeInteger(arr, k)

# Expected output:
-1 -1 -7 -15 -15 0
# check if x can give change to every person in the queue | function to check if every person will get the change from x ; to count the 5 $ and 10 & notes ; serve the customer in order ; increase the number of 5 $ note by one ; decrease the number of note 5 $ and increase 10 $ note by one ; decrease 5 $ and 10 $ note by one ; decrease 5 $ note by three ; queue of customers with available notes . ; 
def isChangeable(notes, n):
    fiveCount = 0
    tenCount = 0
    for i in range(n):
        if (notes[i] == 5):
            fiveCount += 1
        elif (notes[i] == 10):
            if (fiveCount > 0):
                fiveCount -= 1
                tenCount += 1
            else:
                return 0
        else:
            if (fiveCount > 0 and tenCount > 0):
                fiveCount -= 1
                tenCount -= 1
            elif (fiveCount >= 3):
                fiveCount -= 3
            else:
                return 0
    return 1


a = [5, 5, 5, 10, 20]
n = len(a)
if (isChangeable(a, n)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# given level order traversal of a binary tree , check if the tree is a min | returns true if given level order traversal is min heap . ; first non leaf node is at index ( n / 2 - 1 ) . check whether each parent is greater than child ; left child will be at index 2 * i + 1 right child will be at index 2 * i + 2 ; if parent is greater than right child ; 
def isMinHeap(level, n):
    for i in range(int(n / 2) - 1, -1, -1):
        if level[i] > level[2 * i + 1]:
            return False
        if 2 * i + 2 < n:
            if level[i] > level[2 * i + 2]:
                return False
    return True


if __name__ == '__main__':
    level = [10, 15, 14, 25, 30]
    n = len(level)
    if isMinHeap(level, n):
        print("True")
    else:
        print("False")

# Expected output:
True
# minimum delete operations to make all elements of array same | function to get minimum number of elements to be deleted from array to make array elements equal ; create an dictionary and store frequencies of all array elements in it using element as key and frequency as value ; find maximum frequency among all frequencies . ; to minimize delete operations , we remove all elements but the most frequent element . ; 
def minDelete(arr, n):
    freq = {}
    for i in range(n):
        if arr[i] in freq:
            freq[arr[i]] += 1
        else:
            freq[arr[i]] = 1
    max_freq = 0
    for i, j in freq .items():
        max_freq = max(max_freq, j)
    return n - max_freq


arr = [4, 3, 4, 4, 2, 4]
n = len(arr)
print(minDelete(arr, n))

# Expected output:
2
# minimum operation to make all elements equal in array | python3 program to find the minimum number of operations required to make all elements of array equal ; function for min operation ; insert all elements in hash . ; find the max frequency ; return result ; 

from collections import defaultdict


def minOperation(arr, n):
    Hash = defaultdict(lambda: 0)
    for i in range(0, n):
        Hash[arr[i]] += 1
    max_count = 0
    for i in Hash:
        if max_count < Hash[i]:
            max_count = Hash[i]
    return n - max_count


if __name__ == "__main__":
    arr = [1, 5, 2, 1, 3, 2, 1]
    n = len(arr)
    print(minOperation(arr, n))

# Expected output:
4
# maximum distance between two occurrences of same element in array | function to find maximum distance between equal elements ; used to store element to first index mapping ; traverse elements and find maximum distance between same occurrences with the help of map . ; if this is first occurrence of element , insert its index in map ; else update max distance ; 
def maxDistance(arr, n):
    mp = {}
    maxDict = 0
    for i in range(n):
        if arr[i]not in mp .keys():
            mp[arr[i]] = i
        else:
            maxDict = max(maxDict, i - mp[arr[i]])
    return maxDict



if __name__ == '__main__':
    arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2]
    n = len(arr)
    print(maxDistance(arr, n))

# Expected output:
10
# check if a given array contains duplicate elements within k distance from each other | python 3 program to check if a given array contains duplicate elements within k distance from each other ; creates an empty list ; traverse the input array ; if already present n hash , then we found a duplicate within k distance ; add this item to hashset ; remove the k + 1 distant item ; 
def checkDuplicatesWithinK(arr, n, k):
    myset = []
    for i in range(n):
        if arr[i] in myset:
            return True
        myset .append(arr[i])
        if (i >= k):
            myset .remove(arr[i - k])
    return False


if __name__ == "__main__":
    arr = [10, 5, 3, 4, 3, 5, 6]
    n = len(arr)
    if (checkDuplicatesWithinK(arr, n, 3)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# find duplicates in a given array when elements are not limited to a range | function to find the duplicates , if duplicate occurs 2 times or more than 2 times in array so , it will print duplicate value only once at output ; initialize ifpresent as false ; arraylist to store the output ; checking if element is present in the arraylist or not if present then break ; if element is not present in the arraylist then add it to arraylist and make ifpresent at true ; if duplicates is present then print arraylist ; 
def findDuplicates(arr, Len):
    ifPresent = False
    a1 = []
    for i in range(Len - 1):
        for j in range(i + 1, Len):
            if (arr[i] == arr[j]):
                if arr[i] in a1:
                    break
                else:
                    a1 .append(arr[i])
                    ifPresent = True
    if (ifPresent):
        print(a1, end=" ")
    else:
        print("No duplicates present in arrays")


arr = [12, 11, 40, 12, 5, 6, 5, 12, 11]
n = len(arr)
findDuplicates(arr, n)

# Expected output:
[12, 11, 5]
# check if leaf traversal of two binary trees is same ? | binary tree node ; checks if a given node is leaf or not . ; returns true of leaf traversal of two trees is same , else false ; create empty stacks . these stacks are going to be used for iterative traversals . ; loop until either of two stacks is not empty ; if one of the stacks is empty means other stack has extra leaves so return false ; append right and left children of temp1 . note that right child is inserted before left ; same for tree2 ; if one is none and other is not , then return false ; if both are not none and data is not same return false ; if control reaches this point , all leaves are matched ; 

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

    def isLeaf(self):
        return (self .left is None and self .right is None)


def isSame(root1, root2):
    s1 = []
    s2 = []
    s1 .append(root1)
    s2 .append(root2)
    while (len(s1) != 0 or len(s2) != 0):
        if (len(s1) == 0 or len(s2) == 0):
            return False
        temp1 = s1 .pop(-1)
        while (temp1 is not None and not temp1 .isLeaf()):
            if (temp1 .right is not None):
                s1 .append(temp1 .right)
            if (temp1 .left is not None):
                s1 .append(temp1 .left)
                temp1 = s1 .pop(-1)
        temp2 = s2 .pop(-1)
        while (temp2 is not None and not temp2 .isLeaf()):
            if (temp2 .right is not None):
                s2 .append(temp2 .right)
            if (temp2 .left is not None):
                s2 .append(temp2 .left)
            temp2 = s2 .pop(-1)
        if (temp1 is None and temp2 is not None):
            return False
        if (temp1 is not None and temp2 is None):
            return False
        if (temp1 is not None and temp2 is not None):
            if (temp1 .data != temp2 .data):
                return False
    return True


if __name__ == '__main__':
    root1 = Node(1)
    root1 .left = Node(2)
    root1 .right = Node(3)
    root1 .left .left = Node(4)
    root1 .right .left = Node(6)
    root1 .right .right = Node(7)
    root2 = Node(0)
    root2 .left = Node(1)
    root2 .right = Node(5)
    root2 .left .right = Node(4)
    root2 .right .left = Node(6)
    root2 .right .right = Node(7)
    if (isSame(root1, root2)):
        print("Same")
    else:
        print("Not Same")

# Expected output:
Same
# most frequent element in an array | python3 program to find the most frequent element in an array . ; sort the array ; find the max frequency using linear traversal ; if last element is most frequent ; 
def mostFrequent(arr, n):
    arr .sort()
    max_count = 1
    res = arr[0]
    curr_count = 1
    for i in range(1, n):
        if (arr[i] == arr[i - 1]):
            curr_count += 1
        else:
            if (curr_count > max_count):
                max_count = curr_count
                res = arr[i - 1]
            curr_count = 1
    if (curr_count > max_count):
        max_count = curr_count
        res = arr[n - 1]
    return res


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

# Expected output:
1
# most frequent element in an array | python3 program to find the most frequent element in an array . ; insert all elements in hash . ; find the max frequency ; 

import math as mt


def mostFrequent(arr, n):
    Hash = dict()
    for i in range(n):
        if arr[i] in Hash .keys():
            Hash[arr[i]] += 1
        else:
            Hash[arr[i]] = 1
    max_count = 0
    res = -1
    for i in Hash:
        if (max_count < Hash[i]):
            res = i
            max_count = Hash[i]
    return res


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

# Expected output:
1
# smallest subarray with all occurrences of a most frequent element | python3 implementation to find smallest subarray with all occurrences of a most frequent element ; to store left most occurrence of elements ; to store counts of elements ; to store maximum frequency ; to store length and starting index of smallest result window ; first occurrence of an element , store the index ; increase the frequency of elements ; find maximum repeated element and store its last occurrence and first occurrence ; length of subsegment ; select subsegment of smallest size ; print the subsegment with all occurrences of a most frequent element ; 
def smallestSubsegment(a, n):
    left = dict()
    count = dict()
    mx = 0
    mn, strindex = 0, 0
    for i in range(n):
        x = a[i]
        if (x not in count .keys()):
            left[x] = i
            count[x] = 1
        else:
            count[x] += 1
        if (count[x] > mx):
            mx = count[x]
            mn = i - left[x] + 1
            strindex = left[x]
        elif (count[x] == mx and i - left[x] + 1 < mn):
            mn = i - left[x] + 1
            strindex = left[x]
    for i in range(strindex, strindex + mn):
        print(a[i], end=" ")


A = [1, 2, 2, 2, 1]
n = len(A)
smallestSubsegment(A, n)

# Expected output:
2 2 2
# given an array of pairs , find all symmetric pairs in it | print all pairs that have a symmetric counterpart ; creates an empty hashmap hm ; traverse through the given array ; first and second elements of current pair ; if found and value in hash matches with first element of this pair , we found symmetry ; else put sec element of this pair in hash ; 
def findSymPairs(arr, row):
    hM = dict()
    for i in range(row):
        first = arr[i][0]
        sec = arr[i][1]
        if (sec in hM .keys() and hM[sec] == first):
            print("(", sec, ",", first, ")")
        else:
            hM[first] = sec


if __name__ == '__main__':
    arr = [[0 for i in range(2)]for i in range(5)]
    arr[0][0], arr[0][1] = 11, 20
    arr[1][0], arr[1][1] = 30, 40
    arr[2][0], arr[2][1] = 5, 10
    arr[3][0], arr[3][1] = 40, 30
    arr[4][0], arr[4][1] = 10, 5
    findSymPairs(arr, 5)

# Expected output:
( 30 , 40 )
( 5 , 10 )
# find any one of the multiple repeating elements in read only array | python 3 program to find one of the repeating elements in a read only array ; function to find one of the repeating elements ; size of blocks except the last block is sq ; number of blocks to incorporate 1 to n values blocks are numbered from 0 to range - 1 ( both included ) ; count array maintains the count for all blocks ; traversing the read only array and updating count ; arr [ i ] belongs to block number ( arr [ i ] - 1 ) / sq i is considered to start from 0 ; the selected_block is set to last block by default . rest of the blocks are checked ; after finding block with size > sq method of hashing is used to find the element repeating in this block ; checks if the element belongs to the selected_block ; repeating element found ; return - 1 if no repeating element exists ; 

from math import sqrt


def findRepeatingNumber(arr, n):
    sq = sqrt(n)
    range__ = int((n / sq) + 1)
    count = [0 for i in range(range__)]
    for i in range(0, n + 1, 1):
        count[int((arr[i] - 1) / sq)] += 1
    selected_block = range__ - 1
    for i in range(0, range__ - 1, 1):
        if (count[i] > sq):
            selected_block = i
            break
    m = {i: 0 for i in range(n)}
    for i in range(0, n + 1, 1):
        if (((selected_block * sq) < arr[i])
                and (arr[i] <= ((selected_block + 1) * sq))):
            m[arr[i]] += 1
            if (m[arr[i]] > 1):
                return arr[i]
    return -1


if __name__ == '__main__':
    arr = [1, 1, 2, 3, 5, 4]
    n = 5
    print(
        "One of the numbers repeated in the array is:",
        findRepeatingNumber(
            arr,
            n))

# Expected output:
One of the numbers repeated in the array is: 1