giulio98/xlcost-single-prompt huggingface dataset:
# find the element that appears once in an array where every other element appears twice | function to find the once appearing element in array ; do xor of all elements and return ; 
def findSingle(ar, n):
    res = ar[0]
    for i in range(1, n):
        res = res ^ ar[i]
    return res


ar = [2, 3, 5, 4, 5, 3, 4]
print("Element occurring once is", findSingle(ar, len(ar)))

# Expected output:
Element occurring once is 2
# count all triplets whose sum is equal to a perfect cube | python 3 program to calculate all triplets whose sum is perfect cube . ; function to calculate all occurrence of a number in a given range ; if i == 0 assign 1 to present state ; else add + 1 to current state with previous state ; function to calculate triplets whose sum is equal to the perfect cube ; initialize answer ; count all occurrence of third triplet in range from j + 1 to n ; 

dp = [[0 for i in range(15001)]for j in range(1001)]


def computeDpArray(arr, n):
    for i in range(n):
        for j in range(1, 15001, 1):
            if (i == 0):
                dp[i][j] = (j == arr[i])
            else:
                dp[i][j] = dp[i - 1][j] + (arr[i] == j)


def countTripletSum(arr, n):
    computeDpArray(arr, n)
    ans = 0
    for i in range(0, n - 2, 1):
        for j in range(i + 1, n - 1, 1):
            for k in range(1, 25, 1):
                cube = k * k * k
                rem = cube - (arr[i] + arr[j])
                if (rem > 0):
                    ans += dp[n - 1][rem] - dp[j][rem]
    return ans


if __name__ == '__main__':
    arr = [2, 5, 1, 20, 6]
    n = len(arr)
    print(countTripletSum(arr, n))

# Expected output:
3
# find the element that appears once in an array where every other element appears twice | function which find number ; applying the formula . ; 
def singleNumber(nums):
    return 2 * sum(set(nums)) - sum(nums)


a = [2, 3, 5, 4, 5, 3, 4]
print(int(singleNumber(a)))
a = [15, 18, 16, 18, 16, 15, 89]
print(int(singleNumber(a)))

# Expected output:
2
89
# maximum subarray sum excluding certain elements | function to check the element present in array b ; utility function for findmaxsubarraysum ( ) with the following parameters a = > array a , b = > array b , n = > number of elements in array a , m = > number of elements in array b ; set max_so_far to int_min ; if the element is present in b , set current max to 0 and move to the next element ; proceed as in kadane 's algorithm ; wrapper for findmaxsubarraysumutil ( ) ; this case will occour when all elements of a are present in b , thus no subarray can be formed ; 

INT_MIN = -2147483648


def isPresent(B, m, x):
    for i in range(0, m):
        if B[i] == x:
            return True
    return False


def findMaxSubarraySumUtil(A, B, n, m):
    max_so_far = INT_MIN
    curr_max = 0
    for i in range(0, n):
        if isPresent(B, m, A[i]):
            curr_max = 0
            continue
        curr_max = max(A[i], curr_max + A[i])
        max_so_far = max(max_so_far, curr_max)
    return max_so_far


def findMaxSubarraySum(A, B, n, m):
    maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m)
    if maxSubarraySum == INT_MIN:
        print('Maximum Subarray Sum cant be found')
    else:
        print('The Maximum Subarray Sum =', maxSubarraySum)


A = [3, 4, 5, -4, 6]
B = [1, 8, 5]
n = len(A)
m = len(B)
findMaxSubarraySum(A, B, n, m)

# Expected output:
The Maximum Subarray Sum = 7
# number of n | python3 program for counting n digit numbers with non decreasing digits ; returns count of non - decreasing numbers with n digits . ; a [ i ] [ j ] = count of all possible number with i digits having leading digit as j ; initialization of all 0 - digit number ; initialization of all i - digit non - decreasing number leading with 9 ; for all digits we should calculate number of ways depending upon leading digits ; 

import numpy as np


def nonDecNums(n):
    a = np .zeros((n + 1, 10))
    for i in range(10):
        a[0][i] = 1
    for i in range(1, n + 1):
        a[i][9] = 1
    for i in range(1, n + 1):
        for j in range(8, -1, -1):
            a[i][j] = a[i - 1][j] + a[i][j + 1]
    return int(a[n][0])


if __name__ == "__main__":
    n = 2
    print("Non-decreasing digits = ", nonDecNums(n))

# Expected output:
Non-decreasing digits =  55
# count balanced binary trees of height h | python3 program to count number of balanced binary trees of height h . ; base cases ; 
def countBT(h):
    MOD = 1000000007
    dp = [0 for i in range(h + 1)]
    dp[0] = 1
    dp[1] = 1
    for i in range(2, h + 1):
        dp[i] = (dp[i - 1] * ((2 * dp[i - 2]) % MOD + dp[i - 1]) % MOD) % MOD
    return dp[h]


h = 3
print("No. of balanced binary trees of height " +
      str(h) + " is: " + str(countBT(h)))

# Expected output:
No. of balanced binary trees of height 3 is: 15
# maximum subarray sum excluding certain elements | python3 program implementation of the above idea ; function to calculate the max sum of contigous subarray of b whose elements are not present in a ; mark all the elements present in b ; initialize max_so_far with int_min ; traverse the array a ; if current max is greater than max so far then update max so far ; 

import sys


def findMaxSubarraySum(A, B):
    m = dict()
    for i in range(len(B)):
        if B[i]not in m:
            m[B[i]] = 0
        m[B[i]] = 1
    max_so_far = -sys .maxsize - 1
    currmax = 0
    for i in range(len(A)):
        if (currmax < 0 or (A[i] in m and m[A[i]] == 1)):
            currmax = 0
            continue
        currmax = max(A[i], A[i] + currmax)
        if (max_so_far < currmax):
            max_so_far = currmax
    return max_so_far


if __name__ == '__main__':
    a = [3, 4, 5, -4, 6]
    b = [1, 8, 5]
    print(findMaxSubarraySum(a, b))

# Expected output:
7
# equilibrium index of an array | function to find the equilibrium index ; check for indexes one by one until an equilibrium index is found ; get left sum ; get right sum ; if leftsum and rightsum are same , then we are done ; return - 1 if no equilibrium index is found ; 
def equilibrium(arr):
    leftsum = 0
    rightsum = 0
    n = len(arr)
    for i in range(n):
        leftsum = 0
        rightsum = 0
        for j in range(i):
            leftsum += arr[j]
        for j in range(i + 1, n):
            rightsum += arr[j]
        if leftsum == rightsum:
            return i
    return -1


arr = [-7, 1, 5, 2, -4, 3, 0]
print(equilibrium(arr))

# Expected output:
3
# find number of endless points | python3 program to find count of endless points ; returns count of endless points ; fills column matrix . for every column , start from every last row and fill every entry as blockage after a 0 is found . ; flag which will be zero once we get a '0' and it will be 1 otherwise ; encountered a '0' , set the isendless variable to false ; similarly , fill row matrix ; calculate total count of endless points ; if there is no blockage in row or column after this point , increment result . print ( row [ i ] [ j ] , col [ i ] [ j ] ) ; 

import numpy as np


def countEndless(input_mat, n):
    row = np .zeros((n, n))
    col = np .zeros((n, n))
    for j in range(n):
        isEndless = 1
        for i in range(n - 1, -1, -1):
            if (input_mat[i][j] == 0):
                isEndless = 0
            col[i][j] = isEndless
    for i in range(n):
        isEndless = 1
        for j in range(n - 1, -1, -1):
            if (input_mat[i][j] == 0):
                isEndless = 0
            row[i][j] = isEndless
    ans = 0
    for i in range(n):
        for j in range(1, n):
            if (row[i][j] and col[i][j]):
                ans += 1
            print(ans)
    return ans


if __name__ == "__main__":
    input_mat = [[1, 0, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 0]]
    n = 4
    print(countEndless(input_mat, n))

# Expected output:
0
1
1
2
3
3
4
5
5
5
5
5
5
# equilibrium index of an array | function to find the equilibrium index ; finding the sum of whole array ; total_sum is now right sum for index i ; if no equilibrium index found , then return - 1 ; 
def equilibrium(arr):
    total_sum = sum(arr)
    leftsum = 0
    for i, num in enumerate(arr):
        total_sum -= num
        if leftsum == total_sum:
            return i
        leftsum += num
    return -1


arr = [-7, 1, 5, 2, -4, 3, 0]
print('First equilibrium index is ', equilibrium(arr))

# Expected output:
First equilibrium index is  3
# sum of all substrings of a string representing a number | set 1 | returns sum of all substring of num ; allocate memory equal to length of string ; initialize first value with first digit ; loop over all digits of string ; update each sumofdigit from previous value ; add current value to the result ; 
def sumOfSubstrings(num):
    n = len(num)
    sumofdigit = []
    sumofdigit .append(int(num[0]))
    res = sumofdigit[0]
    for i in range(1, n):
        numi = int(num[i])
        sumofdigit .append((i + 1) * numi + 10 * sumofdigit[i - 1])
        res += sumofdigit[i]
    return res


num = "1234"
print(sumOfSubstrings(num))

# Expected output:
1670
# sum of all substrings of a string representing a number | set 1 | returns sum of all substring of num ; storing prev value ; substrings sum upto current index loop over all digits of string ; update each sumofdigit from previous value ; add current value to the result ; prev = current update previous ; 
def sumOfSubstrings(num):
    n = len(num)
    prev = int(num[0])
    res = prev
    current = 0
    for i in range(1, n):
        numi = int(num[i])
        current = (i + 1) * numi + 10 * prev
        res += current
    return res


num = "1234"
print(sumOfSubstrings(num))

# Expected output:
60
# equilibrium index of an array | python program to find the equilibrium index of an array function to find the equilibrium index ; iterate from 0 to len ( arr ) ; if i is not 0 ; iterate from 0 to len ( arr ) ; if no equilibrium index found , then return - 1 ; 
def equilibrium(arr):
    left_sum = []
    right_sum = []
    for i in range(len(arr)):
        if (i):
            left_sum .append(left_sum[i - 1] + arr[i])
            right_sum .append(right_sum[i - 1] + arr[len(arr) - 1 - i])
        else:
            left_sum .append(arr[i])
            right_sum .append(arr[len(arr) - 1])
    for i in range(len(arr)):
        if (left_sum[i] == right_sum[len(arr) - 1 - i]):
            return (i)
    return -1


arr = [-7, 1, 5, 2, -4, 3, 0]
print('First equilibrium index is ', equilibrium(arr))

# Expected output:
First equilibrium index is  3
# leaders in an array | python function to print leaders in array ; if loop didn 't break ; 
def printLeaders(arr, size):
    for i in range(0, size):
        for j in range(i + 1, size):
            if arr[i] <= arr[j]:
                break
        if j == size - 1:
            print(arr[i])


arr = [16, 17, 4, 3, 5, 2]
printLeaders(arr, len(arr))

# Expected output:
17
5
2
# leaders in an array | python function to print leaders in array ; rightmost element is always leader ; 
def printLeaders(arr, size):
    max_from_right = arr[size - 1]
    print(max_from_right)
    for i in range(size - 2, -1, -1):
        if max_from_right < arr[i]:
            print(arr[i])
            max_from_right = arr[i]


arr = [16, 17, 4, 3, 5, 2]
printLeaders(arr, len(arr))

# Expected output:
2
5
17
# unbounded knapsack ( repetition of items allowed ) | returns the maximum value with knapsack of w capacity ; dp [ i ] is going to store maximum value with knapsack capacity i . ; fill dp [ ] using above recursive formula ; 
def unboundedKnapsack(W, n, val, wt):
    dp = [0 for i in range(W + 1)]
    ans = 0
    for i in range(W + 1):
        for j in range(n):
            if (wt[j] <= i):
                dp[i] = max(dp[i], dp[i - wt[j]] + val[j])
    return dp[W]


W = 100
val = [10, 30, 20]
wt = [5, 10, 15]
n = len(val)
print(unboundedKnapsack(W, n, val, wt))

# Expected output:
300
# ceiling in a sorted array | function to get index of ceiling of x in arr [ low . . high ] ; if x is smaller than or equal to first element , then return the first element ; otherwise , linearly search for ceil value ; if x lies between arr [ i ] and arr [ i + 1 ] including arr [ i + 1 ] , then return arr [ i + 1 ] ; if we reach here then x is greater than the last element of the array , return - 1 in this case ; 
def ceilSearch(arr, low, high, x):
    if x <= arr[low]:
        return low
    i = low
    for i in range(high):
        if arr[i] == x:
            return i
        if arr[i] < x and arr[i + 1] >= x:
            return i + 1
    return -1


arr = [1, 2, 8, 10, 10, 12, 19]
n = len(arr)
x = 3
index = ceilSearch(arr, 0, n - 1, x)
if index == -1:
    print("Ceiling of %d doesn't exist in array " % x)
else:
    print("ceiling of %d is %d" % (x, arr[index]))

# Expected output:
ceiling of 3 is 8
# maximum sum subarray removing at most one element | method returns maximum sum of all subarray where removing one element is also allowed ; maximum sum subarrays in forward and backward directions ; initialize current max and max so far . ; calculating maximum sum subarrays in forward direction ; storing current maximum till ith , in forward array ; calculating maximum sum subarrays in backward direction ; storing current maximum from ith , in backward array ; initializing final ans by max_so_far so that , case when no element is removed to get max sum subarray is also handled ; choosing maximum ignoring ith element ; 
def maxSumSubarrayRemovingOneEle(arr, n):
    fw = [0 for k in range(n)]
    bw = [0 for k in range(n)]
    cur_max, max_so_far = arr[0], arr[0]
    fw[0] = cur_max
    for i in range(1, n):
        cur_max = max(arr[i], cur_max + arr[i])
        max_so_far = max(max_so_far, cur_max)
        fw[i] = cur_max
    cur_max = max_so_far = bw[n - 1] = arr[n - 1]
    i = n - 2
    while i >= 0:
        cur_max = max(arr[i], cur_max + arr[i])
        max_so_far = max(max_so_far, cur_max)
        bw[i] = cur_max
        i -= 1
    fans = max_so_far
    for i in range(1, n - 1):
        fans = max(fans, fw[i - 1] + bw[i + 1])
    return fans


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

# Expected output:
9
# ceiling in a sorted array | function to get index of ceiling of x in arr [ low . . high ] ; if x is smaller than or equal to the first element , then return the first element ; if x is greater than the last element , then return - 1 ; get the index of middle element of arr [ low . . high ] low + ( high - low ) / 2 ; if x is same as middle element , then return mid ; if x is greater than arr [ mid ] , then either arr [ mid + 1 ] is ceiling of x or ceiling lies in arr [ mid + 1. . . high ] ; if x is smaller than arr [ mid ] , then either arr [ mid ] is ceiling of x or ceiling lies in arr [ low ... mid - 1 ] ; 
def ceilSearch(arr, low, high, x):
    if x <= arr[low]:
        return low
    if x > arr[high]:
        return -1
    mid = (low + high) / 2
    if arr[mid] == x:
        return mid
    elif arr[mid] < x:
        if mid + 1 <= high and x <= arr[mid + 1]:
            return mid + 1
        else:
            return ceilSearch(arr, mid + 1, high, x)
    else:
        if mid - 1 >= low and x > arr[mid - 1]:
            return mid
        else:
            return ceilSearch(arr, low, mid - 1, x)


arr = [1, 2, 8, 10, 10, 12, 19]
n = len(arr)
x = 20
index = ceilSearch(arr, 0, n - 1, x)
if index == -1:
    print("Ceiling of %d doesn't exist in array " % x)
else:
    print("ceiling of %d is %d" % (x, arr[index]))

# Expected output:
Ceiling of 20 doesn't exist in array
# path with maximum average value | maximum number of rows and / or columns ; method returns maximum average of all path of cost matrix ; initialize first column of total cost ( dp ) array ; initialize first row of dp array ; construct rest of the dp array ; divide maximum sum by constant path length : ( 2 n - 1 ) for getting average ; 

M = 100


def maxAverageOfPath(cost, N):
    dp = [[0 for i in range(N + 1)]for j in range(N + 1)]
    dp[0][0] = cost[0][0]
    for i in range(1, N):
        dp[i][0] = dp[i - 1][0] + cost[i][0]
    for j in range(1, N):
        dp[0][j] = dp[0][j - 1] + cost[0][j]
    for i in range(1, N):
        for j in range(1, N):
            dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + cost[i][j]
    return dp[N - 1][N - 1] / (2 * N - 1)


cost = [[1, 2, 3], [6, 5, 4], [7, 3, 9]]
print(maxAverageOfPath(cost, 3))

# Expected output:
5.2
# maximum weight path ending at any element of last row in a matrix | python3 program to find the path having the maximum weight in matrix ; function which return the maximum weight path sum ; creat 2d matrix to store the sum of the path ; initialize first column of total weight array ( dp [ i to n ] [ 0 ] ) ; calculate rest path sum of weight matrix ; find the max weight path sum to reach the last row ; return maximum weight path sum ; 

MAX = 1000


def maxCost(mat, N):
    dp = [[0 for i in range(N)]for j in range(N)]
    dp[0][0] = mat[0][0]
    for i in range(1, N):
        dp[i][0] = mat[i][0] + dp[i - 1][0]
    for i in range(1, N):
        for j in range(1, min(i + 1, N)):
            dp[i][j] = mat[i][j] + max(dp[i - 1][j - 1], dp[i - 1][j])
    result = 0
    for i in range(N):
        if (result < dp[N - 1][i]):
            result = dp[N - 1][i]
    return result


mat = [[4, 1, 5, 6, 1], [2, 9, 2, 11, 10], [
    15, 1, 3, 15, 2], [16, 92, 41, 4, 3], [8, 142, 6, 4, 8]]
N = 5
print('Maximum Path Sum :', maxCost(mat, N))

# Expected output:
Maximum Path Sum : 255
# number of permutation with k inversions | limit on n and k ; 2d array memo for stopping solving same problem again ; method recursively calculates permutation with k inversion ; base cases ; if already solved then return result directly ; calling recursively all subproblem of permutation size n - 1 ; call recursively only if total inversion to be made are less than size ; store result into memo ; 

M = 100
memo = [[0 for i in range(M)]for j in range(M)]


def numberOfPermWithKInversion(N, K):
    if (N == 0):
        return 0
    if (K == 0):
        return 1
    if (memo[N][K] != 0):
        return memo[N][K]
    sum = 0
    for i in range(K + 1):
        if (i <= N - 1):
            sum += numberOfPermWithKInversion(N - 1, K - i)
    memo[N][K] = sum
    return sum


N = 4
K = 2
print(numberOfPermWithKInversion(N, K))

# Expected output:
5
# check if an array has a majority element | returns true if there is a majority element in a [ ] ; insert all elements in a hash table ; check if frequency of any element is n / 2 or more . ; 
def isMajority(a):
    mp = {}
    for i in a:
        if i in mp:
            mp[i] += 1
        else:
            mp[i] = 1
    for x in mp:
        if mp[x] >= len(a) // 2:
            return True
    return False


a = [2, 3, 9, 2, 2]
print("Yes"if isMajority(a)else "No")

# Expected output:
Yes
# two pointers technique | naive solution to find if there is a pair in a [ 0. . n - 1 ] with given sum . ; as equal i and j means same element ; pair exists ; as the array is sorted ; no pair found with given sum ; 
def isPairSum(A, N, X):
    for i in range(N):
        for j in range(N):
            if (i == j):
                continue
            if (A[i] + A[j] == X):
                return True
            if (A[i] + A[j] > X):
                break
    return 0


arr = [3, 5, 9, 2, 8, 10, 11]
val = 17
print(isPairSum(arr, len(arr), val))

# Expected output:
True
# remove minimum elements from either side such that 2 * min becomes more than max | a utility function to find minimum in arr [ l . . h ] ; a utility function to find maximum in arr [ l . . h ] ; returns the minimum number of removals from either end in arr [ l . . h ] so that 2 * min becomes greater than max . ; if there is 1 or less elements , return 0 for a single element , 2 * min > max ( assumption : all elements are positive in arr [ ] ) ; 1 ) find minimum and maximum in arr [ l . . h ] ; if the property is followed , no removals needed ; otherwise remove a character from left end and recur , then remove a character from right end and recur , take the minimum of two is returned ; 
def mini(arr, l, h):
    mn = arr[l]
    for i in range(l + 1, h + 1):
        if (mn > arr[i]):
            mn = arr[i]
    return mn


def max(arr, l, h):
    mx = arr[l]
    for i in range(l + 1, h + 1):
        if (mx < arr[i]):
            mx = arr[i]
    return mx


def minRemovals(arr, l, h):
    if (l >= h):
        return 0
    mn = mini(arr, l, h)
    mx = max(arr, l, h)
    if (2 * mn > mx):
        return 0
    return (min(minRemovals(arr, l + 1, h), minRemovals(arr, l, h - 1)) + 1)


arr = [4, 5, 100, 9, 10, 11, 12, 15, 200]
n = len(arr)
print(minRemovals(arr, 0, n - 1))

# Expected output:
4
# two pointers technique | two pointer technique based solution to find if there is a pair in a [ 0. . n - 1 ] with a 
def isPairSum(A, N, X):
    i = 0
    j = N - 1
    while (i < j):
        if (A[i] + A[j] == X):
            return True
        elif (A[i] + A[j] < X):
            i += 1
        else:
            j -= 1
    return 0


arr = [3, 5, 9, 2, 8, 10, 11]
val = 17
print(isPairSum(arr, len(arr), val))

# Expected output:
True
# Inorder Tree Traversal without Recursion | A binary tree node ; Iterative function for inorder tree traversal ; traverse the tree ; Reach the left most Node of the current Node ; Place pointer to a tree node on the stack before traversing the node 's left subtree ; BackTrack from the empty subtree and visit the Node at the top of the stack ; however , if the stack is empty you are done ; We have visited the node and its left subtree . Now , it ' s ▁ right ▁ subtree ' s turn ; Constructed binary tree is 1 / \ 2 3 / \ 4 5

class Node:
    def __init__(self, data):
        self .data = data
        self .left = None
        self .right = None


def inOrder(root):
    current = root
    stack = []
    done = 0
    while True:
        if current is not None:
            stack .append(current)
            current = current .left
        elif (stack):
            current = stack .pop()
            print(current .data, end=" ")
            current = current .right
        else:
            break
    print()


root = Node(1)
root .left = Node(2)
root .right = Node(3)
root .left .left = Node(4)
root .left .right = Node(5)
inOrder(root)

# Expected output:
4 2 5 1 3
# count all possible paths from top left to bottom right of a mxn matrix | returns count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; create a 2d table to store results of subproblems one - liner logic to take input for rows and columns mat = [ [ int ( input ( ) ) for x in range ( c ) ] for y in range ( r ) ] ; count of paths to reach any cell in first column is 1 ; count of paths to reach any cell in first column is 1 ; calculate count of paths for other cells in bottom - up manner using the recursive solution ; by uncommenting the last part the code calculates the total possible paths if the diagonal movements are allowed ; 
def numberOfPaths(m, n):
    count = [[0 for x in range(n)]for y in range(m)]
    for i in range(m):
        count[i][0] = 1
    for j in range(n):
        count[0][j] = 1
    for i in range(1, m):
        for j in range(1, n):
            count[i][j] = count[i - 1][j] + count[i][j - 1]
    return count[m - 1][n - 1]


m = 3
n = 3
print(numberOfPaths(m, n))

# Expected output:
6