giulio98/xlcost-single-prompt huggingface dataset:
# rearrange an array in maximum minimum form | set 1 | prints max at first position , min at second position second max at third position , second min at fourth position and so on . ; auxiliary array to hold modified array ; indexes of smallest and largest elements from remaining array . ; to indicate whether we need to copy rmaining largest or remaining smallest at next position ; store result in temp [ ] ; copy temp [ ] to arr [ ] ; 
def rearrange(arr, n):
    temp = n * [None]
    small, large = 0, n - 1
    flag = True
    for i in range(n):
        if flag is True:
            temp[i] = arr[large]
            large -= 1
        else:
            temp[i] = arr[small]
            small += 1
        flag = bool(1 - flag)
    for i in range(n):
        arr[i] = temp[i]
    return arr


arr = [1, 2, 3, 4, 5, 6]
n = len(arr)
print("Original Array")
print(arr)
print("Modified Array")
print(rearrange(arr, n))

# Expected output:
Original Array
[1, 2, 3, 4, 5, 6]
Modified Array
[6, 1, 5, 2, 4, 3]
# minimum number of coins needed to remove all the elements of the array based on given rules | function to calculate minimum number of coins needed ; consider the first element separately , add 1 to the total if it 's of type 1 ; iterate from the second element ; if the current element is of type 2 then any player can remove the element ; second pointer to reach end of type 1 elements ; increment j until arr [ j ] is equal to 1 and j is not out of bounds ; number of type 1 elements in a continious chunk ; from next iteration i pointer will start from index of j ; return the minimum count of coins ; 
def minimumcoins(arr, N):
    coins = 0
    j = 0
    if (arr[0] == 1):
        coins += 1
    for i in range(1, N):
        if (arr[i] == 2):
            continue
        j = i
        while (j < N and arr[j] == 1):
            j += 1
        x = (j - i)
        coins += x // 3
        i = j - 1
    return coins


N = 8
arr = [1, 2, 1, 1, 2, 1, 1, 1]
print(minimumcoins(arr, N))

# Expected output:
2
# rearrange an array in maximum minimum form | set 2 ( o ( 1 ) extra space ) | prints max at first position , min at second position second max at third position , second min at fourth position and so on . ; initialize index of first minimum and first maximum element ; store maximum element of array ; traverse array elements ; at even index : we have to put maximum element ; at odd index : we have to put minimum element ; array elements back to it 's original form ; 
def rearrange(arr, n):
    max_idx = n - 1
    min_idx = 0
    max_elem = arr[n - 1] + 1
    for i in range(0, n):
        if i % 2 == 0:
            arr[i] += (arr[max_idx] % max_elem) * max_elem
            max_idx -= 1
        else:
            arr[i] += (arr[min_idx] % max_elem) * max_elem
            min_idx += 1
    for i in range(0, n):
        arr[i] = arr[i] / max_elem


arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = len(arr)
print("Original Array")
for i in range(0, n):
    print(arr[i], end=" ")
rearrange(arr, n)
print("ModifiedArray")
for i in range(0, n):
    print(int(arr[i]), end=" ")

# Expected output:
Original Array
1 2 3 4 5 6 7 8 9 ModifiedArray
9 1 8 2 7 3 6 4 5
# rearrange an array in maximum minimum form | set 2 ( o ( 1 ) extra space ) | prints max at first position , min at second position second max at third position , second min at fourth position and so on . ; initialize index of first minimum and first maximum element ; traverse array elements ; at even index : we have to put maximum element ; at odd index : we have to put minimum element ; 
def rearrange(arr, n):
    max_ele = arr[n - 1]
    min_ele = arr[0]
    for i in range(n):
        if i % 2 == 0:
            arr[i] = max_ele
            max_ele -= 1
        else:
            arr[i] = min_ele
            min_ele += 1


arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = len(arr)
print("Origianl Array")
for i in range(n):
    print(arr[i], end=" ")
rearrange(arr, n)
print("ModifiedArray")
for i in range(n):
    print(arr[i], end=" ")

# Expected output:
Origianl Array
1 2 3 4 5 6 7 8 9 ModifiedArray
9 1 8 2 7 3 6 4 5
# move all negative numbers to beginning and positive to end with constant extra space | a python 3 program to put all negative numbers before positive numbers ; print an array ; 
def rearrange(arr, n):
    j = 0
    for i in range(0, n):
        if (arr[i] < 0):
            temp = arr[i]
            arr[i] = arr[j]
            arr[j] = temp
            j = j + 1
    print(arr)


arr = [-1, 2, -3, 4, 5, 6, -7, 8, 9]
n = len(arr)
rearrange(arr, n)

# Expected output:
[-1, -3, -7, 4, 5, 6, 2, 8, 9]
# maximize the diamonds by choosing different colour diamonds from adjacent boxes | function to return the maximized value ; number of rows and columns ; creating the dp array ; populating the first column ; iterating over all the rows ; getting the ( i - 1 ) th max value ; adding it to the current cell ; getting the max sum from the last column ; 
def maxSum(arr):
    m = len(arr)
    n = len(arr[0]) - 1
    dp = [[0 for i in range(n + 1)]for j in range(m)]
    for i in range(1, m, 1):
        dp[i][1] = arr[i][1]
    for i in range(1, n + 1, 1):
        for j in range(1, m, 1):
            mx = 0
            for k in range(1, m, 1):
                if (k != j):
                    if (dp[k][i - 1] > mx):
                        mx = dp[k][i - 1]
            if (mx and arr[j][i]):
                dp[j][i] = arr[j][i] + mx
    ans = -1
    for i in range(1, m, 1):
        if (dp[i][n]):
            ans = max(ans, dp[i][n])
    return ans


if __name__ == '__main__':
    arr = [
        [
            0, 0, 0, 0, 0], [
            0, 10, 2, 20, 0], [
                0, 0, 0, 5, 0], [
                    0, 0, 0, 0, 6], [
                        0, 4, 0, 11, 5], [
                            0, 0, 0, 0, 0], [
                                0, 0, 0, 0, 0], [
                                    0, 0, 0, 0, 0]]
    print(maxSum(arr))

# Expected output:
23
# move all negative elements to end in order with extra space allowed | moves all - ve element to end of array in same order . ; create an empty array to store result ; traversal array and store + ve element in temp array index of temp ; if array contains all positive or all negative . ; store - ve element in temp array ; copy contents of temp [ ] to arr [ ] ; 
def segregateElements(arr, n):
    temp = [0 for k in range(n)]
    j = 0
    for i in range(n):
        if (arr[i] >= 0):
            temp[j] = arr[i]
            j += 1
    if (j == n or j == 0):
        return
    for i in range(n):
        if (arr[i] < 0):
            temp[j] = arr[i]
            j += 1
    for k in range(n):
        arr[k] = temp[k]


arr = [1, -1, -3, -2, 7, 5, 11, 6]
n = len(arr)
segregateElements(arr, n)
for i in range(n):
    print(arr[i])

# Expected output:
1
7
5
11
6
-1
-3
-2
# minimum distance between duplicates in a string | this function is used to find minimum distance between same repeating characters ; store minimum distance between same repeating characters ; for loop to consider each element of string ; comparison of string characters and updating the mindis value ; as this value would be least therefore break ; if mindis value is not updated that means no repeating characters ; minimum distance is mindis - 1 ; 
def shortestDistance(S, N):
    minDis = len(S)
    for i in range(N):
        for j in range(i + 1, N):
            if (S[i] == S[j] and (j - i) < minDis):
                minDis = j - i
                break
    if (minDis == len(S)):
        return -1
    else:
        return minDis - 1


S = "geeksforgeeks"
N = 13
print(shortestDistance(S, N))

# Expected output:
0
# positive elements at even and negative at odd positions ( relative order not maintained ) | python 3 program to rearrange positive and negative numbers ; move forward the positive pointer till negative number number not encountered ; move forward the negative pointer till positive number number not encountered ; swap array elements to fix their position . ; break from the while loop when any index exceeds the size of the array ; 
def rearrange(a, size):
    positive = 0
    negative = 1
    while (True):
        while (positive < size and a[positive] >= 0):
            positive = positive + 2
        while (negative < size and a[negative] <= 0):
            negative = negative + 2
        if (positive < size and negative < size):
            temp = a[positive]
            a[positive] = a[negative]
            a[negative] = temp
        else:
            break


arr = [1, -3, 5, 6, -3, 6, 7, -4, 9, 10]
n = len(arr)
rearrange(arr, n)
for i in range(0, n):
    print(arr[i], end=" ")

# Expected output:
1 -3 5 -3 6 6 7 -4 9 10
# print all numbers that can be obtained by adding a or b to n exactly m times | function to find all possible numbers that can be obtained by adding a or b to n exactly m times ; for maintaining increasing order ; smallest number that can be achieved ; if a and b are equal , the only number that can be onbtained is n + m * a ; for finding other numbers , subtract a from number 1 time and add b to number 1 time ; 
def possibleNumbers(N, M, A, B):
    if (A > B):
        temp = A
        A = B
        B = temp
    number = N + M * A
    print(number, end=" ")
    if (A != B):
        for i in range(M):
            number = number - A + B
            print(number, end=" ")


if __name__ == '__main__':
    N = 5
    M = 3
    A = 4
    B = 6
    possibleNumbers(N, M, A, B)

# Expected output:
17 19 21 23
# positive elements at even and negative at odd positions ( relative order not maintained ) | print array function ; 
def printArray(a, n):
    for i in a:
        print(i, end=" ")
    print()


arr = [1, -3, 5, 6, -3, 6, 7, -4, 9, 10]
n = len(arr)
printArray(arr, n)
for i in range(n):
    if (arr[i] >= 0 and i % 2 == 1):
        for j in range(i + 1, n):
            if (arr[j] < 0 and j % 2 == 0):
                arr[i], arr[j] = arr[j], arr[i]
                break
    elif (arr[i] < 0 and i % 2 == 0):
        for j in range(i + 1, n):
            if (arr[j] >= 0 and j % 2 == 1):
                arr[i], arr[j] = arr[j], arr[i]
                break
printArray(arr, n)

# Expected output:
1 -3 5 6 -3 6 7 -4 9 10 
1 -3 5 -3 6 6 7 -4 9 10
# segregate even and odd numbers | set 3 | python3 implementation of the above approach ; 
def arrayEvenAndOdd(arr, n):
    ind = 0
    a = [0 for i in range(n)]
    for i in range(n):
        if (arr[i] % 2 == 0):
            a[ind] = arr[i]
            ind += 1
    for i in range(n):
        if (arr[i] % 2 != 0):
            a[ind] = arr[i]
            ind += 1
    for i in range(n):
        print(a[i], end=" ")
    print()


arr = [1, 3, 2, 4, 7, 6, 9, 10]
n = len(arr)
arrayEvenAndOdd(arr, n)

# Expected output:
2 4 6 10 1 3 7 9
# segregate even and odd numbers | set 3 | function to segregate even odd numbers ; swapping even and odd numbers ; printing segregated array ; 
def arrayEvenAndOdd(arr, n):
    i = -1
    j = 0
    while (j != n):
        if (arr[j] % 2 == 0):
            i = i + 1
            arr[i], arr[j] = arr[j], arr[i]
        j = j + 1
    for i in arr:
        print(str(i) + " ", end='')


if __name__ == '__main__':
    arr = [1, 3, 2, 4, 7, 6, 9, 10]
    n = len(arr)
    arrayEvenAndOdd(arr, n)

# Expected output:
2 4 6 10 7 1 9 3
# check if a matrix can be converted to another by repeatedly adding any value to x consecutive elements in a row or column | function to check whether matrix a [ ] [ ] can be transformed to matrix b [ ] [ ] or not ; traverse the matrix to perform horizontal operations ; calculate difference ; update next x elements ; traverse the matrix to perform vertical operations ; calculate difference ; update next k elements ; a [ i ] [ j ] is not equal to b [ i ] [ j ] ; conversion is not possible ; conversion is possible ; 
def Check(A, B, M, N, X):
    for i in range(M):
        for j in range(N - X + 1):
            if (A[i][j] != B[i][j]):
                diff = B[i][j] - A[i][j]
                for k in range(X):
                    A[i][j + k] = A[i][j + k] + diff
    for i in range(M - X + 1):
        for j in range(N):
            if (A[i][j] != B[i][j]):
                diff = B[i][j] - A[i][j]
                for k in range(X):
                    A[i + k][j] = A[i + k][j] + diff
    for i in range(M):
        for j in range(N):
            if (A[i][j] != B[i][j]):
                return 0
    return 1


if __name__ == '__main__':
    M, N, X = 2, 2, 2
    A = [[0, 0], [0, 0]]
    B = [[1, 2], [0, 1]]
    if (Check(A, B, M, N, X)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# make all array elements equal by reducing array elements to half minimum number of times | function to find minimum number of operations ; initialize map ; traverse the array ; divide current array element until it reduces to 1 ; traverse the map ; find the maximum element having frequency equal to n ; stores the minimum number of operations required ; count operations required to convert current element to mx ; return the answer ; 
def minOperations(arr, N):
    mp = {}
    for i in range(N):
        res = arr[i]
        while (res):
            if res in mp:
                mp[res] += 1
            else:
                mp[res] = 1
            res //= 2
    mx = 1
    for it in mp:
        if (mp[it] == N):
            mx = it
    ans = 0
    for i in range(N):
        res = arr[i]
        while (res != mx):
            ans += 1
            res //= 2
    return ans


arr = [3, 1, 1, 3]
N = len(arr)
print(minOperations(arr, N))

# Expected output:
2
# find the player to reach at least n by multiplying with any value from given range | function to find the winner ; backtrack from n to 1 ; 
def Winner(N):
    player = True
    while N > 1:
        X, Y = divmod(N, (9 if player else 2))
        N = X + 1 if Y else X
        player = not player
    if player:
        return 'B'
    else:
        return 'A'


N = 10
print(Winner(N))

# Expected output:
B
# program to find largest element in an array | returns maximum in arr [ ] of size n ; 
def largest(arr, n):
    return max(arr)


arr = [10, 324, 45, 90, 9808]
n = len(arr)
print(largest(arr, n))

# Expected output:
9808
# find the largest three distinct elements in an array | python3 code to find largest three elements in an array ; it uses tuned quicksort with ; avg . case time complexity = o ( nlogn ) ; to handle duplicate values ; 
def find3largest(arr, n):
    arr = sorted(arr)
    check = 0
    count = 1
    for i in range(1, n + 1):
        if (count < 4):
            if (check != arr[n - i]):
                print(arr[n - i], end=" ")
                check = arr[n - i]
                count += 1
        else:
            break


arr = [12, 45, 1, -1, 45, 54, 23, 5, 0, -10]
n = len(arr)
find3largest(arr, n)

# Expected output:
54 45 23
# minimum characters required to be removed to make frequency of each character unique | function to find the minimum count of characters required to be deleted to make frequencies of all characters unique ; stores frequency of each distinct character of str ; store frequency of each distinct character such that the largest frequency is present at the top ; stores minimum count of characters required to be deleted to make frequency of each character unique ; traverse the string ; update frequency of str [ i ] ; traverse the map ; insert current frequency into pq ; traverse the priority_queue ; stores topmost element of pq ; pop the topmost element ; if pq is empty ; return cntchar ; if frequent and topmost element of pq are equal ; if frequency of the topmost element is greater than 1 ; insert the decremented value of frequent ; update cntchar ; 
def minCntCharDeletionsfrequency(str, N):
    mp = {}
    pq = []
    cntChar = 0
    for i in range(N):
        mp[str[i]] = mp .get(str[i], 0) + 1
    for it in mp:
        pq .append(mp[it])
    pq = sorted(pq)
    while (len(pq) > 0):
        frequent = pq[-1]
        del pq[-1]
        if (len(pq) == 0):
            return cntChar
        if (frequent == pq[-1]):
            if (frequent > 1):
                pq .append(frequent - 1)
            cntChar += 1
        pq = sorted(pq)
    return cntChar


if __name__ == '__main__':
    str = "abbbcccd"
    N = len(str)
    print(minCntCharDeletionsfrequency(str, N))

# Expected output:
2
# find a pair with sum n having minimum absolute difference | function to find the value of x and y having minimum value of abs ( x - y ) ; if n is an odd number ; if n is an even number ; 
def findXandYwithminABSX_Y(N):
    if (N % 2 == 1):
        print((N // 2), (N // 2 + 1))
    else:
        print((N // 2 - 1), (N // 2 + 1))


if __name__ == '__main__':
    N = 12
    findXandYwithminABSX_Y(N)

# Expected output:
5 7
# maximum sum possible by assigning alternate positive and negative sign to elements in a subsequence | function to find the maximum sum subsequence ; base case ; if current state is already calculated then use it ; if current element is positive ; update ans and recursively call with update value of flag ; else current element is negative ; update ans and recursively call with update value of flag ; return maximum sum subsequence ; function that finds the maximum sum of element of the subsequence with alternate + ve and - ve signs ; create auxiliary array dp [ ] [ ] ; function call ; 
def findMax(a, dp, i, flag):
    if (i == len(a)):
        return 0
    if (dp[i][flag] != -1):
        return dp[i][flag]
    ans = 0
    if (flag == 0):
        ans = max(findMax(a, dp, i + 1, 0), a[i] + findMax(a, dp, i + 1, 1))
    else:
        ans = max(findMax(a, dp, i + 1, 1), -1 *
                  a[i] + findMax(a, dp, i + 1, 0))
    dp[i][flag] = ans
    return ans


def findMaxSumUtil(arr, N):
    dp = [[-1 for i in range(2)]for i in range(N)]
    print(findMax(arr, dp, 0, 0))


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

# Expected output:
5
# find the player to last modify a string such that even number of consonants and no vowels are left in the string | function to find a winner of the game if both the player plays optimally ; stores the count of vowels and consonants ; traverse the string ; check if character is vowel ; increment vowels count ; otherwise increment the consonants count ; check if player b wins ; check if player a wins ; check if player a wins ; if game ends in a draw ; 
def findWinner(s):
    vowels_count = 0
    consonants_count = 0
    p = len(s)

    for i in range(0, p):
        if (s[i] == 'a' or s[i] == 'e' or
            s[i] == 'i' or s[i] == 'o' or
                s[i] == 'u'):
            vowels_count = vowels_count + 1
        else:
            consonants_count = consonants_count + 1

    if (vowels_count == 0):
        if (consonants_count % 2 == 0):
            print("Player B")
        else:
            print("Player A")
    elif (vowels_count == 1 and
          consonants_count % 2 != 0):
        print("Player A")
    else:
        print("D")


s = "abcd"

findWinner(s)

# Expected output:
Player A
# k maximum sums of overlapping contiguous sub | function to compute prefix - sum of the input array ; update maxi by k maximum values from maxi and cand ; here cand and maxi arrays are in non - increasing order beforehand . now , j is the index of the next cand element and i is the index of next maxi element . traverse through maxi array . if cand [ j ] > maxi [ i ] insert cand [ j ] at the ith position in the maxi array and remove the minimum element of the maxi array i . e . the last element and increase j by 1 i . e . take the next element from cand . ; insert prefix_sum [ i ] to mini array if needed ; traverse the mini array from left to right . if prefix_sum [ i ] is less than any element then insert prefix_sum [ i ] at that position and delete maximum element of the mini array i . e . the rightmost element from the array . ; function to compute k maximum overlapping sub - array sums ; compute the prefix sum of the input array . ; set all the elements of mini as + infinite except 0 th . set the 0 th element as 0. ; set all the elements of maxi as - infinite . ; initialize cand array . ; for each element of the prefix_sum array do : compute the cand array . take k maximum values from maxi and cand using maxmerge function . insert prefix_sum [ i ] to mini array if needed using insertmini function . ; elements of maxi array is the k maximum overlapping sub - array sums . print out the elements of maxi array . ; test case 1 ; 
def prefix_sum(arr, n):
    pre_sum = list()
    pre_sum .append(arr[0])
    for i in range(1, n):
        pre_sum .append(pre_sum[i - 1] + arr[i])
    return pre_sum


def maxMerge(maxi, cand):
    k = len(maxi)
    j = 0
    for i in range(k):
        if (cand[j] > maxi[i]):
            maxi .insert(i, cand[j])
            del maxi[-1]
            j += 1


def insertMini(mini, pre_sum):
    k = len(mini)
    for i in range(k):
        if (pre_sum < mini[i]):
            mini .insert(i, pre_sum)
            del mini[-1]
            break


def kMaxOvSubArray(arr, k):
    n = len(arr)
    pre_sum = prefix_sum(arr, n)
    mini = [float('inf')for i in range(k)]
    mini[0] = 0
    maxi = [-float('inf')for i in range(k)]
    cand = [0 for i in range(k)]
    for i in range(n):
        for j in range(k):
            cand[j] = pre_sum[i] - mini[j]
        maxMerge(maxi, cand)
        insertMini(mini, pre_sum[i])
    for ele in maxi:
        print(ele, end=' ')
    print('')


arr1 = [4, -8, 9, -4, 1, -8, -1, 6]
k1 = 4
kMaxOvSubArray(arr1, k1)
arr2 = [-2, -3, 4, -1, -2, 1, 5, -3]
k2 = 3
kMaxOvSubArray(arr2, k2)

# Expected output:
9 6 6 5 
7 6 5
# k smallest elements in same order using o ( 1 ) extra space | function to print smallest k numbers in arr [ 0. . n - 1 ] ; for each arr [ i ] find whether it is a part of n - smallest with insertion sort concept ; find largest from first k - elements ; if largest is greater than arr [ i ] shift all element one place left ; make arr [ k - 1 ] = arr [ i ] ; print result ; 
def printSmall(arr, n, k):
    for i in range(k, n):
        max_var = arr[k - 1]
        pos = k - 1
        for j in range(k - 2, -1, -1):
            if (arr[j] > max_var):
                max_var = arr[j]
                pos = j
        if (max_var > arr[i]):
            j = pos
            while (j < k - 1):
                arr[j] = arr[j + 1]
                j += 1
            arr[k - 1] = arr[i]
    for i in range(0, k):
        print(arr[i], end=" ")


arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]
n = len(arr)
k = 5
printSmall(arr, n, k)

# Expected output:
1 3 4 2 0
# find k pairs with smallest sums in two arrays | python3 program to prints first k pairs with least sum from two arrays . ; function to find k pairs with least sum such that one elemennt of a pair is from arr1 [ ] and other element is from arr2 [ ] ; stores current index in arr2 [ ] for every element of arr1 [ ] . initially all values are considered 0. here current index is the index before which all elements are considered as part of output . ; initialize current pair sum as infinite ; to pick next pair , traverse for all elements of arr1 [ ] , for every element , find corresponding current element in arr2 [ ] and pick minimum of all formed pairs . ; check if current element of arr1 [ ] plus element of array2 to be used gives minimum sum ; update index that gives minimum ; update minimum sum ; 

import sys


def kSmallestPair(arr1, n1, arr2, n2, k):
    if (k > n1 * n2):
        print("k pairs don't exist")
        return
    index2 = [0 for i in range(n1)]
    while (k > 0):
        min_sum = sys .maxsize
        min_index = 0
        for i1 in range(0, n1, 1):
            if (index2[i1] < n2 and arr1[i1] + arr2[index2[i1]] < min_sum):
                min_index = i1
                min_sum = arr1[i1] + arr2[index2[i1]]
        print("(", arr1[min_index], ",", arr2[index2[min_index]], ")", end=" ")
        index2[min_index] += 1
        k -= 1


if __name__ == '__main__':
    arr1 = [1, 3, 11]
    n1 = len(arr1)
    arr2 = [2, 4, 8]
    n2 = len(arr2)
    k = 4
    kSmallestPair(arr1, n1, arr2, n2, k)

# Expected output:
( 1 , 2 ) ( 1 , 4 ) ( 3 , 2 ) ( 3 , 4 )