giulio98/xlcost-single-prompt huggingface dataset:
# count number of common elements between a sorted array and a reverse sorted array | function to count the number of elements common in both the arrays ; used to traverse array a [ ] and b [ ] from the front and the back ; stores the count of numbers common in both array ; if a [ first ] is less than b [ second ] ; increment the value of first ; if b [ second ] is less than a [ first ] ; decrement the value of second ; a [ first ] is equal to b [ second ] ; increment the value of count ; increment the value of first ; decrement the value of second ; return the value of count ; 
def countEqual(A, B, N):
    first = 0
    second = N - 1
    count = 0
    while (first < N and second >= 0):
        if (A[first] < B[second]):
            first += 1
        elif (B[second] < A[first]):
            second -= 1
        else:
            count += 1
            first += 1
            second -= 1
    return count


A = [2, 4, 5, 8, 12, 13, 17, 18, 20, 22, 309, 999]
B = [109, 99, 68, 54, 22, 19, 17, 13, 11, 5, 3, 1]
N = len(A)
print(countEqual(A, B, N))

# Expected output:
4
# queries to count palindrome numbers from a range whose sum of digits is a prime number | python 3 program for the above approach ; function to check if the number n is palindrome or not ; store the value of n ; store the reverse of number n ; reverse temp and store in res ; if n is the same as res , then return true ; function to find the sum of the digits of the number n ; stores the sum of the digits ; add the last digit of the number n to the sum ; remove the last digit from n ; return the resultant sum ; function to check if n is prime or not ; if i is 1 or 0 , then return false ; check if i is divisible by any number in the range [ 2 , n / 2 ] ; if n is divisible by i ; function to precompute all the numbers till 10 ^ 5 that are palindromic and whose sum of digits is prime numbers ; iterate over the range 1 to 10 ^ 5 ; if i is a palindrome number ; stores the sum of the digits in i ; if the sum of digits in i is a prime number ; find the prefix sum of arr [ ] ; function to count all the numbers in the given ranges that are palindromic and the sum of digits is prime numbers ; function call to precompute all the numbers till 10 ^ 5 ; traverse the given queries q [ ] ; print the result for each query ; 

arr = [0 for i in range(100005)]


def isPalindrome(N):
    temp = N
    res = 0
    while (temp != 0):
        rem = temp % 10
        res = res * 10 + rem
        temp //= 10
    if (res == N):
        return True
    else:
        return False


def sumOfDigits(N):
    sum = 0
    while (N != 0):
        sum += N % 10
        N //= 10
    return sum


def isPrime(n):
    if (n <= 1):
        return False
    for i in range(2, (n // 2) + 1, 1):
        if (n % i == 0):
            return False
    return True


def precompute():
    for i in range(1, 100001, 1):
        if (isPalindrome(i)):
            sum = sumOfDigits(i)
            if (isPrime(sum)):
                arr[i] = 1
            else:
                arr[i] = 0
        else:
            arr[i] = 0
    for i in range(1, 100001, 1):
        arr[i] = arr[i] + arr[i - 1]


def countNumbers(Q, N):
    precompute()
    for i in range(N):
        print(arr[Q[i][1]] - arr[Q[i][0] - 1])


if __name__ == '__main__':
    Q = [[5, 9], [1, 101]]
    N = len(Q)
    countNumbers(Q, N)

# Expected output:
2
6
# smallest number greater than or equal to n having sum of digits not exceeding s | function to calculate sum of digits of n ; function to find the smallest possible integer satisfying the given condition ; if sum of digits is already smaller than s ; initialize variables ; find the k - th digit ; add remaining ; if sum of digits does not exceed s ; update k ; 
def sum(n):
    sm = 0
    while (n > 0):
        sm += n % 10
        n //= 10
    return sm


def smallestNumber(n, s):
    if (sum(n) <= s):
        return n
    ans, k = n, 1
    for i in range(9):
        digit = (ans // k) % 10
        add = k * ((10 - digit) % 10)
        ans += add
        if (sum(ans) <= s):
            break
        k *= 10
    return ans


n, s = 3, 2
print(smallestNumber(n, s))

# Expected output:
10
# maximize count of decreasing consecutive subsequences from an array | python program to implement the above approach ; function to find the maximum number number of required subsequences ; dictionary to store number of arrows available with height of arrow as key ; stores the maximum count of possible subsequences ; stores the count of possible subsequences ; check if i - th element can be part of any of the previous subsequence ; count of subsequences possible with arr [ i ] as the next element ; if more than one such subsequence exists ; include arr [ i ] in a subsequence ; otherwise ; increase count of subsequence possible with arr [ i ] - 1 as the next element ; start a new subsequence ; increase count of subsequence possible with arr [ i ] - 1 as the next element ; return the answer ; 

from collections import defaultdict


def maxSubsequences(arr, n) -> int:
    m = defaultdict(int)
    maxCount = 0
    count = 0
    for i in range(0, n):
        if arr[i] in m .keys():
            count = m[arr[i]]
            if count > 1:
                m[arr[i]] = count - 1
            else:
                m .pop(arr[i])
            if arr[i] - 1 > 0:
                m[arr[i] - 1] += 1
        else:
            maxCount += 1
        maxCount += 1
        if arr[i] - 1 > 0:
            m[arr[i] - 1] += 1
    return maxCount


if __name__ == '__main__':
    n = 5
    arr = [4, 5, 2, 1, 4]
    print(maxSubsequences(arr, n))

# Expected output:
8
# remove the first and last occurrence of a given character from a string | function to remove first and last occurrence of a given character from the given string ; traverse the given string from the beginning ; if ch is found ; traverse the given string from the end ; if ch is found ; 
def removeOcc(s, ch):
    for i in range(len(s)):
        if (s[i] == ch):
            s = s[0:i] + s[i + 1:]
            break
    for i in range(len(s) - 1, -1, -1):
        if (s[i] == ch):
            s = s[0:i] + s[i + 1:]
            break
    return s


s = "hello world"
ch = 'l'
print(removeOcc(s, ch))

# Expected output:
helo word
# minimum steps for increasing and decreasing array to reach either 0 or n | python3 program for the above approach ; function that finds the minimum steps to reach either 0 or n for given increasing and decreasing arrays ; initialize variable to find the minimum element ; find minimum element in increasing array ; initialize variable to find the maximum element ; find maximum element in decreasing array ; find the minimum steps ; prthe minimum steps ; 

import sys


def minSteps(N, increasing, decreasing):
    Min = sys .maxsize
    for i in increasing:
        if (Min > i):
            Min = i
    Max = -sys .maxsize
    for i in decreasing:
        if (Max < i):
            Max = i
    minSteps = max(Max, N - Min)
    print(minSteps)


if __name__ == '__main__':
    N = 7
    increasing = [3, 5]
    decreasing = [6]
    minSteps(N, increasing, decreasing)

# Expected output:
6
# minimum number of adjacent swaps required to convert a permutation to another permutation by given condition | function to find the minimum number of swaps ; new array to convert to 1 - based indexing ; keeps count of swaps ; check if it is an ' x ' position ; corner case ; swap ; print the minimum swaps ; given number n ; 
def solve(P, n):
    arr = []
    arr .append(0)
    for x in P:
        arr .append(x)
    cnt = 0
    for i in range(1, n):
        if (arr[i] == i):
            arr[i], arr[i + 1] = arr[i + 1], arr[i]
            cnt += 1
    if (arr[n] == n):
        arr[n - 1], arr[n] = arr[n], arr[n - 1]
        cnt += 1
    print(cnt)


N = 9
P = [1, 2, 4, 9, 5, 8, 7, 3, 6]
solve(P, N)

# Expected output:
3
# count of interesting primes upto n | function to find all prime numbers ; create a boolean array " prime [ 0 . . n ] " and initialize all entries as true . a value in prime [ i ] will finally be false if i is not a prime . ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p greater than or equal to the square of it ; store all prime numbers ; function to check if a number is perfect square or not ; to store all primes ; to store all interseting primes ; store all perfect squares ; store all perfect quadruples ; store all interseting primes ; return count of interseting primes ; 
def SieveOfEratosthenes(n, allPrimes):
    prime = [True] * (n + 1)
    p = 2
    while p * p <= n:
        if prime[p]:
            for i in range(p * p, n + 1, p):
                prime[i] = False
        p += 1
    for p in range(2, n + 1):
        if prime[p]:
            allPrimes .add(p)


def countInterestingPrimes(n):
    allPrimes = set()
    SieveOfEratosthenes(n, allPrimes)
    interestingPrimes = set()
    squares, quadruples = [], []
    i = 1
    while i * i <= n:
        squares .append(i * i)
        i += 1
    i = 1
    while i * i * i * i <= n:
        quadruples .append(i * i * i * i)
        i += 1
    for a in squares:
        for b in quadruples:
            if a + b in allPrimes:
                interestingPrimes .add(a + b)
    return len(interestingPrimes)


N = 10
print(countInterestingPrimes(N))

# Expected output:
2
# check if an array is wave array | function to check if array is wave array arr : input array n : size of array ; check the wave form if arr [ 1 ] is greater than left and right . same pattern will be followed by whole elements , else reverse pattern will be followed by array elements ; check for last element ; check for last element ; 
def isWaveArray(arr, n):
    result = True
    if (arr[1] > arr[0] and arr[1] > arr[2]):
        for i in range(1, n - 1, 2):
            if (arr[i] > arr[i - 1] and arr[i] > arr[i + 1]):
                result = True
            else:
                result = False
                break
        if (result and n % 2 == 0):
            if (arr[n - 1] <= arr[n - 2]):
                result = False
    elif (arr[1] < arr[0] and arr[1] < arr[2]):
        for i in range(1, n - 1, 2):
            if (arr[i] < arr[i - 1] and arr[i] < arr[i + 1]):
                result = True
            else:
                result = False
                break
        if (result and n % 2 == 0):
            if (arr[n - 1] >= arr[n - 2]):
                result = False
    return result


if __name__ == "__main__":
    arr = [1, 3, 2, 4]
    n = len(arr)
    if (isWaveArray(arr, n)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# count distinct sequences obtained by replacing all elements of subarrays having equal first and last elements with the first element any number of times | function to count number of sequences satisfying the given criteria ; stores the index of the last occurrence of the element ; initialize an array to store the number of different sequences that are possible of length i ; base case ; if no operation is applied on ith element ; if operation is applied on ith element ; update the last occurrence of curele ; finally , prthe answer ; 
def countPossiblities(arr, n):
    lastOccur = [-1] * 100000
    dp = [0] * (n + 1)
    dp[0] = 1
    for i in range(1, n + 1):
        curEle = arr[i - 1]
        dp[i] = dp[i - 1]
        if (lastOccur[curEle] != -1 and lastOccur[curEle] < i - 1):
            dp[i] += dp[lastOccur[curEle]]
        lastOccur[curEle] = i
    print(dp[n])


if __name__ == '__main__':
    arr = [1, 2, 1, 2, 2]
    N = len(arr)
    countPossiblities(arr, N)

# Expected output:
3
# maximum sum possible from given matrix by performing given operations | function to prthe maximum sum ; dp table ; base case ; traverse each column ; update answer for both rows ; print the maximum sum ; 
def maxSum(arr, n, m):
    dp = [[0 for i in range(m + 1)]for i in range(2)]
    dp[0][m - 1] = arr[0][m - 1]
    dp[1][m - 1] = arr[1][m - 1]
    for j in range(m - 2, -1, -1):
        for i in range(2):
            if (i == 1):
                dp[i][j] = max(arr[i][j] + dp[0][j + 1],
                               arr[i][j] + dp[0][j + 2])
            else:
                dp[i][j] = max(arr[i][j] + dp[1][j + 1],
                               arr[i][j] + dp[1][j + 2])
    print(max(dp[0][0], dp[1][0]))


if __name__ == '__main__':
    arr = [[1, 50, 21, 5], [2, 10, 10, 5]]
    N = len(arr[0])
    maxSum(arr, 2, N)

# Expected output:
67
# maximum sum possible from given matrix by performing given operations | function to print the maximum sum possible by selecting at most one element from each column such that no consecutive pairs are selected from a single row ; initialize variables ; traverse each column ; print answer ; 
def maxSum(arr, n):
    r1 = r2 = 0
    for i in range(n):
        r1, r2 = max(r1, r2 + arr[0][i]), max(r2, r1 + arr[1][i])
    print(max(r1, r2))


arr = [[1, 50, 21, 5], [2, 10, 10, 5]]
n = len(arr[0])
maxSum(arr, n)

# Expected output:
67
# count unimodal and non | python3 program for the above approach ; function to calculate the factorials up to a number ; calculate the factorial ; function to find power ( a , b ) ; iterate until b exists ; if b is divisible by 2 ; decrease the value of b ; return the answer ; function that counts the unimodal and non - unimodal permutations of a given integer n ; function call for finding factorials up to n ; function to count unimodal permutations ; non - unimodal permutation is n ! - unimodal permutations ; 

mod = 1e9 + 7
mx = 1000000
fact = [0] * (mx + 1)


def Calculate_factorial():
    fact[0] = 1
    for i in range(1, mx + 1):
        fact[i] = i * fact[i - 1]
        fact[i] %= mod


def UniModal_per(a, b):
    res = 1
    while (b != 0):
        if (b % 2 != 0):
            res = res * a
        res %= mod
        a = a * a
        a %= mod
        b //= 2
    return res


def countPermutations(n):
    Calculate_factorial()
    uni_modal = UniModal_per(2, n - 1)
    nonuni_modal = fact[n] - uni_modal
    print(int(uni_modal), "", int(nonuni_modal))
    return


N = 4
countPermutations(N)

# Expected output:
8  16
# largest square in a binary matrix with at most k 1 s for multiple queries | python3 implementation to find the largest square in the matrix such that it contains at most k 1 's  ; function to calculate the largest square with atmost k 1 s for q queries ; loop to solve for each query ; traversing the each sub square and counting total ; breaks when exceeds the maximum count ; 

MAX = 100


def largestSquare(matrix, R, C, q_i, q_j, K, Q):
    for q in range(Q):
        i = q_i[q]
        j = q_j[q]
        min_dist = min(min(i, j), min(R - i - 1, C - j - 1))
        ans = -1
        for k in range(min_dist + 1):
            count = 0
            for row in range(i - k, i + k + 1):
                for col in range(j - k, j + k + 1):
                    count += matrix[row][col]
            if count > K:
                break
            ans = 2 * k + 1
        print(ans)


matrix = [[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]]
K = 9
Q = 1
q_i = [1]
q_j = [2]
largestSquare(matrix, 4, 5, q_i, q_j, K, Q)

# Expected output:
3
# largest square in a binary matrix with at most k 1 s for multiple queries | function to find the largest square in the matrix such that it contains atmost k 1 's  ; precomputing the countdp prefix sum of the matrix ; loop to solve queries ; calculating the maximum possible distance of the centre from edge ; calculating the number of 1 s in the submatrix ; 
def largestSquare(matrix, R, C, q_i, q_j, K, Q):
    countDP = [[0 for x in range(C)]for x in range(R)]
    countDP[0][0] = matrix[0][0]
    for i in range(1, R):
        countDP[i][0] = (countDP[i - 1][0] + matrix[i][0])
    for j in range(1, C):
        countDP[0][j] = (countDP[0][j - 1] + matrix[0][j])
    for i in range(1, R):
        for j in range(1, C):
            countDP[i][j] = (matrix[i][j] + countDP[i - 1]
                             [j] + countDP[i][j - 1] - countDP[i - 1][j - 1])
    for q in range(0, Q):
        i = q_i[q]
        j = q_j[q]
        min_dist = min(i, j, R - i - 1, C - j - 1)
        ans = -1
        for k in range(0, min_dist + 1):
            x1 = i - k
            x2 = i + k
            y1 = j - k
            y2 = j + k
            count = countDP[x2][y2]
            if (x1 > 0):
                count -= countDP[x1 - 1][y2]
            if (y1 > 0):
                count -= countDP[x2][y1 - 1]
            if (x1 > 0 and y1 > 0):
                count += countDP[x1 - 1][y1 - 1]
            if (count > K):
                break
            ans = 2 * k + 1
        print(ans)


matrix = [[1, 0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 0, 1, 0]]
K = 9
Q = 1
q_i = [1]
q_j = [2]
largestSquare(matrix, 4, 5, q_i, q_j, K, Q)

# Expected output:
3
# n consecutive ropes problem | function to return the minimum cost to connect the given ropes ; dp [ i ] [ j ] = minimum cost in range ( i , j ) sum [ i ] [ j ] = sum of range ( i , j ) ; initializing the sum table memset ( sum , 0 , sizeof ( 0 ) ) ; ; computing minimum cost for all the possible interval ( i , j ) left range ; right range ; no cost for a single rope ; 
def MinCost(arr, n):
    dp = [[0 for i in range(n + 5)]for i in range(n + 5)]
    sum = [[0 for i in range(n + 5)]for i in range(n + 5)]
    for i in range(n):
        k = arr[i]
        for j in range(i, n):
            if (i == j):
                sum[i][j] = k
            else:
                k += arr[j]
                sum[i][j] = k
    for i in range(n - 1, -1, -1):
        for j in range(i, n):
            dp[i][j] = 10 ** 9
            if (i == j):
                dp[i][j] = 0
            else:
                for k in range(i, j):
                    dp[i][j] = min(dp[i][j],
                                   dp[i][k] + dp[k + 1][j] + sum[i][j])
    return dp[0][n - 1]


arr = [7, 6, 8, 6, 1, 1]
n = len(arr)
print(MinCost(arr, n))

# Expected output:
68
# length of the longest subsegment which is updown after inserting atmost one integer | function to recursively fill the dp array ; if f ( i , state ) is already calculated then return the value ; calculate f ( i , state ) according to the recurrence relation and store in dp [ ] [ ] ; function that calls the resucrsive function to fill the dp array and then returns the result ; dp [ ] [ ] array for storing result of f ( i , 1 ) and f ( 1 , 2 ) populating the array dp [ ] with - 1 ; make sure that longest ud and du sequence starting at each index is calculated ; assume the answer to be - 1 this value will only increase ; y is the length of the longest ud sequence starting at i ; if length is even then add an integer and then a du sequence starting at i + y ; if length is odd then add an integer and then a ud sequence starting at i + y ; 
def f(i, state, A, dp, N):
    if i >= N:
        return 0
    elif dp[i][state] != -1:
        return dp[i][state]
    else:
        if i == N - 1:
            dp[i][state] = 1
        elif state == 1 and A[i] > A[i + 1]:
            dp[i][state] = 1
        elif state == 2 and A[i] < A[i + 1]:
            dp[i][state] = 1
        elif state == 1 and A[i] <= A[i + 1]:
            dp[i][state] = 1 + f(i + 1, 2, A, dp, N)
        elif state == 2 and A[i] >= A[i + 1]:
            dp[i][state] = 1 + f(i + 1, 1, A, dp, N)
        return dp[i][state]


def maxLenSeq(A, N):
    dp = [[-1, -1, -1]for i in range(1000)]
    for i in range(N):
        tmp = f(i, 1, A, dp, N)
        tmp = f(i, 2, A, dp, N)
    ans = -1
    for i in range(N):
        y = dp[i][1]
        if (i + y) >= N:
            ans = max(ans, dp[i][1] + 1)
        elif y % 2 == 0:
            ans = max(ans, dp[i][1] + 1 + dp[i + y][2])
        elif y % 2 == 1:
            ans = max(ans, dp[i][1] + 1 + dp[i + y][1])
    return ans


if __name__ == "__main__":
    A = [1, 10, 3, 20, 25, 24]
    n = len(A)
    print(maxLenSeq(A, n))

# Expected output:
7
# remove an element to maximize the gcd of the given array | python3 implementation of the above approach ; function to return the maximized gcd after removing a single element from the given array ; prefix and suffix arrays ; single state dynamic programming relation for storing gcd of first i elements from the left in prefix [ i ] ; initializing suffix array ; single state dynamic programming relation for storing gcd of all the elements having greater than or equal to i in suffix [ i ] ; if first or last element of the array has to be removed ; if any other element is replaced ; return the maximized gcd ; 

import math as mt


def MaxGCD(a, n):
    Prefix = [0 for i in range(n + 2)]
    Suffix = [0 for i in range(n + 2)]
    Prefix[1] = a[0]
    for i in range(2, n + 1):
        Prefix[i] = mt .gcd(Prefix[i - 1], a[i - 1])
    Suffix[n] = a[n - 1]
    for i in range(n - 1, 0, -1):
        Suffix[i] = mt .gcd(Suffix[i + 1], a[i - 1])
    ans = max(Suffix[2], Prefix[n - 1])
    for i in range(2, n):
        ans = max(ans, mt .gcd(Prefix[i - 1], Suffix[i + 1]))
    return ans


a = [14, 17, 28, 70]
n = len(a)
print(MaxGCD(a, n))

# Expected output:
14
# maximum subarray sum by flipping signs of at most k array elements | python3 implementation of the approach ; function to find the maximum subarray sum with flips starting from index i ; if the number of flips have exceeded ; complete traversal ; if the state has previously been visited ; initially ; use kadane 's algorithm and  call two states ; memoize the answer and return it ; utility function to call flips from index and return the answer ; create dp array int dp [ n , k + 1 ] ; iterate and call recursive function from every index to get the maximum subarray sum ; corner casae ; 

import numpy as np
right = 3
left = 6
dp = np .ones((left, right))
dp = -1 * dp


def findSubarraySum(ind, flips, n, a, k):
    if (flips > k):
        return -1e9
    if (ind == n):
        return 0
    if (dp[ind][flips] != -1):
        return dp[ind][flips]
    ans = 0
    ans = max(0, a[ind] + findSubarraySum(ind + 1, flips, n, a, k))
    ans = max(ans, -a[ind] + findSubarraySum(ind + 1, flips + 1, n, a, k))
    dp[ind][flips] = ans
    return dp[ind][flips]


def findMaxSubarraySum(a, n, k):
    ans = -1e9
    for i in range(n):
        ans = max(ans, findSubarraySum(i, 0, n, a, k))
    if ans == 0 and k == 0:
        return max(a)
    return ans


if __name__ == "__main__":
    a = [-1, -2, -100, -10]
    n = len(a)
    k = 1
    print(findMaxSubarraySum(a, n, k))

# Expected output:
100.0
# find the sum of first n odd fibonacci numbers | python3 program to find the sum of first n odd fibonacci numbers ; function to calculate sum of first n odd fibonacci numbers ; base values ; 

mod = 1000000007


def sumOddFibonacci(n):
    Sum = [0] * (n + 1)
    Sum[0] = 0
    Sum[1] = 1
    Sum[2] = 2
    Sum[3] = 5
    Sum[4] = 10
    Sum[5] = 23
    for i in range(6, n + 1):
        Sum[i] = ((Sum[i - 1] + (4 * Sum[i - 2]) % mod - (4 * Sum[i - 3]) %
                  mod + mod) % mod + (Sum[i - 4] - Sum[i - 5] + mod) % mod) % mod
    return Sum[n]


n = 6
print(sumOddFibonacci(n))

# Expected output:
44
# minimize the total number of teddies to be distributed | python implementation of the above approach ; initializing one tablet for each student ; if left adjacent is having higher marks review and change all the dp values assigned before until assigned dp values are found wrong according to 
def fun(marks, n):
    dp = [1 for i in range(0, n)]
    for i in range(0, n - 1):
        if marks[i] > marks[i + 1]:
            temp = i
            while True:
                if marks[temp] > marks[temp + 1] and temp >= 0:
                    if dp[temp] > dp[temp + 1]:
                        temp -= 1
                        continue
                    else:
                        dp[temp] = dp[temp + 1] + 1
                        temp -= 1
                else:
                    break
        elif marks[i] < marks[i + 1]:
            dp[i + 1] = dp[i] + 1
    return (sum(dp))


n = 6
marks = [1, 4, 5, 2, 2, 1]
print(fun(marks, n))

# Expected output:
10