giulio98/xlcost-single-prompt huggingface dataset:
# selection sort vs bubble sort |  ; 
def Selection_Sort(arr, n):
    for i in range(n - 1):
        min_index = i
        for j in range(i + 1, n):
            if (arr[j] < arr[min_index]):
                min_index = j
        arr[i], arr[min_index] = arr[min_index], arr[i]


n = 5
arr = [2, 0, 1, 4, 3]
Selection_Sort(arr, n)
print("The Sorted Array by using Selection Sort is : ", end='')
for i in range(n):
    print(arr[i], end=" ")

# Expected output:
The Sorted Array by using Selection Sort is : 0 1 2 3 4
# last seen array element ( last appearance is earliest ) | python3 program to find last seen element in an array . ; returns last seen element in arr [ ] ; store last occurrence index of every element ; find an element in hash with minimum index value ; 

import sys


def lastSeenElement(a, n):
    hash = {}
    for i in range(n):
        hash[a[i]] = i
    res_ind = sys .maxsize
    res = 0
    for x, y in hash .items():
        if y < res_ind:
            res_ind = y
            res = x
    return res


if __name__ == "__main__":
    a = [2, 1, 2, 2, 4, 1]
    n = len(a)
    print(lastSeenElement(a, n))

# Expected output:
2
# selection sort vs bubble sort |  ; 
def Bubble_Sort(arr, n):
    for i in range(1, n):
        for j in range(0, n - i):
            if (arr[j] > arr[j + 1]):
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr


n = 5
arr = [2, 0, 1, 4, 3]
arr = Bubble_Sort(arr, n)
print("The Sorted Array by using Bubble Sort is : ", end='')
for i in range(n):
    print(arr[i], end=" ")

# Expected output:
The Sorted Array by using Bubble Sort is : 0 1 2 3 4
# minimum cost required to connect all houses in a city | python3 program for the above approach ; utility function to find set of an element v using path compression technique ; if v is the parent ; otherwise , recursively find its parent ; function to perform union of the sets a and b ; find parent of a and b ; if parent are different ; swap operation ; update parent of b as a ; otherwise , return 0 ; function to create a minimum cost spanning tree for given houses ; stores adjacency list of graph ; traverse each coordinate ; find the manhattan distance ; add the edges ; sort all the edges ; initialize parent [ ] and size [ ] ; stores the minimum cost ; finding the minimum cost ; perform the unioun operation ; print the minimum cost ; 

parent = [0] * 100
size = [0] * 100


def find_set(v):
    if (v == parent[v]):
        return v
    parent[v] = find_set(parent[v])
    return parent[v]


def union_sets(a, b):
    a = find_set(a)
    b = find_set(b)
    if (a != b):
        if (size[a] < size[b]):
            a, b = b, a
        parent[b] = a
        size[a] += size[b]
        return 1
    return 0


def MST(houses, n):
    v = []
    for i in range(n):
        for j in range(i + 1, n):
            p = abs(houses[i][0] - houses[j][0])
            p += abs(houses[i][1] - houses[j][1])
            v .append([p, i, j])
    v = sorted(v)
    for i in range(n):
        parent[i] = i
        size[i] = 1
    ans = 0
    for x in v:
        if (union_sets(x[1], x[2])):
            ans += x[0]
    print(ans)


if __name__ == '__main__':
    houses = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]
    N = len(houses)
    MST(houses, N)

# Expected output:
20
# lexicographically smallest subsequence possible by removing a character from given string | function to find the lexicographically smallest subsequence of length n - 1 ; store index of character to be deleted ; traverse the string ; if ith character > ( i + 1 ) th character then store it ; if any character found in non alphabetical order then remove it ; otherwise remove last character ; print the resultant subsequence ; 
def firstSubsequence(s):
    isMax = -1
    for i in range(len(s)):
        if (s[i] > s[i + 1]):
            isMax = i
            break
    if (isMax >= 0):
        s = s[0:isMax] + s[isMax + 1:len(s)]
    else:
        s = s[0:s .length() - 1]
    print(s)


if __name__ == '__main__':
    S = "geeksforgeeks"
    firstSubsequence(S)

# Expected output:
eeksforgeeks
# maximize product of array by replacing array elements with its sum or product with element from another array | function to find the largest product of array a [ ] ; base case ; store all the elements of the array a [ ] ; sort the array b [ ] ; traverse the array b [ ] ; pop minimum element ; check which operation is producing maximum element ; insert resultant element into the priority queue ; evaluate the product of the elements of a [ ] ; return the maximum product ; 
def largeProduct(A, B, N):
    if (N == 0):
        return 0
    pq = []
    for i in range(N):
        pq .append(A[i])
    B .sort()
    pq .sort(reverse=True)
    for i in range(N):
        minn = pq .pop()
        maximized_element = max(minn * B[i], minn + B[i])
        pq .append(maximized_element)
        pq .sort(reverse=True)
    max_product = 1
    while (len(pq) > 0):
        max_product *= pq .pop()
    return max_product


A = [1, 1, 10]
B = [1, 1, 1]
N = 3
print(largeProduct(A, B, N))

# Expected output:
60
# print all root to leaf paths with there relative positions | python3 program to print the longest leaf to leaf path ; tree node structure used in the program ; prints given root to leafallpaths with underscores ; find the minimum horizontal distance value in current root to leafallpaths ; find minimum horizontal distance ; print the root to leafallpaths with " _ " that indicate the related position ; current tree node ; print underscore ; print current key ; a utility function prall path from root to leaf working of this function is similar to function of " print _ vertical _ order " : prpaths of binary tree in vertical order https : www . geeksforgeeks . org / print - binary - tree - vertical - order - set - 2 / ; base case ; leaf node ; add leaf node and then prpath ; store current path information ; call left sub_tree ; call left sub_tree ; base case ; 

MAX_PATH_SIZE = 1000


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


def printPath(size):
    minimum_Hd = 10 ** 19
    p = []
    global Allpaths
    for it in range(size):
        p = Allpaths[it]
        minimum_Hd = min(minimum_Hd, p[0])
    for it in range(size):
        p = Allpaths[it]
        noOfUnderScores = abs(p[0] - minimum_Hd)
        for i in range(noOfUnderScores):
            print(end="_ ")
        print(p[1])
    print("==============================")


def printAllPathsUtil(root, HD, order):
    global Allpaths
    if (root is None):
        return
    if (root .left is None and root .right is None):
        Allpaths[order] = [HD, root .data]
        printPath(order + 1)
        return
    Allpaths[order] = [HD, root .data]
    printAllPathsUtil(root .left, HD - 1, order + 1)
    printAllPathsUtil(root .right, HD + 1, order + 1)


def printAllPaths(root):
    global Allpaths
    if (root is None):
        return
    printAllPathsUtil(root, 0, 0)


if __name__ == '__main__':
    Allpaths = [[0, 0]for i in range(MAX_PATH_SIZE)]
    root = Node('A')
    root .left = Node('B')
    root .right = Node('C')
    root .left .left = Node('D')
    root .left .right = Node('E')
    root .right .left = Node('F')
    root .right .right = Node('G')
    printAllPaths(root)

# Expected output:
_ _ A
_ B
D
==============================
_ A
B
_ E
==============================
A
_ C
F
==============================
A
_ C
_ _ G
==============================
# minimum steps required to rearrange given array to a power sequence of 2 | function to calculate the minimum steps required to convert given array into a power sequence of 2 ; sort the array in ascending order ; calculate the absolute difference between arr [ i ] and 2 ^ i for each index ; return the answer ; 
def minsteps(arr, n):
    arr .sort()
    ans = 0
    for i in range(n):
        ans += abs(arr[i] - pow(2, i))
    return ans


arr = [1, 8, 2, 10, 6]
n = len(arr)
print(minsteps(arr, n))

# Expected output:
8
# cost required to empty a given array by repeated removal of maximum obtained by given operations | function to find the total cost of removing all array elements ; sort the array in descending order ; stores the total cost ; contribution of i - th greatest element to the cost ; remove the element ; if negative ; add to the final cost ; return the cost ; 
def findCost(a, n):
    a .sort(reverse=True)
    count = 0
    for j in range(n):
        p = a[j] - j
        a[j] = 0
        if (p < 0):
            p = 0
            continue
        count += p
    return count


arr = [1, 6, 7, 4, 2, 5, 3]
N = len(arr)
print(findCost(arr, N))

# Expected output:
16
# count of index pairs with equal elements in an array | set 2 | function that count the pairs having same elements in the array arr [ ] ; hash map to keep track of occurences of elements ; traverse the array arr [ ] ; check if occurence of arr [ i ] > 0 add count [ arr [ i ] ] to answer ; return the result ; 
def countPairs(arr, n):
    ans = 0
    count = {}
    for i in range(n):
        if arr[i] in count:
            ans += count[arr[i]]
        if arr[i] in count:
            count[arr[i]] += 1
        else:
            count[arr[i]] = 1
    return ans


arr = [1, 2, 1, 1]
N = len(arr)
print(countPairs(arr, N))

# Expected output:
3
# maximize shortest path between given vertices by adding a single edge | function that performs bfs traversal ; fill initially each distance as inf fill ( dist , dist + n , inf ) ; perform bfs ; traverse the current edges ; update the distance ; insert in queue ; function that maximizes the shortest path between source and destination vertex by adding a single edge between given selected nodes ; to update the shortest distance between node 1 to other vertices ; to update the shortest distance between node n to other vertices ; store the values x [ i ] - y [ i ] ; sort all the vectors of pairs ; traverse data [ ] ; maximize x [ a ] - y [ b ] ; prminimum cost ; 
def bfs(x, s):
    global edges, dist
    q = [0 for i in range(200000)]
    qh, qt = 0, 0
    q[qh] = s
    qh += 1
    dist[x][s] = 0
    while (qt < qh):
        xx = q[qt]
        qt += 1
        for y in edges[xx]:
            if (dist[x][y] == 10 ** 18):
                dist[x][y] = dist[x][xx] + 1
                q[qh] = y
                qh += 1


def shortestPathCost(selected, K):
    global dist, edges
    data = []
    bfs(0, 0)
    bfs(1, N - 1)
    for i in range(K):
        data .append([dist[0][selected[i]] - dist[1]
                     [selected[i]], selected[i]])
    data = sorted(data)
    best = 0
    MAX = -10 ** 18
    for it in data:
        a = it[1]
        best = max(best, MAX + dist[1][a])
        MAX = max(MAX, dist[0][a])
    print(min(dist[0][N - 1], best + 1))


if __name__ == '__main__':
    edges = [[]for i in range(5)]
    dist = [[10 ** 18 for i in range(1000005)]for i in range(2)]
    N, M = 5, 4
    K = 2
    selected = [1, 3]
    selected = sorted(selected)
    edges[0].append(1)
    edges[1].append(0)
    edges[1].append(2)
    edges[2].append(1)
    edges[2].append(3)
    edges[3].append(2)
    edges[3].append(4)
    edges[4].append(3)
    shortestPathCost(selected, K)

# Expected output:
3
# program to cyclically rotate an array by one | i and j pointing to first and last element respectively ; 
def rotate(arr, n):
    i = 0
    j = n - 1
    while i != j:
        arr[i], arr[j] = arr[j], arr[i]
        i = i + 1
    pass


arr = [1, 2, 3, 4, 5]
n = len(arr)
print("Given array is")
for i in range(0, n):
    print(arr[i], end=' ')
rotate(arr, n)
print("Rotatedarrayis")
for i in range(0, n):
    print(arr[i], end=' ')

# Expected output:
Given array is
1 2 3 4 5 Rotatedarrayis
5 1 2 3 4
# minimum cost to empty array where cost of removing an element is 2 ^ ( removed_count ) * arr [ i ] | function to find the minimum cost of removing elements from the array ; sorting in increasing order ; loop to find the minimum cost of removing elements ; 
def removeElements(arr, n):
    arr .sort(reverse=True)
    ans = 0
    for i in range(n):
        ans += arr[i] * pow(2, i)
    return ans


if __name__ == "__main__":
    n = 4
    arr = [3, 1, 2, 3]
    print(removeElements(arr, n))

# Expected output:
25
# sorting boundary elements of a matrix | python program for the above approach ; appending border elements ; sorting the list ; printing first row with first n elements from a ; printing n - 2 rows ; print elements from last ; print middle elements from original matrix ; print elements from front ; printing last row ; dimensions of a matrix ; 
def printMatrix(grid, m, n):
    A = []
    for i in range(m):
        for j in range(n):
            if j == n - 1 or (i == m - 1) or j == 0 or i == 0:
                A .append(grid[i][j])
    A .sort()
    print(*A[:n])
    for i in range(m - 2):
        print(A[len(A) - i - 1], end=" ")
        for j in range(1, n - 1):
            print(grid[i + 1][j], end=" ")
        print(A[n + i])
    print(*reversed(A[n + m - 2:n + m - 2 + n]))


m, n = 4, 5
grid = [[1, 2, 3, 4, 0], [1, 1, 1, 1, 2], [1, 2, 2, 2, 4], [1, 9, 3, 1, 7]]
printMatrix(grid, m, n)

# Expected output:
0 1 1 1 1
9 1 1 1 1
7 2 2 2 2
4 4 3 3 2
# lexicographically largest string possible in one swap | function to return the lexicographically largest string possible by swapping at most one character ; initialize with - 1 for every character ; keep updating the last occurrence of each character ; if a previously unvisited character occurs ; stores the sorted string ; character to replace ; find the last occurrence of this character ; swap this with the last occurrence ; 
def findLargest(s):
    Len = len(s)
    loccur = [-1 for i in range(26)]
    for i in range(Len - 1, -1, -1):
        chI = ord(s[i]) - ord('a')
        if (loccur[chI] == -1):
            loccur[chI] = i
    sorted_s = sorted(s, reverse=True)
    for i in range(Len):
        if (s[i] != sorted_s[i]):
            chI = (ord(sorted_s[i]) - ord('a'))
            last_occ = loccur[chI]
            temp = list(s)
            temp[i], temp[last_occ] = (temp[last_occ], temp[i])
            s = "".join(temp)
            break
    return s


s = "yrstvw"
print(findLargest(s))

# Expected output:
ywstvr
# given a sorted and rotated array , find if there is a pair with a given sum | this function returns true if arr [ 0. . n - 1 ] has a pair with sum equals to x . ; find the pivot element ; l is now index of smallest element ; r is now index of largest element ; keep moving either l or r till they meet ; if we find a pair with sum x , we return true ; if current pair sum is less , move to the higher sum ; move to the lower sum side ; 
def pairInSortedRotated(arr, n, x):
    for i in range(0, n - 1):
        if (arr[i] > arr[i + 1]):
            break
    l = (i + 1) % n
    r = i
    while (l != r):
        if (arr[l] + arr[r] == x):
            return True
        if (arr[l] + arr[r] < x):
            l = (l + 1) % n
        else:
            r = (n + r - 1) % n
    return False


arr = [11, 15, 6, 8, 9, 10]
sum = 16
n = len(arr)
if (pairInSortedRotated(arr, n, sum)):
    print("Array has two elements with sum 16")
else:
    print("Array doesn't have two elements with sum 16 ")

# Expected output:
Array has two elements with sum 16
# given a sorted and rotated array , find if there is a pair with a given sum | this function returns count of number of pairs with sum equals to x . ; find the pivot element . pivot element is largest element of array . ; l is index of smallest element . ; r is index of largest element . ; variable to store count of number of pairs . ; find sum of pair formed by arr [ l ] and arr [ r ] and update l , r and cnt accordingly . ; if we find a pair with sum x , then increment cnt , move l and r to next element . ; this condition is required to be checked , otherwise l and r will cross each other and loop will never terminate . ; if current pair sum is less , move to the higher sum side . ; if current pair sum is greater , move to the lower sum side . ; 
def pairsInSortedRotated(arr, n, x):
    for i in range(n):
        if arr[i] > arr[i + 1]:
            break
    l = (i + 1) % n
    r = i
    cnt = 0
    while (l != r):
        if arr[l] + arr[r] == x:
            cnt += 1
            if l == (r - 1 + n) % n:
                return cnt
            l = (l + 1) % n
            r = (r - 1 + n) % n
        elif arr[l] + arr[r] < x:
            l = (l + 1) % n
        else:
            r = (n + r - 1) % n
    return cnt


arr = [11, 15, 6, 7, 9, 10]
s = 16
print(pairsInSortedRotated(arr, 6, s))

# Expected output:
2
# find maximum value of sum ( i * arr [ i ] ) with only rotations on 
def maxSum(arr):
    arrSum = 0
    currVal = 0
    n = len(arr)
    for i in range(0, n):
        arrSum = arrSum + arr[i]
        currVal = currVal + (i * arr[i])
    maxVal = currVal
    for j in range(1, n):
        currVal = currVal + arrSum - n * arr[n - j]
        if currVal > maxVal:
            maxVal = currVal
    return maxVal


arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Max sum is: ", maxSum(arr))

# Expected output:
Max sum is:  330
# maximum sum of i * arr [ i ] among all rotations of a given array | a naive python3 program to find maximum sum rotation ; returns maximum value of i * arr [ i ] ; initialize result ; consider rotation beginning with i for all possible values of i . ; initialize sum of current rotation ; compute sum of all values . we don 't  acutally rotation the array, but  compute sum by finding ndexes when  arr[i] is first element ; update result if required ; 

import sys


def maxSum(arr, n):
    res = -sys .maxsize
    for i in range(0, n):
        curr_sum = 0
        for j in range(0, n):
            index = int((i + j) % n)
            curr_sum += j * arr[index]
        res = max(res, curr_sum)
    return res


arr = [8, 3, 1, 2]
n = len(arr)
print(maxSum(arr, n))

# Expected output:
29
# maximum sum of i * arr [ i ] among all rotations of a given array | an efficient python3 program to compute maximum sum of i * arr [ i ] ; compute sum of all array elements ; compute sum of i * arr [ i ] for initial configuration . ; initialize result ; compute values for other iterations ; compute next value using previous value in o ( 1 ) time ; update current value ; update result if required ; 
def maxSum(arr, n):
    cum_sum = 0
    for i in range(0, n):
        cum_sum += arr[i]
    curr_val = 0
    for i in range(0, n):
        curr_val += i * arr[i]
    res = curr_val
    for i in range(1, n):
        next_val = (curr_val - (cum_sum - arr[i - 1]) + arr[i - 1] * (n - 1))
        curr_val = next_val
        res = max(res, next_val)
    return res


arr = [8, 3, 1, 2]
n = len(arr)
print(maxSum(arr, n))

# Expected output:
29
# find the rotation count in rotated sorted array | returns count of rotations for an array which is first sorted in ascending order , then rotated ; we basically find index of minimum element ; 
def countRotations(arr, n):
    min = arr[0]
    for i in range(0, n):
        if (min > arr[i]):
            min = arr[i]
            min_index = i
    return min_index


arr = [15, 18, 2, 3, 6, 12]
n = len(arr)
print(countRotations(arr, n))

# Expected output:
2
# find the rotation count in rotated sorted array | returns count of rotations for an array which is first sorted in ascending order , then rotated ; this condition is needed to handle the case when array is not rotated at all ; if there is only one element left ; find mid ; check if element ( mid + 1 ) is minimum element . consider the cases like { 3 , 4 , 5 , 1 , 2 } ; check if mid itself is minimum element ; decide whether we need to go to left half or right half ; 
def countRotations(arr, low, high):
    if (high < low):
        return 0
    if (high == low):
        return low
    mid = low + (high - low) / 2
    mid = int(mid)
    if (mid < high and arr[mid + 1] < arr[mid]):
        return (mid + 1)
    if (mid > low and arr[mid] < arr[mid - 1]):
        return mid
    if (arr[high] > arr[mid]):
        return countRotations(arr, low, mid - 1)
    return countRotations(arr, mid + 1, high)


arr = [15, 18, 2, 3, 6, 12]
n = len(arr)
print(countRotations(arr, 0, n - 1))

# Expected output:
2
# arrange the array such that upon performing given operations an increasing order is obtained | function to arrange array in such a way that after performing given operation we get increasing sorted array ; size of given array ; sort the given array ; start erasing last element and place it at ith index ; while we reach at starting ; store last element ; shift all elements by 1 position in right ; insert last element at ith position ; print desired array ; 
def Desired_Array(v):
    n = len(v)
    v .sort()
    i = n - 1
    while (i > 0):
        p = v[n - 1]
        for j in range(n - 1, i - 1, -1):
            v[j] = v[j - 1]
        v[i] = p
        i -= 1
    for x in v:
        print(x, end=" ")
    print()


v = [1, 2, 3, 4, 5]
Desired_Array(v)
v1 = [1, 12, 2, 10, 4, 16, 6]
Desired_Array(v1)

# Expected output:
1 5 2 4 3 
1 12 2 10 4 16 6
# quickly find multiple left rotations of an array | set 1 | function to left rotate an array k times ; print array after k rotations ; 
def leftRotate(arr, n, k):
    for i in range(k, k + n):
        print(str(arr[i % n]), end=" ")


arr = [1, 3, 5, 7, 9]
n = len(arr)
k = 2
leftRotate(arr, n, k)
print()
k = 3
leftRotate(arr, n, k)
print()
k = 4
leftRotate(arr, n, k)
print()

# Expected output:
5 7 9 1 3 
7 9 1 3 5 
9 1 3 5 7
# how to sort an array in a single loop ? | function for sorting the array using a single loop ; finding the length of array 'arr ; sorting using a single loop ; checking the condition for two simultaneous elements of the array ; swapping the elements . ; updating the value of j = - 1 so after getting updated for j ++ in the loop it becomes 0 and the loop begins from the start . ; 
def sortArrays(arr):
    length = len(arr)
    j = 0
    while j < length-1:
        if (arr[j] > arr[j+1]):
            temp = arr[j]
            arr[j] = arr[j+1]
            arr[j+1] = temp
            j = -1
        j += 1
    return arr


if __name__ == '__main__':
    arr = [1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3]
    print("Original array: ", arr)
    arr = sortArrays(arr)
    print("Sorted array: ", arr)

# Expected output:
Original array:  [1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3]
Sorted array:  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 99]
# How to sort an array in a single loop ? | Function for Sorting the array using a single loop ; Sorting using a single loop ; Type Conversion of char to int . ; Comparing the ascii code . ; Swapping of the characters ; Declaring a String ; declaring character array ; copying the contents of the string to char array ; Printing the original Array . ; Sorting the array using a single loop ; Printing the sorted array .
def sortArrays(arr, length):
    j = 0
    while (j < length - 1):
        d1 = arr[j]
        d2 = arr[j + 1]
        if (d1 > d2):
            temp = arr[j]
            arr[j] = arr[j + 1]
            arr[j + 1] = temp
            j = -1
        j += 1
    return arr


geeks = "GEEKSFORGEEKS"
n = len(geeks)
arr = [0] * n
for i in range(n):
    arr[i] = geeks[i]
print("Original array: [", end="")
for i in range(n):
    print(arr[i], end="")
    if (i + 1 != n):
        print(", ", end="")
        print("]")
ansarr = sortArrays(arr, n)
print("Sorted array: [", end="")
for i in range(n):
    print(ansarr[i], end="")
    if (i + 1 != n):
        print(", ", end="")
        print("]")

# Expected output:
Original array: [G, ]
E, ]
E, ]
K, ]
S, ]
F, ]
O, ]
R, ]
G, ]
E, ]
E, ]
K, ]
SSorted array: [E, ]
E, ]
E, ]
E, ]
F, ]
G, ]
G, ]
K, ]
K, ]
O, ]
R, ]
S, ]
S