giulio98/xlcost-single-prompt huggingface dataset:
# minimum elements to be removed from the ends to make the array sorted | function to return the minimum number of elements to be removed from the ends of the array to make it sorted ; to store the final answer ; two pointer loop ; while the array is increasing increment j ; updating the ans ; updating the left pointer ; returning the final answer ; 
def findMin(arr, n):
    ans = 1
    for i in range(n):
        j = i + 1
        while (j < n and arr[j] >= arr[j - 1]):
            j += 1
        ans = max(ans, j - i)
        i = j - 1
    return n - ans


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

# Expected output:
2
# number of subsequences of maximum length k containing no repeated elements | returns number of subsequences of maximum length k and contains no repeated element ; sort the array a [ ] ; store the frequencies of all the distinct element in the vector arr ; count is the the number of such subsequences ; create a 2 - d array dp [ n + 1 ] [ m + 1 ] to store the intermediate result ; initialize the first row to 1 ; update the dp [ ] [ ] array based on the recurrence relation ; return the number of subsequences ; 
def countSubSeq(a, n, k):
    a .sort(reverse=False)
    arr = []
    i = 0
    while (i < n):
        count = 1
        x = a[i]
        i += 1
        while (i < n and a[i] == x):
            count += 1
            i += 1
        arr .append(count)
    m = len(arr)
    n = min(m, k)
    count = 1
    dp = [[0 for i in range(m + 1)]for j in range(n + 1)]
    for i in range(m + 1):
        dp[0][i] = 1
    for i in range(1, n + 1, 1):
        j = m
        while (j >= 0):
            if (j > m - i):
                dp[i][j] = 0
            else:
                dp[i][j] = dp[i][j + 1] + arr[j] * dp[i - 1][j + 1]
            j -= 1
        count = count + dp[i][0]
    return count


if __name__ == '__main__':
    a = [2, 2, 3, 3, 5]
    n = len(a)
    k = 3
    print(countSubSeq(a, n, k))

# Expected output:
18
# find the count of unvisited indices in an infinite array | function to return the count of unvisited indices starting from the index 0 ; largest index that cannot be visited ; push the index to the queue ; to store the required count ; current index that cannot be visited ; increment the count for the current index ; ( curr - m ) and ( curr - n ) are also unreachable if they are valid indices ; return the required count ; 
def countUnvisited(n, m):
    i = 0
    X = (m * n) - m - n
    queue = []
    queue .append(X)
    count = 0
    while (len(queue) > 0):
        curr = queue[0]
        queue .remove(queue[0])
        count += 1
        if (curr - m > 0):
            queue .append(curr - m)
        if (curr - n > 0):
            queue .append(curr - n)
    return count


if __name__ == '__main__':
    n = 2
    m = 5
    print(countUnvisited(n, m))

# Expected output:
2
# check whether the string s1 can be made equal to s2 with the given operation | function to return the string formed by the odd indexed characters of s ; function to return the string formed by the even indexed characters of s ; function that returns true if s1 can be made equal to s2 with the given operation ; get the string formed by the even indexed characters of s1 ; get the string formed by the even indexed characters of s2 ; get the string formed by the odd indexed characters of s1 ; get the string formed by the odd indexed characters of s2 ; sorting all the lists ; if the strings can be made equal ; 
def partOdd(s):
    odd = []
    for i in range(len(s)):
        if i % 2 != 0:
            odd .append(s[i])
    return odd


def partEven(s):
    even = []
    for i in range(len(s)):
        if i % 2 == 0:
            even .append(s[i])
    return even


def canBeMadeEqual(s1, s2):
    even_s1 = partEven(s1)
    even_s2 = partEven(s2)
    odd_s1 = partOdd(s1)
    odd_s2 = partOdd(s2)
    even_s1 .sort()
    even_s2 .sort()
    odd_s1 .sort()
    odd_s2 .sort()
    if even_s1 == even_s2 and odd_s1 == odd_s2:
        return True
    return False


s1 = "cdab"
s2 = "abcd"
if canBeMadeEqual(s1, s2):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# sort the given stack elements based on their modulo with k | function to sort the stack using another stack based on the values of elements modulo k ; pop out the first element ; while temporary stack is not empty ; the top of the stack modulo k is greater than ( temp & k ) or if they are equal then compare the values ; pop from temporary stack and push it to the input stack ; push temp in temporary of stack ; push all the elements in the original stack to get the ascending order ; print the sorted elements ; 
def sortStack(input1, k):
    tmpStack = []
    while (len(input1) != 0):
        tmp = input1[-1]
        input1 .pop()
        while (len(tmpStack) != 0):
            tmpStackMod = tmpStack[-1] % k
            tmpMod = tmp % k
            if ((tmpStackMod > tmpMod) or (
                    tmpStackMod == tmpMod and tmpStack[-1] > tmp)):
                input1 .append(tmpStack[-1])
                tmpStack .pop()
            else:
                break
        tmpStack .append(tmp)
    while (len(tmpStack) != 0):
        input1 .append(tmpStack[-1])
        tmpStack .pop()
    while (len(input1) != 0):
        print(input1[-1], end=" ")
        input1 .pop()


if __name__ == "__main__":
    input1 = []
    input1 .append(10)
    input1 .append(3)
    input1 .append(2)
    input1 .append(6)
    input1 .append(12)
    k = 4
    sortStack(input1, k)

# Expected output:
12 2 6 10 3
# longest sub | function to return the length of the largest subsequence with non - negative sum ; to store the current sum ; sort the input array in non - increasing order ; traverse through the array ; add the current element to the sum ; condition when c_sum falls below zero ; complete array has a non - negative sum ; 
def maxLen(arr, n):
    c_sum = 0
    arr .sort(reverse=True)
    for i in range(n):
        c_sum += arr[i]
        if (c_sum < 0):
            return i
    return n


if __name__ == "__main__":
    arr = [3, 5, -6]
    n = len(arr)
    print(maxLen(arr, n))

# Expected output:
3
# find partition line such that sum of values on left and right is equal | python3 implementation of the approach ; function that returns true if the required line exists ; to handle negative values from x [ ] ; update arr [ ] such that arr [ i ] contains the sum of all v [ j ] such that x [ j ] = i for all valid values of j ; update arr [ i ] such that arr [ i ] contains the sum of the subarray arr [ 0. . . i ] from the original array ; if all the points add to 0 then the line can be drawn anywhere ; if the line is drawn touching the leftmost possible points ; if the line is drawn just before the current point ; if the line is drawn touching the current point ; if the line is drawn just after the current point ; if the line is drawn touching the rightmost possible points ; 

MAX = 1000


def lineExists(x, y, v, n):
    size = (2 * MAX) + 1
    arr = [0] * size
    for i in range(n):
        arr[x[i] + MAX] += v[i]
    for i in range(1, size):
        arr[i] += arr[i - 1]
    if (arr[size - 1] == 0):
        return True
    if (arr[size - 1] - arr[0] == 0):
        return True
    for i in range(1, size - 1):
        if (arr[i - 1] == arr[size - 1] - arr[i - 1]):
            return True
        if (arr[i - 1] == arr[size - 1] - arr[i]):
            return True
        if (arr[i] == arr[size - 1] - arr[i]):
            return True
    if (arr[size - 2] == 0):
        return True
    return False


if __name__ == "__main__":
    x = [-3, 5, 8]
    y = [8, 7, 9]
    v = [8, 2, 10]
    n = len(x)
    if (lineExists(x, y, v, n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# maximum sum of minimums of pairs in an array | function to return the maximum required sum of the pairs ; sort the array ; to store the sum ; start making pairs of every two consecutive elements as n is even ; minimum element of the current pair ; return the maximum possible sum ; 
def maxSum(a, n):
    a .sort()
    sum = 0
    for i in range(0, n - 1, 2):
        sum += a[i]
    return sum


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

# Expected output:
7
# sort elements by modulo with k | utility function to prthe contents of an array ; function to sort the array elements based on their modulo with k ; create k empty vectors ; update the vectors such that v [ i ] will contain all the elements that give remainder as i when divided by k ; sorting all the vectors separately ; replacing the elements in arr [ ] with the required modulo sorted elements ; add all the elements of the current vector to the array ; print the sorted array ; 
def printArr(arr, n):
    for i in range(n):
        print(arr[i], end=' ')


def sortWithRemainder(arr, n, k):
    v = [[]for i in range(k)]
    for i in range(n):
        v[arr[i] % k].append(arr[i])
    for i in range(k):
        v[i].sort()
    j = 0
    for i in range(k):
        for it in v[i]:
            arr[j] = it
            j += 1
    printArr(arr, n)


if __name__ == '__main__':
    arr = [10, 7, 2, 6, 12, 3, 33, 46]
    n = len(arr)
    k = 4
    sortWithRemainder(arr, n, k)

# Expected output:
12 33 2 6 10 46 3 7
# minimum increment operations to make k elements equal | function to return the minimum number of increment operations required to make any k elements of the array equal ; sort the array in increasing order ; calculate the number of operations needed to make 1 st k elements equal to the kth element i . e . the 1 st window ; answer will be the minimum of all possible k sized windows ; find the operations needed to make k elements equal to ith element ; slide the window to the right and subtract increments spent on leftmost element of the previous window ; add increments needed to make the 1 st k - 1 elements of this window equal to the kth element of the current window ; 
def minOperations(ar, k):
    ar = sorted(ar)
    opsNeeded = 0
    for i in range(k):
        opsNeeded += ar[k - 1] - ar[i]
    ans = opsNeeded
    for i in range(k, len(ar)):
        opsNeeded = opsNeeded - (ar[i - 1] - ar[i - k])
        opsNeeded += (k - 1) * (ar[i] - ar[i - 1])
        ans = min(ans, opsNeeded)
    return ans


arr = [3, 1, 9, 100]
n = len(arr)
k = 3
print(minOperations(arr, k))

# Expected output:
14
# lexicographical ordering using heap sort | used for index in heap ; predefining the heap array ; defining formation of the heap ; iterative heapify ; just swapping if the element is smaller than already stored element ; swapping the current index with its child ; moving upward in the heap ; defining heap sort ; taking output of the minimum element ; set first element as a last one ; decrement of the size of the string ; initializing the left and right index ; process of heap sort if root element is minimum than its both of the child then break ; otherwise checking that the child which one is smaller , swap them with parent element ; swapping ; changing the left index and right index ; utility function ; to heapify ; calling heap sort function ; 

x = -1
heap = [0] * 1000


def heapForm(k):
    global x
    x += 1
    heap[x] = k
    child = x
    index = x // 2
    while (index >= 0):
        if (heap[index] > heap[child]):
            tmp = heap[index]
            heap[index] = heap[child]
            heap[child] = tmp
            child = index
            index = index // 2
        else:
            break


def heapSort():
    global x
    while (x >= 0):
        k = heap[0]
        print(k, end=" ")
        heap[0] = heap[x]
        x = x - 1
        tmp = -1
        index = 0
        length = x
        left1 = 1
        right1 = left1 + 1
        while (left1 <= length):
            if (heap[index] <= heap[left1] and heap[index] <= heap[right1]):
                break
            else:
                if (heap[left1] < heap[right1]):
                    tmp = heap[index]
                    heap[index] = heap[left1]
                    heap[left1] = tmp
                    index = left1
                else:
                    tmp = heap[index]
                    heap[index] = heap[right1]
                    heap[right1] = tmp
                    index = right1
            left1 = 2 * left1
            right1 = left1 + 1


def sort(k, n):
    for i in range(n):
        heapForm(k[i])
    heapSort()


if __name__ == '__main__':
    arr = ["banana", "orange", "apple", "pineapple", "berries", "lichi"]
    n = len(arr)
    sort(arr, n)

# Expected output:
apple banana berries lichi orange pineapple
# find kth element in an array containing odd elements first and then even elements | function to return the kth element in the modified array ; first odd number ; insert the odd number ; next odd number ; first even number ; insert the even number ; next even number ; return the kth element ; 
def getNumber(n, k):
    arr = [0] * n
    i = 0
    odd = 1
    while (odd <= n):
        arr[i] = odd
        i += 1
        odd += 2
    even = 2
    while (even <= n):
        arr[i] = even
        i += 1
        even += 2
    return arr[k - 1]


if __name__ == '__main__':
    n = 8
    k = 5
    print(getNumber(n, k))

# Expected output:
2
# swap alternate boundary pairs | utility function to print the contents of an array ; function to update the array ; initialize the pointers ; while there are elements to swap ; update the pointers ; print the updated array ; 
def printArr(arr, n):
    for i in range(n):
        print(arr[i], end=" ")


def UpdateArr(arr, n):
    i = 0
    j = n - 1
    while (i < j):
        temp = arr[i]
        arr[i] = arr[j]
        arr[j] = temp
        i += 2
        j -= 2
    printArr(arr, n)


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

# Expected output:
6 2 4 3 5 1
# smallest element greater than x not present in the array | function to return the smallest element greater than x which is not present in a [ ] ; sort the array ; continue until low is less than or equals to high ; find mid ; if element at mid is less than or equals to searching element ; if mid is equals to searching element ; increment searching element ; make high as n - 1 ; make low as mid + 1 ; make high as mid - 1 ; return the next greater element ; 
def Next_greater(a, n, x):
    a = sorted(a)
    low, high, ans = 0, n - 1, x + 1
    while (low <= high):
        mid = (low + high) // 2
        if (a[mid] <= ans):
            if (a[mid] == ans):
                ans += 1
                high = n - 1
            low = mid + 1
        else:
            high = mid - 1
    return ans


a = [1, 5, 10, 4, 7]
x = 4
n = len(a)
print(Next_greater(a, n, x))

# Expected output:
6
# arrange n elements in circular fashion such that all elements are strictly less than sum of adjacent elements | function to print the arrangement that satisifes the given condition ; sort the array initially ; array that stores the arrangement ; once the array is sorted re - fill the array again in the mentioned way in the approach ; iterate in the array and check if the arrangement made satisfies the given condition or not ; for the first element the adjacents will be a [ 1 ] and a [ n - 1 ] ; for the last element the adjacents will be a [ 0 ] and a [ n - 2 ] ; if we reach this position then the arrangement is possible ; 
def printArrangement(a, n):
    a = sorted(a)
    b = [0 for i in range(n)]
    low = 0
    high = n - 1
    for i in range(n):
        if (i % 2 == 0):
            b[low] = a[i]
            low += 1
        else:
            b[high] = a[i]
            high -= 1
    for i in range(n):
        if (i == 0):
            if (b[n - 1] + b[1] <= b[i]):
                print("-1")
                return
        elif (i == (n - 1)):
            if (b[n - 2] + b[0] <= b[i]):
                print("-1")
                return
        else:
            if (b[i - 1] + b[i + 1] <= b[i]):
                print("-1")
                return
    for i in range(n):
        print(b[i], end=" ")


a = [1, 4, 4, 3, 2]
n = len(a)
printArrangement(a, n)

# Expected output:
1 3 4 4 2
# greatest contiguous sub | function that returns the sub - array ; data - structure to store all the sub - arrays of size k ; iterate to find all the sub - arrays ; store the sub - array elements in the array ; push the vector in the container ; sort the vector of elements ; the last sub - array in the sorted order will be the answer ; 
def findSubarray(a, k, n):
    vec = []
    for i in range(n - k + 1):
        temp = []
        for j in range(i, i + k):
            temp .append(a[j])
        vec .append(temp)
    vec = sorted(vec)
    return vec[len(vec) - 1]


a = [1, 4, 3, 2, 5]
k = 4
n = len(a)
ans = findSubarray(a, k, n)
for it in ans:
    print(it, end=" ")

# Expected output:
4 3 2 5
# unbounded fractional knapsack | python implementation of the approach ; function to return the maximum required value ; maxratio will store the maximum value to weight ratio we can have for any item and maxindex will store the index of that element ; find the maximum ratio ; the item with the maximum value to weight ratio will be put into the knapsack repeatedly until full ; 

import sys


def knapSack(W, wt, val, n):
    maxratio = -sys .maxsize - 1
    maxindex = 0
    for i in range(n):
        if ((val[i] / wt[i]) > maxratio):
            maxratio = (val[i] / wt[i])
            maxindex = i
    return (W * maxratio)


val = [14, 27, 44, 19]
wt = [6, 7, 9, 8]
n = len(val)
W = 50
print(knapSack(W, wt, val, n))

# Expected output:
244.44444444444446
# sort an array without changing position of negative numbers | function to sort the array such that negative values do not get affected ; store all non - negative values ; sort non - negative values ; if current element is non - negative then update it such that all the non - negative values are sorted ; print the sorted array ; 
def sortArray(a, n):
    ans = []
    for i in range(n):
        if (a[i] >= 0):
            ans .append(a[i])
    ans = sorted(ans)
    j = 0
    for i in range(n):
        if (a[i] >= 0):
            a[i] = ans[j]
            j += 1
    for i in range(n):
        print(a[i], end=" ")


arr = [2, -6, -3, 8, 4, 1]
n = len(arr)
sortArray(arr, n)

# Expected output:
1 -6 -3 2 4 8
# find a triplet in an array whose sum is closest to a given number | python3 implementation of the approach ; function to return the sum of a triplet which is closest to x ; sort the array ; to store the closest sum ; fix the smallest number among the three integers ; two pointers initially pointing at the last and the element next to the fixed element ; while there could be more pairs to check ; calculate the sum of the current triplet ; if the sum is more closer than the current closest sum ; if sum is greater then x then decrement the second pointer to get a smaller sum ; else increment the first pointer to get a larger sum ; return the closest sum found ; 

import sys


def solution(arr, x):
    arr .sort()
    closestSum = sys .maxsize
    for i in range(len(arr) - 2):
        ptr1 = i + 1
        ptr2 = len(arr) - 1
        while (ptr1 < ptr2):
            sum = arr[i] + arr[ptr1] + arr[ptr2]
            if (abs(x - sum) < abs(x - closestSum)):
                closestSum = sum
            if (sum > x):
                ptr2 -= 1
            else:
                ptr1 += 1
    return closestSum


if __name__ == "__main__":
    arr = [-1, 2, 1, -4]
    x = 1
    print(solution(arr, x))

# Expected output:
2
# merge two bsts with constant extra space | node of the binary tree ; a utility function to print inorder traversal of a binary tree ; the function to print data of two bsts in sorted order ; base cases ; if the first tree is exhausted simply print the inorder traversal of the second tree ; if second tree is exhausted simply print the inoreder traversal of the first tree ; a temporary pointer currently pointing to root of first tree ; previous pointer to store the parent of temporary pointer ; traverse through the first tree until you reach the leftmost element , which is the first element of the tree in the inorder traversal . this is the least element of the tree ; another temporary pointer currently pointing to root of second tree ; previous pointer to store the parent of second temporary pointer ; traverse through the second tree until you reach the leftmost element , which is the first element of the tree in inorder traversal . this is the least element of the tree . ; compare the least current least elements of both the tree ; if first tree 's element is  smaller print it ; if the node has no parent , that means this node is the root ; simply make the right child of the root as new root ; if node has a parent ; as this node is the leftmost node , it is certain that it will not have a let child so we simply assign this node ' s ▁ right ▁ pointer , ▁ which ▁ can ▁ be ▁ ▁ either ▁ null ▁ or ▁ not , ▁ to ▁ its ▁ parent ' s left pointer . this statement is just doing the task of deleting the node ; recursively call the merge function with updated tree ; if the node has no parent , that means this node is the root ; simply make the right child of root as new root ; if node has a parent ; recursively call the merge function with updated tree ; 

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


def inorder(root):
    if (root is not None):
        inorder(root .left)
        print(root .data, end=" ")
        inorder(root .right)


def merge(root1, root2):
    if (not root1 and not root2):
        return
    if (not root1):
        inorder(root2)
        return
    if (not root2):
        inorder(root1)
        return
    temp1 = root1
    prev1 = None
    while (temp1 .left):
        prev1 = temp1
        temp1 = temp1 .left
    temp2 = root2
    prev2 = None
    while (temp2 .left):
        prev2 = temp2
        temp2 = temp2 .left
    if (temp1 .data <= temp2 .data):
        print(temp1 .data, end=" ")
        if (prev1 is None):
            merge(root1 .right, root2)
        else:
            prev1 .left = temp1 .right
            merge(root1, root2)
    else:
        print(temp2 .data, end=" ")
        if (prev2 is None):
            merge(root1, root2 .right)
        else:
            prev2 .left = temp2 .right
            merge(root1, root2)


if __name__ == '__main__':
    root1 = None
    root2 = None
    root1 = node(3)
    root1 .left = node(1)
    root1 .right = node(5)
    root2 = node(4)
    root2 .left = node(2)
    root2 .right = node(6)
    merge(root1, root2)

# Expected output:
1 2 3 4 5 6
# print elements of an array according to the order defined by another array | set 2 | function to print an array according to the order defined by another array ; declaring map and iterator ; store the frequency of each number of a1 [ ] int the map ; traverse through a2 [ ] ; check whether number is present in map or not ; print that number that many times of its frequency ; print those numbers that are not present in a2 [ ] ; 
def print_in_order(a1, a2, n, m):
    mp = dict .fromkeys(a1, 0)
    for i in range(n):
        mp[a1[i]] += 1
    for i in range(m):
        if a2[i] in mp .keys():
            for j in range(mp[a2[i]]):
                print(a2[i], end=" ")
            del (mp[a2[i]])
    for key, value in mp .items():
        for j in range(value):
            print(key, end=" ")
    print()


if __name__ == "__main__":
    a1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8]
    a2 = [2, 1, 8, 3]
    n = len(a1)
    m = len(a2)
    print_in_order(a1, a2, n, m)

# Expected output:
2 2 1 1 8 8 3 5 7 9 6