giulio98/xlcost-single-prompt huggingface dataset:
# maximum non | function to prthe maximum rooks and their positions ; marking the location of already placed rooks ; print number of non - attacking rooks that can be placed ; to store the placed rook location ; print lexographically smallest order ; 
def countRooks(n, k, pos):
    row = [0 for i in range(n)]
    col = [0 for i in range(n)]
    for i in range(k):
        row[pos[i][0] - 1] = 1
        col[pos[i][1] - 1] = 1
    res = n - k
    print(res)
    ri = 0
    ci = 0
    while (res > 0):
        while (row[ri] == 1):
            ri += 1
        while (col[ci] == 1):
            ci += 1
        print((ri + 1), (ci + 1))
        ri += 1
        ci += 1
        res -= 1


if __name__ == '__main__':
    N = 4
    K = 2
    pos = [[1, 4], [2, 2]]
    countRooks(N, K, pos)

# Expected output:
2
3 1
4 3
# minimum insertions to form a palindrome with permutations allowed | python3 program to find minimum number of insertions to make a string palindrome ; function will return number of characters to be added ; to store str1ing length ; to store number of characters occurring odd number of times ; to store count of each character ; to store occurrence of each character ; to count characters with odd occurrence ; as one character can be odd return res - 1 but if str1ing is already palindrome return 0 ; 

import math as mt


def minInsertion(tr1):
    n = len(str1)
    res = 0
    count = [0 for i in range(26)]
    for i in range(n):
        count[ord(str1[i]) - ord('a')] += 1
    for i in range(26):
        if (count[i] % 2 == 1):
            res += 1
    if (res == 0):
        return 0
    else:
        return res - 1


str1 = "geeksforgeeks"
print(minInsertion(str1))

# Expected output:
2
# generate a string which differs by only a single character from all given strings | function to check if a given string differs by a single character from all the strings in an array ; traverse over the strings ; stores the count of characters differing from the strings ; if differs by more than one character ; function to find the string which only differ at one position from the all given strings of the array ; size of the array ; length of a string ; replace i - th character by all possible characters ; check if it differs by a single character from all other strings ; if desired string is obtained ; print the answer ; 
def check(ans, s, n, m):
    for i in range(1, n):
        count = 0
        for j in range(m):
            if (ans[j] != s[i][j]):
                count += 1
        if (count > 1):
            return False
    return True


def findString(s):
    n = len(s)
    m = len(s[0])
    ans = s[0]
    flag = 0
    for i in range(m):
        for j in range(26):
            x = list(ans)
            x[i] = chr(j + ord('a'))
            if (check(x, s, n, m)):
                ans = x
                flag = 1
                break
        if (flag == 1):
            break
    if (flag == 0):
        return "-1"
    else:
        return ''.join(ans)


s = ["geeks", "teeds"]
print(findString(s))

# Expected output:
teeks
# minimum increments of non | function to return to the minimum number of operations required to make the array non - decreasing ; stores the count of operations ; if arr [ i ] > arr [ i + 1 ] , add arr [ i ] - arr [ i + 1 ] to the answer otherwise , add 0 ; 
def getMinOps(arr):
    ans = 0
    for i in range(len(arr) - 1):
        ans += max(arr[i] - arr[i + 1], 0)
    return ans


arr = [1, 3, 1, 2, 4]
print(getMinOps(arr))

# Expected output:
2
# maximum difference between frequency of two elements such that element having greater frequency is also greater | python program to find maximum difference between frequency of any two element such that element with greater frequency is also greater in value . ; return the maximum difference between frequencies of any two elements such that element with greater frequency is also greater in value . ; finding the frequency of each element . ; finding difference such that element having greater frequency is also greater in value . ; 

from collections import defaultdict


def maxdiff(arr, n):
    freq = defaultdict(lambda: 0)
    for i in range(n):
        freq[arr[i]] += 1
    ans = 0
    for i in range(n):
        for j in range(n):
            if freq[arr[i]] > freq[arr[j]] and arr[i] > arr[j]:
                ans = max(ans, freq[arr[i]] - freq[arr[j]])
            elif freq[arr[i]] < freq[arr[j]] and arr[i] < arr[j]:
                ans = max(ans, freq[arr[j]] - freq[arr[i]])
    return ans


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

# Expected output:
2
# maximum difference between frequency of two elements such that element having greater frequency is also greater | return the maximum difference between frequencies of any two elements such that element with greater frequency is also greater in value . ; finding the frequency of each element . ; sorting the distinct element ; iterate through all sorted distinct elements . for each distinct element , maintaining the element with minimum frequency than that element and also finding the maximum frequency difference ; 
def maxdiff(arr, n):
    freq = {}
    dist = [0] * n
    j = 0
    for i in range(n):
        if (arr[i]not in freq):
            dist[j] = arr[i]
            j += 1
            freq[arr[i]] = 0
        if (arr[i] in freq):
            freq[arr[i]] += 1
    dist = sorted(dist[:j])
    min_freq = n + 1
    ans = 0
    for i in range(j):
        cur_freq = freq[dist[i]]
        ans = max(ans, cur_freq - min_freq)
        min_freq = min(min_freq, cur_freq)
    return ans


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

# Expected output:
2
# maximum sum possible by selecting x elements from a matrix based on given conditions | python3 program to implement the above approach ; function to calculate the maximum possible sum by selecting x elements from the matrix ; generate prefix sum of the matrix ; initialize [ , ] dp ; maximum possible sum by selecting 0 elements from the first i rows ; if a single row is present ; if elements from the current row is not selected ; iterate over all possible selections from current row ; return maximum possible sum ; 

import sys


def maxSum(grid):
    prefsum = [[0 for x in range(m)]for y in range(m)]
    for i in range(n):
        for x in range(m):
            if (x == 0):
                prefsum[i][x] = grid[i][x]
            else:
                prefsum[i][x] = (prefsum[i][x - 1] + grid[i][x])
    dp = [[-sys .maxsize - 1 for x in range(X + 1)]for y in range(n)]
    for i in range(n):
        dp[i][0] = 0
    for i in range(1, min(m, X)):
        dp[0][i] = (dp[0][i - 1] + grid[0][i - 1])
    for i in range(1, n):
        for j in range(1, X + 1):
            dp[i][j] = dp[i - 1][j]
            for x in range(1, min(j, m) + 1):
                dp[i][j] = max(dp[i][j], dp[i - 1][j - x] + prefsum[i][x - 1])
    return dp[n - 1][X]


if __name__ == "__main__":
    n = 4
    m = 4
    X = 6
    grid = [[3, 2, 6, 1], [1, 9, 2, 4], [4, 1, 3, 9], [3, 8, 2, 1]]
    ans = maxSum(grid)
    print(ans)

# Expected output:
28
# difference between highest and least frequencies in an array | python3 code to find the difference between highest nd least frequencies ; sort the array ; checking consecutive elements ; 
def findDiff(arr, n):
    arr .sort()
    count = 0
    max_count = 0
    min_count = n
    for i in range(0, (n - 1)):
        if arr[i] == arr[i + 1]:
            count += 1
            continue
        else:
            max_count = max(max_count, count)
            min_count = min(min_count, count)
            count = 0
    return max_count - min_count


arr = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]
n = len(arr)
print(findDiff(arr, n))

# Expected output:
2
# minimum decrements on subarrays required to reduce all array elements to zero | function to count the minimum number of subarrays that are required to be decremented by 1 ; base case ; initializing ans to first element ; for a [ i ] > a [ i - 1 ] , operation ( a [ i ] - a [ i - 1 ] ) is required ; return the count ; 
def min_operations(A):
    if len(A) == 0:
        return 0
    ans = A[0]
    for i in range(1, len(A)):
        if A[i] > A[i - 1]:
            ans += A[i] - A[i - 1]
    return ans


A = [1, 2, 3, 2, 1]
print(min_operations(A))

# Expected output:
3
# difference between highest and least frequencies in an array | python code to find the difference between highest and least frequencies ; put all elements in a hash map ; find counts of maximum and minimum frequent elements ; 

from collections import defaultdict


def findDiff(arr, n):
    mp = defaultdict(lambda: 0)
    for i in range(n):
        mp[arr[i]] += 1
    max_count = 0
    min_count = n
    for key, values in mp .items():
        max_count = max(max_count, values)
        min_count = min(min_count, values)
    return max_count - min_count


arr = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]
n = len(arr)
print(findDiff(arr, n))

# Expected output:
2
# count of n | function to calculate the total count of n - digit numbers such that the sum of digits at even positions and odd positions are divisible by a and b respectively ; for single digit numbers ; largest possible number ; count of possible odd digits ; count of possible even digits ; calculate total count of sequences of length even_count with sum divisible by a where first digit can be zero ; calculate total count of sequences of length odd_count with sum divisible by b where cannot be zero ; return their product as answer ; 
def count(N, A, B):
    if (N == 1):
        return 9 // B + 1
    max_sum = 9 * N
    odd_count = N // 2 + N % 2
    even_count = N - odd_count
    dp = [[0 for x in range(max_sum + 1)]for y in range(even_count)]
    for i in range(10):
        dp[0][i % A] += 1
    for i in range(1, even_count):
        for j in range(10):
            for k in range(max_sum + 1):
                if (dp[i - 1][k] > 0):
                    dp[i][(j + k) % A] += dp[i - 1][k]
    dp1 = [[0 for x in range(max_sum)]for y in range(odd_count)]
    for i in range(1, 10):
        dp1[0][i % B] += 1
    for i in range(1, odd_count):
        for j in range(10):
            for k in range(max_sum + 1):
                if (dp1[i - 1][k] > 0):
                    dp1[i][(j + k) % B] += dp1[i - 1][k]
    return dp[even_count - 1][0] * dp1[odd_count - 1][0]


if __name__ == "__main__":
    N = 2
    A = 2
    B = 5
    print(count(N, A, B))

# Expected output:
5
# maximum possible difference of two subsets of an array | python3 find maximum difference of subset sum ; function for maximum subset diff ; if frequency of any element is two make both equal to zero ; 

import math


def maxDiff(arr, n):
    SubsetSum_1 = 0
    SubsetSum_2 = 0
    for i in range(0, n):
        isSingleOccurance = True
        for j in range(i + 1, n):
            if (arr[i] == arr[j]):
                isSingleOccurance = False
                arr[i] = arr[j] = 0
                break
        if (isSingleOccurance):
            if (arr[i] > 0):
                SubsetSum_1 += arr[i]
            else:
                SubsetSum_2 += arr[i]
    return abs(SubsetSum_1 - SubsetSum_2)


arr = [4, 2, -3, 3, -2, -2, 8]
n = len(arr)
print("Maximum Difference = {}".format(maxDiff(arr, n)))

# Expected output:
Maximum Difference = 20
# largest possible value of m not exceeding n having equal bitwise or and xor between them | python3 program to implement the above approach ; function to find required number m ; initialising m ; finding the index of the most significant bit of n ; calculating required number ; 

from math import log2


def equalXORandOR(n):
    m = 0
    MSB = int(log2(n))
    for i in range(MSB + 1):
        if (not (n & (1 << i))):
            m += (1 << i)
    return m


n = 14
print(equalXORandOR(n))

# Expected output:
1
# maximum possible difference of two subsets of an array | function for maximum subset diff ; sort the array ; calculate the result ; check for last element ; return result ; 
def maxDiff(arr, n):
    result = 0
    arr .sort()
    for i in range(n - 1):
        if (abs(arr[i]) != abs(arr[i + 1])):
            result += abs(arr[i])
        else:
            pass
    if (arr[n - 2] != arr[n - 1]):
        result += abs(arr[n - 1])
    return result


if __name__ == "__main__":
    arr = [4, 2, -3, 3, -2, -2, 8]
    n = len(arr)
    print("Maximum Difference = ", maxDiff(arr, n))

# Expected output:
Maximum Difference =  20
# count of palindromic strings possible by swapping of a pair of characters | function to return the count of possible palindromic strings ; stores the frequencies of each character ; stores the length of the string ; increase the number of swaps , the current character make with its previous occurrences ; increase frequency ; 
def findNewString(s):
    ans = 0
    freq = [0] * 26
    n = len(s)
    for i in range(n):
        ans += freq[ord(s[i]) - ord('a')]
        freq[ord(s[i]) - ord('a')] += 1
    return ans


s = "aaabaaa"
print(findNewString(s))

# Expected output:
15
# maximum possible difference of two subsets of an array | function for maximum subset diff ; construct hash for positive elements ; calculate subset sum for positive elements ; construct hash for negative elements ; calculate subset sum for negative elements ; 
def maxDiff(arr, n):
    hashPositive = dict()
    hashNegative = dict()
    SubsetSum_1, SubsetSum_2 = 0, 0
    for i in range(n):
        if (arr[i] > 0):
            hashPositive[arr[i]] = hashPositive .get(arr[i], 0) + 1
    for i in range(n):
        if (arr[i] > 0 and arr[i] in hashPositive .keys()
                and hashPositive[arr[i]] == 1):
            SubsetSum_1 += arr[i]
    for i in range(n):
        if (arr[i] < 0):
            hashNegative[abs(arr[i])] = hashNegative .get(abs(arr[i]), 0) + 1
    for i in range(n):
        if (arr[i] < 0 and abs(arr[i]) in hashNegative .keys()
                and hashNegative[abs(arr[i])] == 1):
            SubsetSum_2 += arr[i]
    return abs(SubsetSum_1 - SubsetSum_2)


arr = [4, 2, -3, 3, -2, -2, 8]
n = len(arr)
print("Maximum Difference =", maxDiff(arr, n))

# Expected output:
Maximum Difference = 20
# change the given string according to the given conditions | function to proofread the spells ; loop to iterate over the characters of the string ; push the current character c in the stack ; check for rule 1 ; check for rule 2 ; to store the resultant string ; loop to iterate over the characters of stack ; return the resultant string ; 
def proofreadSpell(str):
    result = []
    for c in str:
        result .append(c)
        n = len(result)
        if (n >= 3):
            if (result[n - 1] == result[n - 2]
                    and result[n - 1] == result[n - 3]):
                result .pop()
        n = len(result)
        if (n >= 4):
            if (result[n - 1] == result[n - 2]
                    and result[n - 3] == result[n - 4]):
                result .pop()
    resultStr = ""
    for c in result:
        resultStr += c
    return resultStr


str = "hello"
print(proofreadSpell(str))

# Expected output:
hello
# smallest subarray with k distinct numbers | prints the minimum range that contains exactly k distinct numbers . ; consider every element as starting point . ; find the smallest window starting with arr [ i ] and containing exactly k distinct elements . ; there are less than k distinct elements now , so no need to continue . ; if there was no window with k distinct elements ( k is greater than total distinct elements ) ; 
def minRange(arr, n, k):
    l = 0
    r = n
    for i in range(n):
        s = []
        for j in range(i, n):
            s .append(arr[j])
            if (len(s) == k):
                if ((j - i) < (r - l)):
                    r = j
                    l = i
                break
        if (j == n):
            break
    if (l == 0 and r == n):
        print("Invalid k")
    else:
        print(l, r)


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

# Expected output:
0 2
# smallest subarray with k distinct numbers | python3 program to find the minimum range that contains exactly k distinct numbers . ; prints the minimum range that contains exactly k distinct numbers . ; initially left and right side is - 1 and - 1 , number of distinct elements are zero and range is n . ; initialize right side ; increment right side . ; if number of distinct elements less than k . ; if distinct elements are equal to k and length is less than previous length . ; if number of distinct elements less than k , then break . ; if distinct elements equals to k then try to increment left side . ; increment left side . ; it is same as explained in above loop . ; 

from collections import defaultdict


def minRange(arr, n, k):
    l, r = 0, n
    i = 0
    j = -1
    hm = defaultdict(lambda: 0)
    while i < n:
        while j < n:
            j += 1
            if len(hm) < k and j < n:
                hm[arr[j]] += 1
            if len(hm) == k and ((r - l) >= (j - i)):
                l, r = i, j
                break
        if len(hm) < k:
            break
        while len(hm) == k:
            if hm[arr[i]] == 1:
                del (hm[arr[i]])
            else:
                hm[arr[i]] -= 1
            i += 1
            if len(hm) == k and (r - l) >= (j - i):
                l, r = i, j
        if hm[arr[i]] == 1:
            del (hm[arr[i]])
        else:
            hm[arr[i]] -= 1
        i += 1
    if l == 0 and r == n:
        print("Invalid k")
    else:
        print(l, r)


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

# Expected output:
5 7
# sum of f ( a [ i ] , a [ j ] ) over all pairs in an array of n integers | function to calculate the sum ; map to keep a count of occurrences ; traverse in the list from start to end number of times a [ i ] can be in a pair and to get the difference we subtract pre_sum . ; if the ( a [ i ] - 1 ) is present then subtract that value as f ( a [ i ] , a [ i ] - 1 ) = 0 ; if the ( a [ i ] + 1 ) is present then add that value as f ( a [ i ] , a [ i ] - 1 ) = 0 here we add as a [ i ] - ( a [ i ] - 1 ) < 0 which would have been added as negative sum , so we add to remove this pair from the sum value ; keeping a counter for every element ; 
def sum(a, n):
    cnt = dict()
    ans = 0
    pre_sum = 0
    for i in range(n):
        ans += (i * a[i]) - pre_sum
        pre_sum += a[i]
        if (a[i] - 1) in cnt:
            ans -= cnt[a[i] - 1]
        if (a[i] + 1) in cnt:
            ans += cnt[a[i] + 1]
        if a[i]not in cnt:
            cnt[a[i]] = 0
        cnt[a[i]] += 1
    return ans


if __name__ == '__main__':
    a = [1, 2, 3, 1, 3]
    n = len(a)
    print(sum(a, n))

# Expected output:
4
# minimum distance between the maximum and minimum element of a given array | python3 program to implement the above approach ; function to find the minimum distance between the minimum and the maximum element ; stores the minimum and maximum array element ; stores the most recently traversed indices of the minimum and the maximum element ; stores the minimum distance between the minimum and the maximium ; find the maximum and the minimum element from the given array ; find the minimum distance ; check if current element is equal to minimum ; check if current element is equal to maximum ; if both the minimum and the maximum element has occurred at least once ; 

import sys


def minDistance(a, n):
    maximum = -1
    minimum = sys .maxsize
    min_index = -1
    max_index = -1
    min_dist = n + 1
    for i in range(n):
        if (a[i] > maximum):
            maximum = a[i]
        if (a[i] < minimum):
            minimum = a[i]
    for i in range(n):
        if (a[i] == minimum):
            min_index = i
        if (a[i] == maximum):
            max_index = i
        if (min_index != -1 and max_index != -1):
            min_dist = (min(min_dist, abs(min_index - max_index)))
    return min_dist


if __name__ == "__main__":
    a = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2]
    n = len(a)
    print(minDistance(a, n))

# Expected output:
3
# kth diagonal from the top left of a given matrix | function returns required diagonal ; initialize values to prupper diagonals ; initialize values to print lower diagonals ; traverse the diagonals ; print its contents ; 
def printDiagonal(K, N, M):
    startrow, startcol = 0, 0
    if K - 1 < N:
        startrow = K - 1
        startcol = 0
    else:
        startrow = N - 1
        startcol = K - N
    while startrow >= 0 and startcol < N:
        print(M[startrow][startcol], end=" ")
        startrow -= 1
        startcol += 1


if __name__ == '__main__':
    N, K = 3, 4
    M = [[4, 7, 8], [9, 2, 3], [0, 4, 1]]
    printDiagonal(K, N, M)

# Expected output:
4 3
# longest substring that starts with x and ends with y | function returns length of longest substring starting with x and ending with y ; length of string ; find the length of the string starting with x from the beginning ; find the length of the string ending with y from the end ; longest substring ; print the length ; 
def longestSubstring(str, X, Y):
    N = len(str)
    start = 0
    end = N - 1
    xPos = 0
    yPos = 0
    while (True):
        if (str[start] == X):
            xPos = start
            break
        start += 1
    while (True):
        if (str[end] == Y):
            yPos = end
            break
        end -= 1
    length = (yPos - xPos) + 1
    print(length)


if __name__ == "__main__":
    str = "HASFJGHOGAKZZFEGA"
    X = 'A'
    Y = 'Z'
    longestSubstring(str, X, Y)

# Expected output:
12
# find parent of given node in a binary tree with given postorder traversal | python implementation to find the parent of the given node ; function to find the parent of the given node ; check whether the given node is a root node . if it is then return - 1 because root node has no parent ; loop till we found the given node ; find the middle node of the tree because at every level tree parent is divided into two halves ; if the node is found return the parent always the child nodes of every node is node / 2 or ( node - 1 ) ; if the node to be found is greater than the mid search for left subtree else search in right subtree ; 

import math


def findParent(height, node):
    start = 1
    end = pow(2, height) - 1
    if (end == node):
        return -1
    while (node >= 1):
        end = end - 1
        mid = start + (end - start) // 2
        if (mid == node or end == node):
            return (end + 1)
        elif (node < mid):
            end = mid
        else:
            start = mid


if __name__ == "__main__":
    height = 4
    node = 6
    k = findParent(height, node)
    print(k)

# Expected output:
7
# replace every element with the smallest of the others | python3 code for the above approach . ; there should be atleast two elements ; if current element is smaller than firstsmallest then update both firstsmallest and secondsmallest ; if arr [ i ] is in between firstsmallest and secondsmallest then update secondsmallest ; replace every element by smallest of all other elements ; print the modified array . ; 
def ReplaceElements(arr, n):
    if (n < 2):
        print("Invalid Input")
        return
    firstSmallest = 10 ** 18
    secondSmallest = 10 ** 18
    for i in range(n):
        if (arr[i] < firstSmallest):
            secondSmallest = firstSmallest
            firstSmallest = arr[i]
        elif (arr[i] < secondSmallest and arr[i] != firstSmallest):
            secondSmallest = arr[i]
    for i in range(n):
        if (arr[i] != firstSmallest):
            arr[i] = firstSmallest
        else:
            arr[i] = secondSmallest
    for i in arr:
        print(i, end=", ")


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

# Expected output:
1, 1, 2, 1,