giulio98/xlcost-single-prompt huggingface dataset:
# find number of pairs ( x , y ) in an array such that x ^ y > y ^ x | set 2 | function to return the count of pairs ; compute suffix sums till i = 3 ; base case : x = 0 ; no valid pairs ; base case : x = 1 ; store the count of 0 's ; base case : x = 2 ; store suffix sum upto 5 ; base case : x = 3 ; store count of 2 and suffix sum upto 4 ; for all other values of x ; for all x >= 2 , every y = 0 and every y = 1 makes a valid pair ; return the count of pairs ; 
def countPairs(X, Y, m, n):
    suffix = [0] * 1005
    total_pairs = 0
    for i in range(n):
        suffix[Y[i]] += 1
    for i in range(int(1e3), 2, -1):
        suffix[i] += suffix[i + 1]
    for i in range(m):
        if (X[i] == 0):
            continue
        elif (X[i] == 1):
            total_pairs += suffix[0]
            continue
        elif (X[i] == 2):
            total_pairs += suffix[5]
        elif (X[i] == 3):
            total_pairs += (suffix[2] + suffix[4])
        else:
            total_pairs += suffix[X[i] + 1]
        total_pairs += suffix[0] + suffix[1]
    return total_pairs


if __name__ == '__main__':
    X = [10, 19, 18]
    Y = [11, 15, 9]
    m = len(X)
    n = len(Y)
    print(countPairs(X, Y, m, n))

# Expected output:
2
# min number of moves to traverse entire matrix through connected cells with equal values | function to find the minimum number of moves to traverse the given matrix ; constructing another matrix consisting of distinct values ; updating the array b by checking the values of a that if there are same values connected through an edge or not ; check for boundary condition of the matrix ; if adjacent cells have same value ; check for boundary condition of the matrix ; if adjacent cells have same value ; check for boundary condition of the matrix ; if adjacent cells have same value ; check for boundary condition of the matrix ; if adjacent cells have same value ; store all distinct elements in a set ; return answer ; 
def solve(A, N, M):
    B = []
    c = 1
    s = set()
    for i in range(N):
        new = []
        for j in range(M):
            new .append(c)
            c = c + 1
        B .append(new)
    for i in range(N):
        for j in range(M):
            if i != 0:
                if A[i - 1][j] == A[i][j]:
                    B[i - 1][j] = B[i][j]
            if (i != N - 1):
                if A[i + 1][j] == A[i][j]:
                    B[i + 1][j] = B[i][j]
            if (j != 0):
                if A[i][j - 1] == A[i][j]:
                    B[i][j - 1] = B[i][j]
            if (j != M - 1):
                if (A[i][j + 1] == A[i][j]):
                    B[i][j + 1] = B[i][j]
    for i in range(N):
        for j in range(M):
            s .add(B[i][j])
    return len(s)


N = 2
M = 3
A = [[2, 1, 3], [1, 1, 2]]
print(solve(A, N, M))

# Expected output:
4
# number of times an array can be partitioned repetitively into two subarrays with equal sum | recursion function to calculate the possible splitting ; if there are less than two elements , we cannot partition the sub - array . ; iterate from the start to end - 1. ; recursive call to the left and the right sub - array . ; if there is no such partition , then return 0 ; function to find the total splitting ; prefix array to store the prefix - sum using 1 based indexing ; store the prefix - sum ; function call to count the number of splitting ; 
def splitArray(start, end, arr, prefix_sum):
    if (start >= end):
        return 0
    for k in range(start, end):
        if ((prefix_sum[k] - prefix_sum[start - 1])
                == (prefix_sum[end] - prefix_sum[k])):
            return (
                1 +
                splitArray(
                    start,
                    k,
                    arr,
                    prefix_sum) +
                splitArray(
                    k +
                    1,
                    end,
                    arr,
                    prefix_sum))
    return 0


def solve(arr, n):
    prefix_sum = [0] * (n + 1)
    prefix_sum[0] = 0
    for i in range(1, n + 1):
        prefix_sum[i] = (prefix_sum[i - 1] + arr[i - 1])
    print(splitArray(1, n, arr, prefix_sum))


arr = [12, 3, 3, 0, 3, 3]
N = len(arr)
solve(arr, N)

# Expected output:
4
# minimise the maximum element of n subarrays of size k | function to choose n subarrays of size k such that the maximum element of subarrays is minimum ; condition to check if it is not possible to choose k sized n subarrays ; using binary search ; calculating mid ; loop to find the count of the k sized subarrays possible with elements less than mid ; condition to check if the answer is in right subarray ; 
def minDays(arr, n, k):
    l = len(arr)
    left = 1
    right = 1e9
    if (n * k > l):
        return -1
    while (left < right):
        mid = (left + right) // 2
        cnt = 0
        product = 0
        for j in range(l):
            if (arr[j] > mid):
                cnt = 0
            else:
                cnt += 1
                if (cnt >= k):
                    product += 1
                    cnt = 0
        if (product < n):
            left = mid + 1
        else:
            right = mid
    return left


if __name__ == "__main__":
    arr = [1, 10, 3, 10, 2]
    n = 3
    k = 1
    print(int(minDays(arr, n, k)))

# Expected output:
3
# count of distinct power of prime factor of n | function to count the number of distinct positive power of prime factor of integer n ; iterate for all prime factor ; if it is a prime factor , count the total number of times it divides n . ; find the number of distinct possible positive numbers ; return the final count ; 
def countFac(n):
    m = n
    count = 0
    i = 2
    while ((i * i) <= m):
        total = 0
        while (n % i == 0):
            n /= i
            total += 1
        temp = 0
        j = 1
        while ((temp + j) <= total):
            temp += j
            count += 1
            j += 1
        i += 1
    if (n != 1):
        count += 1
    return count


N = 24
print(countFac(N))

# Expected output:
3
# minimum total sum from the given two arrays | function that prints minimum sum after selecting n elements ; initialise the dp array ; base case ; adding the element of array a if previous element is also from array a ; adding the element of array a if previous element is from array b ; adding the element of array b if previous element is from array a with an extra penalty of integer c ; adding the element of array b if previous element is also from array b ; print the minimum sum ; 
def minimumSum(a, b, c, n):
    dp = [[1e6 for i in range(2)]for j in range(n)]
    dp[0][0] = a[0]
    dp[0][1] = b[0]
    for i in range(1, n):
        dp[i][0] = min(dp[i][0], dp[i - 1][0] + a[i])
        dp[i][0] = min(dp[i][0], dp[i - 1][1] + a[i] + c)
        dp[i][1] = min(dp[i][1], dp[i - 1][0] + b[i] + c)
        dp[i][1] = min(dp[i][1], dp[i - 1][1] + b[i])
    print(min(dp[n - 1][0], dp[n - 1][1]))


if __name__ == '__main__':
    arr1 = [7, 6, 18, 6, 16, 18, 1, 17, 17]
    arr2 = [6, 9, 3, 10, 9, 1, 10, 1, 5]
    C = 2
    N = len(arr1)
    minimumSum(arr1, arr2, C, N)

# Expected output:
49
# minimum flips required in a binary string such that all k | function to calculate and return the minimum number of flips to make string valid ; stores the count of required flips ; stores the last index of '1' in the string ; check for the first substring of length k ; if i - th character is '1 ; if the substring had no '1 ; increase the count of required flips ; flip the last index of the window ; update the last index which contains 1 ; check for remaining substrings ; if last_idx does not belong to current window make it - 1 ; if the last character of the current substring is '1' , then update last_idx to i + k - 1 ; ; if last_idx == - 1 , then the current substring has no 1 ; increase the count of flips ; update the last index of the current window ; store the last index of current window as the index of last '1' in the string ; return the number of operations ; 
def minimumMoves(S, K):

    N = len(S)
    ops = 0
    last_idx = -1
    for i in range(K):
        if (S[i] == '1'):
            last_idx = i
    if (last_idx == -1):
        ops += 1
        S[K - 1] = '1'
        last_idx = K - 1
    for i in range(N - K + 1):
        if (last_idx < i):
            last_idx = -1
        if (S[i + K - 1] == '1'):
            last_idx = i + K - 1

        if (last_idx == -1):

            ops += 1
            S = S[:i + K - 1] + '1' + S[i + K:]

            last_idx = i + K - 1

    return ops


S = "001010000"
K = 3

print(minimumMoves(S, K))

# Expected output:
1
# lexicographically smallest string which differs from given strings at exactly k indices | python3 program for the above approach ; function to find the string which differ at exactly k positions ; initialise s3 as s2 ; number of places at which s3 differ from s2 ; minimum possible value is ceil ( d / 2 ) if it is not possible then - 1 ; case 2 when k is less equal d ; x show the modification such that this position only differ from only one string ; modify the position such that this differ from both s1 & s2 & decrease the t at each step ; finding the character which is different from both s1 and s2 ; after we done t start modification to meet our requirement for x type ; resultant string ; case 1 when k > d in first step , modify all the character which are not same in s1 and s3 ; finding character which is different from both s1 and s2 ; our requirement not satisfied by performing step 1. we need to modify the position which matches in both string ; finding the character which is different from both s1 and s2 ; resultant string ; 

arr = ['a', 'b', 'c']


def findString(n, k, s1, s2):
    s3 = s2
    s3 = list(s3)
    d = 0
    for i in range(len(s1)):
        if (s1[i] != s2[i]):
            d += 1
    if ((d + 1) // 2 > k):
        print("-1")
        return
    else:
        if (k <= d):
            X = d - k
            T = 2 * k - d
            for i in range(len(s3)):
                if (s1[i] != s2[i]):
                    if (T > 0):
                        for j in range(3):
                            if (arr[j] != s1[i] and arr[j] != s2[i]):
                                s3[i] = arr[j]
                                T -= 1
                                break
                    elif (X > 0):
                        s3[i] = s1[i]
                        X -= 1
            print("".join(s3))
        else:
            for i in range(len(s1)):
                if (s1[i] != s3[i]):
                    for j in range(3):
                        if (arr[j] != s1[i] and arr[j] != s3[i]):
                            s3[i] = arr[j]
                            k -= 1
                            break
            for i in range(len(s1)):
                if (s1[i] == s3[i] and k):
                    for j in range(3):
                        if (arr[j] != s1[i] and arr[j] != s3[i]):
                            s3[i] = arr[j]
                            k -= 1
                            break
            print("".join(s3))


if __name__ == "__main__":
    N = 4
    k = 2
    S1 = "zzyy"
    S2 = "zxxy"
    findString(N, k, S1, S2)

# Expected output:
zaay
# count of pairs of integers whose difference of squares is equal to n | python3 program for the above approach ; function to find the integral solutions of the given equation ; initialise count to 0 ; iterate till sqrt ( n ) ; if divisor 's pair sum is even ; print the total possible solutions ; 

import math


def findSolutions(N):
    count = 0
    for i in range(1, int(math .sqrt(N)) + 1):
        if (N % i == 0):
            if ((i + N // i) % 2 == 0):
                count += 1
    print(4 * count)


N = 80
findSolutions(N)

# Expected output:
12
# find the integral roots of a given cubic equation | function to find the value at x of the given equation ; find the value equation at x ; return the value of ans ; function to find the integral solution of the given equation ; initialise start and end ; implement binary search ; find mid ; find the value of f ( x ) using current mid ; check if current mid satisfy the equation ; print mid and return ; print " na " if not found any integral solution ; 
def check(A, B, C, D, x):
    ans = 0
    ans = (A * x * x * x + B * x * x + C * x + D)
    return ans


def findSolution(A, B, C, D, E):
    start = 0
    end = 100000
    mid = 0
    ans = 0
    while (start <= end):
        mid = start + (end - start) // 2
        ans = check(A, B, C, D, mid)
        if (ans == E):
            print(mid)
            return
        if (ans < E):
            start = mid + 1
        else:
            end = mid - 1
    print("NA")


if __name__ == "__main__":
    A = 1
    B = 0
    C = 0
    D = 0
    E = 27
    findSolution(A, B, C, D, E)

# Expected output:
3
# count of ordered triplets ( r , g , b ) in a given original string | function to count the ordered triplets ( r , g , b ) ; count the b ( blue ) colour ; 
def countTriplets(color):
    result = 0
    Blue_Count = 0
    Red_Count = 0
    for c in color:
        if (c == 'B'):
            Blue_Count += 1
    for c in color:
        if (c == 'B'):
            Blue_Count -= 1
        if (c == 'R'):
            Red_Count += 1
        if (c == 'G'):
            result += Red_Count * Blue_Count
    return result


if __name__ == "__main__":
    color = "RRGGBBRGGBB"
    print(countTriplets(color))

# Expected output:
28
# minimum value of k such that sum of cubes of first k natural number is greater than equal to n | function to determine the minimum value of k such that the sum of cubes of first k natural number is greater than or equal to n ; variable to store the sum of cubes ; loop to find the number k ; if c is just greater then n , then break the loop ; 
def naive_find_x(N):
    c = 0
    for i in range(1, N):
        c += i * i * i
        if c >= N:
            break
    return i


if __name__ == "__main__":
    N = 100
    print(naive_find_x(N))

# Expected output:
4
# minimum value of k such that sum of cubes of first k natural number is greater than equal to n | function to determine the minimum value of k such that the sum of cubes of first k natural number is greater than or equal to n ; left bound ; right bound ; variable to store the answer ; applying binary search ; calculating mid value of the range ; if the sum of cubes of first mid natural numbers is greater than equal to n iterate the left half ; sum of cubes of first mid natural numbers is less than n , then move to the right segment ; 
def binary_searched_find_x(k):
    l = 0
    r = k
    ans = 0
    while l <= r:
        mid = l + (r - l) // 2
        if ((mid * (mid + 1)) // 2)**2 >= k:
            ans = mid
            r = mid - 1
        else:
            l = mid + 1
    return ans


if __name__ == "__main__":
    N = 100
    print(binary_searched_find_x(N))

# Expected output:
4
# length of the longest zigzag subarray of the given array | function to find the length of longest zigzag contiguous subarray ; ' _ max ' to store the length of longest zigzag subarray ; ' _ len ' to store the lengths of longest zigzag subarray at different instants of time ; traverse the array from the beginning ; check if ' _ max ' length is less than the length of the current zigzag subarray . if true , then update '_max ; reset ' _ len ' to 1 as from this element , again the length of the new zigzag subarray is being calculated ; comparing the length of the last zigzag subarray with '_max ; return required maximum length ; 
def lenOfLongZigZagArr(a, n):
    _max = 1
    _len = 1
    for i in range(n - 1):

        if i % 2 == 0 and a[i] < a[i + 1]:
            _len += 1

        elif i % 2 == 1 and a[i] > a[i + 1]:
            _len += 1

        else:
            if _max < _len:
                _max = _len
            _len = 1
    if _max < _len:
        _max = _len
    return _max


arr = [1, 2, 3, 4, 5]
n = len(arr)

print(lenOfLongZigZagArr(arr, n))

# Expected output:
2
# check if a given number is a perfect square using binary search | function to check for perfect square number ; find the mid value from start and last ; check if we got the number which is square root of the perfect square number n ; if the square ( mid ) is greater than n it means only lower values then mid will be possibly the square root of n ; if the square ( mid ) is less than n it means only higher values then mid will be possibly the square root of n ; 
def checkPerfectSquare(N, start, last):
    mid = int((start + last) / 2)
    if (start > last):
        return -1
    if (mid * mid == N):
        return mid
    elif (mid * mid > N):
        return checkPerfectSquare(N, start, mid - 1)
    else:
        return checkPerfectSquare(N, mid + 1, last)


N = 65
print(checkPerfectSquare(N, 1, N))

# Expected output:
-1
# maximum count number of valley elements in a subarray of size k | function to find the valley elements in the array which contains in the subarrays of the size k ; increment min_point if element at index i is smaller than element at index i + 1 and i - 1 ; final_point to maintain maximum of min points of subarray ; iterate over array from kth element ; leftmost element of subarray ; rightmost element of subarray ; if new subarray have greater number of min points than previous subarray , then final_point is modified ; max minimum points in subarray of size k ; 
def minpoint(arr, n, k):
    min_point = 0
    for i in range(1, k - 1):
        if (arr[i] < arr[i - 1] and arr[i] < arr[i + 1]):
            min_point += 1
    final_point = min_point
    for i in range(k, n):
        if (arr[i - (k - 1)] < arr[i - (k - 1) + 1]
                and arr[i - (k - 1)] < arr[i - (k - 1) - 1]):
            min_point -= 1
        if (arr[i - 1] < arr[i] and arr[i - 1] < arr[i - 2]):
            min_point += 1
        if (min_point > final_point):
            final_point = min_point
    print(final_point)


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

# Expected output:
1
# for each lowercase english alphabet find the count of strings having these alphabets | function to find the countstrings for each letter [ a - z ] ; initialize result as zero ; mark all letter as not visited ; loop through each strings ; increment the global counter for current character of string ; instead of re - initialising boolean vector every time we just reset all visited letter to false ; print count for each letter ; 
def CountStrings(s):
    size = len(s)
    count = [0] * 26
    visited = [False] * 26
    for i in range(size):
        for j in range(len(s[i])):
            if visited[ord(s[i][j]) - ord('a')] == False:
                count[ord(s[i][j]) - ord('a')] += 1
            visited[ord(s[i][j]) - ord('a')] = True
        for j in range(len(s[i])):
            visited[ord(s[i][j]) - ord('a')] = False
    for i in range(26):
        print(count[i], end=' ')


if __name__ == '__main__':
    s = ["i", "will", "practice", "everyday"]
    CountStrings(s)

# Expected output:
2 0 1 1 2 0 0 0 3 0 0 1 0 0 0 1 0 2 0 1 0 1 1 0 1 0
# find subarray of length k with maximum peak | function to find the subarray ; make prefix array to store the prefix sum of peak count ; count peak for previous index ; check if this element is a peak ; increment the count ; check if number of peak in the sub array whose l = i is greater or not ; print the result ; 
def findSubArray(a, n, k):
    pref = [0 for i in range(n)]
    pref[0] = 0
    for i in range(1, n - 1, 1):
        pref[i] = pref[i - 1]
        if (a[i] > a[i - 1] and a[i] > a[i + 1]):
            pref[i] += 1
    peak = 0
    left = 0
    for i in range(0, n - k + 1, 1):
        if (pref[i + k - 2] - pref[i] > peak):
            peak = pref[i + k - 2] - pref[i]
            left = i
    print("Left =", left + 1)
    print("Right =", left + k)
    print("Peak =", peak)


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

# Expected output:
Left = 2
Right = 4
Peak = 1
# sort integers in array according to their distance from the element k | function to get sorted array based on their distance from given integer k ; vector to store respective elements with their distance from integer k ; find the position of integer k ; insert the elements with their distance from k in vector ; element at distance 0 ; elements at left side of k ; elements at right side of k ; print the vector content in sorted order ; sort elements at same distance ; print elements at distance i from k ; 
def distanceSort(arr, K, n):
    vd = [[]for i in range(n)]
    for i in range(n):
        if (arr[i] == K):
            pos = i
            break
    i = pos - 1
    j = pos + 1
    vd[0].append(arr[pos])
    while (i >= 0):
        vd[pos - i].append(arr[i])
        i -= 1
    while (j < n):
        vd[j - pos].append(arr[j])
        j += 1
    for i in range(max(pos, n - pos - 1) + 1):
        vd[i].sort(reverse=False)
        for element in vd[i]:
            print(element, end=" ")


if __name__ == '__main__':
    arr = [14, 1101, 10, 35, 0]
    K = 35
    n = len(arr)
    distanceSort(arr, K, n)

# Expected output:
35 0 10 1101 14
# find quotient and remainder of two integer without using division operators | function to the quotient and remainder ; check if start is greater than the end ; calculate mid ; check if n is greater than divisor then increment the mid by 1 ; check if n is less than 0 then decrement the mid by 1 ; check if n equals to divisor ; return the final answer ; recursive calls ; 
def find(dividend, divisor, start, end):
    if (start > end):
        return (0, dividend)
    mid = start + (end - start) // 2
    n = dividend - divisor * mid
    if (n > divisor):
        start = mid + 1
    elif (n < 0):
        end = mid - 1
    else:
        if (n == divisor):
            mid += 1
            n = 0
        return (mid, n)
    return find(dividend, divisor, start, end)


def divide(dividend, divisor):
    return find(dividend, divisor, 1, dividend)


if __name__ == "__main__":
    dividend = 10
    divisor = 3
    ans = divide(dividend, divisor)
    print(ans[0], ", ", ans[1])

# Expected output:
3 ,  1
# count the number of unordered triplets with elements in increasing order and product less than or equal to integer x | function to count the number of triplets ; iterate through all the triplets ; rearrange the numbers in ascending order ; check if the necessary conditions satisfy ; increment count ; return the answer ; 
def countTriplets(a, n, x):
    answer = 0
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                temp = []
                temp .append(a[i])
                temp .append(a[j])
                temp .append(a[k])
                temp .sort()
                if (temp[0] < temp[1] and temp[1] < temp[2]
                        and temp[0] * temp[1] * temp[2] <= x):
                    answer += 1
    return answer


A = [3, 2, 5, 7]
N = len(A)
X = 42
print(countTriplets(A, N, X))

# Expected output:
2
# largest value of x such that axx is n | python3 implementation of the above approach ; function to find log_b ( a ) ; set two pointer for binary search ; calculating number of digits of a * mid ^ mid in base b ; if number of digits > n we can simply ignore it and decrease our pointer ; if number of digits <= n , we can go higher to reach value exactly equal to n ; return the largest value of x ; 

from math import log10, ceil, log


def log1(a, b):
    return log10(a) // log10(b)


def get(a, b, n):
    lo = 0
    hi = 1e6
    ans = 0
    while (lo <= hi):
        mid = (lo + hi) // 2
        dig = ceil((mid * log(mid, b) + log(a, b)))
        if (dig > n):
            hi = mid - 1
        else:
            ans = mid
            lo = mid + 1
    return ans


if __name__ == '__main__':
    a = 2
    b = 2
    n = 6
    print(int(get(a, b, n)))

# Expected output:
3