giulio98/xlcost-single-prompt huggingface dataset:
# find integral points with minimum distance from given set of integers using bfs | function to find points at minimum distance ; hash to store points that are encountered ; queue to store initial set of points ; vector to store integral points ; using bfs to visit nearest points from already visited points ; get first element from queue ; check if ( x - 1 ) is not encountered so far ; update hash with this new element ; insert ( x - 1 ) into queue ; push ( x - 1 ) as new element ; decrement counter by 1 ; check if ( x + 1 ) is not encountered so far ; update hash with this new element ; insert ( x + 1 ) into queue ; push ( x + 1 ) as new element ; decrement counter by 1 ; print result array ; 
def minDistancePoints(A, K, n):
    m = {}
    q = []
    for i in range(n):
        m[A[i]] = 1
        q .append(A[i])
    ans = []
    while (K > 0):
        x = q[0]
        q = q[1::]
        if ((x - 1)not in m and K > 0):
            m[x - 1] = m .get(x - 1, 0) + 1
            q .append(x - 1)
            ans .append(x - 1)
            K -= 1
        if ((x + 1)not in m and K > 0):
            m[x + 1] = m .get(x + 1, 0) + 1
            q .append(x + 1)
            ans .append(x + 1)
            K -= 1
    for i in ans:
        print(i, end=" ")


if __name__ == '__main__':
    A = [-1, 4, 6]
    K = 3
    n = len(A)
    minDistancePoints(A, K, n)

# Expected output:
-2 0 3
# leftmost column with atleast one 1 in a row | python3 implementation to find the leftmost column with atleast a 1 in a sorted binary matrix ; function to search for the leftmost column of the matrix with atleast a 1 in sorted binary matrix ; loop to iterate over all the rows of the matrix ; binary search to find the leftmost occurence of the 1 ; condition if the column contains the 1 at this position of matrix ; if there is a better solution then update the answer ; condition if the solution doesn 't exist in the matrix ; 

import sys
N = 3


def search(mat, n, m):
    a = sys .maxsize
    for i in range(n):
        low = 0
        high = m - 1
        ans = sys .maxsize
        while (low <= high):
            mid = (low + high) // 2
            if (mat[i][mid] == 1):
                if (mid == 0):
                    ans = 0
                    break
                elif (mat[i][mid - 1] == 0):
                    ans = mid
                    break
            if (mat[i][mid] == 1):
                high = mid - 1
            else:
                low = mid + 1
        if (ans < a):
            a = ans
    if (a == sys .maxsize):
        return -1
    return a + 1


if __name__ == "__main__":
    mat = [[0, 0, 0], [0, 0, 1], [0, 1, 1]]
    print(search(mat, 3, 3))

# Expected output:
2
# largest index for each distinct character in given string with frequency k | python3 implementation of the approach function to find largest index for each distinct character occuring exactly k times . ; function to find largest index for each distinct character occuring exactly k times ; finding all characters present in s ; finding all distinct characters in s ; to store result for each character ; loop through each lower case english character ; if current character is absent in s ; getting current character ; finding count of character ch in s ; to store max index encountred so far ; printing required result ; if no such character exists , print - 1 ; 
def maxSubstring(S, K, N):
    freq = [0 for i in range(26)]
    for i in range(N):
        freq[ord(S[i]) - 97] = 1
    answer = []
    for i in range(26):
        if (freq[i] == 0):
            continue
        ch = chr(i + 97)
        count = 0
        index = -1

        for j in range(N):
            if (S[j] == ch):
                count += 1

            if (count == K):
                index = j

        answer.append([ch, index])

    flag = 0
    for i in range(len(answer)):
        if (answer[i][1] > -1):
            flag = 1
            print(answer[i][0],
                  answer[i][1])
    if (flag == 0):
        print("-1")


if __name__ == '__main__':

    S = "cbaabaacbcd"
    K = 2
    N = len(S)

    maxSubstring(S, K, N)

# Expected output:
a 4
b 7
c 8
# smallest number greater than n that can be represented as a sum of distinct power of k | function to find the smallest number greater than or equal to n represented as the sum of distinct powers of k ; vector p to store the base k representation of the number ; if the representation is >= 2 , then this power of k has to be added once again and then increase the next power of k and make the current power 0 ; reduce all the lower power of k to 0 ; check if the most significant bit also satisfy the above conditions ; converting back from the k - nary representation to decimal form . ; 
def greaterK(n, k):
    index = 0
    p = [0 for i in range(n + 2)]
    x = n
    while (x > 0):
        p[index] = x % k
        x //= k
        index += 1
    idx = 0
    for i in range(0, len(p) - 1, 1):
        if (p[i] >= 2):
            p[i] = 0
            p[i + 1] += 1
            for j in range(idx, i, 1):
                p[j] = 0
            idx = i + 1
        if (p[i] == k):
            p[i] = 0
            p[i + 1] += 1
    j = len(p) - 1
    if (p[j] >= 2):
        p[index] = 1
        index += 1
    ans = 0
    i = len(p) - 1
    while (i >= 0):
        ans = ans * k + p[i]
        i -= 1
    print(ans)


if __name__ == '__main__':
    n = 29
    k = 7
    greaterK(n, k)

# Expected output:
49
# check if the bracket sequence can be balanced with at most one change in the position of a bracket | set 2 | function that returns true if the can be balanced ; count to check the difference between the frequencies of ' ( ' and ' ) ' and count_1 is to find the minimum value of freq ( ' ( ' ) - freq ( ' ) ' ) ; traverse the given string ; increase the count ; decrease the count ; find the minimum value of freq ( ' ( ' ) - freq ( ' ) ' ) ; if the minimum difference is greater than or equal to - 1 and the overall difference is zero ; 
def canBeBalanced(s, n):
    count = 0
    count_1 = 0
    for i in range(n):
        if (s[i] == '('):
            count += 1
        else:
            count -= 1
        count_1 = min(count_1, count)
    if (count_1 >= -1 and count == 0):
        return True
    return False


s = "())()("
n = len(s)
if (canBeBalanced(s, n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# absolute difference between the xor of non | function to find the absolute difference between the xor of non - primes and the xor of primes in the given array ; find maximum value in the array ; use sieve to find all prime numbers less than or equal to max_val create a boolean array " prime [ 0 . . n ] " . a value in prime [ i ] will finally be false if i is not a prime , else true . ; remaining part of sieve ; if prime [ p ] is not changed , then it is a prime ; update all multiples of p ; store the xor of primes in x1 and the xor of non primes in x2 ; the number is prime ; the number is non - prime ; return the absolute difference ; 
def calculateDifference(arr, n):
    max_val = max(arr)
    prime = [True for i in range(max_val + 1)]
    prime[0] = False
    prime[1] = False
    for p in range(2, max_val + 1):
        if p * p > max_val + 1:
            break
        if (prime[p]):
            for i in range(2 * p, max_val + 1, p):
                prime[i] = False
    X1 = 1
    X2 = 1
    for i in range(n):
        if (prime[arr[i]]):
            X1 ^= arr[i]
        elif (arr[i] != 1):
            X2 ^= arr[i]
    return abs(X1 - X2)


arr = [1, 3, 5, 10, 15, 7]
n = len(arr)
print(calculateDifference(arr, n))

# Expected output:
4
# check if it is possible to form string b from a under the given constraints | function that returns true if it is possible to form b from a satisfying the 
def lower_bound(indexes, k):
    low, high = 0, len(indexes) - 1
    while (low < high):
        mid = (low + high) // 2
        if (indexes[mid] < k):
            low = mid + 1
        else:
            high = mid
    if indexes[low] < k:
        return (low + 1)
    else:
        return low

def isPossible(A, B, b, m):
    S = []
    for i in range(26):
        S .append([])
    box = [0] * len(A)
    for i in range(len(A)):
        S[ord(A[i]) - ord('a')].append(i)
    low = 0
    for i in range(len(B)):
        indexes = S[ord(B[i]) - ord('a')]
        it = lower_bound(indexes, low)
        if (it == len(indexes)):
            return False
        count = indexes[it] // b
        box[count] = box[count] + 1
        if (box[count] >= m):
            count += 1
            low = (count) * b
        else:
            low = indexes[it] + 1
    return True


A = "abcbbcdefxyz"
B = "acdxyz"
b = 5
m = 2
if (isPossible(A, B, b, m)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# remove all occurrences of any element for maximum array sum | python3 program to convert fractional decimal to binary number ; find total sum and frequencies of elements ; find minimum value to be subtracted . ; find maximum sum after removal ; 

from sys import maxsize


def maxSumArray(arr, n):
    sum1 = 0
    mp = {i: 0 for i in range(4)}
    for i in range(n):
        sum1 += arr[i]
        mp[arr[i]] += 1
    minimum = maxsize
    for key, value in mp .items():
        if (key == 0):
            continue
        minimum = min(minimum, value * key)
    return (sum1 - minimum)


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

# Expected output:
11
# find maximum n such that the sum of square of first n natural numbers is not more than x | python implementation of the approach ; function to return the sum of the squares of first n natural numbers ; function to return the maximum n such that the sum of the squares of first n natural numbers is not more than x ; iterate till maxvalue of n ; if the condition fails then return the i - 1 i . e sum of squares till i - 1 ; 

import math


def squareSum(N):
    sum = (N * (N + 1) * (2 * N + 1)) // 6
    return sum


def findMaxN(X):
    N = (int)(math .sqrt(X))
    for i in range(1, N + 1):
        if (squareSum(i) > X):
            return i - 1
    return -1


X = 25
print(findMaxN(X))

# Expected output:
3
# remove exactly one element from the array such that max | python3 implementation of the above approach ; function to calculate max - min ; there should be at - least two elements ; to store first and second minimums ; to store first and second maximums ; 

import sys


def max_min(a, n):
    if (n <= 1):
        return sys .maxsize
    f_min = a[0]
    s_min = sys .maxsize
    f_max = a[0]
    s_max = -(sys .maxsize - 1)
    for i in range(n):
        if (a[i] <= f_min):
            s_min = f_min
            f_min = a[i]
        elif (a[i] < s_min):
            s_min = a[i]
        if (a[i] >= f_max):
            s_max = f_max
            f_max = a[i]
        elif (a[i] > s_max):
            s_max = a[i]
    return min((f_max - s_min), (s_max - f_min))


if __name__ == "__main__":
    a = [1, 3, 3, 7]
    n = len(a)
    print(max_min(a, n))

# Expected output:
2
# minimum in an array which is first decreasing then increasing | function to find the smallest number 's index ; do a binary search ; find the mid element ; check for break point ; return the index ; 
def minimal(a, n):
    lo, hi = 0, n - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < a[mid + 1]:
            hi = mid
        else:
            lo = mid + 1
        return lo
        return lo


a = [8, 5, 4, 3, 4, 10]
n = len(a)
ind = minimal(a, n)
print(a[ind])

# Expected output:
3
# leftmost and rightmost indices of the maximum and the minimum element of an array | python3 implementation of the approach ; if found new minimum ; if arr [ i ] = min then rightmost index for min will change ; if found new maximum ; if arr [ i ] = max then rightmost index for max will change ; 
def findIndices(arr, n):
    leftMin, rightMin = 0, 0
    leftMax, rightMax = 0, 0
    min_element = arr[0]
    max_element = arr[0]
    for i in range(n):
        if (arr[i] < min_element):
            leftMin = rightMin = i
            min_element = arr[i]
        elif (arr[i] == min_element):
            rightMin = i
        if (arr[i] > max_element):
            leftMax = rightMax = i
            max_element = arr[i]
        elif (arr[i] == max_element):
            rightMax = i
    print("Minimum left : ", leftMin)
    print("Minimum right : ", rightMin)
    print("Maximum left : ", leftMax)
    print("Maximum right : ", rightMax)


if __name__ == "__main__":
    arr = [2, 1, 1, 2, 1, 5, 6, 5]
    n = len(arr)
    findIndices(arr, n)

# Expected output:
Minimum left :  1
Minimum right :  4
Maximum left :  6
Maximum right :  6
# find smallest and largest element from square matrix diagonals | function to find smallest and largest element from principal and secondary diagonal ; take length of matrix ; declare and initialize variables with appropriate value ; condition for principal diagonal ; take new smallest value ; take new largest value ; condition for secondary diagonal ; take new smallest value ; take new largest value ; declare and 
def diagonalsMinMax(mat):
    n = len(mat)
    if (n == 0):
        return
    principalMin = mat[0][0]
    principalMax = mat[0][0]
    secondaryMin = mat[0][n - 1]
    secondaryMax = mat[0][n - 1]
    for i in range(1, n):
        for j in range(1, n):
            if (i == j):
                if (mat[i][j] < principalMin):
                    principalMin = mat[i][j]
                if (mat[i][j] > principalMax):
                    principalMax = mat[i][j]
            if ((i + j) == (n - 1)):
                if (mat[i][j] < secondaryMin):
                    secondaryMin = mat[i][j]
                if (mat[i][j] > secondaryMax):
                    secondaryMax = mat[i][j]
    print("Principal Diagonal Smallest Element: ", principalMin)
    print("Principal Diagonal Greatest Element : ", principalMax)
    print("Secondary Diagonal Smallest Element: ", secondaryMin)
    print("Secondary Diagonal Greatest Element: ", secondaryMax)


matrix = [[1, 2, 3, 4, -10], [5, 6, 7, 8, 6],
          [1, 2, 11, 3, 4], [5, 6, 70, 5, 8], [4, 9, 7, 1, -5]]
diagonalsMinMax(matrix)

# Expected output:
Principal Diagonal Smallest Element:  -5
Principal Diagonal Greatest Element :  11
Secondary Diagonal Smallest Element:  -10
Secondary Diagonal Greatest Element:  11
# indexed sequential search | python program for indexed sequential search ; storing element ; storing the index ; 
def indexedSequentialSearch(arr, n, k):
    elements = [0] * 20
    indices = [0] * 20
    j, ind, start, end = 0, 0, 0, 0
    set_flag = 0
    for i in range(0, n, 3):
        elements[ind] = arr[i]
        indices[ind] = i
        ind += 1
    if k < elements[0]:
        print("Not found")
        exit(0)
    else:
        for i in range(1, ind + 1):
            if k <= elements[i]:
                start = indices[i - 1]
                end = indices[i]
                set_flag = 1
                break
    if set_flag == 0:
        start = indices[i - 1]
        end = n
    for i in range(start, end + 1):
        if k == arr[i]:
            j = 1
            break
    if j == 1:
        print("Found at index", i)
    else:
        print("Not found")


if __name__ == "__main__":
    arr = [6, 7, 8, 9, 10]
    n = len(arr)
    k = 8
    indexedSequentialSearch(arr, n, k)

# Expected output:
Found at index 2
# count elements such that there are exactly x elements with values greater than or equal to x | python3 implementation of the approach ; sorting the vector ; count of numbers which are greater than v [ i ] ; 

from bisect import bisect as upper_bound


def getCount(v, n):
    v = sorted(v)
    cnt = 0
    for i in range(n):
        tmp = n - 1 - upper_bound(v, v[i] - 1)
        if (tmp == v[i]):
            cnt += 1
    return cnt


n = 4
v = []
v .append(1)
v .append(2)
v .append(3)
v .append(4)
print(getCount(v, n))

# Expected output:
1
# number of segments where all elements are greater than x | function to count number of segments ; iterate in the array ; check if array element greater then x or not ; if flag is true ; after iteration complete check for the last segment ; 
def countSegments(a, n, x):
    flag = False
    count = 0
    for i in range(n):
        if (a[i] > x):
            flag = True
        else:
            if (flag):
                count += 1
            flag = False
    if (flag):
        count += 1
    return count


if __name__ == '__main__':
    a = [8, 25, 10, 19, 19, 18, 20, 11, 18]
    n = len(a)
    x = 13
    print(countSegments(a, n, x))

# Expected output:
3
# find array elements with frequencies in range [ l , r ] | python 3 program to find the elements whose frequency lies in the range [ l , r ] ; hash map which will store the frequency of the elements of the array . ; increment the frequency of the element by 1. ; print the element whose frequency lies in the range [ l , r ] ; 
def findElements(arr, n, l, r):
    mp = {i: 0 for i in range(len(arr))}
    for i in range(n):
        mp[arr[i]] += 1
    for i in range(n):
        if (l <= mp[arr[i]] and mp[arr[i] <= r]):
            print(arr[i], end=" ")


if __name__ == '__main__':
    arr = [1, 2, 3, 3, 2, 2, 5]
    n = len(arr)
    l = 2
    r = 3
    findElements(arr, n, l, r)

# Expected output:
2 3 3 2 2
# count triplets ( a , b , c ) such that a + b , b + c and a + c are all divisible by k | ''function returns the  count of the triplets ; iterate for all triples pairs ( i , j , l ) ; if the condition is satisfied ; 
def count_triples(n, k):
    count, i, j, l = 0, 0, 0, 0
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            for l in range(1, n + 1):
                if ((i + j) %
                    k == 0 and (i + l) %
                    k == 0 and (j + l) %
                        k == 0):
                    count += 1
    return count


if __name__ == "__main__":
    n, k = 3, 2
    ans = count_triples(n, k)
    print(ans)

# Expected output:
9
# kth smallest / largest in a small range unsorted array | python 3 program of kth smallest / largest in a small range unsorted array ; storing counts of elements ; traverse hash array build above until we reach k - th smallest element . ; 
def kthSmallestLargest(arr, n, k):
    max_val = arr[0]
    for i in range(len(arr)):
        if (arr[i] > max_val):
            max_val = arr[i]
    hash = [0 for i in range(max_val + 1)]
    for i in range(n):
        hash[arr[i]] += 1
    count = 0
    for i in range(max_val + 1):
        while (hash[i] > 0):
            count += 1
            if (count == k):
                return i
            hash[i] -= 1
    return -1


if __name__ == '__main__':
    arr = [11, 6, 2, 9, 4, 3, 16]
    n = len(arr)
    k = 3
    print("kth smallest number is:", kthSmallestLargest(arr, n, k))

# Expected output:
kth smallest number is: 4
# meta binary search | one | function to show the working of meta binary search ; set number of bits to represent ; largest array index while ( ( 1 << lg ) < n - 1 ) : lg += 1 ; incrementally construct the index of the target value ; find the element in one direction and update position ; if element found return pos otherwise - 1 ; 

import math


def bsearch(A, key_to_search):
    n = len(A)
    lg = int(math .log2(n - 1)) + 1
    pos = 0
    for i in range(lg - 1, -1, -1):
        if (A[pos] == key_to_search):
            return pos
        new_pos = pos | (1 << i)
        if ((new_pos < n) and (A[new_pos] <= key_to_search)):
            pos = new_pos
    return (pos if (A[pos] == key_to_search)else -1)


if __name__ == "__main__":
    A = [-2, 10, 100, 250, 32315]
    print(bsearch(A, 10))

# Expected output:
1
# queries to check if a number lies in n ranges of l | python program to check if the number lies in given range ; function that answers every query ; container to store all range ; hash the l and r ; push the element to container and hash the l and r ; sort the elements in container ; each query ; get the number same or greater than integer ; if it lies ; check if greater is hashed as 2 ; check if greater is hashed as 1 ; 

from bisect import bisect_left as lower_bound


def answerQueries(a: list, n, queries: list, q):
    v = list()
    mpp = dict()
    for i in range(n):
        v .append(a[i][0])
        mpp[a[i][0]] = 1
        v .append(a[i][1])
        mpp[a[i][1]] = 2
    v .sort()
    for i in range(q):
        num = queries[i]
        ind = lower_bound(v, num)
        if v[ind] == num:
            print("Yes")
        else:
            if mpp[v[ind]] == 2:
                print("Yes")
            else:
                print("No")


if __name__ == "__main__":
    a = [[5, 6], [1, 3], [8, 10]]
    n = 3
    queries = [2, 3, 4, 7]
    q = len(queries)
    answerQueries(a, n, queries, q)

# Expected output:
Yes
Yes
No
No
# median of two sorted arrays of different sizes | set 1 ( linear ) | this function returns median of a [ ] and b [ ] . assumptions in this function : both a [ ] and b [ ] are sorted arrays ; current index of i / p array a [ ] ; current index of i / p array b [ ] ; below is to handle the case where all elements of a [ ] are smaller than smallest ( or first ) element of b [ ] or a [ ] is empty ; below is to handle case where all elements of b [ ] are smaller than smallest ( or first ) element of a [ ] or b [ ] is empty ; below is to handle the case where sum of number of elements of the arrays is even ; below is to handle the case where sum of number of elements of the arrays is odd ; 
def findmedian(a, n1, b, n2):
    i = 0
    j = 0
    m1 = -1
    m2 = -1
    for k in range(((n1 + n2) // 2) + 1):
        if (i < n1 and j < n2):
            if (a[i] < b[j]):
                m2 = m1
                m1 = a[i]
                i += 1
            else:
                m2 = m1
                m1 = b[j]
                j += 1
        elif (i == n1):
            m2 = m1
            m1 = b[j]
            j += 1
        elif (j == n2):
            m2 = m1
            m1 = a[i]
            i += 1
    if ((n1 + n2) % 2 == 0):
        return (m1 + m2) * 1.0 / 2
    return m1


if __name__ == "__main__":
    a = [1, 12, 15, 26, 38]
    b = [2, 13, 24]
    n1 = len(a)
    n2 = len(b)
    print(findmedian(a, n1, b, n2))

# Expected output:
14.0
# next smaller element | prints element and nse pair for all elements of list ; 
def printNSE(arr):
    for i in range(0, len(arr), 1):
        next = -1
        for j in range(i + 1, len(arr), 1):
            if arr[i] > arr[j]:
                next = arr[j]
                break
        print(str(arr[i]) + " -- " + str(next))


arr = [11, 13, 21, 3]
printNSE(arr)

# Expected output:
11 -- 3
13 -- 3
21 -- 3
3 -- -1
# longest subarray such that the difference of max and min is at | python 3 code to find longest subarray with difference between max and min as at - most 1. ; longest constant range length ; first number ; if we see same number ; if we see different number , but same as previous . ; if number is neither same as previous nor as current . ; 
def longestSubarray(input, length):
    prev = -1
    prevCount = 0
    currentCount = 1
    longest = 1
    current = input[0]
    for i in range(1, length):
        next = input[i]
        if next == current:
            currentCount += 1
        elif next == prev:
            prevCount += currentCount
            prev = current
            current = next
            currentCount = 1
        else:
            longest = max(longest, currentCount + prevCount)
            prev = current
            prevCount = currentCount
            current = next
            currentCount = 1
    return max(longest, currentCount + prevCount)


if __name__ == "__main__":
    input = [5, 5, 6, 7, 6]
    n = len(input)
    print(longestSubarray(input, n))

# Expected output:
3