giulio98/xlcost-single-prompt huggingface dataset:
# count subarrays with equal number of 1 ' s ▁ and ▁ 0' s | function to count subarrays with equal number of 1 ' s ▁ and ▁ 0' s ; ' um ' implemented as hash table to store frequency of values obtained through cumulative sum ; traverse original array and compute cumulative sum and increase count by 1 for this sum in ' um ' . adds ' - 1' when arr [ i ] == 0 ; traverse the hash table um ; if there are more than one prefix subarrays with a particular sum ; add the subarrays starting from 1 st element and have equal number of 1 ' s ▁ and ▁ 0' s ; required count of subarrays ; 
def countSubarrWithEqualZeroAndOne(arr, n):
    um = dict()
    curr_sum = 0
    for i in range(n):
        curr_sum += (-1 if (arr[i] == 0)else arr[i])
        if um .get(curr_sum):
            um[curr_sum] += 1
        else:
            um[curr_sum] = 1
    count = 0
    for itr in um:
        if um[itr] > 1:
            count += ((um[itr] * int(um[itr] - 1)) / 2)
    if um .get(0):
        count += um[0]
    return int(count)


arr = [1, 0, 0, 1, 0, 1, 1]
n = len(arr)
print("Count =", countSubarrWithEqualZeroAndOne(arr, n))

# Expected output:
Count = 8
# longest subarray having count of 1 s one more than count of 0 s | function to find the length of longest subarray having count of 1 ' s ▁ one ▁ more ▁ than ▁ count ▁ of ▁ 0' s ; unordered_map ' um ' implemented as hash table ; traverse the given array ; consider '0' as '-1   ; when subarray starts form index '0   ; make an entry for ' sum ' if it is not present in 'um   ; check if ' sum - 1' is present in ' um ' or not ; update maxlength ; required maximum length ; 
def lenOfLongSubarr(arr, n):
    um = {i: 0 for i in range(10)}
    sum = 0
    maxLen = 0
    for i in range(n):
        if arr[i] == 0:
            sum += -1
        else:
            sum += 1
        if (sum == 1):
            maxLen = i + 1
        elif (sum not in um):
            um[sum] = i
        if ((sum - 1) in um):
            if (maxLen < (i - um[sum - 1])):
                maxLen = i - um[sum - 1]
    return maxLen


if __name__ == '__main__':
    arr = [0, 1, 1, 0, 0, 1]
    n = len(arr)
    print("Length =", lenOfLongSubarr(arr, n))

# Expected output:
Length = 5
# print all triplets in sorted array that form ap | function to print all triplets in given sorted array that forms ap ; use hash to find if there is a previous element with difference equal to arr [ j ] - arr [ i ] ; 
def printAllAPTriplets(arr, n):
    s = []
    for i in range(0, n - 1):
        for j in range(i + 1, n):
            diff = arr[j] - arr[i]
            if ((arr[i] - diff) in arr):
                print(
                    "{} {} {}".format(
                        (arr[i] - diff),
                        arr[i],
                        arr[j]),
                    end="")
    s .append(arr[i])


arr = [2, 6, 9, 12, 17, 22, 31, 32, 35, 42]
n = len(arr)
printAllAPTriplets(arr, n)

# Expected output:
6 9 122 12 2212 17 222 17 3212 22 329 22 352 22 4222 32 42
# print all triplets in sorted array that form ap | function to print all triplets in given sorted array that forms ap ; search other two elements of ap with arr [ i ] as middle . ; if a triplet is found ; since elements are distinct , arr [ k ] and arr [ j ] cannot form any more triplets with arr [ i ] ; if middle element is more move to higher side , else move lower side . ; 
def printAllAPTriplets(arr, n):
    for i in range(1, n - 1):
        j = i - 1
        k = i + 1
        while (j >= 0 and k < n):
            if (arr[j] + arr[k] == 2 * arr[i]):
                print(arr[j], "", arr[i], "", arr[k])
                k += 1
                j -= 1
            elif (arr[j] + arr[k] < 2 * arr[i]):
                k += 1
            else:
                j -= 1


arr = [2, 6, 9, 12, 17, 22, 31, 32, 35, 42]
n = len(arr)
printAllAPTriplets(arr, n)

# Expected output:
6  9  12
2  12  22
12  17  22
2  17  32
12  22  32
9  22  35
2  22  42
22  32  42
# check if there is a root to leaf path with given sequence | class of node ; util function ; if root is null or reached end of the array ; if current node is leaf ; if current node is equal to arr [ index ] this means that till this level path has been matched and remaining path can be either in left subtree or right subtree . ; function to check given sequence of root to leaf path exist in tree or not . index represents current element in sequence of rooth to leaf path ; 

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


def existPathUtil(root, arr, n, index):
    if not root or index == n:
        return False
    if not root .left and not root .right:
        if root .val == arr[index] and index == n - 1:
            return True
        return False
    return ((index < n) and (root .val == arr[index]) and (existPathUtil(
        root .left, arr, n, index + 1) or existPathUtil(root .right, arr, n, index + 1)))


def existPath(root, arr, n, index):
    if not root:
        return (n == 0)
    return existPathUtil(root, arr, n, 0)


if __name__ == "__main__":
    arr = [5, 8, 6, 7]
    n = len(arr)
    root = Node(5)
    root .left = Node(3)
    root .right = Node(8)
    root .left .left = Node(2)
    root .left .right = Node(4)
    root .left .left .left = Node(1)
    root .right .left = Node(6)
    root .right .left .right = Node(7)
    if existPath(root, arr, n, 0):
        print("Path Exists")
    else:
        print("Path does not Exist")

# Expected output:
Path Exists
# all unique triplets that sum up to a given value | function to all find unique triplets without using extra space ; sort the input array ; for handling the cases when no such triplets exits . ; iterate over the array from start to n - 2. ; index of the first element in remaining range . ; index of the last element ; setting our new target ; checking if current element is same as previous ; checking if current element is same as previous ; if we found the triplets then print it and set the flag ; if target is greater then increment the start index ; if target is smaller than decrement the end index ; if no such triplets found ; 
def findTriplets(a, n, sum):
    a .sort()
    flag = False
    for i in range(n - 2):
        if (i == 0 or a[i] > a[i - 1]):
            start = i + 1
            end = n - 1
            target = sum - a[i]
            while (start < end):
                if (start > i + 1 and a[start] == a[start - 1]):
                    start += 1
                    continue
                if (end < n - 1 and a[end] == a[end + 1]):
                    end -= 1
                    continue
                if (target == a[start] + a[end]):
                    print("[", a[i], ",", a[start], ",", a[end], "]", end=" ")
                    flag = True
                    start += 1
                    end -= 1
                elif (target > (a[start] + a[end])):
                    start += 1
                else:
                    end -= 1
    if (flag == False):
        print("No Such Triplets Exist")


if __name__ == "__main__":
    a = [12, 3, 6, 1, 6, 9]
    n = len(a)
    sum = 24
    findTriplets(a, n, sum)

# Expected output:
[ 3 , 9 , 12 ] [ 6 , 6 , 12 ]
# find the position of the given row in a 2 | python implementation of the approach ; function to find a row in the given matrix using linear search ; assume that the current row matched with the given array ; if any element of the current row doesn 't  match with the corresponding element  of the given array ; set matched to false and break ; ; if matched then return the row number ; no row matched with the given array ; 

m, n = 6, 4


def linearCheck(ar, arr):
    for i in range(m):
        matched = True
        for j in range(n):
            if (ar[i][j] != arr[j]):
                matched = False
                break
        if (matched):
            return i + 1
    return -1


if __name__ == "__main__":
    mat = [[0, 0, 1, 0], [10, 9, 22, 23], [40, 40, 40, 40], [
        43, 44, 55, 68], [81, 73, 100, 132], [100, 75, 125, 133]]
    row = [10, 9, 22, 23]
    print(linearCheck(mat, row))

# Expected output:
2
# count number of triplets with product equal to given number | method to count such triplets ; consider all triplets and count if their product is equal to m ; 
def countTriplets(arr, n, m):
    count = 0
    for i in range(n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
                if (arr[i] * arr[j] * arr[k] == m):
                    count += 1
    return count


if __name__ == "__main__":
    arr = [1, 4, 6, 2, 3, 8]
    m = 24
    print(countTriplets(arr, len(arr), m))

# Expected output:
3
# count number of triplets with product equal to given number | function to find the triplet ; consider all pairs and check for a third number so their product is equal to product ; check if current pair divides product or not if yes , then search for ( product / li [ i ] * li [ j ] ) ; check if the third number is present in the map and it is not equal to any other two elements and also check if this triplet is not counted already using their indexes ; 
def countTriplets(li, product):
    flag = 0
    count = 0
    for i in range(len(li)):
        if li[i] != 0 and product % li[i] == 0:
            for j in range(i + 1, len(li)):
                if li[j] != 0 and product % (li[j] * li[i]) == 0:
                    if product // (li[j] * li[i]) in li:
                        n = li .index(product // (li[j] * li[i]))
                        if n > i and n > j:
                            flag = 1
                            count += 1
    print(count)


li = [1, 4, 6, 2, 3, 8]
product = 24
countTriplets(li, product)

# Expected output:
3
# count of index pairs with equal elements in an array | return the number of pairs with equal values . ; for each index i and j ; finding the index with same value but different index . ; 
def countPairs(arr, n):
    ans = 0
    for i in range(0, n):
        for j in range(i + 1, n):
            if (arr[i] == arr[j]):
                ans += 1
    return ans


arr = [1, 1, 2]
n = len(arr)
print(countPairs(arr, n))

# Expected output:
1
# queries to answer the number of ones and zero to the left of given index | function to pre - calculate the left [ ] array ; iterate in the binary array ; initialize the number of 1 and 0 ; increase the count ; 
def preCalculate(binary, n, left):
    count1, count0 = 0, 0
    for i in range(n):
        left[i][0] = count1
        left[i][1] = count0
        if (binary[i]):
            count1 += 1
        else:
            count0 += 1


binary = [1, 1, 1, 0, 0, 1, 0, 1, 1]
n = len(binary)
left = [[0 for i in range(2)]for i in range(n)]
preCalculate(binary, n, left)
queries = [0, 1, 2, 4]
q = len(queries)
for i in range(q):
    print(left[queries[i]][0], "ones", left[queries[i]][1], "zeros")

# Expected output:
0 ones 0 zeros
1 ones 0 zeros
2 ones 0 zeros
3 ones 1 zeros
# count of index pairs with equal elements in an array | python3 program to count of index pairs with equal elements in an array . ; return the number of pairs with equal values . ; finding frequency of each number . ; calculating pairs of each value . ; 

import math as mt


def countPairs(arr, n):
    mp = dict()
    for i in range(n):
        if arr[i] in mp .keys():
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    ans = 0
    for it in mp:
        count = mp[it]
        ans += (count * (count - 1)) // 2
    return ans


arr = [1, 1, 2]
n = len(arr)
print(countPairs(arr, n))

# Expected output:
1
# partition the array into three equal sum segments | this function returns true if the array can be divided into three equal sum segments ; prefix sum array ; suffix sum array ; stores the total sum of the array ; we can also take pre [ pos2 - 1 ] - pre [ pos1 ] == total_sum / 3 here . ; 
def equiSumUtil(arr, pos1, pos2):
    n = len(arr)
    pre = [0] * n
    sum = 0
    for i in range(n):
        sum += arr[i]
        pre[i] = sum
    suf = [0] * n
    sum = 0
    for i in range(n - 1, -1, -1):
        sum += arr[i]
        suf[i] = sum
    total_sum = sum
    i = 0
    j = n - 1
    while (i < j - 1):
        if (pre[i] == total_sum // 3):
            pos1 = i
        if (suf[j] == total_sum // 3):
            pos2 = j
        if (pos1 != -1 and pos2 != -1):
            if (suf[pos1 + 1] - suf[pos2] == total_sum // 3):
                return [True, pos1, pos2]
            else:
                return [False, pos1, pos2]
        if (pre[i] < suf[j]):
            i += 1
        else:
            j -= 1
    return [False, pos1, pos2]


def equiSum(arr):
    pos1 = -1
    pos2 = -1
    ans = equiSumUtil(arr, pos1, pos2)
    pos1 = ans[1]
    pos2 = ans[2]
    if (ans[0]):
        print("First Segment : ", end="")
        for i in range(pos1 + 1):
            print(arr[i], end=" ")
        print("")
        print("Second Segment : ", end="")
        for i in range(pos1 + 1, pos2):
            print(arr[i], end=" ")
        print("")
        print("Third Segment : ", end="")
        for i in range(pos2, len(arr)):
            print(arr[i], end=" ")
        print("")
    else:
        println("Array cannot be divided into", "three equal sum segments")


arr = [1, 3, 6, 2, 7, 1, 2, 8]
equiSum(arr)

# Expected output:
First Segment : 1 3 6 
Second Segment : 2 7 1 
Third Segment : 2 8
# elements to be added so that all elements of a range are present in array | function to count numbers to be added ; sort the array ; check if elements are consecutive or not . if not , update count ; 
def countNum(arr, n):
    count = 0
    arr .sort()
    for i in range(0, n - 1):
        if (arr[i] != arr[i + 1] and arr[i] != arr[i + 1] - 1):
            count += arr[i + 1] - arr[i] - 1
    return count


arr = [3, 5, 8, 6]
n = len(arr)
print(countNum(arr, n))

# Expected output:
2
# find the k smallest numbers after deleting given elements | python3 program to find the k maximum number from the array after n deletions ; find k maximum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; hash map of the numbers to be deleted ; increment the count of del [ i ] ; search if the element is present ; decrement its frequency ; if the frequency becomes 0 , erase it from the map ; else push it ; 

import math as mt


def findElementsAfterDel(arr, m, dell, n, k):
    mp = dict()
    for i in range(n):
        if dell[i] in mp .keys():
            mp[dell[i]] += 1
        else:
            mp[dell[i]] = 1
    heap = list()
    for i in range(m):
        if (arr[i] in mp .keys()):
            mp[arr[i]] -= 1
            if (mp[arr[i]] == 0):
                mp .pop(arr[i])
        else:
            heap .append(arr[i])
    heap .sort()
    return heap[:k]


array = [5, 12, 33, 4, 56, 12, 20]
m = len(array)
dell = [12, 56, 5]
n = len(dell)
k = 3
print(*findElementsAfterDel(array, m, dell, n, k))

# Expected output:
4 12 20
# elements to be added so that all elements of a range are present in array | function to count numbers to be added ; make a hash of elements and store minimum and maximum element ; traverse all elements from minimum to maximum and count if it is not in the hash ; 
def countNum(arr, n):
    s = dict()
    count, maxm, minm = 0, -10 ** 9, 10 ** 9
    for i in range(n):
        s[arr[i]] = 1
        if (arr[i] < minm):
            minm = arr[i]
        if (arr[i] > maxm):
            maxm = arr[i]
    for i in range(minm, maxm + 1):
        if i not in s .keys():
            count += 1
    return count


arr = [3, 5, 8, 6]
n = len(arr)
print(countNum(arr, n))

# Expected output:
2
# find minimum speed to finish all jobs | function to check if the person can do all jobs in h hours with speed k ; function to return the minimum speed of person to complete all jobs ; if h < n it is not possible to complete all jobs as person can not move from one element to another during current hour ; max element of array ; use binary search to find smallest k ; 
def isPossible(A, n, H, K):
    time = 0
    for i in range(n):
        time += (A[i] - 1) // K + 1
    return time <= H


def minJobSpeed(A, n, H):
    if H < n:
        return -1
    Max = max(A)
    lo, hi = 1, Max
    while lo < hi:
        mi = lo + (hi - lo) // 2
        if not isPossible(A, n, H, mi):
            lo = mi + 1
        else:
            hi = mi
    return lo


if __name__ == "__main__":
    A = [3, 6, 7, 11]
    H = 8
    n = len(A)
    print(minJobSpeed(A, n, H))

# Expected output:
4
# number of anomalies in an array | python3 program to implement the above approach ; sort the array so that we can apply binary search . ; one by one check every element if it is anomaly or not using binary search . ; if arr [ i ] is not largest element and element just greater than it is within k , then return false . ; if there are more than one occurrences of arr [ i ] , return false . ; if arr [ i ] is not smallest element and just smaller element is not k distance away ; 
def lower_bound(a, low, high, element):
    while (low < high):
        middle = int(low + int(high - low) / 2)
        if (element > a[middle]):
            low = middle + 1
        else:
            high = middle
    return low


def upper_bound(a, low, high, element):
    while (low < high):
        middle = int(low + (high - low) / 2)
        if (a[middle] > element):
            high = middle
        else:
            low = middle + 1
    return low

def countAnomalies(a, n, k):
    a = sorted(a)
    res = 0
    for i in range(n):
        u = upper_bound(a, 0, n, a[i])
        if (u < n and a[u] - a[i] <= k):
            continue
        s = lower_bound(a, 0, n, a[i])
        if (u - s > 1):
            continue
        if (s > 0 and a[s - 1] - a[i] <= k):
            continue
        res += 1
    return res


if __name__ == '__main__':
    arr = [7, 1, 8]
    k = 5
    n = len(arr)
    print(countAnomalies(arr, n, k))

# Expected output:
1
# subarrays with distinct elements | returns sum of lengths of all subarrays with distinct elements . ; for maintaining distinct elements . ; initialize ending point and result ; fix starting point ; calculating and adding all possible length subarrays in arr [ i . . j ] ; remove arr [ i ] as we pick new stating point from next ; 
def sumoflength(arr, n):
    s = []
    j = 0
    ans = 0
    for i in range(n):
        while (j < n and (arr[j]not in s)):
            s .append(arr[j])
            j += 1
        ans += ((j - i) * (j - i + 1)) // 2
        s .remove(arr[i])
    return ans


if __name__ == "__main__":
    arr = [1, 2, 3, 4]
    n = len(arr)
    print(sumoflength(arr, n))

# Expected output:
20
# count subarrays having total distinct elements same as original array | function to calculate distinct sub - array ; count distinct elements in whole array ; reset the container by removing all elements ; use sliding window concept to find count of subarrays having k distinct elements . ; if window size equals to array distinct element size , then update answer ; decrease the frequency of previous element for next sliding window ; if frequency is zero then decrease the window size ; 
def countDistictSubarray(arr, n):
    vis = dict()
    for i in range(n):
        vis[arr[i]] = 1
    k = len(vis)
    vid = dict()
    ans = 0
    right = 0
    window = 0
    for left in range(n):
        while (right < n and window < k):
            if arr[right] in vid .keys():
                vid[arr[right]] += 1
            else:
                vid[arr[right]] = 1
            if (vid[arr[right]] == 1):
                window += 1
            right += 1
        if (window == k):
            ans += (n - right + 1)
        vid[arr[left]] -= 1
        if (vid[arr[left]] == 0):
            window -= 1
    return ans


arr = [2, 1, 3, 2, 3]
n = len(arr)
print(countDistictSubarray(arr, n))

# Expected output:
5
# count subarrays with same even and odd elements | function that returns the count of subarrays that contain equal number of odd as well as even numbers ; initialize difference and answer with 0 ; initialize these auxiliary arrays with 0 ; since the difference is initially 0 , we have to initialize hash_positive [ 0 ] with 1 ; for loop to iterate through whole array ( zero - based indexing is used ) ; incrementing or decrementing difference based on arr [ i ] being even or odd , check if arr [ i ] is odd ; adding hash value of ' difference ' to our answer as all the previous occurrences of the same difference value will make even - odd subarray ending at index ' i ' . after that , we will increment hash array for that ' difference ' value for its occurrence at index ' i ' . if difference is negative then use hash_negative ; else use hash_positive ; return total number of even - odd subarrays ; 
def countSubarrays(arr, n):
    difference = 0
    ans = 0
    hash_positive = [0] * (n + 1)
    hash_negative = [0] * (n + 1)
    hash_positive[0] = 1
    for i in range(n):
        if (arr[i] & 1 == 1):
            difference = difference + 1
        else:
            difference = difference - 1
        if (difference < 0):
            ans += hash_negative[-difference]
            hash_negative[-difference] = hash_negative[-difference] + 1
        else:
            ans += hash_positive[difference]
            hash_positive[difference] = hash_positive[difference] + 1
    return ans


arr = [3, 4, 6, 8, 1, 10, 5, 7]
n = len(arr)
print("Total Number of Even-Odd subarrays are " + str(countSubarrays(arr, n)))

# Expected output:
Total Number of Even-Odd subarrays are 7
# minimum number of distinct elements after removing m items | function to find distintc id 's ; store the occurrence of ids ; store into the list value as key and vice - versa ; start removing elements from the beginning ; remove if current value is less than or equal to mi ; return the remaining size ; 
def distinctIds(arr, n, mi):
    m = {}
    v = []
    count = 0
    for i in range(n):
        if arr[i] in m:
            m[arr[i]] += 1
        else:
            m[arr[i]] = 1
    for i in m:
        v .append([m[i], i])
    v .sort()
    size = len(v)
    for i in range(size):
        if (v[i][0] <= mi):
            mi -= v[i][0]
            count += 1
        else:
            return size - count
    return size - count


arr = [2, 3, 1, 2, 3, 3]
n = len(arr)
m = 3
print(distinctIds(arr, n, m))

# Expected output:
1
# number of larger elements on right side in a string | python3 program to find counts of right greater characters for every character . ; 
def printGreaterCount(str):
    len__ = len(str)
    right = [0 for i in range(len__)]
    for i in range(len__):
        for j in range(i + 1, len__, 1):
            if (str[i] < str[j]):
                right[i] += 1
    for i in range(len__):
        print(right[i], end=" ")


if __name__ == '__main__':
    str = "abcd"
    printGreaterCount(str)

# Expected output:
3 2 1 0
# maximum consecutive numbers present in an array | python3 program to find largest consecutive numbers present in arr . ; we insert all the array elements into unordered set . ; check each possible sequence from the start then update optimal length ; if current element is the starting element of a sequence ; then check for next elements in the sequence ; increment the value of array element and repeat search in the set ; update optimal length if this length is more . to get the length as it is incremented one by one ; 
def findLongestConseqSubseq(arr, n):
    S = set()
    for i in range(n):
        S .add(arr[i])
    ans = 0
    for i in range(n):
        if S .__contains__(arr[i]):
            j = arr[i]
            while (S .__contains__(j)):
                j += 1
            ans = max(ans, j - arr[i])
    return ans


if __name__ == '__main__':
    arr = [1, 94, 93, 1000, 5, 92, 78]
    n = len(arr)
    print(findLongestConseqSubseq(arr, n))

# Expected output:
3