giulio98/xlcost-single-prompt huggingface dataset:
# maximum product subarray | returns the product of max product subarray . ; initializing result ; traversing in current subarray ; updating result every time to keep an eye over the maximum product ; updating the result for ( n - 1 ) th index . ; 
def maxSubarrayProduct(arr, n):
    result = arr[0]
    for i in range(n):
        mul = arr[i]
        for j in range(i + 1, n):
            result = max(result, mul)
            mul *= arr[j]
        result = max(result, mul)
    return result


arr = [1, -2, -3, 0, 7, -8, -2]
n = len(arr)
print("Maximum Sub array product is", maxSubarrayProduct(arr, n))

# Expected output:
Maximum Sub array product is 112
# maximum circular subarray sum | the function returns maximum circular contiguous sum in a [ ] ; corner case ; initialize sum variable which store total sum of the array . ; initialize every variable with first value of array . ; concept of kadane 's algorithm ; kadane 's algorithm to find maximum subarray sum. ; kadane 's algorithm to find minimum subarray sum. ; returning the maximum value ; 
def maxCircularSum(a, n):
    if (n == 1):
        return a[0]
    sum = 0
    for i in range(n):
        sum += a[i]
    curr_max = a[0]
    max_so_far = a[0]
    curr_min = a[0]
    min_so_far = a[0]
    for i in range(1, n):
        curr_max = max(curr_max + a[i], a[i])
        max_so_far = max(max_so_far, curr_max)
        curr_min = min(curr_min + a[i], a[i])
        min_so_far = min(min_so_far, curr_min)
    if (min_so_far == sum):
        return max_so_far
    return max(max_so_far, sum - min_so_far)


a = [11, 10, -20, 5, -3, -5, 8, -13, 10]
n = len(a)
print("Maximum circular sum is", maxCircularSum(a, n))

# Expected output:
Maximum circular sum is 31
# construction of longest increasing subsequence ( n log n ) | binary search ; add boundary case , when array n is zero depend on smart pointers ; initialized with - 1 ; it will always point to empty location ; new smallest value ; arr [ i ] wants to extend largest subsequence ; arr [ i ] wants to be a potential condidate of future subsequence it will replace ceil value in tailindices ; 
def GetCeilIndex(arr, T, l, r, key):
    while (r - l > 1):
        m = l + (r - l) // 2
        if (arr[T[m]] >= key):
            r = m
        else:
            l = m
    return r


def LongestIncreasingSubsequence(arr, n):
    tailIndices = [0 for i in range(n + 1)]
    prevIndices = [-1 for i in range(n + 1)]
    len = 1
    for i in range(1, n):
        if (arr[i] < arr[tailIndices[0]]):
            tailIndices[0] = i
        elif (arr[i] > arr[tailIndices[len - 1]]):
            prevIndices[i] = tailIndices[len - 1]
            tailIndices[len] = i
            len += 1
        else:
            pos = GetCeilIndex(arr, tailIndices, -1, len - 1, arr[i])
            prevIndices[i] = tailIndices[pos - 1]
            tailIndices[pos] = i
    print("LIS of given input")
    i = tailIndices[len - 1]
    while (i >= 0):
        print(arr[i], " ", end="")
        i = prevIndices[i]
    print()
    return len


arr = [2, 5, 3, 7, 11, 8, 10, 13, 6]
n = len(arr)
print("LISsize", LongestIncreasingSubsequence(arr, n))

# Expected output:
LIS of given input
13  10  8  7  3  2  
LISsize 6
# maximize sum of consecutive differences in a circular array | return the maximum sum of difference between consecutive elements ; sorting the array ; subtracting a1 , a2 , a3 , ... . . , a ( n / 2 ) - 1 , an / 2 twice and adding a ( n / 2 ) + 1 , a ( n / 2 ) + 2 , a ( n / 2 ) + 3 , . ... . , an - 1 , an twice . ; 
def maxSum(arr, n):
    sum = 0
    arr .sort()
    for i in range(0, int(n / 2)):
        sum -= (2 * arr[i])
        sum += (2 * arr[n - i - 1])
    return sum


arr = [4, 2, 1, 8]
n = len(arr)
print(maxSum(arr, n))

# Expected output:
18
# three way partitioning of an array around a given range | partitions arr [ 0. . n - 1 ] around [ lowval . . highval ] ; initialize ext available positions for smaller ( than range ) and greater lements ; traverse elements from left ; if current element is smaller than range , put it on next available smaller position . ; if current element is greater than range , put it on next available greater position . ; 
def threeWayPartition(arr, n, lowVal, highVal):
    start = 0
    end = n - 1
    i = 0
    while i <= end:
        if arr[i] < lowVal:
            temp = arr[i]
            arr[i] = arr[start]
            arr[start] = temp
            i += 1
            start += 1
        elif arr[i] > highVal:
            temp = arr[i]
            arr[i] = arr[end]
            arr[end] = temp
            end -= 1
        else:
            i += 1


if __name__ == "__main__":
    arr = [1, 14, 5, 20, 4, 2, 54, 20, 87, 98, 3, 1, 32]
    n = len(arr)
    threeWayPartition(arr, n, 10, 20)
    print("Modified array")
    for i in range(n):
        print(arr[i], end=" ")

# Expected output:
Modified array
1 5 4 2 1 3 14 20 20 98 87 32 54
# generate all possible sorted arrays from alternate elements of two given sorted arrays | function to generates and prints all sorted arrays from alternate elements of ' a [ i . . m - 1 ] ' and ' b [ j . . n - 1 ] ' if ' flag ' is true , then current element is to be included from a otherwise from b . ' len ' is the index in output array c [ ] . we print output array each time before including a character from a only if length of output array is greater than 0. we try than all possible combinations ; include valid element from a ; print output if there is at least one ' b ' in output array 'c   ; recur for all elements of a after current index ; this block works for the very first call to include the first element in the output array ; don 't increment lem  as b is included yet ; include valid element from a and recur ; include valid element from b and recur ; wrapper function ; output array ; a utility function to print an array ; 
def generateUtil(A, B, C, i, j, m, n, len, flag):
    if (flag):
        if (len):
            printArr(C, len + 1)
        for k in range(i, m):
            if (not len):
                C[len] = A[k]
                generateUtil(A, B, C, k + 1, j, m, n, len, not flag)
            else:
                if (A[k] > C[len]):
                    C[len + 1] = A[k]
                    generateUtil(A, B, C, k + 1, j, m, n, len + 1, not flag)
    else:
        for l in range(j, n):
            if (B[l] > C[len]):
                C[len + 1] = B[l]
                generateUtil(A, B, C, i, l + 1, m, n, len + 1, not flag)


def printArr(arr, n):
    for i in range(n):
        print(arr[i], " ", end="")
    print()


def generate(A, B, m, n):
    C = []
    for i in range(m + n + 1):
        C .append(0)
    generateUtil(A, B, C, 0, 0, m, n, 0, True)


A = [10, 15, 25]
B = [5, 20, 30]
n = len(A)
m = len(B)
generate(A, B, n, m)

# Expected output:
10  20  
10  20  25  30  
10  30  
15  20  
15  20  25  30  
15  30  
25  30
# Minimum number of swaps required for arranging pairs adjacent to each other | This function updates indexes of elements ' a ' and 'b   ; This function returns minimum number of swaps required to arrange all elements of arr [ i . . n ] become arranged ; If all pairs procesed so no swapping needed return 0 ; If current pair is valid so DO NOT DISTURB this pair and move ahead . ; Swap pair of arr [ i ] with arr [ i + 1 ] and recursively compute minimum swap required if this move is made . ; Backtrack to previous configuration . Also restore the previous indices , of one and two ; Now swap arr [ i ] with pair of arr [ i + 1 ] and recursively compute minimum swaps required for the subproblem after this move ; Backtrack to previous configuration . Also restore 3 the previous indices , of one and two ; Return minimum of two cases ; Returns minimum swaps required ; To store indices of array elements ; Store index of each element in array index ; Call the recursive function ; For simplicity , it is assumed that arr [ 0 ] is not used . The elements from index 1 to n are only valid elements ; if ( a , b ) is pair than we have assigned elements in array such that pairs [ a ] = b and pairs [ b ] = a ; Number of pairs n is half of total elements ; If there are n elements in array , then there are n pairs
def updateindex(index, a, ai, b, bi):
    index[a] = ai
    index[b] = bi


def minSwapsUtil(arr, pairs, index, i, n):
    if (i > n):
        return 0
    if (pairs[arr[i]] == arr[i + 1]):
        return minSwapsUtil(arr, pairs, index, i + 2, n)
    one = arr[i + 1]
    indextwo = i + 1
    indexone = index[pairs[arr[i]]]
    two = arr[index[pairs[arr[i]]]]
    arr[i + 1], arr[indexone] = arr[indexone], arr[i + 1]
    updateindex(index, one, indexone, two, indextwo)
    a = minSwapsUtil(arr, pairs, index, i + 2, n)
    arr[i + 1], arr[indexone] = arr[indexone], arr[i + 1]
    updateindex(index, one, indextwo, two, indexone)
    one = arr[i]
    indexone = index[pairs[arr[i + 1]]]
    two = arr[index[pairs[arr[i + 1]]]]
    indextwo = i
    arr[i], arr[indexone] = arr[indexone], arr[i]
    updateindex(index, one, indexone, two, indextwo)
    b = minSwapsUtil(arr, pairs, index, i + 2, n)
    arr[i], arr[indexone] = arr[indexone], arr[i]
    updateindex(index, one, indextwo, two, indexone)
    return 1 + min(a, b)


def minSwaps(n, pairs, arr):
    index = []
    for i in range(2 * n + 1 + 1):
        index .append(0)
    for i in range(1, 2 * n + 1):
        index[arr[i]] = i
    return minSwapsUtil(arr, pairs, index, 1, 2 * n)


arr = [0, 3, 5, 6, 4, 1, 2]
pairs = [0, 3, 6, 1, 5, 4, 2]
m = len(pairs)
n = m // 2
print("Min swaps required is ", minSwaps(n, pairs, arr))

# Expected output:
Min swaps required is  2
# replace two consecutive equal values with one greater | python program to replace two elements with equal values with one greater . ; function to replace consecutive equal elements ; index in result ; to print new array ; 

from __future__ import print_function


def replace_elements(arr, n):
    pos = 0
    for i in range(0, n):
        arr[pos] = arr[i]
        pos = pos + 1
        while (pos > 1 and arr[pos - 2] == arr[pos - 1]):
            pos -= 1
            arr[pos - 1] += 1
    for i in range(0, pos):
        print(arr[i], end=" ")


arr = [6, 4, 3, 4, 3, 3, 5]
n = len(arr)
replace_elements(arr, n)

# Expected output:
6 4 3 6
# rearrange a binary string as alternate x and y occurrences | function which arrange the given string ; counting number of 0 ' s ▁ and ▁ 1' s in the given string . ; printing first all 0 ' s ▁ x - times ▁ ▁ and ▁ decrement ▁ count ▁ of ▁ 0' s x - times and do the similar task with '1   ; 
def arrangeString(str1, x, y):
    count_0 = 0
    count_1 = 0
    n = len(str1)
    for i in range(n):
        if str1[i] == '0':
            count_0 += 1
        else:
            count_1 += 1
    while count_0 > 0 or count_1 > 0:
        for i in range(0, x):
            if count_0 > 0:
                print("0", end="")
                count_0 -= 1
        for j in range(0, y):
            if count_1 > 0:
                print("1", end="")
                count_1 -= 1


if __name__ == '__main__':
    str1 = "01101101101101101000000"
    x = 1
    y = 2
    arrangeString(str1, x, y)

# Expected output:
01101101101101101000000
# shuffle 2 n integers as a1 | python program to shuffle an array in the form of a1 , b1 , a2 , b2 , ... ; function to rearrange the array ; if size is null or odd return because it is not possible to rearrange ; start from the middle index ; each time we will set two elements from the start to the valid position by swapping ; 

arr = [1, 3, 5, 2, 4, 6]


def rearrange(n):
    global arr
    if (n % 2 == 1):
        return
    currIdx = int((n - 1) / 2)
    while (currIdx > 0):
        count = currIdx
        swapIdx = currIdx
        while (count > 0):
            temp = arr[swapIdx + 1]
            arr[swapIdx + 1] = arr[swapIdx]
            arr[swapIdx] = temp
            swapIdx = swapIdx + 1
            count = count - 1
        currIdx = currIdx - 1


n = len(arr)
rearrange(n)
for i in range(0, n):
    print("{} ".format(arr[i]), end="")

# Expected output:
1 2 3 4 5 6
# maximum difference between two elements such that larger element appears after the smaller number | the function assumes that there are at least two elements in array . the function returns a negative value if the array is sorted in decreasing order . returns 0 if elements are equal ; 
def maxDiff(arr, arr_size):
    max_diff = arr[1] - arr[0]
    for i in range(0, arr_size):
        for j in range(i + 1, arr_size):
            if (arr[j] - arr[i] > max_diff):
                max_diff = arr[j] - arr[i]
    return max_diff


arr = [1, 2, 90, 10, 110]
size = len(arr)
print("Maximum difference is", maxDiff(arr, size))

# Expected output:
Maximum difference is 109
# maximum difference between two elements such that larger element appears after the smaller number | the function assumes that there are at least two elements in array . the function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal ; initialize result ; initialize max element from right side ; 
def maxDiff(arr, n):
    maxDiff = -1
    maxRight = arr[n - 1]
    for i in range(n - 2, -1, -1):
        if (arr[i] > maxRight):
            maxRight = arr[i]
        else:
            diff = maxRight - arr[i]
            if (diff > maxDiff):
                maxDiff = diff
    return maxDiff


if __name__ == '__main__':
    arr = [1, 2, 90, 10, 110]
    n = len(arr)
    print("Maximum difference is", maxDiff(arr, n))

# Expected output:
Maximum difference is 109
# maximum difference between two elements such that larger element appears after the smaller number | the function assumes that there are at least two elements in array . the function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal ; initialize diff , current sum and max sum ; calculate current diff ; calculate current sum ; update max sum , if needed ; 
def maxDiff(arr, n):
    diff = arr[1] - arr[0]
    curr_sum = diff
    max_sum = curr_sum
    for i in range(1, n - 1):
        diff = arr[i + 1] - arr[i]
        if (curr_sum > 0):
            curr_sum += diff
        else:
            curr_sum = diff
        if (curr_sum > max_sum):
            max_sum = curr_sum
    return max_sum


if __name__ == '__main__':
    arr = [80, 2, 6, 3, 100]
    n = len(arr)
    print("Maximum difference is", maxDiff(arr, n))

# Expected output:
Maximum difference is 98
# find the maximum element in an array which is first increasing and then decreasing | python3 program to find maximum element ; 
def findMaximum(arr, low, high):
    max = arr[low]
    i = low
    for i in range(high + 1):
        if arr[i] > max:
            max = arr[i]
    return max


arr = [1, 30, 40, 50, 60, 70, 23, 20]
n = len(arr)
print("The maximum element is %d" % findMaximum(arr, 0, n - 1))

# Expected output:
The maximum element is 70
# find the maximum element in an array which is first increasing and then decreasing |  ; base case : only one element is present in arr [ low . . high ] ; if there are two elements and first is greater then the first element is maximum ; if there are two elements and second is greater then the second element is maximum ; if we reach a point where arr [ mid ] is greater than both of its adjacent elements arr [ mid - 1 ] and arr [ mid + 1 ] , then arr [ mid ] is the maximum element ; if arr [ mid ] is greater than the next element and smaller than the previous element then maximum lies on left side of mid ; when arr [ mid ] is greater than arr [ mid - 1 ] and smaller than arr [ mid + 1 ] ; 
def findMaximum(arr, low, high):
    if low == high:
        return arr[low]
    if high == low + 1 and arr[low] >= arr[high]:
        return arr[low]
    if high == low + 1 and arr[low] < arr[high]:
        return arr[high]
    mid = (low + high) // 2
    if arr[mid] > arr[mid + 1] and arr[mid] > arr[mid - 1]:
        return arr[mid]
    if arr[mid] > arr[mid + 1] and arr[mid] < arr[mid - 1]:
        return findMaximum(arr, low, mid - 1)
    else:
        return findMaximum(arr, mid + 1, high)


arr = [1, 3, 50, 10, 9, 7, 6]
n = len(arr)
print("The maximum element is %d" % findMaximum(arr, 0, n - 1))

# Expected output:
The maximum element is 50
# find the smallest positive number missing from an unsorted array | set 1 | utility function that puts all non - positive ( 0 and negative ) numbers on left side of arr [ ] and return count of such numbers ; increment count of non - positive integers ; find the smallest positive missing number in an array that contains all positive integers ; mark arr [ i ] as visited by making arr [ arr [ i ] - 1 ] negative . note that 1 is subtracted because index start from 0 and positive numbers start from 1 ; return the first index value at which is positive ; 1 is added because indexes start from 0 ; find the smallest positive missing number in an array that contains both positive and negative integers ; first separate positive and negative numbers ; shift the array and call findmissingpositive for positive part ; 
def segregate(arr, size):
    j = 0
    for i in range(size):
        if (arr[i] <= 0):
            arr[i], arr[j] = arr[j], arr[i]
            j += 1
    return j


def findMissingPositive(arr, size):
    for i in range(size):
        if (abs(arr[i]) - 1 < size and arr[abs(arr[i]) - 1] > 0):
            arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1]
    for i in range(size):
        if (arr[i] > 0):
            return i + 1
    return size + 1


def findMissing(arr, size):
    shift = segregate(arr, size)
    return findMissingPositive(arr[shift:], size - shift)


arr = [0, 10, 2, -10, -20]
arr_size = len(arr)
missing = findMissing(arr, arr_size)
print("The smallest positive missing number is ", missing)

# Expected output:
The smallest positive missing number is  1
# given an array of size n and a number k , find all elements that appear more than n / k times | python3 implementation ; function to find the number of array elements with frequency more than n / k times ; calculating n / k ; counting frequency of every element using counter ; traverse the map and print all the elements with occurrence more than n / k times ; 

from collections import Counter


def printElements(arr, n, k):
    x = n // k
    mp = Counter(arr)
    for it in mp:
        if mp[it] > x:
            print(it)


arr = [1, 1, 2, 2, 3, 5, 4, 2, 2, 3, 1, 1, 1]
n = len(arr)
k = 4
printElements(arr, n, k)

# Expected output:
1
2
# maximum sum path in two arrays | this function returns the sum of elements on maximum path from beginning to end ; initialize indexes for ar1 [ ] and ar2 [ ] ; initialize result and current sum through ar1 [ ] and ar2 [ ] ; below 3 loops are similar to merge in merge sort ; add elements of ar1 [ ] to sum1 ; add elements of ar2 [ ] to sum2 ; we reached a common point ; take the maximum of two sums and add to result ; update sum1 and sum2 to be considered fresh for next elements ; update i and j to move to next element in each array ; add remaining elements of ar1 [ ] ; add remaining elements of b [ ] ; add maximum of two sums of remaining elements ; 
def maxPathSum(ar1, ar2, m, n):
    i, j = 0, 0
    result, sum1, sum2 = 0, 0, 0
    while (i < m and j < n):
        if ar1[i] < ar2[j]:
            sum1 += ar1[i]
            i += 1
        elif ar1[i] > ar2[j]:
            sum2 += ar2[j]
            j += 1
        else:
            result += max(sum1, sum2) + ar1[i]
            sum1 = 0
            sum2 = 0
            i += 1
            j += 1
    while i < m:
        sum1 += ar1[i]
        i += 1
    while j < n:
        sum2 += ar2[j]
        j += 1
    result += max(sum1, sum2)
    return result


ar1 = [2, 3, 7, 10, 12, 15, 30, 34]
ar2 = [1, 5, 7, 8, 10, 15, 16, 19]
m = len(ar1)
n = len(ar2)
print("Maximum sum path is", maxPathSum(ar1, ar2, m, n))

# Expected output:
Maximum sum path is 122
# smallest greater elements in whole array | simple python3 program to find smallest greater element in whole array for every element . ; find the closest greater element for arr [ j ] in the entire array . ; check if arr [ i ] is largest ; 
def smallestGreater(arr, n):
    for i in range(0, n):
        diff = 1000
        closest = -1
        for j in range(0, n):
            if (arr[i] < arr[j] and arr[j] - arr[i] < diff):
                diff = arr[j] - arr[i]
                closest = j
        if (closest == -1):
            print("_ ", end="")
        else:
            print("{} ".format(arr[closest]), end="")


ar = [6, 3, 9, 8, 10, 2, 1, 15, 7]
n = len(ar)
smallestGreater(ar, n)

# Expected output:
7 6 10 9 15 3 2 _ 8
# smallest greater elements in whole array | efficient python3 program to find smallest greater element in whole array for every element ; lowerbound function ; 
def lowerBound(vec, low, high, element):
    array = [0] * (len(vec))
    k = 0
    for val in vec:
        array[k] = val
        k += 1
    while (low < high):
        middle = low + int((high - low) / 2)
        if (element > array[middle]):
            low = middle + 1
        else:
            high = middle
    return low + 1


def smallestGreater(arr, n):
    s = set()
    for i in range(n):
        s .add(arr[i])
    newAr = []
    for p in s:
        newAr .append(p)
    for i in range(n):
        temp = lowerBound(newAr, 0, len(newAr), arr[i])
        if (temp < n):
            print(newAr[temp], end=" ")
        else:
            print("_ ", end="")


if __name__ == '__main__':
    ar = [6, 3, 9, 8, 10, 2, 1, 15, 7]
    n = len(ar)
    smallestGreater(ar, n)

# Expected output:
7 6 10 9 15 3 2 _ 8
# find zeroes to be flipped so that number of consecutive 1 's is maximized | m is maximum of number zeroes allowed to flip , n is size of array ; left and right indexes of current window ; left index and size of the widest window ; count of zeroes in current window ; while right boundary of current window doesn 't cross right end ; if zero count of current window is less than m , widen the window toward right ; if zero count of current window is more than m , reduce the window from left ; updqate widest window if this window size is more ; print positions of zeroes in the widest window ; 
def findZeroes(arr, n, m):
    wL = wR = 0
    bestL = bestWindow = 0
    zeroCount = 0
    while wR < n:
        if zeroCount <= m:
            if arr[wR] == 0:
                zeroCount += 1
            wR += 1
        if zeroCount > m:
            if arr[wL] == 0:
                zeroCount -= 1
            wL += 1
        if (wR - wL > bestWindow) and (zeroCount <= m):
            bestWindow = wR - wL
            bestL = wL
    for i in range(0, bestWindow):
        if arr[bestL + i] == 0:
            print(bestL + i, end=" ")


arr = [1, 0, 0, 1, 1, 0, 1, 0, 1, 1]
m = 2
n = len(arr)
print("Indexes of zeroes to be flipped are", end=" ")
findZeroes(arr, n, m)

# Expected output:
Indexes of zeroes to be flipped are 5 7
# count strictly increasing subarrays | python3 program to count number of strictly increasing subarrays ; initialize count of subarrays as 0 ; pick starting point ; pick ending point ; if subarray arr [ i . . j ] is not strictly increasing , then subarrays after it , i . e . , arr [ i . . j + 1 ] , arr [ i . . j + 2 ] , ... . cannot be strictly increasing ; 
def countIncreasing(arr, n):
    cnt = 0
    for i in range(0, n):
        for j in range(i + 1, n):
            if arr[j] > arr[j - 1]:
                cnt += 1
            else:
                break
    return cnt


arr = [1, 2, 2, 4]
n = len(arr)
print("Count of strictly increasing subarrays is", countIncreasing(arr, n))

# Expected output:
Count of strictly increasing subarrays is 2