giulio98/xlcost-single-prompt huggingface dataset:
# minimum operations of given type to make all elements of a matrix equal | function to return the minimum number of operations required ; create another array to store the elements of matrix ; if not possible ; sort the array to get median ; to count the minimum operations ; if there are even elements , then there are two medians . we consider the best of two as answer . ; return minimum operations required ; 
def minOperations(n, m, k, matrix):
    arr = [0] * (n * m)
    mod = matrix[0][0] % k
    for i in range(0, n):
        for j in range(0, m):
            arr[i * m + j] = matrix[i][j]
            if matrix[i][j] % k != mod:
                return -1
    arr .sort()
    median = arr[(n * m) // 2]
    minOperations = 0
    for i in range(0, n * m):
        minOperations += abs(arr[i] - median) // k
    if (n * m) % 2 == 0:
        median2 = arr[((n * m) // 2) - 1]
        minOperations2 = 0
        for i in range(0, n * m):
            minOperations2 += abs(arr[i] - median2) // k
        minOperations = min(minOperations, minOperations2)
    return minOperations


if __name__ == "__main__":
    matrix = [[2, 4, 6], [8, 10, 12], [14, 16, 18], [20, 22, 24]]
    n = len(matrix)
    m = len(matrix[0])
    k = 2
    print(minOperations(n, m, k, matrix))

# Expected output:
36
# count distinct elements in an array | python3 program to count distinct elements in a given array ; pick all elements one by one ; if not printed earlier , then print it ; 
def countDistinct(arr, n):
    res = 1
    for i in range(1, n):
        j = 0
        for j in range(i):
            if (arr[i] == arr[j]):
                break
        if (i == j + 1):
            res += 1
    return res


arr = [12, 10, 9, 45, 2, 10, 10, 45]
n = len(arr)
print(countDistinct(arr, n))

# Expected output:
5
# count distinct elements in an array | python3 program to count all distinct elements in a given array ; first sort the array so that all occurrences become consecutive ; traverse the sorted array ; move the index ahead while there are duplicates ; 
def countDistinct(arr, n):
    arr .sort()
    res = 0
    i = 0
    while (i < n):
        while (i < n - 1 and arr[i] == arr[i + 1]):
            i += 1
        res += 1
        i += 1
    return res


arr = [6, 10, 5, 4, 9, 120, 4, 6, 10]
n = len(arr)
print(countDistinct(arr, n))

# Expected output:
6
# choose n elements such that their mean is maximum | utility function to print the contents of an array ; function to print the array with maximum mean ; sort the original array ; construct new array ; print the resultant array ; 
def printArray(arr, n):
    for i in range(n):
        print(arr[i], end=" ")


def printMaxMean(arr, n):
    newArr = [0] * n
    arr .sort()
    for i in range(n):
        newArr[i] = arr[i + n]
    printArray(newArr, n)


if __name__ == "__main__":
    arr = [4, 8, 3, 1, 3, 7, 0, 4]
    n = len(arr)
    printMaxMean(arr, n // 2)

# Expected output:
4 4 7 8
# average of remaining elements after removing k largest and k smallest elements from array | function to find average ; base case if 2 * k >= n means all element get removed ; first sort all elements ; sum of req number ; find average ; 
def average(arr, n, k):
    total = 0
    if (2 * k >= n):
        return 0
    arr .sort()
    start, end = k, n - k - 1
    for i in range(start, end + 1):
        total += arr[i]
    return (total / (n - 2 * k))


if __name__ == "__main__":
    arr = [1, 2, 4, 4, 5, 6]
    n = len(arr)
    k = 2
    print(average(arr, n, k))

# Expected output:
4.0
# minimum sum after subtracting multiples of k from the elements of the array | function to calculate minimum sum after transformation ; no element can be reduced further ; if all the elements of the array are identical ; check if a [ i ] can be reduced to a [ 0 ] ; one of the elements cannot be reduced to be equal to the other elements ; if k = 1 then all elements can be reduced to 1 ; 
def min_sum(n, k, a):
    a .sort(reverse=False)
    if (a[0] < 0):
        return -1
    if (k == 0):
        if (a[0] == a[n - 1]):
            return (n * a[0])
        else:
            return -1
    else:
        f = 0
        for i in range(1, n, 1):
            p = a[i] - a[0]
            if (p % k == 0):
                continue
            else:
                f = 1
                break
        if (f):
            return -1
        else:
            if (k == 1):
                return n
            else:
                return (n * (a[0] % k))


if __name__ == '__main__':
    arr = [2, 3, 4, 5]
    K = 1
    N = len(arr)
    print(min_sum(N, K, arr))

# Expected output:
4
# minimum increment / decrement to make array elements equal | function to return minimum operations need to be make each element of array equal ; initialize cost to 0 ; sort the array ; middle element ; find cost ; if n , is even . take minimum of the cost obtained by considering both middle elements ; find cost again ; take minimum of two cost ; return total cost ; 
def minCost(A, n):
    cost = 0
    A .sort()
    K = A[int(n / 2)]
    for i in range(0, n):
        cost = cost + abs(A[i] - K)
    if n % 2 == 0:
        tempCost = 0
        K = A[int(n / 2) - 1]
        for i in range(0, n):
            tempCost = tempCost + abs(A[i] - K)
        cost = min(cost, tempCost)
    return cost


A = [1, 6, 7, 10]
n = len(A)
print(minCost(A, n))

# Expected output:
10
# print array elements in alternatively increasing and decreasing order | function to print array elements in alternative increasing and decreasing order ; first sort the array in increasing order ; start with 2 elements in increasing order ; till all the elements are not printed ; printing the elements in increasing order ; else : printing the elements in decreasing order ; increasing the number of elements to printed in next iteration ; 
def printArray(arr, n):
    arr .sort()
    l = 0
    r = n - 1
    flag = 0
    k = 2
    while (l <= r):
        if (flag == 0):
            i = l
            while i < l + k and i <= r:
                print(arr[i], end=" ")
                i += 1
            flag = 1
            l = i
            i = r
            while i > r - k and i >= l:
                print(arr[i], end=" ")
                i -= 1
            flag = 0
            r = i
        k += 1


if __name__ == "__main__":
    n = 6
    arr = [1, 2, 3, 4, 5, 6]
    printArray(arr, n)

# Expected output:
1 2 6 5 3 4
# check if the characters of a given string are in alphabetical order | function that checks whether the string is in alphabetical order or not ; if element at index ' i ' is less than the element at index ' i - 1' then the string is not sorted ; 
def isAlphabaticOrder(s):
    n = len(s)
    for i in range(1, n):
        if (s[i] < s[i - 1]):
            return False
    return True


if __name__ == "__main__":
    s = "aabbbcc"
    if (isAlphabaticOrder(s)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# product of non | function to find the product of all non - repeated elements in an array ; sort all elements of array ; 
def findProduct(arr, n):
    sorted(arr)
    prod = 1
    for i in range(0, n, 1):
        if (arr[i - 1] != arr[i]):
            prod = prod * arr[i]
    return prod


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

# Expected output:
720
# check if it is possible to rearrange rectangles in a non | python3 implementation of above approach ; function to check if it possible to form rectangles with heights as non - ascending ; set maximum ; replace the maximum with previous maximum ; replace the minimum with previous minimum ; print no if the above two conditions fail at least once ; initialize the number of rectangles ; 

import sys


def rotateRec(n, L, B):
    m = sys .maxsize
    for i in range(n):
        if (max(L[i], B[i]) <= m):
            m = max(L[i], B[i])
        elif (min(L[i], B[i]) <= m):
            m = min(L[i], B[i])
        else:
            return 0
    return 1


n = 3
L = [5, 5, 6]
B = [6, 7, 8]
if (rotateRec(n, L, B) == 1):
    print("YES")
else:
    print("NO")

# Expected output:
NO
# find a point such that sum of the manhattan distances is minimized | function to print the required points which minimizes the sum of manhattan distances ; sorting points in all dimension ; output the required k points ; 
def minDistance(n, k, point):
    for i in range(k):
        point[i].sort()
    for i in range(k):
        print(point[i][((n + 1) // 2) - 1], end=" ")


n = 4
k = 4
point = [[1, 5, 2, 4], [6, 2, 0, 6], [9, 5, 1, 3], [6, 7, 5, 9]]
minDistance(n, k, point)

# Expected output:
2 2 3 6
# sort first k values in ascending order and remaining n | function to sort the array ; store the k elements in an array ; store the remaining n - k elements in an array ; sorting the array from 0 to k - 1 places ; sorting the array from k to n places ; storing the values in the final array arr ; printing the array ; 
def printOrder(arr, n, k):
    len1 = k
    len2 = n - k
    arr1 = [0] * k
    arr2 = [0] * (n - k)
    for i in range(k):
        arr1[i] = arr[i]
    for i in range(k, n):
        arr2[i - k] = arr[i]
    arr1 .sort()
    arr2 .sort()
    for i in range(n):
        if (i < k):
            arr[i] = arr1[i]
        else:
            arr[i] = arr2[len2 - 1]
            len2 -= 1
    for i in range(n):
        print(arr[i], end=" ")


if __name__ == "__main__":
    arr = [5, 4, 6, 2, 1, 3, 8, 9, -1]
    k = 4
    n = len(arr)
    printOrder(arr, n, k)

# Expected output:
2 4 5 6 9 8 3 1 -1
# find the largest number that can be formed with the given digits | function to generate largest possible number with given digits ; declare a hash array of size 10 and initialize all the elements to zero ; store the number of occurrences of the digits in the given array into the hash table ; traverse the hash in descending order to print the required number ; print the number of times a digits occurs ; 
def findMaxNum(arr, n):
    hash = [0] * 10
    for i in range(n):
        hash[arr[i]] += 1
    for i in range(9, -1, -1):
        for j in range(hash[i]):
            print(i, end="")


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

# Expected output:
543210
# equally divide into two sets such that one set has maximum distinct elements | python 3 program to equally divide n elements into two sets such that second set has maximum distinct elements . ; 
def distribution(arr, n):
    arr .sort(reverse=False)
    count = 1
    for i in range(1, n, 1):
        if (arr[i] > arr[i - 1]):
            count += 1
    return min(count, n / 2)


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

# Expected output:
3
# print all the pairs that contains the positive and negative values of an element | function to print pairs of positive and negative values present in the array ; store all the positive elements in the unordered_set ; start traversing the array ; check if the positive value of current element exists in the set or not ; print that pair ; 
def printPairs(arr, n):
    pairs = set()
    pair_exists = False
    for i in range(0, n):
        if arr[i] > 0:
            pairs .add(arr[i])
    for i in range(0, n):
        if arr[i] < 0:
            if (-arr[i]) in pairs:
                print("{}, {}".format(arr[i], -arr[i]))
                pair_exists = True
    if not pair_exists:
        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:
-4, 4
-1, 1
-8, 8
-9, 9
# print triplets with sum less than k | a simple python 3 program to count triplets with sum smaller than a given value ; fix the first element as a [ i ] ; fix the second element as a [ j ] ; now look for the third number ; 
def printTriplets(arr, n, sum):
    for i in range(0, n - 2, 1):
        for j in range(i + 1, n - 1, 1):
            for k in range(j + 1, n, 1):
                if (arr[i] + arr[j] + arr[k] < sum):
                    print(arr[i], ",", arr[j], ",", arr[k])


if __name__ == '__main__':
    arr = [5, 1, 3, 4, 7]
    n = len(arr)
    sum = 12
    printTriplets(arr, n, sum)

# Expected output:
5 , 1 , 3
5 , 1 , 4
1 , 3 , 4
1 , 3 , 7
# count number of triplets in an array having sum in the range [ a , b ] | function to count triplets ; initialize result ; fix the first element as a [ i ] ; fix the second element as a [ j ] ; now look for the third number ; 
def countTriplets(arr, n, a, b):
    ans = 0
    for i in range(0, n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
                if ((arr[i] + arr[j] + arr[k] >= a)
                        and (arr[i] + arr[j] + arr[k] <= b)):
                    ans += 1
    return ans


if __name__ == "__main__":
    arr = [2, 7, 5, 3, 8, 4, 1, 9]
    n = len(arr)
    a = 8
    b = 16
    print(countTriplets(arr, n, a, b))

# Expected output:
36
# count number of triplets in an array having sum in the range [ a , b ] | function to find count of triplets having sum less than or equal to val . ; sort the input array . ; initialize result ; to store sum ; fix the first element ; initialize other two elements as corner elements of subarray arr [ j + 1. . k ] ; use meet in the middle concept . ; if sum of current triplet is greater , then to reduce it decrease k . ; if sum is less than or equal to given value , then add possible triplets ( k - j ) to result . ; function to return count of triplets having sum in range [ a , b ] . ; to store count of triplets . ; find count of triplets having sum less than or equal to b and subtract count of triplets having sum less than or equal to a - 1. ; 
def countTripletsLessThan(arr, n, val):
    arr .sort()
    ans = 0
    j = 0
    k = 0
    sum = 0
    for i in range(0, n - 2):
        j = i + 1
        k = n - 1
        while j != k:
            sum = arr[i] + arr[j] + arr[k]
            if sum > val:
                k -= 1
            else:
                ans += (k - j)
                j += 1
    return ans


def countTriplets(arr, n, a, b):
    res = 0
    res = (
        countTripletsLessThan(
            arr,
            n,
            b) -
        countTripletsLessThan(
            arr,
            n,
            a -
            1))
    return res


if __name__ == "__main__":
    arr = [2, 7, 5, 3, 8, 4, 1, 9]
    n = len(arr)
    a = 8
    b = 16
    print(countTriplets(arr, n, a, b))

# Expected output:
36
# sum of areas of rectangles possible for an array | function to find area of rectangles ; sorting the array in descending order ; store the final sum of all the rectangles area possible ; temporary variable to store the length of rectangle ; selecting the length of rectangle so that difference between any two number is 1 only . here length is selected so flag is set ; flag is set means we have got length of rectangle ; length is set to a [ i + 1 ] so that if a [ i + 1 ] is less than a [ i ] by 1 then also we have the correct chice for length ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; selecting the width of rectangle so that difference between any two number is 1 only . here width is selected so now flag is again unset for next rectangle ; area is calculated for rectangle ; flag is set false for another rectangle which we can get from elements in array ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; 
def MaxTotalRectangleArea(a, n):
    a .sort(reverse=True)
    sum = 0
    flag = False
    len = 0
    i = 0
    while (i < n - 1):
        if (i != 0):
            i = i + 1
        if ((a[i] == a[i + 1] or a[i] - a[i + 1] == 1) and flag == False):
            flag = True
            len = a[i + 1]
            i = i + 1
        elif ((a[i] == a[i + 1] or a[i] - a[i + 1] == 1) and flag):
            sum = sum + a[i + 1] * len
            flag = False
            i = i + 1
    return sum


a = [10, 10, 10, 10, 11, 10, 11, 10, 9, 9, 8, 8]
n = len(a)
print(MaxTotalRectangleArea(a, n))

# Expected output:
282
# stable sort for descending order | bubble sort implementation to sort elements in descending order . ; sorts a [ ] in descending order using bubble sort . ; 
def print1(a, n):
    for i in range(0, n + 1):
        print(a[i], end=" ")
    print("")


def sort(a, n):
    for i in range(n, 0, -1):
        for j in range(n, n - i, -1):
            if (a[j] > a[j - 1]):
                a[j], a[j - 1] = a[j - 1], a[j]
    print1(a, n)


n = 7
a = [2, 4, 3, 2, 4, 5, 3]
sort(a, n - 1)

# Expected output:
5 4 4 3 3 2 2
# subtraction in the array | function to perform the given operation on arr [ ] ; skip elements which are 0 ; pick smallest non - zero element ; if all the elements of arr [ ] are 0 ; 
def operations(arr, n, k):
    arr .sort()
    i = 0
    sum = 0
    while (k > 0):
        while (i < n and arr[i] - sum == 0):
            i += 1
        if (i < n and arr[i] - sum > 0):
            print(arr[i] - sum, end=" ")
            sum = arr[i]
        else:
            print(0)
        k -= 1


k = 5
arr = [3, 6, 4, 2]
n = len(arr)
operations(arr, n, k)

# Expected output:
2 1 1 2 0
# alternate lower upper string sort | python3 program for unusul string sorting ; function for alternate sorting of string ; count occurrences of individual lower case and upper case characters ; traverse through count arrays and one by one pick characters . below loop takes o ( n ) time considering the max is constant . ; 

MAX = 26


def alternateSort(s):
    n = len(s)
    lCount = [0 for i in range(MAX)]
    uCount = [0 for i in range(MAX)]
    s = list(s)
    for i in range(n):
        if (s[i].isupper()):
            uCount[ord(s[i]) - ord('A')] += 1
        else:
            lCount[ord(s[i]) - ord('a')] += 1
    i = 0
    j = 0
    k = 0
    while (k < n):
        while (i < MAX and uCount[i] == 0):
            i += 1
        if (i < MAX):
            s[k] = chr(ord('A') + i)
            k += 1
            uCount[i] -= 1
        while (j < MAX and lCount[j] == 0):
            j += 1
        if (j < MAX):
            s[k] = chr(ord('a') + j)
            k += 1
            lCount[j] -= 1
    print("".join(s))


str = "bAwutndekWEdkd"
alternateSort(str)

# Expected output:
AbEdWddekkntuw
# sum of manhattan distances between all pairs of points | return the sum of distance between all the pair of points . ; for each point , finding distance to rest of the point ; 
def distancesum(x, y, n):
    sum = 0
    for i in range(n):
        for j in range(i + 1, n):
            sum += (abs(x[i] - x[j]) + abs(y[i] - y[j]))
    return sum


x = [-1, 1, 3, 2]
y = [5, 6, 5, 3]
n = len(x)
print(distancesum(x, y, n))

# Expected output:
22
# sum of manhattan distances between all pairs of points | return the sum of distance of one axis . ; sorting the array . ; for each point , finding the distance . ; 
def distancesum(arr, n):
    arr .sort()
    res = 0
    sum = 0
    for i in range(n):
        res += (arr[i] * i - sum)
        sum += arr[i]
    return res


def totaldistancesum(x, y, n):
    return distancesum(x, n) + distancesum(y, n)


x = [-1, 1, 3, 2]
y = [5, 6, 5, 3]
n = len(x)
print(totaldistancesum(x, y, n))

# Expected output:
22
# sort an array with swapping only with a special element is allowed | n is total number of elements . index is index of 999 or space . k is number of elements yet to be sorted . ; print the sorted array when loop reaches the base case ; else if k > 0 and space is at 0 th index swap each number with space and store index at second last index ; if space is neither start of array nor last element of array and element before it greater than / the element next to space ; first swap space and element next to space in case of { 3 , 999 , 2 } make it { 3 , 2 , 999 } ; than swap space and greater element convert { 3 , 2 , 999 } to { 999 , 2 , 3 } ; wrapper over sortrec . ; find index of space ( or 999 ) ; invalid input ; 
def sortRec(arr, index, k, n):
    if (k == 0):
        for i in range(1, n):
            print(arr[i], end=" ")
        print(999, end="")
    elif (k > 0 and index == 0):
        index = n - 2
        for i in range(1, index + 1):
            arr[i - 1] = arr[i]
        arr[index] = 999
    if (index - 1 >= 0 and index + 1 < n and arr[index - 1] > arr[index + 1]):
        arr[index], arr[index + 1] = arr[index + 1], arr[index]
        arr[index - 1], arr[index + 1] = arr[index + 1], arr[index - 1]
    else:
        if (index - 1 < 0):
            return
        arr[index], arr[index - 1] = arr[index - 1], arr[index]
    sortRec(arr, index - 1, k - 1, n)


def sort(arr, n):
    index = -1
    for i in range(n):
        if (arr[i] == 999):
            index = i
            break
    if (index == -1):
        return
    sortRec(arr, index, n, n)


arr = [3, 2, 999, 1]
n = len(arr)
sort(arr, n)

# Expected output:
1 2 3 999
# find array with k number of merge sort calls | python program to find an array that can be sorted with k merge sort calls . ; we make two recursive calls , so reduce k by 2. ; create an array with values in [ 1 , n ] ; calling unsort function ; 
def unsort(l, r, a, k):
    if (k < 1 or l + 1 == r):
        return
    k -= 2
    mid = (l + r) // 2
    temp = a[mid - 1]
    a[mid - 1] = a[mid]
    a[mid] = temp
    unsort(l, mid, a, k)
    unsort(mid, r, a, k)


def arrayWithKCalls(n, k):
    if (k % 2 == 0):
        print("NO SOLUTION")
        return
    a = [0 for i in range(n + 2)]
    a[0] = 1
    for i in range(1, n):
        a[i] = i + 1
    k -= 1
    unsort(0, n, a, k)
    for i in range(n):
        print(a[i], " ", end="")


n = 10
k = 17
arrayWithKCalls(n, k)

# Expected output:
3  1  4  6  2  8  5  9  10  7
# program to sort string in descending order | python program to sort a string of characters in descending order ; function to print string in sorted order ; hash array to keep count of characters . initially count of all charters is initialized to zero . ; traverse string and increment count of characters ; ' a ' - ' a ' will be 0 , ' b ' - ' a ' will be 1 , so for location of character in count array we wil do str [ i ] - ' a ' . ; traverse the hash array and print characters ; 

MAX_CHAR = 26


def sortString(str):
    charCount = [0] * MAX_CHAR
    for i in range(len(str)):
        charCount[ord(str[i]) - ord('a')] += 1
    for i in range(MAX_CHAR - 1, -1, -1):
        for j in range(charCount[i]):
            print(chr(97 + i), end="")


s = "alkasingh"
sortString(s)

# Expected output:
snlkihgaa
# median after k additional integers | find median of array after adding k elements ; sorting the array in increasing order . ; printing the median of array . since n + k is always odd and k < n , so median of array always lies in the range of n . ; 
def printMedian(arr, n, K):
    arr .sort()
    print(arr[int((n + K) / 2)])


arr = [5, 3, 2, 8]
k = 3
n = len(arr)
printMedian(arr, n, k)

# Expected output:
8