giulio98/xlcost-single-prompt huggingface dataset:
# maximum size square sub | function to find the maximum size of matrix with sum <= k ; n size of rows and m size of cols ; to store the prefix sum of matrix ; create prefix sum ; traverse each rows ; update the prefix sum till index i x j ; to store the maximum size of matrix with sum <= k ; traverse the sum matrix ; index out of bound ; maximum possible size of matrix ; binary search ; find middle index ; check whether sum <= k or not if yes check for other half of the search ; else check it in first half ; update the maximum size matrix ; print the final answer ; 
def findMaxMatrixSize(arr, K):
    n = len(arr)
    m = len(arr[0])
    sum = [[0 for i in range(m + 1)]for j in range(n + 1)]
    for i in range(n + 1):
        for j in range(m + 1):
            if (i == 0 or j == 0):
                sum[i][j] = 0
                continue
            sum[i][j] = arr[i - 1][j - 1] + sum[i - 1][j] + \
                sum[i][j - 1] - sum[i - 1][j - 1]
    ans = 0
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if (i + ans - 1 > n or j + ans - 1 > m):
                break
            mid = ans
            lo = ans
            hi = min(n - i + 1, m - j + 1)
            while (lo < hi):
                mid = (hi + lo + 1) // 2
                if (sum[i + mid - 1][j + mid - 1] + sum[i - 1][j - 1] -
                        sum[i + mid - 1][j - 1] - sum[i - 1][j + mid - 1] <= K):
                    lo = mid
                else:
                    hi = mid - 1
            ans = max(ans, lo)
    print(ans)


if __name__ == '__main__':
    arr = [[1, 1, 3, 2, 4, 3, 2], [1, 1, 3, 2, 4, 3, 2], [1, 1, 3, 2, 4, 3, 2]]
    K = 4
    findMaxMatrixSize(arr, K)

# Expected output:
2
# rank of all elements in a stream in descending order when they arrive | findrank function to find rank ; rank of first element is always 1 ; iterate over array ; as element let say its rank is 1 ; element is compared with previous elements ; if greater than previous than rank is incremented ; print rank ; 
def FindRank(arr, length):
    print(1, end=" ")
    for i in range(1, length):
        rank = 1
        for j in range(0, i):
            if (arr[j] > arr[i]):
                rank = rank + 1
        print(rank, end=" ")


if __name__ == '__main__':
    arr = [88, 14, 69, 30, 29, 89]
    length = len(arr)
    FindRank(arr, length)

# Expected output:
1 2 2 3 4 1
# longest permutation subsequence in a given array | program to find length of longest permutation subsequence in a given array ; function to find the longest permutation subsequence ; map data structure to count the frequency of each element ; if frequency of element is 0 , then we can not move forward as every element should be present ; increasing the length by one ; 

from collections import defaultdict


def longestPermutation(a, n):
    freq = defaultdict(int)
    for i in range(n):
        freq[a[i]] += 1
    length = 0
    for i in range(1, n + 1):
        if (freq[i] == 0):
            break
        length += 1
    return length


if __name__ == "__main__":
    arr = [3, 2, 1, 6, 5]
    n = len(arr)
    print(longestPermutation(arr, n))

# Expected output:
3
# count of numbers whose difference with fibonacci count upto them is atleast k | python 3 program to find the count of numbers whose difference with fibonacci count upto them is atleast k ; fibupto [ i ] denotes the count of fibonacci numbers upto i ; function to compute all the fibonacci numbers and update fibupto array ; store the first two fibonacci numbers ; compute the fibonacci numbers and store them in isfib array ; compute fibupto array ; function to return the count of valid numbers ; compute fibupto array ; binary search to find the minimum number that follows the condition ; check if the number is valid , try to reduce it ; ans is the minimum valid number ; 

MAX = 1000005
fibUpto = [0] * (MAX + 1)


def compute(sz):
    isFib = [False] * (sz + 1)
    prev = 0
    curr = 1
    isFib[prev] = True
    isFib[curr] = True
    while (curr <= sz):
        temp = curr + prev
        if (temp <= sz):
            isFib[temp] = True
        prev = curr
        curr = temp
    fibUpto[0] = 1
    for i in range(1, sz + 1):
        fibUpto[i] = fibUpto[i - 1]
        if (isFib[i]):
            fibUpto[i] += 1


def countOfNumbers(N, K):
    compute(N)
    low, high, ans = 1, N, 0
    while (low <= high):
        mid = (low + high) >> 1
        if (mid - fibUpto[mid] >= K):
            ans = mid
            high = mid - 1
        else:
            low = mid + 1
    if (ans):
        return (N - ans + 1)
    return 0


if __name__ == "__main__":
    N = 10
    K = 3
    print(countOfNumbers(N, K))

# Expected output:
2
# length of longest fibonacci subarray formed by removing only one element | python3 program to find length of the longest subarray with all fibonacci numbers ; function to create hash table to check for fibonacci numbers ; insert first two fibnonacci numbers ; summation of last two numbers ; update the variable each time ; function to find the longest fibonacci subarray ; find maximum value in the array ; creating a set containing fibonacci numbers ; left array is used to count number of continuous fibonacci numbers starting from left of current element ; check if current element is a fibonacci number ; right array is used to count number of continuous fibonacci numbers starting from right of current element ; check if current element is a fibonacci number ; 

N = 100000


def createHash(hash, maxElement):
    prev = 0
    curr = 1
    hash .add(prev)
    hash .add(curr)
    while (curr <= maxElement):
        temp = curr + prev
        hash .add(temp)
        prev = curr
        curr = temp


def longestFibSubarray(arr, n):
    max_val = max(arr)
    hash = {int}
    createHash(hash, max_val)
    left = [0 for i in range(n)]
    right = [0 for i in range(n)]
    fibcount = 0
    res = -1
    for i in range(n):
        left[i] = fibcount
        if (arr[i] in hash):
            fibcount += 1
        else:
            fibcount = 0
    fibcount = 0
    for i in range(n - 1, -1, -1):
        right[i] = fibcount
        if (arr[i] in hash):
            fibcount += 1
        else:
            fibcount = 0
    for i in range(0, n):
        res = max(res, left[i] + right[i])
    return res


arr = [2, 8, 5, 7, 3, 5, 7]
n = len(arr)
print(longestFibSubarray(arr, n))

# Expected output:
5
# minimum window size containing atleast p primes in every window of given range | python3 implementation to find the minimum window size in the range such that each window of that size contains atleast p primes ; function to check that a number is a prime or not in o ( sqrt ( n ) ) ; loop to check if any number number is divisible by any other number or not ; function to check whether window size satisfies condition or not ; loop to check each window of size have atleast p primes ; checking condition using prefix sum ; function to find the minimum window size possible for the given range in x and y ; prefix array ; mark those numbers which are primes as 1 ; convert to prefix sum ; applying binary search over window size ; check whether mid satisfies the condition or not ; if satisfies search in first half ; else search in second half ; 

from math import sqrt


def isPrime(N):
    if (N < 2):
        return False
    if (N < 4):
        return True
    if ((N & 1) == 0):
        return False
    if (N % 3 == 0):
        return False
    curr = 5
    s = sqrt(N)
    while (curr <= s):
        if (N % curr == 0):
            return False
        curr += 2
        if (N % curr == 0):
            return False
        curr += 4
    return True


def check(s, p, prefix_sum, n):
    satisfies = True
    for i in range(n):
        if (i + s - 1 >= n):
            break
        if (i - 1 >= 0):
            x = prefix_sum[i - 1]
        else:
            x = 0
        if (prefix_sum[i + s - 1] - x < p):
            satisfies = False
    return satisfies


def minimumWindowSize(x, y, p):
    prefix_sum = [0] * (y - x + 1)
    for i in range(x, y + 1):
        if (isPrime(i)):
            prefix_sum[i - x] = 1
    for i in range(1, y - x + 1):
        prefix_sum[i] += prefix_sum[i - 1]
    low = 1
    high = y - x + 1
    while (high - low > 1):
        mid = (low + high) // 2
        if (check(mid, p, prefix_sum, y - x + 1)):
            high = mid
        else:
            low = mid
    if (check(low, p, prefix_sum, y - x + 1)):
        return low
    return high


x = 12
y = 42
p = 3
print(minimumWindowSize(x, y, p))

# Expected output:
14
# xor of pairwise sum of every unordered pairs in an array | function to find xor of pairwise sum of every unordered pairs ; loop to choose every possible pairs in the array ; 
def xorOfSum(a, n):
    answer = 0
    for i in range(n):
        for j in range(i + 1, n):
            answer ^= (a[i] + a[j])
    return answer


if __name__ == '__main__':
    n = 3
    A = [1, 2, 3]
    print(xorOfSum(A, n))

# Expected output:
2
# maximum size of square such that all submatrices of that size have sum less than k | size of matrix ; 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 find the maximum square size possible with the such that every submatrix have sum less than the given sum ; loop to choose the size of matrix ; loop to find the sum of the matrix of every possible submatrix ; 

N = 4
M = 5


def preProcess(mat, aux):
    for i in range(M):
        aux[0][i] = mat[0][i]
    for i in range(1, N):
        for j in range(M):
            aux[i][j] = (mat[i][j] + aux[i - 1][j])
    for i in range(N):
        for j in range(1, M):
            aux[i][j] += aux[i][j - 1]


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 maximumSquareSize(mat, K):
    aux = [[0 for x in range(M)]for y in range(N)]
    preProcess(mat, aux)
    for i in range(min(N, M), 0, -1):
        satisfies = True
        for x in range(N):
            for y in range(M):
                if (x + i - 1 <= N - 1 and y + i - 1 <= M - 1):
                    if (sumQuery(aux, x, y, x + i - 1, y + i - 1) > K):
                        satisfies = False
        if (satisfies):
            return (i)
    return 0


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
# find two fibonacci numbers whose sum can be represented as n | function to create hash table to check fibonacci numbers ; storing the first two numbers in the hash ; finding fibonacci numbers up to n and storing them in the hash ; function to find the fibonacci pair with the given sum ; creating a set containing all fibonacci numbers ; traversing all numbers to find first pair ; if both i and ( n - i ) are fibonacci ; printing the pair because i + ( n - i ) = n ; if no fibonacci pair is found whose sum is equal to n ; 
def createHash(hash1, maxElement):
    prev, curr = 0, 1
    hash1 .add(prev)
    hash1 .add(curr)
    while (curr < maxElement):
        temp = curr + prev
        hash1 .add(temp)
        prev = curr
        curr = temp


def findFibonacciPair(n):
    hash1 = set()
    createHash(hash1, n)
    for i in range(n):
        if (i in hash1 and (n - i) in hash1):
            print(i, ", ", (n - i))
            return
    print("-1")


if __name__ == "__main__":
    N = 90
    findFibonacciPair(N)

# Expected output:
1 ,  89
# count of multiples in an array before every element | python 3 program to count of multiples in an array before every element ; function to find all factors of n and keep their count in map ; traverse from 1 to sqrt ( n ) if i divides n , increment i and n / i in map ; function to count of multiples in an array before every element ; to store factors all of all numbers ; traverse for all possible i 's ; printing value of a [ i ] in map ; now updating the factors of a [ i ] in the map ; 

from collections import defaultdict
import math


def add_factors(n, mp):
    for i in range(1, int(math .sqrt(n)) + 1,):
        if (n % i == 0):
            if (n // i == i):
                mp[i] += 1
            else:
                mp[i] += 1
                mp[n // i] += 1


def count_divisors(a, n):
    mp = defaultdict(int)
    for i in range(n):
        print(mp[a[i]], end=" ")
        add_factors(a[i], mp)


if __name__ == "__main__":
    arr = [8, 1, 28, 4, 2, 6, 7]
    n = len(arr)
    count_divisors(arr, n)

# Expected output:
0 1 0 2 3 0 1
# reduce the array such that each element appears at most 2 times | function to remove duplicates ; initialise 2 nd pointer ; iterate over the array ; updating the 2 nd pointer ; 
def removeDuplicates(arr, n):
    st = 0
    for i in range(n):
        if (i < n - 2 and arr[i] == arr[i + 1] and arr[i] == arr[i + 2]):
            continue
        else:
            arr[st] = arr[i]
            st += 1
    print("{", end="")
    for i in range(st):
        print(arr[i], end="")
        if (i != st - 1):
            print(", ", end="")
    print("}", end="")


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

# Expected output:
{1, 1, 2, 2, 3, 3, 4, 5}
# check if an array is a permutation of numbers from 1 to n | function to check if an array represents a permutation or not ; set to check the count of non - repeating elements ; insert all elements in the set ; calculating the max element ; check if set size is equal to n ; 
def permutation(arr, n):
    s = set()
    maxEle = 0
    for i in range(n):
        s .add(arr[i])
        maxEle = max(maxEle, arr[i])
    if (maxEle != n):
        return False
    if (len(s) == n):
        return True
    return False


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

# Expected output:
No
# count of subsets of a given set with element x present in it | python3 code to implement the above approach ; n stores total number of subsets ; generate each subset one by one ; check every bit of i ; if j 'th bit of i is set,  check arr[j] with x ; 
def CountSubSet(arr, n, X):
    N = 2 ** n
    count = 0
    for i in range(N):
        for j in range(n):
            if (i & (1 << j)):
                if (arr[j] == X):
                    count += 1
    return count


if __name__ == "__main__":
    arr = [4, 5, 6, 7]
    X = 5
    n = len(arr)
    print(CountSubSet(arr, n, X))

# Expected output:
8
# count of subsets of a given set with element x present in it | function to calculate ( 2 ^ ( n - 1 ) ) ; initially initialize answer to 1 ; if e is odd , multiply b with answer ; function to count subsets in which x element is present ; check if x is present in given subset or not ; if x is present in set then calculate 2 ^ ( n - 1 ) as count ; if x is not present in a given set ; 
def calculatePower(b, e):
    ans = 1
    while (e > 0):
        if (e % 2 == 1):
            ans = ans * b
        e = e // 2
        b = b * b
    return ans


def CountSubSet(arr, n, X):
    count = 0
    checkX = 0
    for i in range(n):
        if (arr[i] == X):
            checkX = 1
            break
    if (checkX == 1):
        count = calculatePower(2, n - 1)
    else:
        count = 0
    return count


if __name__ == "__main__":
    arr = [4, 5, 6, 7]
    X = 5
    n = len(arr)
    print(CountSubSet(arr, n, X))

# Expected output:
8
# value to be subtracted from array elements to make sum of all elements equals k | function to return the amount of wood collected if the cut is made at height m ; function that returns height at which cut should be made ; sort the heights of the trees ; the minimum and the maximum cut that can be made ; binary search to find the answer ; the amount of wood collected when cut is made at the mid ; if the current collected wood is equal to the required amount ; if it is more than the required amount then the cut needs to be made at a height higher than the current height ; else made the cut at a lower height ; 
def woodCollected(height, n, m):
    sum = 0
    for i in range(n - 1, -1, -1):
        if (height[i] - m <= 0):
            break
        sum += (height[i] - m)
    return sum


def collectKWood(height, n, k):
    height = sorted(height)
    low = 0
    high = height[n - 1]
    while (low <= high):
        mid = low + ((high - low) // 2)
        collected = woodCollected(height, n, mid)
        if (collected == k):
            return mid
        if (collected > k):
            low = mid + 1
        else:
            high = mid - 1
    return -1


height = [1, 2, 1, 2]
n = len(height)
k = 2
print(collectKWood(height, n, k))

# Expected output:
1
# check if given string contains all the digits | python3 implementation of the approach ; function that returns true if ch is a digit ; function that returns true if st contains all the digits from 0 to 9 ; to mark the present digits ; for every character of the string ; if the current character is a digit ; mark the current digit as present ; for every digit from 0 to 9 ; if the current digit is not present in st ; 

MAX = 10


def isDigit(ch):
    ch = ord(ch)
    if (ch >= ord('0') and ch <= ord('9')):
        return True
    return False


def allDigits(st, le):
    present = [False for i in range(MAX)]
    for i in range(le):
        if (isDigit(st[i])):
            digit = ord(st[i]) - ord('0')
            present[digit] = True
    for i in range(MAX):
        if (present[i] == False):
            return False
    return True


st = "Geeks12345for69708"
le = len(st)
if (allDigits(st, le)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check if a symmetric plus is possible from the elements of the given array | function that return true if a symmetric is possible with the elements of the array ; map to store the frequency of the array elements ; traverse through array elements and count frequencies ; for every unique element ; element has already been found ; the frequency of the element something other than 0 and 1 ; 
def isPlusPossible(arr, n):
    mp = dict()
    for i in range(n):
        mp[arr[i]] = mp .get(arr[i], 0) + 1
    foundModOne = False
    for x in mp:
        element = x
        frequency = mp[x]
        if (frequency % 4 == 0):
            continue
        if (frequency % 4 == 1):
            if (foundModOne):
                return False
            foundModOne = True
        else:
            return False
    return True


arr = [1, 1, 1, 1, 2, 2, 2, 3, 2]
n = len(arr)
if (isPlusPossible(arr, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# calculate the sum of gcd over all subarrays | utility function to calculate sum of gcd of all sub - arrays . ; fixing the starting index of a subarray ; fixing the ending index of a subarray ; finding the gcd of this subarray ; adding this gcd in our sum ; 
def __gcd(a, b):
    return a if (b == 0)else __gcd(b, a % b)

def findGCDSum(n, a):
    GCDSum = 0
    tempGCD = 0
    for i in range(n):
        for j in range(i, n):
            tempGCD = 0
            for k in range(i, j + 1):
                tempGCD = __gcd(tempGCD, a[k])
            GCDSum += tempGCD
    return GCDSum


if __name__ == '__main__':
    n = 5
    a = [1, 2, 3, 4, 5]
    totalSum = findGCDSum(n, a)
    print(totalSum)

# Expected output:
25
# check if the array has an element which is equal to xor of remaining elements | function that returns true if the array contains an element which is equal to the xor of the remaining elements ; to store the xor of all the array elements ; for every element of the array ; take the xor after excluding the current element ; if the xor of the remaining elements is equal to the current element ; if no such element is found ; 
def containsElement(arr, n):
    xorArr = 0
    for i in range(n):
        xorArr ^= arr[i]
    for i in range(n):
        x = xorArr ^ arr[i]
        if (arr[i] == x):
            return True
    return False


arr = [8, 2, 4, 15, 1]
n = len(arr)
if (containsElement(arr, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# square root of a number without using sqrt ( ) function | python3 implementation of the approach ; recursive function that returns square root of a number with precision upto 5 decimal places ; if mid itself is the square root , return mid ; if mul is less than n , recur second half ; else recur first half ; function to find the square root of n ; while the square root is not found ; if n is a perfect square ; square root will lie in the interval i - 1 and i ; 

import math


def Square(n, i, j):
    mid = (i + j) / 2
    mul = mid * mid
    if ((mul == n) or (abs(mul - n) < 0.00001)):
        return mid
    elif (mul < n):
        return Square(n, mid, j)
    else:
        return Square(n, i, mid)


def findSqrt(n):
    i = 1
    found = False
    while (found == False):
        if (i * i == n):
            print(i)
            found = True
        elif (i * i > n):
            res = Square(n, i - 1, i)
            print("{0:.5f}".format(res))
            found = True
        i += 1


if __name__ == '__main__':
    n = 3
    findSqrt(n)

# Expected output:
1.73205
# length of longest substring having all characters as k | function to find the length of longest sub - string having all characters same as character k ; initialize variables ; iterate till size of string ; check if current character is k ; assingning the max value to max_len ; 
def length_substring(S, K):
    curr_cnt = 0
    prev_cnt = 0
    max_len = 0
    for i in range(len(S)):
        if (S[i] == K):
            curr_cnt += 1
        else:
            prev_cnt = max(prev_cnt, curr_cnt)
            curr_cnt = 0
    prev_cnt = max(prev_cnt, curr_cnt)
    max_len = prev_cnt
    return max_len


if __name__ == '__main__':
    S = "abcd1111aabc"
    K = '1'
    print(length_substring(S, K))

# Expected output:
4
# find a partition point in array to maximize its xor sum | function to find partition point in array to maximize xor sum ; traverse through the array ; calculate xor of elements left of index i including ith element ; calculate xor of the elements right of index i ; keep the maximum possible xor sum ; return the 1 based index of the array ; 
def Xor_Sum(arr, n):
    sum = 0
    index, left_xor = 0, 0
    right_xor = 0
    for i in range(n):
        left_xor = left_xor ^ arr[i]
        right_xor = 0
        for j in range(i + 1, n):
            right_xor = right_xor ^ arr[j]
        if (left_xor + right_xor > sum):
            sum = left_xor + right_xor
            index = i
    return index + 1


arr = [1, 4, 6, 3, 8, 13, 34, 2, 21, 10]
n = len(arr)
print(Xor_Sum(arr, n))

# Expected output:
2