giulio98/xlcost-single-prompt huggingface dataset:
# minimum initial points to reach destination | python3 program to find minimum initial points to reach destination ; dp [ i ] [ j ] represents the minimum initial points player should have so that when starts with cell ( i , j ) successfully reaches the destination cell ( m - 1 , n - 1 ) ; base case ; fill last row and last column as base to fill entire table ; fill the table in bottom - up fashion ; 

import math as mt
R = 3
C = 3


def minInitialPoints(points):
    dp = [[0 for x in range(C + 1)]for y in range(R + 1)]
    m, n = R, C
    if points[m - 1][n - 1] > 0:
        dp[m - 1][n - 1] = 1
    else:
        dp[m - 1][n - 1] = abs(points[m - 1][n - 1]) + 1
    for i in range(m - 2, -1, -1):
        dp[i][n - 1] = max(dp[i + 1][n - 1] - points[i][n - 1], 1)
    for i in range(2, -1, -1):
        dp[m - 1][i] = max(dp[m - 1][i + 1] - points[m - 1][i], 1)
    for i in range(m - 2, -1, -1):
        for j in range(n - 2, -1, -1):
            min_points_on_exit = min(dp[i + 1][j], dp[i][j + 1])
            dp[i][j] = max(min_points_on_exit - points[i][j], 1)
    return dp[0][0]


points = [[-2, -3, 3], [-5, -10, 1], [10, 30, -5]]
print("Minimum Initial Points Required:", minInitialPoints(points))

# Expected output:
Minimum Initial Points Required: 7
# find a peak element | find the peak element in the array ; first or last element is peak element ; check for every other element ; check if the neighbors are smaller ; 
def findPeak(arr, n):
    if (n == 1):
        return 0
    if (arr[0] >= arr[1]):
        return 0
    if (arr[n - 1] >= arr[n - 2]):
        return n - 1
    for i in range(1, n - 1):
        if (arr[i] >= arr[i - 1] and arr[i] >= arr[i + 1]):
            return i


arr = [1, 3, 20, 4, 1, 0]
n = len(arr)
print("Index of a peak point is", findPeak(arr, n))

# Expected output:
Index of a peak point is 2
# find a peak element | a binary search based function that returns index of a peak element ; find index of middle element ( low + high ) / 2 ; compare middle element with its neighbours ( if neighbours exist ) ; if middle element is not peak and its left neighbour is greater than it , then left half must have a peak element ; if middle element is not peak and its right neighbour is greater than it , then right half must have a peak element ; a wrapper over recursive function findpeakutil ( ) ; 
def findPeakUtil(arr, low, high, n):
    mid = low + (high - low) / 2
    mid = int(mid)
    if ((mid == 0 or arr[mid - 1] <= arr[mid])
            and (mid == n - 1 or arr[mid + 1] <= arr[mid])):
        return mid
    elif (mid > 0 and arr[mid - 1] > arr[mid]):
        return findPeakUtil(arr, low, (mid - 1), n)
    else:
        return findPeakUtil(arr, (mid + 1), high, n)


def findPeak(arr, n):
    return findPeakUtil(arr, 0, n - 1, n)


arr = [1, 3, 20, 4, 1, 0]
n = len(arr)
print("Index of a peak point is", findPeak(arr, n))

# Expected output:
Index of a peak point is 2
# find the two repeating elements in a given array | print repeating function ; 
def printRepeating(arr, size):
    print("Repeating elements are ", end='')
    for i in range(0, size):
        for j in range(i + 1, size):
            if arr[i] == arr[j]:
                print(arr[i], end=' ')


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

# Expected output:
Repeating elements are 4 2
# find the two repeating elements in a given array | function ; 
def printRepeating(arr, size):
    count = [0] * size
    print(" Repeating elements are ", end="")
    for i in range(0, size):
        if (count[arr[i]] == 1):
            print(arr[i], end=" ")
        else:
            count[arr[i]] = count[arr[i]] + 1


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

# Expected output:
 Repeating elements are 4 2
# find the two repeating elements in a given array | python3 code for find the two repeating elements in a given array ; printrepeating function ; s is for sum of elements in arr [ ] ; p is for product of elements in arr [ ] ; calculate sum and product of all elements in arr [ ] ; s is x + y now ; p is x * y now ; d is x - y now ; factorial of n ; 

import math


def fact(n):
    if (n == 0):
        return 1
    else:
        return (n * fact(n - 1))


def printRepeating(arr, size):
    S = 0
    P = 1
    n = size - 2
    for i in range(0, size):
        S = S + arr[i]
        P = P * arr[i]
    S = S - n * (n + 1) // 2
    P = P // fact(n)
    D = math .sqrt(S * S - 4 * P)
    x = (D + S) // 2
    y = (S - D) // 2
    print("The two Repeating elements are ", (int)(x), " & ", (int)(y))


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

# Expected output:
The two Repeating elements are  4  &  2
# find the two repeating elements in a given array | python3 code to find the two repeating elements in a given array ; will hold xor of all elements ; will have only single set bit of xor ; get the xor of all elements in arr [ ] and 1 , 2 . . n ; get the rightmost set bit in set_bit_no ; now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element . ; xor of first set in arr [ ] ; xor of second set in arr [ ] ; xor of first set in arr [ ] and 1 , 2 , ... n ; xor of second set in arr [ ] and 1 , 2 , ... n ; 
def printRepeating(arr, size):
    xor = arr[0]
    n = size - 2
    x = 0
    y = 0
    for i in range(1, size):
        xor ^= arr[i]
    for i in range(1, n + 1):
        xor ^= i
    set_bit_no = xor & ~(xor - 1)
    for i in range(0, size):
        if (arr[i] & set_bit_no):
            x = x ^ arr[i]
        else:
            y = y ^ arr[i]
    for i in range(1, n + 1):
        if (i & set_bit_no):
            x = x ^ i
        else:
            y = y ^ i
    print("The two repeating", "elements are", y, x)


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

# Expected output:
The two repeating elements are 4 2
# find the two repeating elements in a given array | function to print repeating ; 
def printRepeating(arr, size):
    print(" The repeating elements are", end=" ")
    for i in range(0, size):
        if (arr[abs(arr[i])] > 0):
            arr[abs(arr[i])] = (-1) * arr[abs(arr[i])]
        else:
            print(abs(arr[i]), end=" ")


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

# Expected output:
 The repeating elements are 4 2
# find subarray with given sum | set 1 ( nonnegative numbers ) | returns true if the there is a subarray of arr [ ] with sum equal to ' sum ' otherwise returns false . also , prints the result ; pick a starting point ; try all subarrays starting with 'i   ; 
def subArraySum(arr, n, sum_):
    for i in range(n):
        curr_sum = arr[i]
        j = i + 1
        while j <= n:
            if curr_sum == sum_:
                print("Sum found between")
                print("indexes % d and % d" % (i, j - 1))
                return 1
            if curr_sum > sum_ or j == n:
                break
            curr_sum = curr_sum + arr[j]
            j += 1
    print("No subarray found")
    return 0


arr = [15, 2, 4, 8, 9, 5, 10, 23]
n = len(arr)
sum_ = 23
subArraySum(arr, n, sum_)

# Expected output:
Sum found between
indexes  1 and  4
# find subarray with given sum | set 1 ( nonnegative numbers ) | returns true if the there is a subarray of arr [ ] with sum equal to ' sum ' otherwise returns false . also , prints the result . ; initialize curr_sum as value of first element and starting point as 0 ; add elements one by one to curr_sum and if the curr_sum exceeds the sum , then remove starting element ; if curr_sum exceeds the sum , then remove the starting elements ; if curr_sum becomes equal to sum , then return true ; add this element to curr_sum ; if we reach here , then no subarray ; 
def subArraySum(arr, n, sum_):
    curr_sum = arr[0]
    start = 0
    i = 1
    while i <= n:
        while curr_sum > sum_ and start < i - 1:
            curr_sum = curr_sum - arr[start]
            start += 1
        if curr_sum == sum_:
            print("Sum found between indexes")
            print("% d and % d" % (start, i - 1))
            return 1
        if i < n:
            curr_sum = curr_sum + arr[i]
        i += 1
    print("No subarray found")
    return 0


arr = [15, 2, 4, 8, 9, 5, 10, 23]
n = len(arr)
sum_ = 23
subArraySum(arr, n, sum_)

# Expected output:
Sum found between indexes
 1 and  4
# smallest difference triplet from three arrays | function to find maximum number ; function to find minimum number ; finds and prints the smallest difference triplet ; sorting all the three arrays ; to store resultant three numbers ; pointers to arr1 , arr2 , arr3 respectively ; loop until one array reaches to its end find the smallest difference . ; maximum number ; find minimum and increment its index . ; comparing new difference with the previous one and updating accordingly ; print result ; 
def maximum(a, b, c):
    return max(max(a, b), c)


def minimum(a, b, c):
    return min(min(a, b), c)


def smallestDifferenceTriplet(arr1, arr2, arr3, n):
    arr1 .sort()
    arr2 .sort()
    arr3 .sort()
    res_min = 0
    res_max = 0
    res_mid = 0
    i = 0
    j = 0
    k = 0
    diff = 2147483647
    while (i < n and j < n and k < n):
        sum = arr1[i] + arr2[j] + arr3[k]
        max = maximum(arr1[i], arr2[j], arr3[k])
        min = minimum(arr1[i], arr2[j], arr3[k])
        if (min == arr1[i]):
            i += 1
        elif (min == arr2[j]):
            j += 1
        else:
            k += 1
        if (diff > (max - min)):
            diff = max - min
            res_max = max
            res_mid = sum - (max + min)
            res_min = min
    print(res_max, ",", res_mid, ",", res_min)


arr1 = [5, 2, 8]
arr2 = [10, 7, 12]
arr3 = [9, 14, 6]
n = len(arr1)
smallestDifferenceTriplet(arr1, arr2, arr3, n)

# Expected output:
7 , 6 , 5
# find a triplet that sum to a given value | returns true if there is triplet with sum equal to ' sum ' present in a [ ] . also , prints the triplet ; fix the first element as a [ i ] ; fix the second element as a [ j ] ; now look for the third number ; if we reach here , then no triplet was found ; 
def find3Numbers(A, arr_size, sum):
    for i in range(0, arr_size - 2):
        for j in range(i + 1, arr_size - 1):
            for k in range(j + 1, arr_size):
                if A[i] + A[j] + A[k] == sum:
                    print("Triplet is", A[i], ", ", A[j], ", ", A[k])
                    return True
    return False


A = [1, 4, 45, 6, 10, 8]
sum = 22
arr_size = len(A)
find3Numbers(A, arr_size, sum)

# Expected output:
Triplet is 4 ,  10 ,  8
# find a triplet that sum to a given value | returns true if there is triplet with sum equal to ' sum ' present in a [ ] . also , prints the triplet ; sort the elements ; now fix the first element one by one and find the other two elements ; to find the other two elements , start two index variables from two corners of the array and move them toward each other index of the first element in the remaining elements ; index of the last element ; a [ i ] + a [ l ] + a [ r ] > sum ; if we reach here , then no triplet was found ; 
def find3Numbers(A, arr_size, sum):
    A .sort()
    for i in range(0, arr_size - 2):
        l = i + 1
        r = arr_size - 1
        while (l < r):
            if (A[i] + A[l] + A[r] == sum):
                print("Triplet is", A[i], ', ', A[l], ', ', A[r])
                return True
            elif (A[i] + A[l] + A[r] < sum):
                l += 1
            else:
                r -= 1
    return False


A = [1, 4, 45, 6, 10, 8]
sum = 22
arr_size = len(A)
find3Numbers(A, arr_size, sum)

# Expected output:
Triplet is 4 ,  8 ,  10
# find a triplet that sum to a given value | returns true if there is triplet with sum equal to ' sum ' present in a [ ] . also , prints the triplet ; fix the first element as a [ i ] ; find pair in subarray a [ i + 1. . n - 1 ] with sum equal to sum - a [ i ] ; if we reach here , then no triplet was found ; 
def find3Numbers(A, arr_size, sum):
    for i in range(0, arr_size - 1):
        s = set()
        curr_sum = sum - A[i]
        for j in range(i + 1, arr_size):
            if (curr_sum - A[j]) in s:
                print("Triplet is", A[i], ", ", A[j], ", ", curr_sum - A[j])
                return True
            s .add(A[j])
    return False


A = [1, 4, 45, 6, 10, 8]
sum = 22
arr_size = len(A)
find3Numbers(A, arr_size, sum)

# Expected output:
Triplet is 4 ,  8 ,  10
# subarray / substring vs subsequence and programs to generate them | prints all subarrays in arr [ 0. . n - 1 ] ; pick starting point ; pick ending point ; print subarray between current starting and ending points ; 
def subArray(arr, n):
    for i in range(0, n):
        for j in range(i, n):
            for k in range(i, j + 1):
                print(arr[k], end=" ")
            print("", end="")


arr = [1, 2, 3, 4]
n = len(arr)
print("All Non-empty Subarrays")
subArray(arr, n)

# Expected output:
All Non-empty Subarrays
1 1 2 1 2 3 1 2 3 4 2 2 3 2 3 4 3 3 4 4
# subarray / substring vs subsequence and programs to generate them | python3 code to generate all possible subsequences . time complexity o ( n * 2 ^ n ) ; number of subsequences is ( 2 * * n - 1 ) ; run from counter 000. . 1 to 111. . 1 ; check if jth bit in the counter is set if set then print jth element from arr [ ] ; 

import math


def printSubsequences(arr, n):
    opsize = math .pow(2, n)
    for counter in range(1, (int)(opsize)):
        for j in range(0, n):
            if (counter & (1 << j)):
                print(arr[j], end=" ")
        print()


arr = [1, 2, 3, 4]
n = len(arr)
print("All Non-empty Subsequences")
printSubsequences(arr, n)

# Expected output:
All Non-empty Subsequences
1 
2 
1 2 
3 
1 3 
2 3 
1 2 3 
4 
1 4 
2 4 
1 2 4 
3 4 
1 3 4 
2 3 4 
1 2 3 4
# a product array puzzle | function to print product array for a given array arr [ ] of size n ; base case ; allocate memory for the product array ; in this loop , temp variable contains product of elements on left side excluding arr [ i ] ; initialize temp to 1 for product on right side ; in this loop , temp variable contains product of elements on right side excluding arr [ i ] ; print the constructed prod array ; 
def productArray(arr, n):
    if n == 1:
        print(0)
        return
    i, temp = 1, 1
    prod = [1 for i in range(n)]
    for i in range(n):
        prod[i] = temp
        temp *= arr[i]
    temp = 1
    for i in range(n - 1, -1, -1):
        prod[i] *= temp
        temp *= arr[i]
    for i in range(n):
        print(prod[i], end=" ")
    return


arr = [10, 3, 5, 6, 2]
n = len(arr)
print("The product array is: n")
productArray(arr, n)

# Expected output:
The product array is: n
180 600 360 300 900
# check if array elements are consecutive | added method 3 | the function checks if the array elements are consecutive . if elements are consecutive , then returns true , else returns false ; 1 ) get the minimum element in array ; 2 ) get the maximum element in array ; 3 ) max - min + 1 is equal to n , then only check all elements ; create a temp array to hold visited flag of all elements . note that , calloc is used here so that all values are initialized as false ; if we see an element again , then return false ; if visited first time , then mark the element as visited ; if all elements occur once , then return true ; if ( max - min + 1 != n ) ; 
def areConsecutive(arr, n):
    if (n < 1):
        return False
    Min = min(arr)
    Max = max(arr)
    if (Max - Min + 1 == n):
        visited = [False for i in range(n)]
        for i in range(n):
            if (visited[arr[i] - Min]):
                return False
            visited[arr[i] - Min] = True
        return True
    return False


arr = [5, 4, 2, 3, 1, 6]
n = len(arr)
if (areConsecutive(arr, n)):
    print("Array elements are consecutive ")
else:
    print("Array elements are not consecutive ")

# Expected output:
Array elements are consecutive
# check if array elements are consecutive | added method 3 | helper functions to get minimum and maximum in an array the function checks if the array elements are consecutive . if elements are consecutive , then returns true , else returns false ; 1 ) get the minimum element in array ; 2 ) get the maximum element in array ; 3 ) max - min + 1 is equal to n then only check all elements ; if the value at index j is negative then there is repetition ; if we do not see a negative value then all elements are distinct ; if ( max - min + 1 != n ) ; utility functions ; 
def areConsecutive(arr, n):
    if (n < 1):
        return False
    min = getMin(arr, n)
    max = getMax(arr, n)
    if (max - min + 1 == n):
        for i in range(n):
            if (arr[i] < 0):
                j = -arr[i] - min
            else:
                j = arr[i] - min
            if (arr[j] > 0):
                arr[j] = -arr[j]
            else:
                return False
        return True
    return False


def getMin(arr, n):
    min = arr[0]
    for i in range(1, n):
        if (arr[i] < min):
            min = arr[i]
    return min


def getMax(arr, n):
    max = arr[0]
    for i in range(1, n):
        if (arr[i] > max):
            max = arr[i]
    return max


if __name__ == "__main__":
    arr = [1, 4, 5, 3, 2, 6]
    n = len(arr)
    if (areConsecutive(arr, n)):
        print(" Array elements are consecutive ")
    else:
        print(" Array elements are not consecutive ")

# Expected output:
 Array elements are consecutive
# find relative complement of two sorted arrays | python program to find all those elements of arr1 [ ] that are not present in arr2 [ ] ; if current element in arr2 [ ] is greater , then arr1 [ i ] can 't be  present in arr2[j..m-1] ; skipping smaller elements of arr2 [ ] ; equal elements found ( skipping in both arrays ) ; printing remaining elements of arr1 [ ] ; 
def relativeComplement(arr1, arr2, n, m):
    i = 0
    j = 0
    while (i < n and j < m):
        if (arr1[i] < arr2[j]):
            print(arr1[i], " ", end="")
            i += 1
        elif (arr1[i] > arr2[j]):
            j += 1
        elif (arr1[i] == arr2[j]):
            i += 1
            j += 1
    while (i < n):
        print(arr1[i], " ", end="")


arr1 = [3, 6, 10, 12, 15]
arr2 = [1, 3, 5, 10, 16]
n = len(arr1)
m = len(arr2)
relativeComplement(arr1, arr2, n, m)

# Expected output:
6  12  15
# minimum increment by k operations to make all elements equal | function for calculating min operations ; max elements of array ; iterate for all elements ; check if element can make equal to max or not if not then return - 1 ; else update res fo required operations ; return result ; 
def minOps(arr, n, k):
    max1 = max(arr)
    res = 0
    for i in range(0, n):
        if ((max1 - arr[i]) % k != 0):
            return -1
        else:
            res += (max1 - arr[i]) / k
    return int(res)


arr = [21, 33, 9, 45, 63]
n = len(arr)
k = 6
print(minOps(arr, n, k))

# Expected output:
24
# minimize ( max ( a [ i ] , b [ j ] , c [ k ] ) | python code for above approach . ; assigning the length - 1 value to each of three variables ; calculating min difference from last index of lists ; checking condition ; calculating max term from list ; moving to smaller value in the array with maximum out of three . ; 
def solve(A, B, C):
    i = len(A) - 1
    j = len(B) - 1
    k = len(C) - 1
    min_diff = abs(max(A[i], B[j], C[k]) - min(A[i], B[j], C[k]))
    while i != -1 and j != -1 and k != -1:
        current_diff = abs(max(A[i], B[j], C[k]) - min(A[i], B[j], C[k]))
        if current_diff < min_diff:
            min_diff = current_diff
        max_term = max(A[i], B[j], C[k])
        if A[i] == max_term:
            i -= 1
        elif B[j] == max_term:
            j -= 1
        else:
            k -= 1
    return min_diff


A = [5, 8, 10, 15]
B = [6, 9, 15, 78, 89]
C = [2, 3, 6, 6, 8, 8, 10]
print(solve(A, B, C))

# Expected output:
1
# analysis of algorithms | set 2 ( worst , average and best cases ) | linearly search x in arr [ ] . if x is present then return the index , otherwise return - 1 ; 
def search(arr, x):
    for index, value in enumerate(arr):
        if value == x:
            return index
    return -1


arr = [1, 10, 30, 15]
x = 30
print(x, "is present at index", search(arr, x))

# Expected output:
30 is present at index 2
# binary search | returns index of x in arr if present , else - 1 ; if element is present at the middle itself ; if element is smaller than mid , then it can only be present in left subarray ; else the element can only be present in right subarray ; element is not present in the array ; 
def binarySearch(arr, l, r, x):
    if r >= l:
        mid = l + (r - l) // 2
        if arr[mid] == x:
            return mid
        elif arr[mid] > x:
            return binarySearch(arr, l, mid - 1, x)
        else:
            return binarySearch(arr, mid + 1, r, x)
    else:
        return -1


arr = [2, 3, 4, 10, 40]
x = 10
result = binarySearch(arr, 0, len(arr) - 1, x)
if result != -1:
    print("Element is present at index % d" % result)
else:
    print("Element is not present in array")

# Expected output:
Element is present at index  3
# binary search | it returns location of x in given array arr if present , else returns - 1 ; check if x is present at mid ; if x is greater , ignore left half ; if x is smaller , ignore right half ; if we reach here , then the element was not present ; 
def binarySearch(arr, l, r, x):
    while l <= r:
        mid = l + (r - l) // 2
        if arr[mid] == x:
            return mid
        elif arr[mid] < x:
            l = mid + 1
        else:
            r = mid - 1
    return -1


arr = [2, 3, 4, 10, 40]
x = 10
result = binarySearch(arr, 0, len(arr) - 1, x)
if result != -1:
    print("Element is present at index % d" % result)
else:
    print("Element is not present in array")

# Expected output:
Element is present at index  3
# jump search | python3 code to implement jump search ; finding block size to be jumped ; finding the block where element is present ( if it is present ) ; doing a linear search for x in block beginning with prev . ; if we reached next block or end of array , element is not present . ; if element is found ; 

import math


def jumpSearch(arr, x, n):
    step = math .sqrt(n)
    prev = 0
    while arr[int(min(step, n) - 1)] < x:
        prev = step
        step += math .sqrt(n)
        if prev >= n:
            return -1
    while arr[int(prev)] < x:
        prev += 1
        if prev == min(step, n):
            return -1
    if arr[int(prev)] == x:
        return prev
    return -1


arr = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
x = 55
n = len(arr)
index = jumpSearch(arr, x, n)
print("Number", x, "is at index", "%.0f" % index)

# Expected output:
Number 55 is at index 10
# Interpolation Search | If x is present in arr [ 0. . n - 1 ] , then returns index of it , else returns - 1. ; Since array is sorted , an element present in array must be in range defined by corner ; Probing the position with keeping uniform distribution in mind . ; Condition of target found ; If x is larger , x is in right subarray ; If x is smaller , x is in left subarray ; Array of items in which search will be conducted ; Element to be searched ; If element was found
def interpolationSearch(arr, lo, hi, x):
    if (lo <= hi and x >= arr[lo] and x <= arr[hi]):
        pos = lo + ((hi - lo) // (arr[hi] - arr[lo]) * (x - arr[lo]))
        if arr[pos] == x:
            return pos
        if arr[pos] < x:
            return interpolationSearch(arr, pos + 1, hi, x)
        if arr[pos] > x:
            return interpolationSearch(arr, lo, pos - 1, x)
    return -1


arr = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47]
n = len(arr)
x = 18
index = interpolationSearch(arr, 0, n - 1, x)
if index != -1:
    print("Element found at index", index)
else:
    print("Element not found")

# Expected output:
Element found at index 4