giulio98/xlcost-single-prompt huggingface dataset:
# longest subarray with first element greater than or equal to last element | search function for searching the first element of the subarray which is greater or equal to the last element ( num ) ; returns length of the longest array with first element smaller than the last element . ; search space for the potential first elements . ; it will store the indexes of the elements of search space in the original array . ; initially the search space is empty . ; we will add an ith element in the search space if the search space is empty or if the ith element is greater than the last element of the search space . ; we will search for the index first element in the search space and we will use it find the index of it in the original array . ; update the answer if the length of the subarray is greater than the previously calculated lengths . ; 
def binarySearch(searchSpace, s, e, num):
    while (s <= e):
        mid = (s + e) // 2
        if searchSpace[mid] >= num:
            ans = mid
            e = mid - 1
        else:
            s = mid + 1
    return ans


def longestSubArr(arr, n):
    searchSpace = [None] * n
    index = [None] * n
    j = 0
    ans = 0
    for i in range(n):
        if (j == 0 or searchSpace[j - 1] < arr[i]):
            searchSpace[j] = arr[i]
            index[j] = i
            j += 1
        idx = binarySearch(searchSpace, 0, j - 1, arr[i])
        ans = max(ans, i - index[idx] + 1)
    return ans


if __name__ == "__main__":
    arr = [-5, -1, 7, 5, 1, -2]
    n = len(arr)
    print(longestSubArr(arr, n))

# Expected output:
5
# print all pairs with given sum | python3 program for the above approach ; 
def pairedElements(arr, sum):
    low = 0
    high = len(arr) - 1
    while (low < high):
        if (arr[low] + arr[high] == sum):
            print("The pair is : (", arr[low], ", ", arr[high], ")")
        if (arr[low] + arr[high] > sum):
            high -= 1
        else:
            low += 1


if __name__ == '__main__':
    arr = [2, 3, 4, -2, 6, 8, 9, 11]
    arr .sort()
    pairedElements(arr, 6)

# Expected output:
The pair is : ( -2 ,  8 )
The pair is : ( 2 ,  4 )
# check if a string is suffix of another | python 3 program to find if a string is suffix of another ; 
def isSuffix(s1, s2):
    n1 = len(s1)
    n2 = len(s2)
    if (n1 > n2):
        return False
    for i in range(n1):
        if (s1[n1 - i - 1] != s2[n2 - i - 1]):
            return False
    return True


if __name__ == "__main__":
    s1 = "geeks"
    s2 = "geeksforgeeks"
    result = isSuffix(s1, s2)
    if (result):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check if all occurrences of a character appear together | function to find if all occurrences of a character appear together in a string . ; to indicate if one or more occurrences of ' c ' are seen or not . ; traverse given string ; if current character is same as c , we first check if c is already seen . ; if this is very first appearance of c , we traverse all consecutive occurrences . ; to indicate that character is seen once . ; 
def checkIfAllTogether(s, c):
    oneSeen = False
    i = 0
    n = len(s)
    while (i < n):
        if (s[i] == c):
            if (oneSeen):
                return False
            while (i < n and s[i] == c):
                i = i + 1
            oneSeen = True
        else:
            i = i + 1
    return True


s = "110029"
if (checkIfAllTogether(s, '1')):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# front and back search in unsorted array | python program to implement front and back search ; start searching from both ends ; keep searching while two indexes do not cross . ; 
def search(arr, n, x):
    front = 0
    back = n - 1
    while (front <= back):
        if (arr[front] == x or arr[back] == x):
            return True
        front += 1
        back -= 1
    return False


arr = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170]
x = 130
n = len(arr)
if (search(arr, n, x)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# even | python3 code to find max ( x , y ) / min ( x , y ) after p turns ; 1 st test case ; 2 nd 
def findValue(X, Y, P):
    if P % 2 == 0:
        return int(max(X, Y) / min(X, Y))
    else:
        return int(max(2 * X, Y) / min(2 * X, Y))


X = 1
Y = 2
P = 1
print(findValue(X, Y, P))
X = 3
Y = 7
P = 2
print((findValue(X, Y, P)))

# Expected output:
1
2
# the painter 's partition problem | function to calculate sum between two indices in list ; bottom up tabular dp ; initialize table ; base cases k = 1 ; n = 1 ; 2 to k partitions for i in range ( 2 , k + 1 ) : 2 to n boards ; track minimum ; i - 1 th separator before position arr [ p = 1. . j ] ; required ; 
def sum(arr, start, to):
    total = 0
    for i in range(start, to + 1):
        total += arr[i]
    return total


def findMax(arr, n, k):
    dp = [[0 for i in range(n + 1)]for j in range(k + 1)]
    for i in range(1, n + 1):
        dp[1][i] = sum(arr, 0, i - 1)
    for i in range(1, k + 1):
        dp[i][1] = arr[0]
        for j in range(2, n + 1):
            best = 100000000
            for p in range(1, j + 1):
                best = min(best, max(dp[i - 1][p], sum(arr, p, j - 1)))
            dp[i][j] = best
    return dp[k][n]


arr = [10, 20, 60, 50, 30, 40]
n = len(arr)
k = 3
print(findMax(arr, n, k))
n = len(arr)
k = 3
print(findMax(arr, n, k))

# Expected output:
0
0
# counting cross lines in an array | function return count of cross line in an array ; move elements of arr [ 0. . i - 1 ] , that are greater than key , to one position ahead of their current position ; increment cross line by one ; 
def countCrossLine(arr, n):
    count_crossline = 0
    i, key, j = 0, 0, 0
    for i in range(1, n):
        key = arr[i]
        j = i - 1
        while (j >= 0 and arr[j] > key):
            arr[j + 1] = arr[j]
            j = j - 1
            count_crossline += 1
        arr[j + 1] = key
    return count_crossline


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

# Expected output:
5
# recursive programs to find minimum and maximum elements of array | function to return maximum element using recursion ; if n = 0 means whole array has been traversed ; 
def findMaxRec(A, n):
    if (n == 1):
        return A[0]
    return max(A[n - 1], findMaxRec(A, n - 1))


if __name__ == "__main__":
    A = [1, 4, 45, 6, -50, 10, 2]
    n = len(A)
    print(findMaxRec(A, n))

# Expected output:
45
# program to remove vowels from a string | python program to remove vowels from a string function to remove vowels ; 

import re


def rem_vowel(string):
    return (re .sub("[aeiouAEIOU]", "", string))


string = "GeeksforGeeks - A Computer Science Portal for Geeks"
print(rem_vowel(string))

# Expected output:
GksfrGks -  Cmptr Scnc Prtl fr Gks
# minimum number of swaps required to minimize sum of absolute differences between adjacent array elements | function to find the minimum number of swaps required to sort the array in increasing order ; stores the array elements with its index ; sort the array in the increasing order ; keeps the track of visited elements ; stores the count of swaps required ; traverse array elements ; if the element is already swapped or at correct position ; find out the number of nodes in this cycle ; update the value of j ; move to the next element ; increment cycle_size ; update the ans by adding current cycle ; function to find the minimum number of swaps required to sort the array in decreasing order ; stores the array elements with its index ; sort the array in the descending order ; keeps track of visited elements ; stores the count of resultant swap required ; traverse array elements ; if the element is already swapped or at correct position ; find out the number of node in this cycle ; update the value of j ; move to the next element ; increment the cycle_size ; update the ans by adding current cycle size ; function to find minimum number of swaps required to minimize the sum of absolute difference of adjacent elements ; sort in ascending order ; sort in descending order ; return the minimum value ; 
def minSwapsAsc(arr, n):
    arrPos = [[arr[i], i]for i in range(n)]
    arrPos = sorted(arrPos)
    vis = [False] * (n)
    ans = 0
    for i in range(n):
        if (vis[i] or arrPos[i][1] == i):
            continue
        cycle_size = 0
        j = i
        while (not vis[j]):
            vis[j] = 1
            j = arrPos[j][1]
            cycle_size += 1
        if (cycle_size > 0):
            ans += (cycle_size - 1)
    return ans


def minSwapsDes(arr, n):
    arrPos = [[0, 0]for i in range(n)]
    for i in range(n):
        arrPos[i][0] = arr[i]
        arrPos[i][1] = i
    arrPos = sorted(arrPos)[::-1]
    vis = [False] * n
    ans = 0
    for i in range(n):
        if (vis[i] or arrPos[i][1] == i):
            continue
        cycle_size = 0
        j = i
        while (not vis[j]):
            vis[j] = 1
            j = arrPos[j][1]
            cycle_size += 1
        if (cycle_size > 0):
            ans += (cycle_size - 1)
    return ans


def minimumSwaps(arr):
    S1 = minSwapsAsc(arr, len(arr))
    S2 = minSwapsDes(arr, len(arr))
    return min(S1, S2)


if __name__ == '__main__':
    arr = [3, 4, 2, 5, 1]
    print(minimumSwaps(arr))

# Expected output:
2
# sort an array of 0 s , 1 s , 2 s and 3 s | function to sort the array having array element only 0 , 1 , 2 , and 3 ; iterate until mid <= j ; if arr [ mid ] is 0 ; swap integers at indices i and mid ; increment i ; increment mid ; otherwise if the value of arr [ mid ] is 3 ; swap arr [ mid ] and arr [ j ] ; decrement j ; otherwise if the value of arr [ mid ] is either 1 or 2 ; increment the value of mid ; iterate until i <= j ; if arr [ i ] the value of is 2 ; swap arr [ i ] and arr [ j ] ; decrement j ; otherwise , increment i ; print the sorted array arr [ ] ; 
def sortArray(arr, N):
    i = 0
    j = N - 1
    mid = 0
    while (mid <= j):
        if (arr[mid] == 0):
            arr[i], arr[mid] = arr[mid], arr[i]
            i += 1
            mid += 1
        elif (arr[mid] == 3):
            arr[mid], arr[j] = arr[j], arr[mid]
            j -= 1
        elif (arr[mid] == 1 or arr[mid] == 2):
            mid += 1
    while (i <= j):
        if (arr[i] == 2):
            arr[i], arr[j] = arr[j], arr[i]
            j -= 1
        else:
            i += 1
    for i in range(N):
        print(arr[i], end=" ")


if __name__ == '__main__':
    arr = [3, 2, 1, 0, 2, 3, 1, 0]
    N = len(arr)
    sortArray(arr, N)

# Expected output:
0 0 1 1 2 2 3 3
# check whether an array can be made strictly increasing by removing at most one element | function to find if is it possible to make the array strictly increasing by removing at most one element ; stores the count of numbers that are needed to be removed ; store the index of the element that needs to be removed ; traverse the range [ 1 , n - 1 ] ; if arr [ i - 1 ] is greater than or equal to arr [ i ] ; increment the count by 1 ; update index ; if count is greater than one ; if no element is removed ; if only the last or the first element is removed ; if a [ index ] is removed ; if a [ index - 1 ] is removed ; 
def check(arr, n):
    count = 0
    index = -1
    for i in range(1, n):
        if (arr[i - 1] >= arr[i]):
            count += 1
            index = i
    if (count > 1):
        return False
    if (count == 0):
        return True
    if (index == n - 1 or index == 1):
        return True
    if (arr[index - 1] < arr[index + 1]):
        return True
    if (arr[index - 2] < arr[index]):
        return True
    return False


if __name__ == '__main__':
    arr = [1, 2, 5, 3, 5]
    N = len(arr)
    if (check(arr, N)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# modify string by rearranging vowels in alphabetical order at their respective indices | function to arrange the vowels in sorted order in the string at their respective places ; store the size of the string ; stores vowels of string s ; traverse the string , s and push all the vowels to string vow ; if vow is empty , then print s and return ; sort vow in alphabetical order ; traverse the string , s ; replace s [ i ] with vow [ j ] iif s [ i ] is a vowel , and increment j by 1 ; print the string ; 
def sortVowels(S):
    n = len(S)
    vow = ""
    for i in range(n):
        if (S[i] == 'a' or S[i] == 'e' or S[i] ==
                'i' or S[i] == 'o' or S[i] == 'u'):
            vow += S[i]
    if len(vow) == 0:
        print(S, end="")
        return
    vow = list(vow)
    vow .sort()
    j = 0
    for i in range(n):
        if (S[i] == 'a' or S[i] == 'e' or S[i] ==
                'i' or S[i] == 'o' or S[i] == 'u'):
            S[i] = vow[j]
            j += 1
    print("".join(S), end="")


if __name__ == "__main__":
    S = "geeksforgeeks"
    sortVowels(list(S))

# Expected output:
geeksfergeoks
# maximum number of buckets that can be filled | function to find the maximum number of buckets that can be filled with the amount of water available ; find the total available water ; sort the array in ascending order ; check if bucket can be filled with available water ; print count of buckets ; 
def getBuckets(arr, N):
    availableWater = N * (N - 1) // 2
    arr .sort()
    i, Sum = 0, 0
    while (Sum <= availableWater):
        Sum += arr[i]
        i += 1
    print(i - 1, end="")


arr = [1, 5, 3, 4, 7, 9]
N = len(arr)
getBuckets(arr, N)

# Expected output:
4
# minimize the number of strictly increasing subsequences in an array | set 2 | function to find the number of strictly increasing subsequences in an array ; sort the array ; stores final count of subsequences ; traverse the array ; stores current element ; stores frequency of the current element ; count frequency of the current element ; if current element frequency is greater than count ; print the final count ;  ; 
def minimumIncreasingSubsequences(arr, N):
    arr .sort()
    count = 0
    i = 0
    while (i < N):
        x = arr[i]
        freqX = 0
        while (i < N and arr[i] == x):
            freqX += 1
            i += 1
        count = max(count, freqX)
    print(count)


arr = [2, 1, 2, 1, 4, 3]
N = len(arr)
minimumIncreasingSubsequences(arr, N)

# Expected output:
2
# maximize difference between the sum of absolute differences of each element with the remaining array | function to maximize difference of the sum of absolute difference of an element with the rest of the elements in the array ; sort the array in ascending order ; stores prefix sum at any instant ; store the total array sum ; initialize minimum and maximum absolute difference ; traverse the array to find the total array sum ; traverse the array arr [ ] ; store the number of elements to its left ; store the number of elements to its right ; update the sum of elements on its left ; store the absolute difference sum ; update the minimum ; update the maximum ; update sum of elements on its left ; prthe result ; 
def findMaxDifference(arr, n):
    arr = sorted(arr)
    Leftsum = 0
    Totalsum = 0
    Min, Max = 10 ** 8, -10 ** 8
    for i in range(n):
        Totalsum += arr[i]
    for i in range(n):
        leftNumbers = i
        rightNumbers = n - i - 1
        Totalsum = Totalsum - arr[i]
        sum = (leftNumbers * arr[i]) - Leftsum + \
            Totalsum - (rightNumbers * arr[i])
        Min = min(Min, sum)
        Max = max(Max, sum)
        Leftsum += arr[i]
    print(Max - Min)


if __name__ == '__main__':
    arr = [1, 2, 4, 7]
    N = len(arr)
    findMaxDifference(arr, N)

# Expected output:
6
# minimum pairs required to be removed such that the array does not contain any pair with sum k | function to find the maximum count of pairs required to be removed such that no pairs exist whose sum equal to k ; stores maximum count of pairs required to be removed such that no pairs exist whose sum equal to k ; base case ; sort the array ; stores index of left pointer ; stores index of right pointer ; stores sum of left and right pointer ; if s equal to k ; update cntpairs ; update left ; update right ; if s > k ; update right ; update left ; return the cntpairs ; 
def maxcntPairsSumKRemoved(arr, k):
    cntPairs = 0
    if not arr or len(arr) == 1:
        return cntPairs
    arr .sort()
    left = 0
    right = len(arr) - 1
    while left < right:
        s = arr[left] + arr[right]
        if s == k:
            cntPairs += 1
            left += 1
            right -= 1
        elif s > k:
            right -= 1
        else:
            left += 1
    return cntPairs


if __name__ == "__main__":
    arr = [1, 2, 3, 4]
    K = 5
    print(maxcntPairsSumKRemoved(arr, K))

# Expected output:
2
# minimize cost to split an array into k subsets such that the cost of each element is its product with its position in the subset | function to find the minimum cost to split array into k subsets ; sort the array in descending order ; stores minimum cost to split the array into k subsets ; stores position of elements of a subset ; iterate over the range [ 1 , n ] ; calculate the cost to select x - th element of every subset ; update min_cost ; update x ; 
def getMinCost(arr, n, k):
    arr .sort(reverse=True)
    min_cost = 0
    X = 0
    for i in range(0, n, k):
        for j in range(i, n, 1):
            if (j < i + k):
                min_cost += arr[j] * (X + 1)
        X += 1
    return min_cost


if __name__ == '__main__':
    arr = [9, 20, 7, 8]
    K = 2
    N = len(arr)
    print(getMinCost(arr, N, K))

# Expected output:
59
# minimize difference between the largest and smallest array elements by k replacements | function to find minimum difference between largest and smallest element after k replacements ; sort array in ascending order ; length of array ; minimum difference ; check for all k + 1 possibilities ; return answer ; 
def minDiff(A, K):
    A .sort()
    n = len(A)
    if (n <= K):
        return 0
    mindiff = A[n - 1] - A[0]
    if (K == 0):
        return mindiff
    i = 0
    for j in range(n - 1 - K, n):
        mindiff = min(mindiff, A[j] - A[i])
        i += 1
        j += 1
    return mindiff


if __name__ == '__main__':
    A = [-1, 3, -1, 8, 5, 4]
    K = 3
    print(minDiff(A, K))

# Expected output:
2
# minimize difference between the largest and smallest array elements by k replacements | python3 program for above approach ; function to find minimum difference between the largest and smallest element after k replacements ; create a maxheap ; create a minheap ; update maxheap and minheap with highest and smallest k elements respectively ; insert current element into the maxheap ; if maxheap size exceeds k + 1 ; remove top element ; insert current element into the maxheap ; if maxheap size exceeds k + 1 ; remove top element ; store all max element from maxheap ; store all min element from minheap ; generating all k + 1 possibilities ; return answer ; 

import sys


def minDiff(A, K):
    if (len(A) <= K + 1):
        return 0
    maxHeap = []
    minHeap = []
    for n in A:
        maxHeap .append(n)
        maxHeap .sort()
        if (len(maxHeap) > K + 1):
            del maxHeap[0]
        minHeap .append(n)
        minHeap .sort()
        minHeap .reverse()
        if (len(minHeap) > K + 1):
            del minHeap[0]
    maxList = []
    while (len(maxHeap) > 0):
        maxList .append(maxHeap[0])
        del maxHeap[0]
    minList = []
    while (len(minHeap) > 0):
        minList .append(minHeap[0])
        del minHeap[0]
    mindiff = sys .maxsize
    for i in range(K):
        mindiff = min(mindiff, maxList[i] - minList[K - i])
    return mindiff


A = [-1, 3, -1, 8, 5, 4]
K = 3
print(minDiff(A, K))

# Expected output:
2
# check if all k | function to check all subset - sums of k - length subsets in a [ ] is greater that that in the array b [ ] or not ; sort the array in ascending order ; sort the array in descending order ; stores sum of first k elements of a [ ] ; stores sum of first k elements of b [ ] ; traverse both the arrays ; update sum1 ; update sum2 ; if sum1 exceeds sum2 ; 
def checkSubsetSum(A, B, N, K):
    A .sort()
    B .sort(reverse=True)
    sum1 = 0
    sum2 = 0
    for i in range(K):
        sum1 += A[i]
        sum2 += B[i]
    if (sum1 > sum2):
        return True
    return False


A = [12, 11, 10, 13]
B = [7, 10, 6, 2]
N = len(A)
K = 3
if (checkSubsetSum(A, B, N, K)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# sort given array to descending | function to sort first k array elements in descending and last n - k in ascending order ; sort the array in descending order ; sort last ( n - k ) array elements in ascending order ; 
def sortArrayInDescAsc(arr, N, K):
    arr = sorted(arr)
    arr = arr[::-1]
    for i in arr[:K]:
        print(i, end=" ")
    for i in reversed(arr[K:]):
        print(i, end=" ")


if __name__ == '__main__':
    arr = [7, 6, 8, 9, 0, 1, 2, 2, 1, 8, 9, 6, 7]
    N = len(arr)
    K = 6
    sortArrayInDescAsc(arr, N, K)

# Expected output:
9 9 8 8 7 7 0 1 1 2 2 6 6
# median of all non | function to calculate the median of all possible subsets by given operations ; stores sum of elements of arr [ ] ; traverse the array arr [ ] ; update sum ; sort the array ; dp [ i ] [ j ] : stores total number of ways to form the sum j by either selecting ith element or not selecting ith item . ; base case ; fill dp [ i ] [ 0 ] ; base case ; fill all the dp states based on the mentioned dp relation ; if j is greater than or equal to arr [ i ] ; update dp [ i ] [ j ] ; update dp [ i ] [ j ] ; stores all possible subset sum ; traverse all possible subset sum ; stores count of subsets whose sum is j ; itearate over the range [ 1 , m ] ; insert j into sumsub ; stores middle element of sumsub ; 
def findMedianOfsubSum(arr, N):
    sum = 0
    for i in range(N):
        sum += arr[i]
    arr .sort(reverse=False)
    dp = [[0 for i in range(sum + 1)]for j in range(N)]
    for i in range(N):
        dp[i][0] = 1
    dp[0][arr[0]] = 1
    for i in range(1, N, 1):
        for j in range(1, sum + 1, 1):
            if (j >= arr[i]):
                dp[i][j] = (dp[i - 1][j] + dp[i - 1][j - arr[i]])
            else:
                dp[i][j] = dp[i - 1][j]
    sumSub = []
    for j in range(1, sum + 1, 1):
        M = dp[N - 1][j]
        for i in range(1, M + 1, 1):
            sumSub .append(j)
    mid = sumSub[len(sumSub) // 2]
    return mid


if __name__ == '__main__':
    arr = [2, 3, 3]
    N = len(arr)
    print(findMedianOfsubSum(arr, N))

# Expected output:
5
# reduce array to a single element by repeatedly replacing adjacent unequal pairs with their maximum | function to prthe index from where the operation can be started ; initialize b ; initialize save ; make b equals to arr ; sort the array b ; traverse from n - 1 to 1 ; if b [ i ] & b [ i - 1 ] are unequal ; if all elements are same ; if arr [ 1 ] is maximum element ; if arr [ n - 1 ] is maximum element ; find the maximum element ; 
def printIndex(arr, N):
    B = [0] * (N)
    save = -1
    for i in range(N):
        B[i] = arr[i]
    B = sorted(B)
    for i in range(N - 1, 1, -1):
        if (B[i] != B[i - 1]):
            save = B[i]
            break
    if (save == -1):
        print(-1 + "")
        return
    if (save == arr[0] and save != arr[1]):
        print(1)
    elif (save == arr[N - 1] and save != arr[N - 2]):
        print(N)
    for i in range(1, N - 1):
        if (save == arr[i] and (save != arr[i - 1] or save != arr[i + 1])):
            print(i + 1)
            break


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

# Expected output:
1
# lexicographically smallest subsequence possible by removing a character from given string | function to find the lexicographically smallest subsequence of length n - 1 ; generate all subsequence of length n - 1 ; store main value of string str ; erasing element at position i ; sort the vector ; print first element of vector ; 
def firstSubsequence(s):
    allsubseq = []
    k = []
    for i in range(len(s)):
        k = [i for i in s]
        del k[i]
        allsubseq .append("".join(k))
    allsubseq = sorted(allsubseq)
    print(allsubseq[0])


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

# Expected output:
eeksforgeeks