giulio98/xlcost-single-prompt huggingface dataset:
# count of ways to obtain given sum from the given array elements | python3 program to implement the above approach ; function to call dfs to calculate the number of ways ; iterate till the length of array ; initialize the memorization table ; function to perform the dfs to calculate the number of ways ; base case : reached the end of array ; if current sum is obtained ; otherwise ; if previously calculated subproblem occurred ; check if the required sum can be obtained by adding current element or by subtracting the current index element ; store the count of ways ; 

import sys


def dfs(memo, nums, S, curr_sum, index, sum):
    if (index == len(nums)):
        if (S == curr_sum):
            return 1
        else:
            return 0
    if (memo[index][curr_sum + sum] != -sys .maxsize - 1):
        return memo[index][curr_sum + sum]
    ans = (dfs(memo,
               nums,
               index + 1,
               curr_sum + nums[index],
               S,
               sum) + dfs(memo,
                          nums,
                          index + 1,
                          curr_sum - nums[index],
                          S,
                          sum))
    memo[index][curr_sum + sum] = ans
    return ans


def findWays(nums, S):
    sum = 0
    for i in range(len(nums)):
        sum += nums[i]
    memo = [
        [-sys .maxsize - 1 for i in range(2 * sum + 1)]for j in range(len(nums) + 1)]
    return dfs(memo, nums, S, 0, 0, sum)


if __name__ == '__main__':
    S = 3
    arr = [1, 2, 3, 4, 5]
    answer = findWays(arr, S)
    print(answer)

# Expected output:
3
# longest subarray with sum not divisible by x | function to print the longest subarray with sum of elements not divisible by x ; pref [ ] stores the prefix sum suff [ ] stores the suffix sum ; if array element is divisibile by x ; increase count ; if all the array elements are divisible by x ; no subarray possible ; reverse v to calculate the suffix sum ; calculate the suffix sum ; reverse to original form ; reverse the suffix sum array ; calculate the prefix sum ; stores the starting index of required subarray ; stores the ending index of required subarray ; if suffix sum till i - th index is not divisible by x ; update the answer ; if prefix sum till i - th index is not divisible by x ; update the answer ; print the longest subarray ; 
def max_length(N, x, v):
    preff, suff = [], []
    ct = 0
    for i in range(N):
        a = v[i]
        if a % x == 0:
            ct += 1
    if ct == N:
        print(-1)
        return
    v .reverse()
    suff .append(v[0])
    for i in range(1, N):
        suff .append(v[i] + suff[i - 1])
    v .reverse()
    suff .reverse()
    preff .append(v[0])
    for i in range(1, N):
        preff .append(v[i] + preff[i - 1])
    ans = 0
    lp = 0
    rp = N - 1
    for i in range(N):
        if suff[i] % x != 0 and ans < N - 1:
            lp = i
            rp = N - 1
            ans = max(ans, N - i)
        if preff[i] % x != 0 and ans < i + 1:
            lp = 0
            rp = i
            ans = max(ans, i + 1)
    for i in range(lp, rp + 1):
        print(v[i], end=" ")


x = 3
v = [1, 3, 2, 6]
N = len(v)
max_length(N, x, v)

# Expected output:
3 2 6
# number of times maximum and minimum value updated during traversal of array | function to find the count the number of times maximum and minimum value updated ; update the maximum and minimum values during traversal ; 
def maximumUpdates(arr):
    min = arr[0]
    max = arr[0]
    minCount, maxCount = 1, 1
    for arr in arr:
        if arr > max:
            maxCount += 1
            max = arr
        if arr < min:
            minCount += 1
            min = arr
    print("Number of times maximum ", end="")
    print("value updated = ", maxCount)
    print("Number of times minimum ", end="")
    print("value updated = ", minCount)


if __name__ == "__main__":
    arr = [10, 5, 20, 22]
    maximumUpdates(arr)

# Expected output:
Number of times maximum value updated =  3
Number of times minimum value updated =  2
# find the farthest smaller number in the right side | function to find the farthest smaller number in the right side ; to store minimum element in the range i to n ; if current element in the suffix_min is less than a [ i ] then move right ; print the required answer ; 
def farthest_min(a, n):
    suffix_min = [0 for i in range(n)]
    suffix_min[n - 1] = a[n - 1]
    for i in range(n - 2, -1, -1):
        suffix_min[i] = min(suffix_min[i + 1], a[i])
    for i in range(n):
        low = i + 1
        high = n - 1
        ans = -1
        while (low <= high):
            mid = (low + high) // 2
            if (suffix_min[mid] < a[i]):
                ans = mid
                low = mid + 1
            else:
                high = mid - 1
        print(ans, end=" ")


a = [3, 1, 5, 2, 4]
n = len(a)
farthest_min(a, n)

# Expected output:
3 -1 4 -1 -1
# print numbers in descending order along with their frequencies | function to print the elements in descending along with their frequencies ; sorts the element in decreasing order ; traverse the array elements ; prints the number and count ; prints the last step ; 
def printElements(a, n):
    a .sort(reverse=True)
    cnt = 1
    for i in range(n - 1):
        if (a[i] != a[i + 1]):
            print(a[i], " occurs ", cnt, "times")
            cnt = 1
        else:
            cnt += 1
    print(a[n - 1], "occurs", cnt, "times")


if __name__ == "__main__":
    a = [1, 1, 1, 2, 3, 4, 9, 9, 10]
    n = len(a)
    printElements(a, n)

# Expected output:
10  occurs  1 times
9  occurs  2 times
4  occurs  1 times
3  occurs  1 times
2  occurs  1 times
1 occurs 3 times
# find element position in given monotonic sequence | python 3 implementation of the approach ; function to return the value of f ( n ) for given values of a , b , c , n ; if c is 0 , then value of n can be in order of 10 ^ 15. if c != 0 , then n ^ 3 value has to be in order of 10 ^ 18 so maximum value of n can be 10 ^ 6. ; for efficient searching , use binary search . ; 

from math import log2, floor
SMALL_N = 1000000
LARGE_N = 1000000000000000


def func(a, b, c, n):
    res = a * n
    logVlaue = floor(log2(n))
    res += b * n * logVlaue
    res += c * (n * n * n)
    return res


def getPositionInSeries(a, b, c, k):
    start = 1
    end = SMALL_N
    if (c == 0):
        end = LARGE_N
    ans = 0
    while (start <= end):
        mid = (start + end) // 2
        val = func(a, b, c, mid)
        if (val == k):
            ans = mid
            break
        elif (val > k):
            end = mid - 1
        else:
            start = mid + 1
    return ans


if __name__ == "__main__":
    a = 2
    b = 1
    c = 1
    k = 12168587437017
    print(getPositionInSeries(a, b, c, k))

# Expected output:
23001
# check if array can be sorted with one swap | a linear python 3 program to check if array becomes sorted after one swap ; create a sorted copy of original array ; check if 0 or 1 swap required to get the sorted array ; 
def checkSorted(n, arr):
    b = []
    for i in range(n):
        b .append(arr[i])
    b .sort()
    ct = 0
    for i in range(n):
        if arr[i] != b[i]:
            ct += 1
    if ct == 0 or ct == 2:
        return True
    else:
        return False


if __name__ == '__main__':
    arr = [1, 5, 3, 4, 2]
    n = len(arr)
    if checkSorted(n, arr):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check whether ( i , j ) exists such that arr [ i ] != arr [ j ] and arr [ arr [ i ] ] is equal to arr [ arr [ j ] ] | function that will tell whether such indices present or not . ; checking 1 st condition i . e whether arr [ i ] equal to arr [ j ] or not ; checking 2 nd condition i . e whether arr [ arr [ i ] ] equal to arr [ arr [ j ] ] or not . ; 
def checkIndices(Arr, N):
    for i in range(N - 1):
        for j in range(i + 1, N):
            if (Arr[i] != Arr[j]):
                if (Arr[Arr[i] - 1] == Arr[Arr[j] - 1]):
                    return True
    return False


if __name__ == "__main__":
    Arr = [3, 2, 1, 1, 4]
    N = len(Arr)
    if checkIndices(Arr, N):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# find two non | function to find two non - overlapping with same sum in an array ; first create an empty map key -> which is sum of a pair of elements in the array value -> vector storing index of every pair having that sum ; consider every pair ( arr [ i ] , arr [ j ] ) and where ( j > i ) ; calculate sum of current pair ; if sum is already present in the map ; check every pair having equal sum ; if pairs don 't overlap,  print them and return ; insert current pair into the map ; if no such pair found ; 
def findPairs(arr, size):
    Map = {}
    for i in range(0, size - 1):
        for j in range(i + 1, size):
            Sum = arr[i] + arr[j]
            if Sum in Map:
                for pair in Map[Sum]:
                    m, n = pair
                    if ((m != i and m != j) and (n != i and n != j)):
                        print("Pair First ({}, {})".format(arr[i], arr[j]))
                        print("Pair Second ({}, {})".format(arr[m], arr[n]))
                        return
            if Sum not in Map:
                Map[Sum] = []
            Map[Sum].append((i, j))
    print("No such non-overlapping pairs present")


if __name__ == "__main__":
    arr = [8, 4, 7, 8, 4]
    size = len(arr)
    findPairs(arr, size)

# Expected output:
Pair First (4, 8)
Pair Second (8, 4)
# print all pairs with given sum | returns number of pairs in arr [ 0. . n - 1 ] with sum equal to 'sum ; consider all possible pairs and check their sums ; 
def printPairs(arr, n, sum):
    for i in range(0, n):
        for j in range(i + 1, n):
            if (arr[i] + arr[j] == sum):
                print("(", arr[i], ", ", arr[j], ")", sep="")


arr = [1, 5, 7, -1, 5]
n = len(arr)
sum = 6
printPairs(arr, n, sum)

# Expected output:
(1, 5)
(1, 5)
(7, -1)
# making elements distinct in a sorted array by minimum increments | to find minimum sum of unique elements . ; while current element is same as previous or has become smaller than previous . ; 
def minSum(arr, n):
    sm = arr[0]
    for i in range(1, n):
        if arr[i] == arr[i - 1]:
            j = i
            while j < n and arr[j] <= arr[j - 1]:
                arr[j] = arr[j] + 1
                j += 1
        sm = sm + arr[i]
    return sm


arr = [2, 2, 3, 5, 6]
n = len(arr)
print(minSum(arr, n))

# Expected output:
20
# making elements distinct in a sorted array by minimum increments | to find minimum sum of unique elements ; if violation happens , make current value as 1 plus previous value and add to sum . ; no violation . ; 
def minSum(arr, n):
    sum = arr[0]
    prev = arr[0]
    for i in range(1, n):
        if arr[i] <= prev:
            prev = prev + 1
            sum = sum + prev
        else:
            sum = sum + arr[i]
            prev = arr[i]
    return sum


arr = [2, 2, 3, 5, 6]
n = len(arr)
print(minSum(arr, n))

# Expected output:
20
# randomized binary search algorithm | python3 program to implement recursive randomized algorithm . to generate random number between x and y ie . . [ x , y ] ; a recursive randomized binary search function . it returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; here we have defined middle as random index between l and r ie . . [ l , r ] ; if the 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 ; we reach here when element is not present in array ; 

import random


def getRandom(x, y):
    tmp = (x + random .randint(0, 100000) % (y - x + 1))
    return tmp


def randomizedBinarySearch(arr, l, r, x):
    if r >= l:
        mid = getRandom(l, r)
        if arr[mid] == x:
            return mid
        if arr[mid] > x:
            return randomizedBinarySearch(arr, l, mid - 1, x)
        return randomizedBinarySearch(arr, mid + 1, r, x)
    return -1


if __name__ == '__main__':
    arr = [2, 3, 4, 10, 40]
    n = len(arr)
    x = 10
    result = randomizedBinarySearch(arr, 0, n - 1, x)
    if result == -1:
        print('Element is not present in array')
    else:
        print('Element is present at index ', result)

# Expected output:
Element is present at index  3
# program to remove vowels from a string | python program to remove vowels from a string function to remove vowels ; 
def rem_vowel(string):
    vowels = ['a', 'e', 'i', 'o', 'u']
    result = [letter for letter in string if letter .lower()not in vowels]
    result = ''.join(result)
    print(result)


string = "GeeksforGeeks - A Computer Science Portal for Geeks"
rem_vowel(string)
string = "Loving Python LOL"
rem_vowel(string)

# Expected output:
GksfrGks -  Cmptr Scnc Prtl fr Gks
Lvng Pythn LL
# make all array elements equal with minimum cost | this function assumes that a [ ] is sorted . if a [ ] is not sorted , we need to sort it first . ; if there are odd elements , we choose middle element ; if there are even elements , then we choose the average of middle two . ; after deciding the final value , find the result . ; 
def minCostToMakeElementEqual(a):
    l = len(a)
    if (l % 2 == 1):
        y = a[l // 2]
    else:
        y = (a[l // 2] + a[(l - 2) // 2]) // 2
    s = 0
    for i in range(l):
        s += abs(a[i] - y)
    return s


a = [1, 100, 101]
print(minCostToMakeElementEqual(a))

# Expected output:
100
# check if an array can be sorted by rearranging odd and even | function to check if array can be sorted or not ; function to check if given array can be sorted or not ; traverse the array ; traverse remaining elements at indices separated by 2 ; if current element is the minimum ; if any smaller minimum exists ; swap with current element ; if array is sorted ; otherwise ; 
def isSorted(arr):
    for i in range(len(arr) - 1):
        if arr[i] > arr[i + 1]:
            return False
    return True


def sortPoss(arr):
    for i in range(len(arr)):

        idx = -1
        minVar = arr[i]
        for j in range(i, len(arr), 2):
            if arr[j] < minVar:

                minVar = arr[j]
                idx = j
        if idx != -1:
            arr[i], arr[idx] = arr[idx], arr[i]
    if isSorted(arr):
        return True
    else:
        return False


arr = [3, 5, 1, 2, 6]
print(sortPoss(arr))

# Expected output:
True
# print all array elements appearing more than n / k times | function to + find the upper_bound of an array element ; stores minimum index in which k lies ; stores maximum index in which k lies ; calculate the upper bound of k ; stores mid element of l and r ; if arr [ mid ] is less than or equal to k ; right subarray ; left subarray ; function to prall array elements whose frequency is greater than n / k ; sort the array arr ; stores index of an array element ; traverse the array ; stores upper bound of arr [ i ] ; if frequency of arr [ i ] is greater than n / 4 ; update i ; 
def upperBound(arr, N, K):
    l = 0
    r = N
    while (l < r):
        mid = (l + r) // 2
        if (arr[mid] <= K):
            l = mid + 1
        else:
            r = mid
    return l


def NDivKWithFreq(arr, N, K):
    arr .sort()
    i = 0
    while (i < N):
        X = upperBound(arr, N, arr[i])
        if ((X - i) > N // 4):
            print(arr[i], end="")
        i = X


if __name__ == '__main__':
    arr = [1, 2, 2, 6, 6, 6, 6, 7, 10]
    N = len(arr)
    K = 4
    NDivKWithFreq(arr, N, K)

# Expected output:
6
# maximize sum of given array by rearranging array such that the difference between adjacent elements is atmost 1 | function to find maximum possible sum after changing the array elements as per the given constraints ; stores the frequency of elements in given array ; update frequency ; stores the previously selected integer ; stores the maximum possible sum ; traverse over array count [ ] ; run loop for each k ; update ans ; return maximum possible sum ; 
def maxSum(a, n):
    count = [0] * (n + 1)
    for i in range(0, n):
        count[min(a[i], n)] += 1
    size = 0
    ans = 0
    for k in range(1, n + 1):
        while (count[k] > 0 and size < k):
            size += 1
            ans += size
            count[k] -= 1
        ans += k * count[k]
    return ans


if __name__ == '__main__':
    arr = [3, 5, 1]
    n = len(arr)
    print(maxSum(arr, n))

# Expected output:
6
# find sum of product of every number and its frequency in given range | function to solve queries ; calculating answer for every query ; the end points of the ith query ; map for storing frequency ; incrementing the frequency ; iterating over map to find answer ; adding the contribution of ith number ; print answer ; 
def answerQueries(arr, n, queries):
    for i in range(len(queries)):
        ans = 0
        l = queries[i][0] - 1
        r = queries[i][1] - 1
        freq = dict()
        for j in range(l, r + 1):
            freq[arr[j]] = freq .get(arr[j], 0) + 1
        for i in freq:
            ans += (i * freq[i])
        print(ans)


if __name__ == '__main__':
    arr = [1, 2, 1]
    n = len(arr)
    queries = [[1, 2], [1, 3]]
    answerQueries(arr, n, queries)

# Expected output:
3
4
# longest subsequence with first and last element greater than all other elements | python implementation of the above approach ; function to update the value in fenwick tree ; function to return the query result ; function to return the length of subsequence ; store the value in struct array ; if less than 2 elements are present return that element . ; set the left and right pointers to extreme ; calculate left and right pointer index . ; store the queries from [ l + 1 , r - 1 ] . ; sort array and queries for fenwick updates ; for each query calculate maxx for the answer and store it in ans array . ; if queries [ i ] . index < q : ; mx will be mx + 2 as while calculating mx , we excluded element at index left and right ; 

from typing import List


class Query:
    def __init__(self) -> None:
        self .l = 0
        self .r = 0
        self .x = 0
        self .index = 0


class Arrays:
    def __init__(self) -> None:
        self .val = 0
        self .index = 0


def update(Fenwick: List[int], index: int, val: int, n: int) -> None:
    while (index <= n):
        Fenwick[index] += val
        index += index & (-index)


def query(Fenwick: List[int], index: int, n: int) -> int:
    summ = 0
    while (index > 0):
        summ = summ + Fenwick[index]
        index -= index & (-index)
    return summ


def maxLength(n: int, v: List[int]) -> int:
    where = [0 for _ in range(n + 2)]
    arr = [Arrays()for _ in range(n)]
    for i in range(1, n + 1):
        v[i - 1] = v[i - 1] - 1
        x = v[i - 1]
        where[x] = i - 1
        arr[i - 1].val = x
        arr[i - 1].index = i - 1
    if (n <= 2):
        print(n)
        return 0
    left = n
    right = 0
    mx = 0
    queries = [Query()for _ in range(4 * n)]
    j = 0
    for i in range(n - 1, -1, -1):
        left = min(left, where[i])
        right = max(right, where[i])
        diff = right - left
        if (diff == 0 or diff == 1):
            continue
        val1 = v[left]
        val2 = v[right]
        minn = min(val1, val2)
        queries[j].l = left + 1
        queries[j].r = right - 1
        queries[j].x = minn
        queries[j].index = j
        j += 1
    Fenwick = [0 for _ in range(n + 1)]
    q = j - 1
    arr[:n + 1].sort(key=lambda x: x .val)
    queries[:q + 1].sort(key=lambda val: val .x)
    curr = 0
    ans = [0 for _ in range(q + 1)]
    for i in range(q + 1):
        while (arr[curr].val <= queries[i].x and curr < n):
            update(Fenwick, arr[curr].index + 1, 1, n)
            curr += 1
        ans[queries[i].index] = query(
            Fenwick, queries[i].r + 1, n) - query(Fenwick, queries[i].l, n)
    for i in range(q + 1):
        mx = max(mx, ans[i])
    mx = mx + 2
    return mx


if __name__ == "__main__":
    n = 6
    v = [4, 2, 6, 5, 3, 1]
    print(maxLength(n, v))

# Expected output:
3
# pandigital product | calculate the multiplicand , multiplier , and product eligible for pandigital ; to check the string formed from multiplicand multiplier and product is pandigital ; 
def isPandigital(Str):
    if (len(Str) != 9):
        return bool(False)
    ch = "".join(sorted(Str))
    if (ch == "123456789"):
        return bool(True)
    else:
        return bool(False)


def PandigitalProduct_1_9(n):
    i = 1
    while i * i <= n:
        if ((n % i == 0) and bool(isPandigital(str(n) + str(i) + str(n // i)))):
            return bool(True)
        i += 1
    return bool(False)


n = 6952
if (bool(PandigitalProduct_1_9(n))):
    print("yes")
else:
    print("no")

# Expected output:
yes
# median and mode using counting sort | function that sort input array a [ ] and calculate mode and median using counting sort ; the output array b [ ] will have sorted array ; variable to store max of input array which will to have size of count array ; auxiliary ( count ) array to store count . initialize count array as 0. size of count array will be equal to ( max + 1 ) . ; store count of each element of input array ; mode is the index with maximum count ; update count [ ] array with sum ; sorted output array b [ ] to calculate median ; median according to odd and even array size respectively . ; output the result ; 
def printModeMedian(a, n):
    b = [0] * n
    Max = max(a)
    t = Max + 1
    count = [0] * t
    for i in range(n):
        count[a[i]] += 1
    mode = 0
    k = count[0]
    for i in range(1, t):
        if (count[i] > k):
            k = count[i]
            mode = i
    for i in range(1, t):
        count[i] = count[i] + count[i - 1]
    for i in range(n):
        b[count[a[i]] - 1] = a[i]
        count[a[i]] -= 1
    median = 0.0
    if (n % 2 != 0):
        median = b[n // 2]
    else:
        median = ((b[(n - 1) // 2] + b[n // 2]) / 2.0)
    print("median =", median)
    print("mode =", mode)


if __name__ == '__main__':
    arr = [1, 4, 1, 2, 7, 1, 2, 5, 3, 6]
    n = len(arr)
    printModeMedian(arr, n)

# Expected output:
median = 2.5
mode = 1
# check if both halves of the string have at least one different character | python implementation to check if both halves of the string have at least one different character ; function which break string into two halves counts frequency of characters in each half compares the two counter array and returns true if these counter arrays differ ; declaration and initialization of counter array ; 

MAX = 26


def function(st):
    global MAX
    l = len(st)
    counter1, counter2 = [0] * MAX, [0] * MAX
    for i in range(l // 2):
        counter1[ord(st[i]) - ord('a')] += 1
    for i in range(l // 2, l):
        counter2[ord(st[i]) - ord('a')] += 1
    for i in range(MAX):
        if (counter2[i] != counter1[i]):
            return True
    return False


st = "abcasdsabcae"
if function(st):
    print("Yes, both halves differ ", "by at least one character")
else:
    print("No, both halves do not differ at all")

# Expected output:
Yes, both halves differ  by at least one character
# check if both halves of the string have at least one different character | python3 implementation to check if both halves of the string have at least one different character ; function which break string into two halves increments frequency of characters for first half decrements frequency of characters for second half true if any index has non - zero value ; declaration and initialization of counter array ; 

MAX = 26


def function(st):
    global MAX
    l = len(st)
    counter = [0] * MAX
    for i in range(l // 2):
        counter[ord(st[i]) - ord('a')] += 1
    for i in range(l // 2, l):
        counter[ord(st[i]) - ord('a')] -= 1
    for i in range(MAX):
        if (counter[i] != 0):
            return True
    return False


st = "abcasdsabcae"
if function(st):
    print("Yes, both halves differ by at ", "least one character")
else:
    print("No, both halves do not differ at all")

# Expected output:
Yes, both halves differ by at  least one character