giulio98/xlcost-single-prompt huggingface dataset:
# partition a set into two subsets such that difference between max of one and min of other is minimized | function to split the array ; sort the array in increasing order ; calculating the max difference between consecutive elements ; return the final minimum difference ; 
def splitArray(arr, N):
    arr = sorted(arr)
    result = 10 ** 9
    for i in range(1, N):
        result = min(result, arr[i] - arr[i - 1])
    return result


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

# Expected output:
1
# find the element at r ' th ▁ row ▁ and ▁ c ' th column in given a 2d pattern | function to find the r ' th ▁ row ▁ and ▁ c ' th column value in the given pattern ; first element of a given row ; element in the given column ; 
def findValue(R, C):
    k = (R * (R - 1)) // 2 + 1
    diff = R + 1
    for i in range(1, C):
        k = (k + diff)
        diff += 1
    return k


if __name__ == "__main__":
    R = 4
    C = 4
    k = findValue(R, C)
    print(k)

# Expected output:
25
# maximize number of groups formed with size not smaller than its largest element | function that prints the number of maximum groups ; store the number of occurrence of elements ; make all groups of similar elements and store the left numbers ; condition for finding first leftover element ; condition for current leftover element ; condition if group size is equal to or more than current element ; printing maximum number of groups ; 
def makeGroups(a, n):
    v = [0] * (n + 1)
    for i in range(n):
        v[a[i]] += 1
    no_of_groups = 0
    for i in range(1, n + 1):
        no_of_groups += v[i] // i
        v[i] = v[i] % i
    i = 1
    total = 0
    for i in range(1, n + 1):
        if (v[i] != 0):
            total = v[i]
            break
    i += 1
    while (i <= n):
        if (v[i] != 0):
            total += v[i]
            if (total >= i):
                rem = total - i
                no_of_groups += 1
                total = rem
        i += 1
    print(no_of_groups)


if __name__ == "__main__":
    arr = [2, 3, 1, 2, 2]
    size = len(arr)
    makeGroups(arr, size)

# Expected output:
2
# leftmost column with atleast one 1 in a row | python3 program to calculate leftmost column having at least a 1 ; function return leftmost column having at least a 1 ; if current element is 1 decrement column by 1 ; if current element is 0 increment row by 1 ; 

N = 3
M = 4


def findColumn(mat: list) -> int:
    row = 0
    col = M - 1
    while row < N and col >= 0:
        if mat[row][col] == 1:
            col -= 1
            flag = 1
        else:
            row += 1
    col += 1
    if flag:
        return col + 1
    else:
        return -1


if __name__ == "__main__":
    mat = [[0, 0, 0, 1], [0, 1, 1, 1], [0, 0, 1, 1]]
    print(findColumn(mat))

# Expected output:
2
# find two numbers made up of a given digit such that their difference is divisible by n | function to implement the above approach ; hashmap to store remainder - length of the number as key - value pairs ; iterate till n + 1 length ; search remainder in the map ; if remainder is not already present insert the length for the corresponding remainder ; keep increasing m ; to keep m in range of integer ; length of one number is the current length ; length of the other number is the length paired with current remainder in map ; 
def findNumbers(N, M):
    m = M
    remLen = {}
    for len1 in range(1, N + 1, 1):
        remainder = M % N
        if (remLen .get(remainder) is None):
            remLen[remainder] = len1
        else:
            break
        M = M * 10 + m
        M = M % N
    LenA = len1
    LenB = remLen[remainder]
    for i in range(LenB):
        print(m, end="")
    print(" ", end="")
    for i in range(LenA):
        print(m, end="")
    return


if __name__ == '__main__':
    N = 8
    M = 2
    findNumbers(N, M)

# Expected output:
22 222
# number of ways to select equal sized subarrays from two arrays having atleast k equal pairs of elements | 2d prefix sum for submatrix sum query for matrix ; function to find the prefix sum of the matrix from i and j ; function to count the number of ways to select equal sized subarrays such that they have atleast k common elements ; combining the two arrays ; calculating the 2d prefix sum ; iterating through all the elements of matrix and considering them to be the bottom right ; applying binary search over side length ; if sum of this submatrix >= k then new search space will be [ low , mid ] ; else new search space will be [ mid + 1 , high ] ; adding the total submatrices ; 

prefix_2D = [[0 for x in range(2005)]for y in range(2005)]


def subMatrixSum(i, j, length):
    return (prefix_2D[i][j] - prefix_2D[i][j - length] -
            prefix_2D[i - length][j] + prefix_2D[i - length][j - length])


def numberOfWays(a, b, n, m, k):
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if (a[i - 1] == b[j - 1]):
                prefix_2D[i][j] = 1
            else:
                prefix_2D[i][j] = 0
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            prefix_2D[i][j] += prefix_2D[i][j - 1]
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            prefix_2D[i][j] += prefix_2D[i - 1][j]
    answer = 0
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            low = 1
            high = min(i, j)
            while (low < high):
                mid = (low + high) >> 1
                if (subMatrixSum(i, j, mid) >= k):
                    high = mid
                else:
                    low = mid + 1
            if (subMatrixSum(i, j, low) >= k):
                answer += (min(i, j) - low + 1)
    return answer


if __name__ == "__main__":
    N = 2
    M = 3
    A = [1, 2]
    B = [1, 2, 3]
    K = 1
    print(numberOfWays(A, B, N, M, K))

# Expected output:
4
# find lexicographically smallest string in at most one swaps | function to return the lexicographically smallest string that can be formed by swapping at most one character . the characters might not necessarily be adjacent . ; set - 1 as default for every character . ; character index to fill in the last occurrence array ; if this is true then this character is being visited for the first time from the last thus last occurrence of this character is stored in this index ; character to replace ; find the last occurrence of this character . ; swap this with the last occurrence swap ( s [ i ] , s [ last_occ ] ) ; ; 
def findSmallest(s):
    length = len(s)
    loccur = [-1] * 26
    for i in range(length - 1, -1, -1):
        chI = ord(s[i]) - ord('a')
        if (loccur[chI] == -1):
            loccur[chI] = i
    sorted_s = s
    sorted_s .sort()
    for i in range(length):
        if (s[i] != sorted_s[i]):
            chI = ord(sorted_s[i]) - ord('a')
            last_occ = loccur[chI]
            s[i], s[last_occ] = s[last_occ], s[i]
            break
    return "".join(s)


if __name__ == "__main__":
    s = "geeks"
    print(findSmallest(list(s)))

# Expected output:
eegks
# maximum size of square such that all submatrices of that size have sum less than k | function to preprocess the matrix for computing the sum of every possible matrix of the given size ; loop to copy the first row of the matrix into the aux matrix ; computing the sum column - wise ; computing row wise sum ; function to find the sum of a submatrix with the given indices ; overall sum from the top to right corner of matrix ; removing the sum from the top corer of the matrix ; remove the overlapping sum ; add the sum of top corner which is subtracted twice ; function to check whether square sub matrices of size mid satisfy the condition or not ; iterating throught all possible submatrices of given size ; function to find the maximum square size possible with the such that every submatrix have sum less than the given sum ; search space ; binary search for size ; check if the mid satisfies the given condition ; 
def preProcess(mat, aux):
    for i in range(5):
        aux[0][i] = mat[0][i]
    for i in range(1, 4):
        for j in range(5):
            aux[i][j] = (mat[i][j] + aux[i - 1][j])
    for i in range(4):
        for j in range(1, 5):
            aux[i][j] += aux[i][j - 1]
    return aux


def sumQuery(aux, tli, tlj, rbi, rbj):
    res = aux[rbi][rbj]
    if (tli > 0):
        res = res - aux[tli - 1][rbj]
    if (tlj > 0):
        res = res - aux[rbi][tlj - 1]
    if (tli > 0 and tlj > 0):
        res = res + aux[tli - 1][tlj - 1]
    return res


def check(mid, aux, K):
    satisfies = True
    for x in range(4):
        for y in range(5):
            if (x + mid - 1 <= 4 - 1 and y + mid - 1 <= 5 - 1):
                if (sumQuery(aux, x, y, x + mid - 1, y + mid - 1) > K):
                    satisfies = False
    return True if satisfies else False


def maximumSquareSize(mat, K):
    aux = [[0 for i in range(5)]for i in range(4)]
    aux = preProcess(mat, aux)
    low, high = 1, min(4, 5)
    mid = 0
    while (high - low > 1):
        mid = (low + high) // 2
        if (check(mid, aux, K)):
            low = mid
        else:
            high = mid
    if (check(high, aux, K)):
        return high
    return low


if __name__ == '__main__':
    K = 30
    mat = [[1, 2, 3, 4, 6], [5, 3, 8, 1, 2], [4, 6, 7, 5, 5], [2, 4, 8, 9, 4]]
    print(maximumSquareSize(mat, K))

# Expected output:
2
# count of numbers from range [ l , r ] that end with any of the given digits | function to return the count of the required numbers ; last digit of the current number ; if the last digit is equal to any of the given digits ; 
def countNums(l, r):
    cnt = 0
    for i in range(l, r + 1):
        lastDigit = (i % 10)
        if ((lastDigit %
             10) == 2 or (lastDigit %
                          10) == 3 or (lastDigit %
                                       10) == 9):
            cnt += 1
    return cnt


if __name__ == "__main__":
    l = 11
    r = 33
    print(countNums(l, r))

# Expected output:
8
# minimum k such that sum of array elements after division by k does not exceed s | function to return the minimum value of k that satisfies the given condition ; find the maximum element ; lowest answer can be 1 and the highest answer can be ( maximum + 1 ) ; binary search ; get the mid element ; calculate the sum after dividing the array by new k which is mid ; search in the second half ; first half ; 
def findMinimumK(a, n, s):
    maximum = a[0]
    for i in range(n):
        maximum = max(maximum, a[i])
    low = 1
    high = maximum + 1
    ans = high
    while (low <= high):
        mid = (low + high) // 2
        sum = 0
        for i in range(n):
            sum += (a[i] // mid)
        if (sum > s):
            low = mid + 1
        else:
            ans = min(ans, mid)
            high = mid - 1
    return ans


a = [10, 7, 8, 10, 12, 19]
n = len(a)
s = 27
print(findMinimumK(a, n, s))

# Expected output:
3
# calculate the sum of gcd over all subarrays | python3 program to find sum of gcd over all subarrays ;  ; build sparse table ; building the sparse table for gcd [ l , r ] queries ; utility function to calculate gcd in range [ l , r ] ; calculating where the answer is stored in our sparse table ; utility function to find next - farther position where gcd is same ; binarysearch for next position for endpointer ; utility function to calculate sum of gcd ; initializing all the values ; finding the next position for endpointer ; adding the suitable sum to our answer ; changing prevendpointer ; recalculating tempgcd ; 

from math import gcd as __gcd, log, floor

SparseTable = [[0 for i in range(51)]for i in range(100001)]


def buildSparseTable(a, n):
    for i in range(n):
        SparseTable[i][0] = a[i]
    for j in range(1, 20):
        for i in range(n - (1 << j) + 1):
            SparseTable[i][j] = __gcd(
                SparseTable[i][j - 1], SparseTable[i + (1 << (j - 1))][j - 1])


def queryForGCD(L, R):
    j = floor(log(R - L + 1, 2))
    returnValue = __gcd(SparseTable[L][j], SparseTable[R - (1 << j) + 1][j])
    return returnValue


def nextPosition(tempGCD, startPointer, prevEndPointer, n):
    high = n - 1
    low = prevEndPointer
    mid = prevEndPointer
    nextPos = prevEndPointer
    while (high >= low):
        mid = ((high + low) >> 1)
        if (queryForGCD(startPointer, mid) == tempGCD):
            nextPos = mid
            low = mid + 1
        else:
            high = mid - 1
    return nextPos + 1


def calculateSum(a, n):
    buildSparseTable(a, n)
    tempAns = 0
    for i in range(n):
        endPointer = i
        startPointer = i
        prevEndPointer = i
        tempGCD = a[i]
        while (endPointer < n):
            endPointer = nextPosition(tempGCD, startPointer, prevEndPointer, n)
            tempAns += ((endPointer - prevEndPointer) * tempGCD)
            prevEndPointer = endPointer
            if (endPointer < n):
                tempGCD = __gcd(tempGCD, a[endPointer])
    return tempAns


if __name__ == '__main__':
    n = 6
    a = [2, 2, 2, 3, 5, 5]
    print(calculateSum(a, n))

# Expected output:
41
# quickselect ( a simple iterative implementation ) | standard lomuto partition function ; implementation of quickselect ; partition a [ left . . right ] around a pivot and find the position of the pivot ; if pivot itself is the k - th smallest element ; if there are more than k - 1 elements on left of pivot , then k - th smallest must be on left side . ; else k - th smallest is on right side . ; 
def partition(arr, low, high):
    pivot = arr[high]
    i = (low - 1)
    for j in range(low, high):
        if arr[j] <= pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return (i + 1)


def kthSmallest(a, left, right, k):
    while left <= right:
        pivotIndex = partition(a, left, right)
        if pivotIndex == k - 1:
            return a[pivotIndex]
        elif pivotIndex > k - 1:
            right = pivotIndex - 1
        else:
            left = pivotIndex + 1
    return -1


arr = [10, 4, 5, 8, 11, 6, 26]
n = len(arr)
k = 5
print("K-th smallest element is", kthSmallest(arr, 0, n - 1, k))

# Expected output:
K-th smallest element is 10
# pair with largest sum which is less than k in the array | function to find pair with largest sum which is less than k in the array ; to store the break point ; sort the given array ; find the break point ; no need to look beyond i 'th index ; find the required pair ; print the required answer ; 
def Max_Sum(arr, n, k):
    p = n
    arr .sort()
    for i in range(0, n):
        if (arr[i] >= k):
            p = i
            break
    maxsum = 0
    a = 0
    b = 0
    for i in range(0, p):
        for j in range(i + 1, p):
            if (arr[i] + arr[j] < k and arr[i] + arr[j] > maxsum):
                maxsum = arr[i] + arr[j]
                a = arr[i]
                b = arr[j]
    print(a, b)


arr = [5, 20, 110, 100, 10]
k = 85
n = len(arr)
Max_Sum(arr, n, k)

# Expected output:
10 20
# maximum length palindromic substring such that it starts and ends with given char | function that returns true if str [ i ... j ] is a palindrome ; function to return the length of the longest palindromic sub - string such that it starts and ends with the character ch ; if current character is a valid starting index ; instead of finding the ending index from the beginning , find the index from the end this is because if the current sub - string is a palindrome then there is no need to check the sub - strings of smaller length and we can skip to the next iteration of the outer loop ; if current character is a valid ending index ; if str [ i ... j ] is a palindrome then update the length of the maximum palindrome so far ; 
def isPalindrome(str, i, j):
    while (i < j):
        if (str[i] != str[j]):
            return False
        i += 1
        j -= 1
    return True


def maxLenPalindrome(str, n, ch):
    maxLen = 0
    for i in range(n):
        if (str[i] == ch):
            for j in range(n - 1, i + 1, -1):
                if (str[j] == ch):
                    if (isPalindrome(str, i, j)):
                        maxLen = max(maxLen, j - i + 1)
                        break
    return maxLen


str = "lapqooqpqpl"
n = len(str)
ch = 'p'
print(maxLenPalindrome(str, n, ch))

# Expected output:
6
# longest sub | function to find the starting and the ending index of the sub - array with equal number of alphabets and numeric digits ; if its an alphabet ; else its a number ; pick a starting poas i ; consider all sub - arrays starting from i ; if this is a 0 sum sub - array then compare it with maximum size sub - array calculated so far ; if no valid sub - array found ; 
def findSubArray(arr, n):
    sum = 0
    maxsize = -1
    startindex = 0
    for i in range(n):
        if (arr[i].isalpha()):
            arr[i] = 0
        else:
            arr[i] = 1
    for i in range(n - 1):
        if arr[i] == '1':
            sum = 1
        else:
            sum = -1
        for j in range(i + 1, n):
            if arr[j] == 0:
                sum -= 1
            else:
                sum += 1
            if (sum == 0 and maxsize < j - i + 1):
                maxsize = j - i + 1
                startindex = i
    if (maxsize == -1):
        print(maxsize, end=" ")
    else:
        print(startindex, (startindex + maxsize - 1))


arr = ['A', 'B', 'X', '4', '6', 'X', 'a']
size = len(arr)
findSubArray(arr, size)

# Expected output:
1 4
# check if given string can be formed by two other strings or their permutations | python 3 implementation of the approach ; function to sort the given string using counting sort ; array to store the count of each character ; insert characters in the string in increasing order ; function that returns true if str can be generated from any permutation of the two strings selected from the given vector ; sort the given string ; select two strings at a time from given vector ; get the concatenated string ; sort the resultant string ; if the resultant string is equal to the given string str ; no valid pair found ; 

MAX = 26


def countingsort(s):
    count = [0 for i in range(MAX)]
    for i in range(len(s)):
        count[ord(s[i]) - ord('a')] += 1
    index = 0
    for i in range(MAX):
        j = 0
        while (j < count[i]):
            s = s .replace(s[index], chr(97 + i))
            index += 1
            j += 1


def isPossible(v, str1):
    countingsort(str1)
    for i in range(len(v) - 1):
        for j in range(i + 1, len(v), 1):
            temp = v[i] + v[j]
            countingsort(temp)
            if (temp == str1):
                return False
    return True


if __name__ == '__main__':
    str1 = "amazon"
    v = ["fds", "oxq", "zoa", "epw", "amn"]
    if (isPossible(v, str1)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# length of the largest substring which have character with frequency greater than or equal to half of the substring | python3 implementation of the above approach ; function to return the length of the longest sub string having frequency of a character greater than half of the length of the sub string ; for each of the character ' a ' to 'z ; finding frequency prefix array of the character ; finding the r [ ] and l [ ] arrays . ; for each j from 0 to n ; finding the lower bound of i . ; storing the maximum value of i - j + 1 ; clearing all the vector so that it can be used for other characters . ; 

import sys


def maxLength(s, n):
    ans = -(sys .maxsize + 1)
    A, L, R = [], [], []
    freq = [0] * (n + 5)

    for i in range(26):
        count = 0
        for j in range(n):
            if (ord(s[j]) - ord('a') == i):
                count += 1
            freq[j] = count
        for j in range(n):
            L .append((2 * freq[j - 1]) - j)
            R .append((2 * freq[j]) - j)
        max_len = -(sys .maxsize + 1)
        min_val = sys .maxsize
        for j in range(n):
            min_val = min(min_val, L[j])
            A .append(min_val)
            l = 0
            r = j
            while (l <= r):
                mid = (l + r) >> 1
                if (A[mid] <= R[j]):
                    max_len = max(max_len, j - mid + 1)
                    r = mid - 1
                else:
                    l = mid + 1
        ans = max(ans, max_len)
        A .clear()
        R .clear()
        L .clear()
    return ans


if __name__ == "__main__":
    s = "ababbbacbcbcca"
    n = len(s)
    print(maxLength(s, n))

# Expected output:
13
# repeated character whose first appearance is leftmost | python3 program to find first repeating character ; the function returns index of the first repeating character in a string . if all characters are repeating then returns - 1 ; mark all characters as not visited ; traverse from right and update res as soon as we see a visited character . ; 

NO_OF_CHARS = 256


def firstRepeating(string):
    visited = [False] * NO_OF_CHARS
    for i in range(NO_OF_CHARS):
        visited[i] = False
    res = -1
    for i in range(len(string) - 1, -1, -1):
        if (visited[string .index(string[i])] == False):
            visited[string .index(string[i])] = True
        else:
            res = i
    return res


if __name__ == "__main__":
    string = "geeksforgeeks"
    index = firstRepeating(string)
    if (index == -1):
        print("Either all characters are", "distinct or string is empty")
    else:
        print("First Repeating character is:", string[index])

# Expected output:
First Repeating character is: g
# find maximum sum taking every kth element in the array | function to return the maximum sum for every possible sequence such that a [ i ] + a [ i + k ] + a [ i + 2 k ] + ... + a [ i + qk ] is maximized ; initialize the maximum with the smallest value ; initialize the sum array with zero ; iterate from the right ; update the sum starting at the current element ; update the maximum so far ; 
def maxSum(arr, n, K):
    maximum = -2 ** 32
    sum = [0] * n
    for i in range(n - 1, -1, -1):
        if (i + K < n):
            sum[i] = sum[i + K] + arr[i]
        else:
            sum[i] = arr[i]
        maximum = max(maximum, sum[i])
    return maximum


arr = [3, 6, 4, 7, 2]
n = len(arr)
K = 2
print(maxSum(arr, n, K))

# Expected output:
13
# count common characters in two strings | function to return the count of valid indices pairs ; to store the frequencies of characters of string s1 and s2 ; to store the count of valid pairs ; update the frequencies of the characters of string s1 ; update the frequencies of the characters of string s2 ; find the count of valid pairs ; 
def countPairs(s1, n1, s2, n2):
    freq1 = [0] * 26
    freq2 = [0] * 26
    count = 0
    for i in range(n1):
        freq1[ord(s1[i]) - ord('a')] += 1
    for i in range(n2):
        freq2[ord(s2[i]) - ord('a')] += 1
    for i in range(26):
        count += min(freq1[i], freq2[i])
    return count


if __name__ == "__main__":
    s1 = "geeksforgeeks"
    s2 = "platformforgeeks"
    n1 = len(s1)
    n2 = len(s2)
    print(countPairs(s1, n1, s2, n2))

# Expected output:
8
# find a distinct pair ( x , y ) in given range such that x divides y | python 3 implementation of the approach ; 
def findpair(l, r):
    c = 0
    for i in range(l, r + 1):
        for j in range(i + 1, r + 1):
            if (j % i == 0 and j != i):
                print(i, ", ", j)
                c = 1
                break
        if (c == 1):
            break


if __name__ == "__main__":
    l = 1
    r = 10
    findpair(l, r)

# Expected output:
1 ,  2
# check if the given array can be reduced to zeros with the given operation performed given number of times | function that returns true if the array can be reduced to 0 s with the given operation performed given number of times ; set to store unique elements ; add every element of the array to the set ; count of all the unique elements in the array ; 
def check(arr, N, K):
    unique = dict()
    for i in range(N):
        unique[arr[i]] = 1
    if len(unique) == K:
        return True
    return False


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

# Expected output:
Yes