giulio98/xlcost-single-prompt huggingface dataset:
# sorting array elements with set bits equal to k | function to sort elements with set bits equal to k ; initialise two vectors ; first vector contains indices of required element ; second vector contains required elements ; sorting the elements in second vector ; replacing the elements with k set bits with the sorted elements ; printing the new sorted array elements ; 
def sortWithSetbits(arr, n, k):
    v1 = []
    v2 = []
    for i in range(0, n, 1):
        if (bin(arr[i]).count('1') == k):
            v1 .append(i)
            v2 .append(arr[i])
    v2 .sort(reverse=False)
    for i in range(0, len(v1), 1):
        arr[v1[i]] = v2[i]
    for i in range(0, n, 1):
        print(arr[i], end=" ")


if __name__ == '__main__':
    arr = [14, 255, 1, 7, 13]
    n = len(arr)
    k = 3
    sortWithSetbits(arr, n, k)

# Expected output:
7 255 1 13 14
# minimum boxes required to carry all gifts | function to return number of boxes ; sort the boxes in ascending order ; try to fit smallest box with current heaviest box ( from right side ) ; 
def numBoxex(A, n, K):
    A .sort()
    i = 0
    j = n - 1
    ans = 0
    while i <= j:
        ans += 1
        if A[i] + A[j] <= K:
            i += 1
        j -= 1
    return ans


if __name__ == '__main__':
    A = [3, 2, 2, 1]
    K = 3
    n = len(A)
    print(numBoxex(A, n, K))

# Expected output:
3
# maximize the profit by selling at | function to find profit ; calculating profit for each gadget ; sort the profit array in descending order ; variable to calculate total profit ; check for best m profits ; 
def solve(N, M, cp, sp):
    profit = []
    for i in range(N):
        profit .append(sp[i] - cp[i])
    profit .sort(reverse=True)
    sum = 0
    for i in range(M):
        if profit[i] > 0:
            sum += profit[i]
        else:
            break
    return sum


if __name__ == "__main__":
    N, M = 5, 3
    CP = [5, 10, 35, 7, 23]
    SP = [11, 10, 0, 9, 19]
    print(solve(N, M, CP, SP))

# Expected output:
8
# find the largest number that can be formed with the given digits | function to generate largest possible number with given digits ; sort the given array in descending order ; generate the number ; 
def findMaxNum(arr, n):
    arr.sort(reverse=True)
    num = arr[0]
    for i in range(1, n):
        num = num * 10 + arr[i]

    return num


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

# Expected output:
543210
# minimum partitions of maximum size 2 and sum limited by given value | python 3 program to count minimum number of partitions of size 2 and sum smaller than or equal to given key . ; sort the array ; if sum of ith smaller and jth larger element is less than key , then pack both numbers in a set otherwise pack the jth larger number alone in the set ; after ending of loop i will contain minimum number of sets ; 
def minimumSets(arr, n, key):
    arr .sort(reverse=False)
    j = n - 1
    for i in range(0, j + 1, 1):
        if (arr[i] + arr[j] <= key):
            j -= 1
    return i + 1


if __name__ == '__main__':
    arr = [3, 5, 3, 4]
    n = len(arr)
    key = 5
    print(minimumSets(arr, n, key))

# Expected output:
4
# substring sort | alternative code to sort substrings ; sort the input array ; repeated length should be the same string ; two different strings with the same length 
def substringSort(arr, n, maxLen):
    count = [0] * (maxLen)
    sortedArr = [""] * (maxLen)
    for i in range(n):
        s = arr[i]
        Len = len(s)
        if (count[Len - 1] == 0):
            sortedArr[Len - 1] = s
            count[Len - 1] = 1
        elif (sortedArr[Len - 1] == s):
            count[Len - 1] += 1
        else:
            print("Cannot be sorted")
            return
    index = 0
    while (count[index] == 0):
        index += 1
    prev = index
    prevString = sortedArr[prev]
    index += 1
    while index < maxLen:
        if (count[index] != 0):
            current = sortedArr[index]
            if (prevString in current):
                prev = index
                prevString = current
            else:
                print("Cannot be sorted")
                return
        index += 1
    for i in range(maxLen):
        s = sortedArr[i]
        for j in range(count[i]):
            print(s)


maxLen = 100
arr1 = ["d", "zddsaaz", "ds", "ddsaa", "dds", "dds"]
substringSort(arr1, len(arr1), maxLen)
arr2 = ["for", "rof"]
substringSort(arr2, len(arr2), maxLen)

# Expected output:
d
ds
dds
dds
ddsaa
zddsaaz
Cannot be sorted
# print all the pairs that contains the positive and negative values of an element | utility binary search ; function ; sort the array ; traverse the array ; for every arr [ i ] < 0 element , do a binary search for arr [ i ] > 0. ; if found , print the pair . ; 
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 printPairs(arr, n):
    pair_exists = False
    arr .sort()
    for i in range(n):
        if (arr[i] < 0):
            if (binary_search(arr, -arr[i])):
                print(arr[i], ", ", -arr[i])
                pair_exists = True
        else:
            break
    if (pair_exists == False):
        print("No such pair exists")


if __name__ == '__main__':
    arr = [4, 8, 9, -4, 1, -1, -8, -9]
    n = len(arr)
    printPairs(arr, n)

# Expected output:
-9 ,  9
-8 ,  8
-4 ,  4
-1 ,  1
# multiset equivalence problem | python3 program to check if two given multisets are equivalent ; sort the elements of both multisets ; return true if both multisets are same . ; 
def areSame(a, b):
    a .sort()
    b .sort()
    return (a == b)


a = [7, 7, 5]
b = [7, 5, 5]
if (areSame(a, b)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# minimum swaps so that binary search can be applied | function to find minimum swaps . ; here we are getting number of smaller and greater elements of k . ; here we are calculating the actual position of k in the array . ; implementing binary search as per the above - discussed cases . ; if we find the k . ; if we need minimum element swap . ; else the element is at the right position . ; if we need maximum element swap . ; else element is at the right position ; calculating the required swaps . ; if it is impossible . ; 
def findMinimumSwaps(arr, n, k):
    num_min = num_max = need_minimum = 0
    need_maximum = swaps = 0
    for i in range(n):
        if (arr[i] < k):
            num_min += 1
        elif (arr[i] > k):
            num_max += 1
    for i in range(n):
        if (arr[i] == k):
            pos = i
            break
    left = 0
    right = n - 1
    while (left <= right):
        mid = (left + right) // 2
        if (arr[mid] == k):
            break
        elif (arr[mid] > k):
            if (pos > mid):
                need_minimum += 1
            else:
                num_min -= 1
            left = mid + 1
        else:
            if (pos < mid):
                need_maximum += 1
            else:
                num_max -= 1
            right = mid - 1
    if (need_minimum > need_maximum):
        swaps = swaps + need_maximum
        num_min = num_min - need_maximum
        need_minimum = (need_minimum - need_maximum)
        need_maximum = 0
    else:
        swaps = swaps + need_minimum
        num_max = num_max - need_minimum
        need_maximum = (need_maximum - need_minimum)
        need_minimum = 0
    if (need_maximum > num_max or need_minimum > num_min):
        return -1
    else:
        return (swaps + need_maximum + need_minimum)


if __name__ == "__main__":
    arr = [3, 10, 6, 7, 2, 5, 4]
    k = 4
    n = len(arr)
    print(findMinimumSwaps(arr, n, k))

# Expected output:
2
# check if both halves of the string have at least one different character | function which break string into two halves sorts the two halves separately compares the two halves return true if any index has non - zero value ; declaration and initialization of counter array ; 
def function(st):
    st = list(st)
    l = len(st)
    st[:l // 2] = sorted(st[:l // 2])
    st[l // 2:] = sorted(st[l // 2:])
    for i in range(l // 2):
        if (st[i] != st[l // 2 + i]):
            return True
    return False


st = "abcasdsabcae"
if function(st):
    print("Yes, both halves differ ", "by at least one character")
else:
    print("No, both halves do not differ at all")

# Expected output:
Yes, both halves differ  by at least one character
# number of visible boxes after putting one inside another | python3 program to count number of visible boxes . ; return the minimum number of visible boxes ; new queue of integers . ; sorting the array ; traversing the array ; checking if current element is greater than or equal to twice of front element ; pushing each element of array ; 

import collections


def minimumBox(arr, n):
    q = collections .deque([])
    arr .sort()
    q .append(arr[0])
    for i in range(1, n):
        now = q[0]
        if (arr[i] >= 2 * now):
            q .popleft()
        q .append(arr[i])
    return len(q)


if __name__ == '__main__':
    arr = [4, 1, 2, 8]
    n = len(arr)
    print(minimumBox(arr, n))

# Expected output:
1
# sort a binary array using one traversal | a python program to sort a binary array ; if number is smaller than 1 then swap it with j - th number ; 
def sortBinaryArray(a, n):
    j = -1
    for i in range(n):
        if a[i] < 1:
            j = j + 1
            a[i], a[j] = a[j], a[i]


a = [1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0]
n = len(a)
sortBinaryArray(a, n)
for i in range(n):
    print(a[i], end=" ")

# Expected output:
0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1
# smallest element in an array that is repeated exactly ' k ' times . | finds the smallest number in arr [ ] that is repeated k times ; sort the array ; find the first element with exactly k occurrences . ; 
def findDuplicate(arr, n, k):
    arr .sort()
    i = 0
    while (i < n):
        j, count = i + 1, 1
        while (j < n and arr[j] == arr[i]):
            count += 1
            j += 1
        if (count == k):
            return arr[i]
        i = j
    return -1


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

# Expected output:
1
# longest common prefix using sorting | python 3 program to find longest common prefix of given array of words . ; if size is 0 , return empty string ; sort the array of strings ; find the minimum length from first and last string ; find the common prefix between the first and last string ; 
def longestCommonPrefix(a):
    size = len(a)
    if (size == 0):
        return ""
    if (size == 1):
        return a[0]
    a .sort()
    end = min(len(a[0]), len(a[size - 1]))
    i = 0
    while (i < end and a[0][i] == a[size - 1][i]):
        i += 1
    pre = a[0][0:i]
    return pre


if __name__ == "__main__":
    input = ["geeksforgeeks", "geeks", "geek", "geezer"]
    print("The longest Common Prefix is :", longestCommonPrefix(input))

# Expected output:
The longest Common Prefix is : gee
# find the minimum and maximum amount to buy all n candies | python implementation to find the minimum and maximum amount ; function to find the maximum and the minimum cost required ; sort the array ; print the minimum cost ; print the maximum cost ; 

from math import ceil


def find(arr, n, k):
    arr .sort()
    b = int(ceil(n / k))
    print("minimum ", sum(arr[:b]))
    print("maximum ", sum(arr[-b:]))


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

# Expected output:
minimum  3
maximum  7
# check if it is possible to sort an array with conditional swapping of adjacent allowed | returns true if it is possible to sort else false / ; we need to do something only if previousl element is greater ; if difference is more than one , then not possible ; 
def checkForSorting(arr, n):
    for i in range(0, n - 1):
        if (arr[i] > arr[i + 1]):
            if (arr[i] - arr[i + 1] == 1):
                arr[i], arr[i + 1] = arr[i + 1], arr[i]
            else:
                return False
    return True


arr = [1, 0, 3, 2]
n = len(arr)
if (checkForSorting(arr, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# k | return the k - th smallest element . ; sort ( arr , arr + n ) ; checking if k lies before 1 st element ; if k is the first element of array arr [ ] . ; if k is more than last element ; if first element of array is 1. ; reducing k by numbers before arr [ 0 ] . ; finding k 'th smallest element  after removing array elements. ; finding count of element between i - th and ( i - 1 ) - th element . ; 
def ksmallest(arr, n, k):
    arr .sort()
    if (k < arr[0]):
        return k
    if (k == arr[0]):
        return arr[0] + 1
    if (k > arr[n - 1]):
        return k + n
    if (arr[0] == 1):
        k -= 1
    else:
        k -= (arr[0] - 1)
    for i in range(1, n):
        c = arr[i] - arr[i - 1] - 1
        if (k <= c):
            return arr[i - 1] + k
        else:
            k -= c
    return arr[n - 1] + k


k = 1
arr = [1]
n = len(arr)
print(ksmallest(arr, n, k))

# Expected output:
2
# count nodes within k | python3 program to count nodes inside k distance range from marked nodes ; utility bfs method to fill distance vector and returns most distant marked node from node u ; push node u in queue and initialize its distance as 0 ; loop untill all nodes are processed ; if node is marked , update lastmarked variable ; loop over all neighbors of u and update their distance before pushing in queue ; if not given value already ; return last updated marked value ; method returns count of nodes which are in k - distance range from marked nodes ; vertices in a tree are one more than number of edges ; fill vector for graph ; fill boolean array mark from marked array ; vectors to store distances ; first bfs ( from any random node ) to get one distant marked node ; second bfs to get other distant marked node and also dl is filled with distances from first chosen marked node ; third bfs to fill dr by distances from second chosen marked node ; loop over all nodes ; increase res by 1 , if current node has distance less than k from both extreme nodes ; 

import queue


def bfsWithDistance(g, mark, u, dis):
    lastMarked = 0
    q = queue .Queue()
    q .put(u)
    dis[u] = 0
    while (not q .empty()):
        u = q .get()
        if (mark[u]):
            lastMarked = u
        for i in range(len(g[u])):
            v = g[u][i]
            if (dis[v] == -1):
                dis[v] = dis[u] + 1
                q .put(v)
    return lastMarked


def nodesKDistanceFromMarked(edges, V, marked, N, K):
    V = V + 1
    g = [[]for i in range(V)]
    u, v = 0, 0
    for i in range(V - 1):
        u = edges[i][0]
        v = edges[i][1]
        g[u].append(v)
        g[v].append(u)
    mark = [False] * V
    for i in range(N):
        mark[marked[i]] = True
    tmp = [-1] * V
    dl = [-1] * V
    dr = [-1] * V
    u = bfsWithDistance(g, mark, 0, tmp)
    u = bfsWithDistance(g, mark, u, dl)
    bfsWithDistance(g, mark, u, dr)
    res = 0
    for i in range(V):
        if (dl[i] <= K and dr[i] <= K):
            res += 1
    return res


if __name__ == '__main__':
    edges = [
        [
            1, 0], [
            0, 3], [
                0, 8], [
                    2, 3], [
                        3, 5], [
                            3, 6], [
                                3, 7], [
                                    4, 5], [
                                        5, 9]]
    V = len(edges)
    marked = [1, 2, 4]
    N = len(marked)
    K = 3
    print(nodesKDistanceFromMarked(edges, V, marked, N, K))

# Expected output:
6
# check whether a given number is even or odd | returns true if n is even , else odd ; n & 1 is 1 , then odd , else even ; 
def isEven(n):
    return (not (n & 1))


n = 101
print("Even"if isEven(n)else "Odd")

# Expected output:
Odd
# count distinct occurrences as a subsequence | python3 program to count number of times s appears as a subsequence in t ; t can 't appear as a subsequence in s ; mat [ i ] [ j ] stores the count of occurrences of t ( 1. . i ) in s ( 1. . j ) . ; initializing first column with all 0 s . x an empty string can 't have another  string as suhsequence ; initializing first row with all 1 s . an empty string is subsequence of all . ; fill mat [ ] [ ] in bottom up manner ; if last characters don 't match,  then value is same as the value  without last character in s. ; else value is obtained considering two cases . a ) all substrings without last character in s b ) all substrings without last characters in both . ; 
def findSubsequenceCount(S, T):
    m = len(T)
    n = len(S)
    if m > n:
        return 0
    mat = [[0 for _ in range(n + 1)]for __ in range(m + 1)]
    for i in range(1, m + 1):
        mat[i][0] = 0
    for j in range(n + 1):
        mat[0][j] = 1
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if T[i - 1] != S[j - 1]:
                mat[i][j] = mat[i][j - 1]
            else:
                mat[i][j] = (mat[i][j - 1] + mat[i - 1][j - 1])
    return mat[m][n]


if __name__ == "__main__":
    T = "ge"
    S = "geeksforgeeks"
    print(findSubsequenceCount(S, T))

# Expected output:
6
# check if a regular bracket sequence can be formed with concatenation of given strings | function to check possible rbs from the given strings ; stores the values { sum , min_prefix } ; iterate over the range ; stores the total sum ; stores the minimum prefix ; check for minimum prefix ; store these values in vector ; store values according to the mentioned approach ; sort the positive vector ; stores the extra count of open brackets ; no valid bracket sequence can be formed ; sort the negative vector ; stores the count of the negative elements ; no valid bracket sequence can be formed ; check if open is equal to negative ; 
def checkRBS(S):
    N = len(S)
    v = [0] * (N)
    for i in range(N):
        s = S[i]
        sum = 0
        pre = 0
        for c in s:
            if (c == '('):
                sum += 1
            else:
                sum -= 1
            pre = min(sum, pre)
        v[i] = [sum, pre]
    pos = []
    neg = []
    for i in range(N):
        if (v[i][0] >= 0):
            pos .append([-v[i][1], v[i][0]])
        else:
            neg .append([v[i][0] - v[i][1], -v[i][0]])
    pos .sort()
    open = 0
    for p in pos:
        if (open - p[0] >= 0):
            open += p[1]
        else:
            print("No")
            return 0
    neg .sort()
    negative = 0
    for p in neg:
        if (negative - p[0] >= 0):
            negative += p[1]
        else:
            print("No")
            return 0
    if (open != negative):
        print("No")
        return 0
    print("Yes")


if __name__ == "__main__":
    arr = [")", "()("]
    checkRBS(arr)

# Expected output:
Yes
# maximize count of unique squares that can be formed with n arbitrary points in coordinate plane | python program for the above approach ; function to find the maximum number of unique squares that can be formed from the given n points ; stores the resultant count of squares formed ; base case ; subtract the maximum possible grid size as sqrt ( n ) ; find the total squares till now for the maximum grid ; a i * i grid contains ( i - 1 ) * ( i - 1 ) + ( i - 2 ) * ( i - 2 ) + ... + 1 * 1 squares ; when n >= len then more squares will be counted ; return total count of squares ; 

import math


def maximumUniqueSquares(N):
    ans = 0
    if N < 4:
        return 0
    len = int(math .sqrt(N))
    N -= len * len
    for i in range(1, len):
        ans += i * i
    if (N >= len):
        N -= len
        for i in range(1, len):
            ans += i
    for i in range(1, N):
        ans += i
    return ans


if __name__ == "__main__":
    N = 9
    print(maximumUniqueSquares(N))

# Expected output:
5
# lexicographically smallest permutation number up to k having given array as a subsequence | function to find the lexicographically smallest permutation such that the given array is a subsequence of it ; stores the missing elements in arr in the range [ 1 , k ] ; stores if the ith element is present in arr or not ; loop to mark all integers present in the array as visited ; loop to insert all the integers not visited into missing ; append int_max at end in order to prevent going out of bounds ; pointer to the current element ; pointer to the missing element ; stores the required permutation ; loop to construct the permutation using greedy approach ; if missing element is smaller that the current element insert missing element ; insert current element ; print the required permutation ; 
def findPermutation(K, arr):
    missing = []
    visited = [0] * (K + 1)
    for i in range(4):
        visited[arr[i]] = 1
    for i in range(1, K + 1):
        if (not visited[i]):
            missing .append(i)
    INT_MAX = 2147483647
    arr .append(INT_MAX)
    missing .append(INT_MAX)
    p1 = 0
    p2 = 0
    ans = []
    while (len(ans) < K):
        if (arr[p1] < missing[p2]):
            ans .append(arr[p1])
            p1 = p1 + 1
        else:
            ans .append(missing[p2])
            p2 = p2 + 1
    for i in range(0, K):
        print(ans[i], end=" ")


if __name__ == "__main__":
    K = 7
    arr = [6, 4, 2, 1]
    findPermutation(K, arr)

# Expected output:
3 5 6 4 2 1 7
# last element remaining after repeated removal of array elements at perfect square indices | python 3 program for the above approach ; function to find last remaining index after repeated removal of perfect square indices ; initialize the ans variable as n ; iterate a while loop and discard the possible values ; total discarded values ; check if this forms a perfect square ; decrease answer by 1 ; subtract the value from the current value of n ; return the value remained ; function to find last remaining element after repeated removal of array element at perfect square indices ; find the remaining index ; print the element at that index as the result ; 

from math import sqrt


def findRemainingIndex(N):
    ans = N
    while (N > 1):
        discard = int(sqrt(N))
        if (discard * discard == N):
            ans -= 1
        N -= discard
    return ans


def findRemainingElement(arr, N):
    remainingIndex = findRemainingIndex(N)
    print(arr[remainingIndex - 1])


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

# Expected output:
-3