giulio98/xlcost-single-prompt huggingface dataset:
# smallest index in given range of indices which is not equal to x | precompute the index of next different element in the array for every array element ; default value ; compute nextpos [ i ] using nextpos [ i + 1 ] ; function to return the smallest index ; nextpos [ i ] will store the next position p where arr [ p ] != arr [ i ] ; if x is not present at l ; otherwise ; find the index which stores a value different from x ; if that index is within the range ; 
def precompute(nextpos, arr, N):
    nextpos[N - 1] = N
    for i in range(N - 2, -1, -1):
        if arr[i] == arr[i + 1]:
            nextpos[i] = nextpos[i + 1]
        else:
            nextpos[i] = i + 1


def findIndex(query, arr, N, Q):
    nextpos = [0] * N
    precompute(nextpos, arr, N)
    for i in range(Q):
        l = query[i][0]
        r = query[i][1]
        x = query[i][2]
        ans = -1
        if arr[l] != x:
            ans = l
        else:
            d = nextpos[l]
            if d <= r:
                ans = d
        print(ans)


N = 6
Q = 3
arr = [1, 2, 1, 1, 3, 5]
query = [[0, 3, 1], [1, 5, 2], [2, 3, 1]]
findIndex(query, arr, N, Q)

# Expected output:
1
2
-1
# count number of ways to convert string s to t by performing k cyclic shifts | python3 program for the above approach ; function to count number of ways to convert string s to string t by performing k cyclic shifts ; calculate length of string ; a is no . of good cyclic shifts b is no . of bad cyclic shifts ; iterate in string ; precompute the number of good and bad cyclic shifts ; dp2 [ i ] to store the no of ways to get to a bad shift in i moves ; calculate good and bad shifts ; return the required number of ways ; given strings ; 

mod = 1000000007


def countWays(s, t, k):
    n = len(s)
    a = 0
    b = 0
    for i in range(n):
        p = s[i:n - i + 1] + s[:i + 1]
        if (p == t):
            a += 1
        else:
            b += 1
    dp1 = [0] * (k + 1)
    dp2 = [0] * (k + 1)
    if (s == t):
        dp1[0] = 1
        dp2[0] = 0
    else:
        dp1[0] = 0
        dp2[0] = 1
    for i in range(1, k + 1):
        dp1[i] = ((dp1[i - 1] * (a - 1)) % mod + (dp2[i - 1] * a) % mod) % mod
        dp2[i] = ((dp1[i - 1] * (b)) %
                  mod + (dp2[i - 1] * (b - 1)) % mod) % mod
    return (dp1[k])


S = 'ab'
T = 'ab'
K = 2
print(countWays(S, T, K))

# Expected output:
1
# minimize steps to reach k from 0 by adding 1 or doubling at each step | function to find minimum operations ; dp is initialised to store the steps ; for all even numbers ; 
def minOperation(k):
    dp = [0] * (k + 1)
    for i in range(1, k + 1):
        dp[i] = dp[i - 1] + 1
        if (i % 2 == 0):
            dp[i] = min(dp[i], dp[i // 2] + 1)
    return dp[k]


if __name__ == '__main__':
    k = 12
    print(minOperation(k))

# Expected output:
5
# find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum | function to find the maximum subset sum ; ignore the current element ; including element in partition 1 ; including element in partition 2 ; 
def maxSum(p0, p1, a, pos, n):
    if (pos == n):
        if (p0 == p1):
            return p0
        else:
            return 0
    ans = maxSum(p0, p1, a, pos + 1, n)
    ans = max(ans, maxSum(p0 + a[pos], p1, a, pos + 1, n))
    ans = max(ans, maxSum(p0, p1 + a[pos], a, pos + 1, n))
    return ans


if __name__ == "__main__":
    n = 4
    a = [1, 2, 3, 6]
    print(maxSum(0, 0, a, 0, n))

# Expected output:
6
# find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum | python3 implementation for the above mentioned dynamic programming approach ; function to find the maximum subset sum ; sum of all elements ; bottom up lookup table ; ; initialising dp table with int_min where , int_min means no solution ; case when diff is 0 ; putting ith element in g0 ; putting ith element in g1 ; ignoring ith element ; 

import numpy as np
import sys
INT_MIN = -(sys .maxsize - 1)


def maxSum(a, n):
    sum = 0
    for i in range(n):
        sum += a[i]
    limit = 2 * sum + 1
    dp = np .zeros((n + 1, limit))
    for i in range(n + 1):
        for j in range(limit):
            dp[i][j] = INT_MIN
    dp[0][sum] = 0
    for i in range(1, n + 1):
        for j in range(limit):
            if ((j - a[i - 1]) >= 0 and dp[i - 1][j - a[i - 1]] != INT_MIN):
                dp[i][j] = max(dp[i][j], dp[i - 1][j - a[i - 1]] + a[i - 1])
            if ((j + a[i - 1]) < limit and dp[i - 1][j + a[i - 1]] != INT_MIN):
                dp[i][j] = max(dp[i][j], dp[i - 1][j + a[i - 1]])
            if (dp[i - 1][j] != INT_MIN):
                dp[i][j] = max(dp[i][j], dp[i - 1][j])
    return dp[n][sum]


if __name__ == "__main__":
    n = 4
    a = [1, 2, 3, 6]
    print(maxSum(a, n))

# Expected output:
6.0
# golomb sequence | set 2 | python3 program to find the first n terms of golomb sequence ; function to print the golomb sequence ; initialise the array ; initialise the cnt to 0 ; first and second element of golomb sequence is 0 , 1 ; map to store the count of current element in golomb sequence ; store the count of 2 ; iterate over 2 to n ; if cnt is equals to 0 then we have new number for golomb sequence which is 1 + previous element ; else the current element is the previous element in this sequence ; map the current index to current value in arr [ ] ; print the golomb sequence ; 

MAX = 100001


def printGolombSequence(N):
    arr = [0] * MAX
    cnt = 0
    arr[0] = 0
    arr[1] = 1
    M = dict()
    M[2] = 2
    for i in range(2, N + 1):
        if (cnt == 0):
            arr[i] = 1 + arr[i - 1]
            cnt = M[arr[i]]
            cnt -= 1
        else:
            arr[i] = arr[i - 1]
            cnt -= 1
        M[i] = arr[i]
    for i in range(1, N + 1):
        print(arr[i], end=" ")


N = 11
printGolombSequence(N)

# Expected output:
1 2 2 3 3 4 4 4 5 5 5
# count ways to reach nth stairs by taking 1 and 2 steps with exactly one 3 step | function to find the number the number of ways to reach nth stair ; array including number of ways that includes 3 ; array including number of ways that doesn 't includes 3 ; initially to reach 3 stairs by taking 3 steps can be reached by 1 way ; loop to find the number the number of ways to reach nth stair ; 
def number_of_ways(n):
    includes_3 = [0] * (n + 1)
    not_includes_3 = [0] * (n + 1)
    includes_3[3] = 1
    not_includes_3[1] = 1
    not_includes_3[2] = 2
    not_includes_3[3] = 3
    for i in range(4, n + 1):
        includes_3[i] = includes_3[i - 1] + \
            includes_3[i - 2] + not_includes_3[i - 3]
        not_includes_3[i] = not_includes_3[i - 1] + not_includes_3[i - 2]
    return includes_3[n]


n = 7
print(number_of_ways(n))

# Expected output:
20
# maximum number of multiples in an array before any element | python3 implementation of the approach ; map to store the divisor count ; function to generate the divisors of all the array elements ; function to find the maximum number of multiples in an array before it ; to store the maximum divisor count ; update ans if more number of divisors are found ; generating all the divisors of the next element of the array ; 

from math import ceil, sqrt
MAX = 100000
divisors = [0] * MAX


def generateDivisors(n):
    for i in range(1, ceil(sqrt(n)) + 1):
        if (n % i == 0):
            if (n // i == i):
                divisors[i] += 1
            else:
                divisors[i] += 1
                divisors[n // i] += 1


def findMaxMultiples(arr, n):
    ans = 0
    for i in range(n):
        ans = max(divisors[arr[i]], ans)
        generateDivisors(arr[i])
    return ans


arr = [8, 1, 28, 4, 2, 6, 7]
n = len(arr)
print(findMaxMultiples(arr, n))

# Expected output:
3
# number of ways to reach the end of matrix with non | python3 implementation of the approach ; 3d array to store states of dp ; array to determine whether a state has been solved before ; function to return the count of required paths ; base cases ; if a state has been solved before it won 't be evaluated again ; recurrence relation ; 

n = 3
maxV = 20
dp = [[[0 for i in range(maxV)]for i in range(n)]for i in range(n)]
v = [[[0 for i in range(maxV)]for i in range(n)]for i in range(n)]


def countWays(i, j, x, arr):
    if (i == n or j == n):
        return 0
    x = (x & arr[i][j])
    if (x == 0):
        return 0
    if (i == n - 1 and j == n - 1):
        return 1
    if (v[i][j][x]):
        return dp[i][j][x]
    v[i][j][x] = 1
    dp[i][j][x] = countWays(i + 1, j, x, arr) + countWays(i, j + 1, x, arr)
    return dp[i][j][x]


arr = [[1, 2, 1], [1, 1, 0], [2, 1, 1]]
print(countWays(0, 0, arr[0][0], arr))

# Expected output:
1
# number of ways to make binary string of length n such that 0 s always occur together in groups of size k | python3 iimplementation of the above approach ; function to return no of ways to build a binary string of length n such that 0 s always occur in groups of size k ; 

mod = 1000000007


def noOfBinaryStrings(N, k):
    dp = [0] * 100002
    for i in range(1, K):
        dp[i] = 1
    dp[k] = 2
    for i in range(k + 1, N + 1):
        dp[i] = (dp[i - 1] + dp[i - k]) % mod
    return dp[N]


if __name__ == "__main__":
    N = 4
    K = 2
    print(noOfBinaryStrings(N, K))

# Expected output:
5
# number of ways to pair people | function to find number of ways to pair people in party ; to store count of number of ways . ; using the recurrence defined find count for different values of p . ; 
def findWays(p):
    dp = [0] * (p + 1)
    dp[1] = 1
    dp[2] = 2
    for i in range(3, p + 1):
        dp[i] = (dp[i - 1] + (i - 1) * dp[i - 2])
    return dp[p]


p = 3
print(findWays(p))

# Expected output:
4
# count ways to reach a score using 1 and 2 with no consecutive 2 s | a simple recursive implementation for counting ways to reach a score using 1 and 2 with consecutive 2 allowed ; base case ; for cases n > 2 ; 
def CountWays(n):
    if n == 0:
        return 1
    if n == 1:
        return 1
    if n == 2:
        return 1 + 1
    return CountWays(n - 1) + CountWays(n - 3)


if __name__ == '__main__':
    n = 5
    print(CountWays(n))

# Expected output:
6
# weird number | python 3 program to check if the number is weird or not ; code to find all the factors of the number excluding the number itself ; vector to store the factors ; note that this loop runs till sqrt ( n ) ; if the value of i is a factor ; condition to check the divisor is not the number itself ; return the vector ; function to check if the number is abundant or not ; find the divisors using function ; sum all the factors ; check for abundant or not ; function to check if the number is semi - perfect or not ; find the divisors ; sorting the vector ; subset to check if no is semiperfect ; initialising 1 st column to true ; initialing 1 st row except zero position to 0 ; loop to find whether the number is semiperfect ; calculation to check if the number can be made by summation of divisors ; if not possible to make the number by any combination of divisors ; function to check for weird or not ; 

from math import sqrt


def factors(n):
    v = []
    v .append(1)
    for i in range(2, int(sqrt(n)) + 1, 1):
        if (n % i == 0):
            v .append(i)
            if (int(n / i) != i):
                v .append(int(n / i))
    return v


def checkAbundant(n):
    sum = 0
    v = factors(n)
    for i in range(len(v)):
        sum += v[i]
    if (sum > n):
        return True
    else:
        return False


def checkSemiPerfect(n):
    v = factors(n)
    v .sort(reverse=False)
    r = len(v)
    subset = [[0 for i in range(n + 1)]for j in range(r + 1)]
    for i in range(r + 1):
        subset[i][0] = True
    for i in range(1, n + 1):
        subset[0][i] = False
    for i in range(1, r + 1):
        for j in range(1, n + 1):
            if (j < v[i - 1]):
                subset[i][j] = subset[i - 1][j]
            else:
                subset[i][j] = (subset[i - 1][j]
                                or subset[i - 1][j - v[i - 1]])
    if ((subset[r][n]) == 0):
        return False
    else:
        return True


def checkweird(n):
    if (checkAbundant(n) and checkSemiPerfect(n) == False):
        return True
    else:
        return False


if __name__ == '__main__':
    n = 70
    if (checkweird(n)):
        print("Weird Number")
    else:
        print("Not Weird Number")

# Expected output:
Weird Number
# maximum subarray sum in an array created after repeated concatenation | returns sum of maximum sum subarray created after concatenating a [ 0. . n - 1 ] k times . ; this is where it differs from kadane 's  algorithm. we use  modular arithmetic to  find next element. ; 
def maxSubArraySumRepeated(a, n, k):
    max_so_far = -2147483648
    max_ending_here = 0
    for i in range(n * k):
        max_ending_here = max_ending_here + a[i % n]
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here
        if (max_ending_here < 0):
            max_ending_here = 0
    return max_so_far


a = [10, 20, -30, -1]
n = len(a)
k = 3
print("Maximum contiguous sum is ", maxSubArraySumRepeated(a, n, k))

# Expected output:
Maximum contiguous sum is  30
# longest increasing odd even subsequence | function to find the longest increasing odd even subsequence ; lioes [ i ] stores longest increasing odd even subsequence ending at arr [ i ] ; to store the length of longest increasing odd even subsequence ; initialize lioes values for all indexes ; compute optimized lioes values in bottom up manner ; pick maximum of all lioes values ; required maximum length ; 
def longOddEvenIncSeq(arr, n):
    lioes = list()
    maxLen = 0
    for i in range(n):
        lioes .append(1)
    i = 1
    for i in range(n):
        for j in range(i):
            if (arr[i] > arr[j] and (arr[i] + arr[j]) %
                    2 != 0 and lioes[i] < lioes[j] + 1):
                lioes[i] = lioes[j] + 1
    for i in range(n):
        if maxLen < lioes[i]:
            maxLen = lioes[i]
    return maxLen


arr = [1, 12, 2, 22, 5, 30, 31, 14, 17, 11]
n = len(arr)
print(
    "Longest Increasing Odd Even " +
    "Subsequence: ",
    longOddEvenIncSeq(
        arr,
        n))

# Expected output:
Longest Increasing Odd Even Subsequence:  5
# minimum and maximum values of an expression with * and + | utility method to check whether a character is operator or not ; method prints minimum and maximum value obtainable from an expression ; store operator and numbers in different vectors ; storing last number in vector ; initializing minval and maxval 2d array ; initializing main diagonal by num values ; looping similar to matrix chain multiplication and updating both 2d arrays ; if current operator is ' + ' , updating tmp variable by addition ; if current operator is ' * ' , updating tmp variable by multiplication ; updating array values by tmp variables ; last element of first row will store the result ; 
def isOperator(op):
    return (op == '+' or op == '*')


def printMinAndMaxValueOfExp(exp):
    num = []
    opr = []
    tmp = ""
    for i in range(len(exp)):
        if (isOperator(exp[i])):
            opr .append(exp[i])
            num .append(int(tmp))
            tmp = ""
        else:
            tmp += exp[i]
    num .append(int(tmp))
    llen = len(num)
    minVal = [[0 for i in range(llen)]for i in range(llen)]
    maxVal = [[0 for i in range(llen)]for i in range(llen)]
    for i in range(llen):
        for j in range(llen):
            minVal[i][j] = 10 ** 9
            maxVal[i][j] = 0
            if (i == j):
                minVal[i][j] = maxVal[i][j] = num[i]
    for L in range(2, llen + 1):
        for i in range(llen - L + 1):
            j = i + L - 1
            for k in range(i, j):
                minTmp = 0
                maxTmp = 0
                if (opr[k] == '+'):
                    minTmp = minVal[i][k] + minVal[k + 1][j]
                    maxTmp = maxVal[i][k] + maxVal[k + 1][j]
                elif (opr[k] == '*'):
                    minTmp = minVal[i][k] * minVal[k + 1][j]
                    maxTmp = maxVal[i][k] * maxVal[k + 1][j]
                if (minTmp < minVal[i][j]):
                    minVal[i][j] = minTmp
                if (maxTmp > maxVal[i][j]):
                    maxVal[i][j] = maxTmp
    print("Minimum value : ",
          minVal[0][llen - 1],
          ", \\ Maximum value : ",
          maxVal[0][llen - 1])


expression = "1+2*3+4*5"
printMinAndMaxValueOfExp(expression)

# Expected output:
Minimum value :  27 , \ Maximum value :  105
# matrix chain multiplication | dp | a naive recursive implementation that simply follows the above optimal substructure property ; matrix a [ i ] has dimension p [ i - 1 ] x p [ i ] for i = 1. . n ; place parenthesis at different places between first and last matrix , recursively calculate count of multiplications for each parenthesis placement and return the minimum count ; return minimum count ; 

import sys


def MatrixChainOrder(p, i, j):
    if i == j:
        return 0
    _min = sys .maxsize
    for k in range(i, j):
        count = (MatrixChainOrder(p, i, k) +
                 MatrixChainOrder(p, k + 1, j) + p[i - 1] * p[k] * p[j])
        if count < _min:
            _min = count
    return _min


arr = [1, 2, 3, 4, 3]
n = len(arr)
print("Minimum number of multiplications is ", MatrixChainOrder(arr, 1, n - 1))

# Expected output:
Minimum number of multiplications is  30
# numbers formed by flipping common set bits in two given integers | function to flip bits of a and b which are set in both of them ; clear the bits of a which are set in both a and b ; clear the bits of b which are set in both a and b ; print updated a and b ; 
def flipBitsOfAandB(A, B):
    A = A ^ (A & B)
    B = B ^ (A & B)
    print(A, B)


if __name__ == "__main__":
    A = 10
    B = 20
    flipBitsOfAandB(A, B)

# Expected output:
10 20
# sum of hamming difference of consecutive numbers from 0 to n | set 2 | function to calculate and return the hamming distance between all consecutive numbers from 0 to n ; 
def TotalHammingDistance(n):
    i = 1
    sum = 0
    while (n // i > 0):
        sum = sum + n // i
        i = i * 2
    return sum


if __name__ == '__main__':
    N = 9
    print(TotalHammingDistance(N))

# Expected output:
16
# sum of all divisors from 1 to n | set 3 | python3 program to implement the above approach ; function to find the sum of all divisors of all numbers from 1 to n ; stores the sum ; marks the last poof occurence with same count ; calculate the sum ; return the result ; 

import math
m = 1000000007


def solve(n):
    s = 0
    l = 1
    while (l < n + 1):
        r = (int)(n / math .floor(n / l))
        x = ((((r % m) * ((r + 1) % m)) / 2) % m)
        y = ((((l % m) * ((l - 1) % m)) / 2) % m)
        p = (int)((n / l) % m)
        s = ((s + (((x - y) % m) * p) % m + m) % m)
        s %= m
        l = r + 1
    print(int((s + m) % m))


if __name__ == '__main__':
    n = 12
    solve(n)

# Expected output:
127
# minimize number of cuts required to break n length stick into n unit length sticks | python3 program to find minimum time required to split a stick of n length into unit pieces ; function to return the minimum time required to split stick of n into length into unit pieces ; return the minimum unit of time required ; 

import math


def min_time_to_cut(N):
    if (N == 0):
        return 0
    return int(math .log2(N)) + 1


N = 100
print(min_time_to_cut(N))

# Expected output:
7
# count of distinct pair sum between two 1 to n value arrays | function to find the distinct sums ; set to store distinct sums ; inserting every sum ; returning distinct sums ; 
def findDistinctSums(n):
    s = set()
    for i in range(1, n + 1):
        for j in range(i, n + 1):
            s .add(i + j)
    return len(s)


N = 3
print(findDistinctSums(N))

# Expected output:
5
# find starting index for every occurrence of given array b in array a using z | python3 implementation for pattern searching in an array using z - algorithm ; function to calculate z - array ; loop to calculate z - array ; outside the z - box ; inside z - box ; helper function to merge two arrays and create a single array ; array to store merged array ; copying array b ; adding a separator ; copying array a ; calling z - function ; function to help compute the z array ; printing indexes where array b occur ; 

import sys


def zArray(arr):
    n = len(arr)
    z = [0] * n
    r = 0
    l = 0
    for k in range(1, n):
        if (k > r):
            r = l = k
            while (r < n and arr[r] == arr[r - l]):
                r += 1
            z[k] = r - l
            r -= 1
        else:
            k1 = k - l
            if (z[k1] < r - k + 1):
                z[k] = z[k1]
            else:
                l = k
                while (r < n and arr[r] == arr[r - l]):
                    r += 1
                z[k] = r - l
                r -= 1
    return z


def mergeArray(A, B):
    n = len(A)
    m = len(B)
    c = [0] * (n + m + 1)
    for i in range(m):
        c[i] = B[i]
    c[m] = sys .maxsize
    for i in range(n):
        c[m + i + 1] = A[i]
    z = zArray(c)
    return z


def findZArray(A, B, n):
    flag = 0
    z = mergeArray(A, B)
    for i in range(len(z)):
        if (z[i] == n):
            print(i - n - 1, end=" ")
            flag = 1
    if (flag == 0):
        print("Not Found")


if __name__ == "__main__":
    A = [1, 2, 3, 2, 3, 2]
    B = [2, 3]
    n = len(B)
    findZArray(A, B, n)

# Expected output:
1 3
# check if a string can be repeated to make another string | function to return the count of repetitions of string a to generate string b ; if b cannot be generated by repeating a ; repeat a count number of times ; 
def getCount(a, b):
    if (len(b) % len(a) != 0):
        return -1
    count = int(len(b) / len(a))
    a = a * count
    if (a == b):
        return count
    return -1


if __name__ == '__main__':
    a = 'geeks'
    b = 'geeksgeeks'
    print(getCount(a, b))

# Expected output:
2
# check if a string can be formed from another string using given constraints | python3 program to check if a given string can be formed from another string using given constraints ; function to check if s2 can be formed of s1 ; length of strings ; hash - table to store count ; store count of each character ; traverse and check for every character ; if the character of s2 is present in s1 ; if the character of s2 is not present in s1 , then check if previous two ascii characters are present in s1 ; 

from collections import defaultdict


def check(S1, S2):
    n1 = len(S1)
    n2 = len(S2)
    mp = defaultdict(lambda: 0)
    for i in range(0, n1):
        mp[S1[i]] += 1
    for i in range(0, n2):
        if mp[S2[i]]:
            mp[S2[i]] -= 1
        elif (mp[chr(ord(S2[i]) - 1)] and mp[chr(ord(S2[i]) - 2)]):
            mp[chr(ord(S2[i]) - 1)] -= 1
            mp[chr(ord(S2[i]) - 2)] -= 1
        else:
            return False
    return True


if __name__ == "__main__":
    S1 = "abbat"
    S2 = "cat"
    if check(S1, S2):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# count of occurrences of a "1(0 + ) 1" pattern in a string | returns count of occurrences of "1(0 + ) 1" ; count = 0 initialize result ; check if encountered '1' forms a valid pattern as specified ; if 1 encountered for first time set oneseen to 1 ; check if there is any other character other than '0' or '1' . if so then set oneseen to 0 to search again for new pattern ; 
def countPattern(s):
    length = len(s)
    oneSeen = False
    count = 0
    for i in range(length):
        if (s[i] == '1' and oneSeen):
            if (s[i - 1] == '0'):
                count += 1
        if (s[i] == '1' and oneSeen == 0):
            oneSeen = True
        if (s[i] != '0' and s[i] != '1'):
            oneSeen = False
    return count


s = "100001abc101"
print(countPattern(s))

# Expected output:
2