giulio98/xlcost-single-prompt huggingface dataset:
# minimum difference between max and min of all k | returns min difference between max and min of any k - size subset ; sort the array so that close elements come together . ; initialize result by a big integer number ; loop over first ( n - k ) elements of the array only ; get difference between max and min of current k - sized segment ; 
def minDifferenceAmongMaxMin(arr, N, K):
    arr .sort()
    res = 2147483647
    for i in range((N - K) + 1):
        curSeqDiff = arr[i + K - 1] - arr[i]
        res = min(res, curSeqDiff)
    return res


arr = [10, 20, 30, 100, 101, 102]
N = len(arr)
K = 3
print(minDifferenceAmongMaxMin(arr, N, K))

# Expected output:
2
# position of an element after stable sort | python program to get index of array element in sorted array method returns the position of arr [ idx ] after performing stable - sort on array ; count of elements smaller than current element plus the equal element occurring before given index ; if element is smaller then increase the smaller count ; if element is equal then increase count only if it occurs before ; 
def getIndexInSortedArray(arr, n, idx):
    result = 0
    for i in range(n):
        if (arr[i] < arr[idx]):
            result += 1
        if (arr[i] == arr[idx] and i < idx):
            result += 1
    return result


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

# Expected output:
4
# find permutation of numbers upto n with a specific sum in a specific range | function to check if sum is possible with remaining numbers ; stores the minimum sum possible with x numbers ; stores the maximum sum possible with x numbers ; if s lies in the range [ minsum , maxsum ] ; function to find the resultant permutation ; stores the count of numbers in the given segment ; if the sum is not possible with numbers in the segment ; output - 1 ; stores the numbers present within the given segment ; iterate over the numbers from 1 to n ; if ( s - i ) is a positive non - zero sum and if it is possible to obtain ( s - i ) remaining numbers ; update sum s ; update required numbers in the segement ; push i in vector v ; if sum has been obtained ; break from the loop ; if sum is not obtained ; output - 1 ; stores the numbers which are not present in given segment ; loop to check the numbers not present in the segment ; pointer to check if i is present in vector v or not ; if i is not present in v ; push i in vector v1 ; point to the first elements of v1 and v respectively ; print the required permutation ; 
def possible(x, S, N):
    minSum = (x * (x + 1)) // 2
    maxSum = (x * ((2 * N) - x + 1)) // 2
    if (S < minSum or S > maxSum):
        return False
    return True


def findPermutation(N, L, R, S):
    x = R - L + 1
    if (not possible(x, S, N)):
        print("-1")
        return
    else:
        v = []
        for i in range(N, 0, -1):
            if ((S - i) >= 0 and possible(x - 1, S - i, i - 1)):
                S = S - i
                x -= 1
                v .append(i)
            if (S == 0):
                break
        if (S != 0):
            print(-1)
            return
        v1 = []
        for i in range(1, N + 1):
            it = i in v
            if (not it):
                v1 .append(i)
        j = 0
        f = 0
        for i in range(1, L):
            print(v1[j], end=" ")
            j += 1
        for i in range(L, R + 1):
            print(v[f], end=" ")
            f += 1
        for i in range(R + 1, N + 1):
            print(v1[j], end=" ")
            j += 1
    return


if __name__ == "__main__":
    N = 6
    L = 3
    R = 5
    S = 8
    findPermutation(N, L, R, S)

# Expected output:
3 4 5 2 1 6
# minimum count of indices to be skipped for every index of array to keep sum till that index at most t | function to calculate minimum indices to be skipped so that sum till i remains smaller than t ; store the sum of all indices before i ; store the elements that can be skipped ; traverse the array , a [ ] ; store the total sum of elements that needs to be skipped ; store the number of elements need to be removed ; traverse from the back of map so as to take bigger elements first ; update sum ; update map with the current element ; 
def skipIndices(N, T, arr):
    sum = 0
    count = {}
    for i in range(N):
        d = sum + arr[i] - T
        k = 0
        if (d > 0):
            for u in list(count .keys())[::-1]:
                j = u
                x = j * count[j]
                if (d <= x):
                    k += (d + j - 1) // j
                    break
                k += count[j]
                d -= x
        sum += arr[i]
        count[arr[i]] = count .get(arr[i], 0) + 1
        print(k, end=" ")


if __name__ == '__main__':
    N = 7
    T = 15
    arr = [1, 2, 3, 4, 5, 6, 7]
    skipIndices(N, T, arr)

# Expected output:
0 0 0 0 0 2 3
# count triplets ( a , b , c ) such that a + b , b + c and a + c are all divisible by k | set 2 | function to count the number of triplets from the range [ 1 , n - 1 ] having sum of all pairs divisible by k ; if k is even ; otherwise ; 
def countTriplets(N, K):
    if (K % 2 == 0):
        x = N // K
        y = (N + (K // 2)) // K
        return x * x * x + y * y * y
    else:
        x = N // K
        return x * x * x


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

# Expected output:
2
# maximize count of 3 | function to count the maximum number of palindrome subsequences of length 3 considering the same index only once ; index of the s ; stores the frequency of every character ; stores the pair of frequency containing same characters ; number of subsequences having length 3 ; counts the frequency ; counts the pair of frequency ; returns the minimum value ; 
def maxNumPalindrome(S):
    i = 0
    freq = [0] * 26
    freqPair = 0
    ln = len(S) // 3
    while (i < len(S)):
        freq[ord(S[i]) - ord('a')] += 1
        i += 1
    for i in range(26):
        freqPair += (freq[i] // 2)
    return min(freqPair, ln)


if __name__ == '__main__':
    S = "geeksforg"
    print(maxNumPalindrome(S))

# Expected output:
2
# sum of subsets of all the subsets of an array | o ( 2 ^ n ) | store the answer ; function to sum of all subsets of a given array ; function to generate the subsets ; base - case ; finding the sum of all the subsets of the generated subset ; recursively accepting and rejecting the current number ; 

c = []
ans = 0


def subsetSum():
    global ans
    L = len(c)
    mul = pow(2, L - 1)
    i = 0
    while (i < len(c)):
        ans += c[i] * mul
        i += 1


def subsetGen(arr, i, n):
    if (i == n):
        subsetSum()
        return
    subsetGen(arr, i + 1, n)
    c .append(arr[i])
    subsetGen(arr, i + 1, n)
    c .pop()


if __name__ == "__main__":
    arr = [1, 1]
    n = len(arr)
    subsetGen(arr, 0, n)
    print(ans)

# Expected output:
6
# find the maximum possible value of a [ i ] % a [ j ] over all pairs of i and j | function that returns the second largest element in the array if exists , else 0 ; there must be at least two elements ; to store the maximum and the second maximum element from the array ; if current element is greater than first then update both first and second ; if arr [ i ] is in between first and second then update second ; no second maximum found ; 

import sys


def getMaxValue(arr, arr_size):
    if (arr_size < 2):
        return 0
    first = -sys .maxsize - 1
    second = -sys .maxsize - 1
    for i in range(arr_size):
        if (arr[i] > first):
            second = first
            first = arr[i]
        elif (arr[i] > second and arr[i] != first):
            second = arr[i]
    if (second == -sys .maxsize - 1):
        return 0
    else:
        return second


if __name__ == '__main__':
    arr = [4, 5, 1, 8]
    n = len(arr)
    print(getMaxValue(arr, n))

# Expected output:
5
# maximize the value of the given expression | function to return the maximum result ; to store the count of negative integers ; sum of all the three integers ; product of all the three integers ; to store the smallest and the largest among all the three integers ; calculate the count of negative integers ; when all three are positive integers ; for single negative integer ; for two negative integers ; for three negative integers ; 
def maximumResult(a, b, c):
    countOfNegative = 0
    Sum = a + b + c
    product = a * b * c
    largest = max(a, b, c)
    smallest = min(a, b, c)
    if a < 0:
        countOfNegative += 1
    if b < 0:
        countOfNegative += 1
    if c < 0:
        countOfNegative += 1
    if countOfNegative == 0:
        return (Sum - largest) * largest
    elif countOfNegative == 1:
        return (product // smallest) + smallest
    elif countOfNegative == 2:
        return (product // largest) + largest
    elif countOfNegative == 3:
        return (Sum - smallest) * smallest


if __name__ == "__main__":
    a, b, c = -2, -1, -4
    print(maximumResult(a, b, c))

# Expected output:
12
# maximum students to pass after giving bonus to everybody and not exceeding 100 marks | function to return the number of students that can pass ; maximum marks ; maximum bonus marks that can be given ; counting the number of students that can pass ; 
def check(n, marks):
    x = max(marks)
    bonus = 100 - x
    c = 0
    for i in range(n):
        if (marks[i] + bonus >= 50):
            c += 1
    return c


n = 5
marks = [0, 21, 83, 45, 64]
print(check(n, marks))

# Expected output:
3
# sum of first n natural numbers which are not powers of k | function to return the sum of first n natural numbers which are not positive powers of k ; sum of first n natural numbers ; subtract all positive powers of k which are less than n ; next power of k ; 
def find_sum(n, k):
    total_sum = (n * (n + 1)) // 2
    power = k
    while power <= n:
        total_sum -= power
        power *= k
    return total_sum


n = 11
k = 2
print(find_sum(n, k))

# Expected output:
52
# minimum number of operations required to delete all elements of the array | python 3 implementation of the above approach ; function to find minimum operations ; sort array ; prepare hash of array ; 

MAX = 10000
hashTable = [0] * MAX


def minOperations(arr, n):
    arr .sort()
    for i in range(n):
        hashTable[arr[i]] += 1
    res = 0
    for i in range(n):
        if (hashTable[arr[i]]):
            for j in range(i, n):
                if (arr[j] % arr[i] == 0):
                    hashTable[arr[j]] = 0
            res += 1
    return res


if __name__ == "__main__":
    arr = [4, 6, 2, 8, 7, 21, 24, 49, 44]
    n = len(arr)
    print(minOperations(arr, n))

# Expected output:
2
# sorting array with reverse around middle | python 3 program to find possibility to sort by multiple subarray reverse operarion ; making the copy of the original array ; sorting the copied array ; checking mirror image of elements of sorted copy array and equivalent element of original array ; 
def ifPossible(arr, n):
    cp = [0] * n
    cp = sorted(arr)
    for i in range(0, n):
        if (not (arr[i] == cp[i]) and not (arr[n - 1 - i] == cp[i])):
            return False
    return True


arr = [1, 7, 6, 4, 5, 3, 2, 8]
n = len(arr)
if (ifPossible(arr, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# program for shortest job first ( sjf ) scheduling | set 2 ( preemptive ) | function to find the waiting time for all processes ; copy the burst time into rt [ ] ; process until all processes gets completed ; find process with minimum remaining time among the processes that arrives till the current time ` ; reduce remaining time by one ; update minimum ; if a process gets completely executed ; increment complete ; find finish time of current process ; calculate waiting time ; increment time ; function to calculate turn around time ; calculating turnaround time ; function to calculate average waiting and turn - around times . ; function to find waiting time of all processes ; function to find turn around time for all processes ; display processes along with all details ; 
def findWaitingTime(processes, n, wt):
    rt = [0] * n
    for i in range(n):
        rt[i] = processes[i][1]
    complete = 0
    t = 0
    minm = 999999999
    short = 0
    check = False
    while (complete != n):
        for j in range(n):
            if ((processes[j][2] <= t) and (rt[j] < minm) and rt[j] > 0):
                minm = rt[j]
                short = j
                check = True
        if (check == False):
            t += 1
            continue
        rt[short] -= 1
        minm = rt[short]
        if (minm == 0):
            minm = 999999999
        if (rt[short] == 0):
            complete += 1
            check = False
            fint = t + 1
            wt[short] = (fint - proc[short][1] - proc[short][2])
            if (wt[short] < 0):
                wt[short] = 0
        t += 1


def findTurnAroundTime(processes, n, wt, tat):
    for i in range(n):
        tat[i] = processes[i][1] + wt[i]


def findavgTime(processes, n):
    wt = [0] * n
    tat = [0] * n
    findWaitingTime(processes, n, wt)
    findTurnAroundTime(processes, n, wt, tat)
    print("Processes Burst Time Waiting", "Time Turn-Around Time")
    total_wt = 0
    total_tat = 0
    for i in range(n):
        total_wt = total_wt + wt[i]
        total_tat = total_tat + tat[i]
        print(
            " ",
            processes[i][0],
            "TABSYMBOLTABSYMBOL",
            processes[i][1],
            "TABSYMBOLTABSYMBOL",
            wt[i],
            "TABSYMBOLTABSYMBOL",
            tat[i])
    print("Averagewaitingtime=%.5f" % (total_wt / n))
    print("Average turn around time = ", total_tat / n)


if __name__ == "__main__":
    proc = [[1, 6, 1], [2, 8, 1], [3, 7, 2], [4, 3, 3]]
    n = 4
    findavgTime(proc, n)

# Expected output:
Processes Burst Time Waiting Time Turn-Around Time
  1 TABSYMBOLTABSYMBOL 6 TABSYMBOLTABSYMBOL 3 TABSYMBOLTABSYMBOL 9
  2 TABSYMBOLTABSYMBOL 8 TABSYMBOLTABSYMBOL 16 TABSYMBOLTABSYMBOL 24
  3 TABSYMBOLTABSYMBOL 7 TABSYMBOLTABSYMBOL 8 TABSYMBOLTABSYMBOL 15
  4 TABSYMBOLTABSYMBOL 3 TABSYMBOLTABSYMBOL 0 TABSYMBOLTABSYMBOL 3
Averagewaitingtime=6.75000
Average turn around time =  12.75
# count n | function to count n - length strings consisting of vowels only sorted lexicographically ; 
def findNumberOfStrings(N):
    counts = []
    for i in range(5):
        counts .append(1)
    for i in range(2, N + 1):
        for j in range(3, -1, -1):
            counts[j] += counts[j + 1]
    ans = 0
    for c in counts:
        ans += c
    return ans


N = 2
print(findNumberOfStrings(N))

# Expected output:
15
# count n | stores the value of overlapping states ; function to check whether a number have only digits x or y or not ; until sum is positive ; if any digit is not x or y then return 0 ; return 1 ; function to find the count of numbers that are formed by digits x and y and whose sum of digit also have digit x or y ; initialize dp array ; base case ; check if sum of digits formed by only x or y ; return the already computed ; place the digit x at the current position ; place the digit y at the current position ; update current state result ; 

dp = [[-1 for x in range(9000 + 5)]for y in range(1000 + 5)]
mod = 1000000007


def check(sum, x, y):
    while (sum > 0):
        ln = sum % 10
        if (ln != x and ln != y):
            return 0
        sum //= 10
    return 1


def countNumbers(n, x, y, sum):
    global dp
    if (n == 0):
        return check(sum, x, y)
    if (dp[n][sum] != -1):
        return dp[n][sum] % mod
    option1 = countNumbers(n - 1, x, y, sum + x) % mod
    option2 = countNumbers(n - 1, x, y, sum + y) % mod
    dp[n][sum] = (option1 + option2) % mod
    return dp[n][sum]


if __name__ == "__main__":
    N = 3
    X = 1
    Y = 5
    print(countNumbers(N, X, Y, 0) % mod)

# Expected output:
4
# minimum cost to generate any permutation of the given string | function to find the minimum cost to form any permutation of string s ; base case ; return the precomputed state ; iterate over the string and check all possible characters available for current position ; check if character can be placed at current position ; as there is no previous character so the cost for 1 st character is 0 ; find the cost of current character and move to next position ; store the answer for each current state ; function that returns true if the current bit is set ; function that generates any permutation of the given string with minimum cost ; initialize dp table ; set all the bits of the current character id ; minimum cost of generating the permutation ; 
def solve(a, s, n, prev, mask, dp):
    if (mask == 0):
        return 0
    if (dp[mask][prev + 1] != -1):
        return dp[mask][prev + 1]
    ans = 10000
    for i in range(len(s)):
        id = ord(s[i]) - ord('a')
        if (check(mask, id)):
            if (prev == -1):
                ans = min(ans, solve(a, s, n, id, mask ^ (1 << id), dp))
            else:
                ans = min(
                    ans,
                    a[prev][id] +
                    solve(
                        a,
                        s,
                        n,
                        id,
                        mask ^ (
                            1 << id),
                        dp))
    dp[mask][prev + 1] = ans
    return ans


def check(mask, i):
    c = (mask & (1 << i))
    return c != 0


def generatePermutation(mask, n, a, s):
    dp = [[-1 for i in range(n + 5)]for j in range((1 << n) + 5)]
    for i in range(len(s)):
        id = ord(s[i]) - ord('a')
        mask |= (1 << id)
    print(solve(a, s, n, -1, mask, dp))


if __name__ == '__main__':
    N = 5
    str = "abcde"
    mat = [[0, 5, 1, 5, 3], [4, 0, 9, 4, 2], [
        7, 9, 0, 10, 7], [1, 2, 8, 0, 2], [3, 9, 7, 7, 0]]
    generatePermutation(0, N, mat, str)

# Expected output:
8
# minimize operations required to obtain n | ''function to find the minimum number of operations ; storing the minimum operations to obtain all numbers up to n ; initial state ; iterate for the remaining numbers ; if the number can be obtained by multiplication by 2 ; if the number can be obtained by multiplication by 3 ; obtaining the number by adding 1 ; return the minimum operations to obtain n ; 

import sys


def minOperations(n):
    dp = [sys .maxsize] * (n + 1)
    dp[1] = 0
    for i in range(2, n + 1):
        if i % 2 == 0:
            x = dp[i // 2]
            if x + 1 < dp[i]:
                dp[i] = x + 1
        if i % 3 == 0:
            x = dp[i // 3]
            if x + 1 < dp[i]:
                dp[i] = x + 1
        x = dp[i - 1]
        if x + 1 < dp[i]:
            dp[i] = x + 1
    return dp[n]


n = 15
print(minOperations(n))

# Expected output:
4
# longest reverse bitonic sequence | function to return the length of the longest reverse bitonic subsequence in the array ; allocate memory for lis [ ] and initialize lis values as 1 for all indexes ; compute lis values from left to right ; allocate memory for lds and initialize lds values for all indexes ; compute lds values from right to left loop from n - 2 downto 0 ; loop from n - 1 downto i - 1 ; return the maximum value of ( lis [ i ] + lds [ i ] - 1 ) ; 
def ReverseBitonic(arr):
    N = len(arr)
    lds = [1 for i in range(N + 1)]
    for i in range(1, N):
        for j in range(0, i):
            if ((arr[i] < arr[j]) and (lds[i] < lds[j] + 1)):
                lds[i] = lds[j] + 1
    lis = [1 for i in range(N + 1)]
    for i in reversed(range(N - 1)):
        for j in reversed(range(i - 1, N)):
            if (arr[i] < arr[j] and lis[i] < lis[j] + 1):
                lis[i] = lis[j] + 1
    maximum = lis[0] + lds[0] - 1
    for i in range(1, N):
        maximum = max((lis[i] + lds[i] - 1), maximum)
    return maximum


arr = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
print("Length of LBS is", ReverseBitonic(arr))

# Expected output:
Length of LBS is 7
# maze with n doors and 1 key | recursive function to check whether there is a path from the top left cell to the bottom right cell of the maze ; check whether the current cell is within the maze ; if key is required to move further ; if the key hasn 't been used before ; if current cell is the destination ; either go down or right ; key has been used before ; if current cell is the destination ; either go down or right ; 
def findPath(maze, xpos, ypos, key):
    if xpos < 0 or xpos >= len(maze) or ypos < 0 or ypos >= len(maze):
        return False
    if maze[xpos][ypos] == '1':
        if key:
            if xpos == len(maze) - 1 and ypos == len(maze) - 1:
                return True
            return findPath(
                maze,
                xpos + 1,
                ypos,
                False) or findPath(
                maze,
                xpos,
                ypos + 1,
                False)
        return False
    if xpos == len(maze) - 1 and ypos == len(maze) - 1:
        return True
    return findPath(
        maze,
        xpos +
        1,
        ypos,
        key) or findPath(
        maze,
        xpos,
        ypos +
        1,
        key)


def mazeProb(maze, xpos, ypos):
    key = True
    if findPath(maze, xpos, ypos, key):
        return True
    return False


if __name__ == "__main__":
    maze = [['0', '0', '1'], ['1', '0', '1'], ['1', '1', '0']]
    n = len(maze)
    if mazeProb(maze, 0, 0):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimum cost to reach end of array array when a maximum jump of k index is allowed | python 3 implementation of the approach ; function to return the minimum cost to reach the last index ; if we reach the last index ; already visited state ; initially maximum ; visit all possible reachable index ; if inside range ; we cannot move any further ; memoize ; 

import sys


def FindMinimumCost(ind, a, n, k, dp):
    if (ind == (n - 1)):
        return 0
    elif (dp[ind] != -1):
        return dp[ind]
    else:
        ans = sys .maxsize
        for i in range(1, k + 1):
            if (ind + i < n):
                ans = min(ans, abs(a[ind + i] - a[ind]) +
                          FindMinimumCost(ind + i, a, n, k, dp))
            else:
                break
        dp[ind] = ans
        return ans


if __name__ == '__main__':
    a = [10, 30, 40, 50, 20]
    k = 3
    n = len(a)
    dp = [-1 for i in range(n)]
    print(FindMinimumCost(0, a, n, k, dp))

# Expected output:
30
# count of numbers between range having only non | function to return the count of required numbers from 0 to num ; last position ; if this result is already computed simply return it ; maximum limit upto which we can place digit . if tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; if the current digit is zero and nonz is 1 , we can 't place it ; function to convert x into its digit vector and uses count ( ) function to return the required count ; initialize dp ; 
def count(pos, Sum, rem, tight, nonz, num):
    if pos == len(num):
        if rem == 0 and Sum == n:
            return 1
        return 0
    if dp[pos][Sum][rem][tight] != -1:
        return dp[pos][Sum][rem][tight]
    ans = 0
    if tight:
        limit = 9
    else:
        limit = num[pos]
    for d in range(0, limit + 1):
        if d == 0 and nonz:
            continue
        currSum = Sum + d
        currRem = (rem * 10 + d) % m
        currF = int(tight or (d < num[pos]))
        ans += count(pos + 1, currSum, currRem, currF, nonz or d, num)
    dp[pos][Sum][rem][tight] = ans
    return ans


def solve(x):
    num = []
    global dp
    while x > 0:
        num .append(x % 10)
        x //= 10
    num .reverse()
    dp = [[[[-1, -1]for i in range(M)]for j in range(165)]for k in range(M)]
    return count(0, 0, 0, 0, 0, num)


if __name__ == "__main__":
    L, R = 1, 100
    n, m, M = 8, 2, 20
    dp = []
    print(solve(R) - solve(L))

# Expected output:
4