giulio98/xlcost-single-prompt huggingface dataset:
# print all numbers in given range having digits in strictly increasing order | function to print all numbers in the range [ l , r ] having digits in strictly increasing order ; iterate over the range ; iterate over the digits ; check if the current digit is >= the previous digit ; if the digits are in ascending order ; 
def printNum(L, R):
    for i in range(L, R + 1):
        temp = i
        c = 10
        flag = 0
        while (temp > 0):
            if (temp % 10 >= c):
                flag = 1
                break
            c = temp % 10
            temp //= 10
        if (flag == 0):
            print(i, end=" ")


L = 10
R = 15
printNum(L, R)

# Expected output:
12 13 14 15
# find the missing number in unordered arithmetic progression | python3 program for the above approach ; function to find the missing element ; fix left and right boundary for binary search ; find index of middle element ; check if the element just after the middle element is missing ; check if the element just before mid is missing ; check if the elements till mid follow the ap , then recur for right half ; else recur for left half ; function to find the missing element in ap series ; sort the array arr [ ] ; calculate common difference ; binary search for the missing ; 

import sys


def findMissing(arr, left, right, diff):
    if (right <= left):
        return sys .maxsize
    mid = left + (right - left) // 2
    if (arr[mid + 1] - arr[mid] != diff):
        return (arr[mid] + diff)
    if (mid > 0 and arr[mid] - arr[mid - 1] != diff):
        return (arr[mid - 1] + diff)
    if (arr[mid] == arr[0] + mid * diff):
        return findMissing(arr, mid + 1, right, diff)
    return findMissing(arr, left, mid - 1, diff)


def missingElement(arr, n):
    arr .sort()
    diff = (arr[n - 1] - arr[0]) // n
    return findMissing(arr, 0, n - 1, diff)


arr = [2, 8, 6, 10]
n = len(arr)
print(missingElement(arr, n))

# Expected output:
4
# floor value kth root of a number using recursive binary search | function to calculate x raised to the power y in o ( logn ) ; function to find the kth root of the number n using bs ; if the range is still valid ; find the mid - value of range ; base case ; condition to check if the left search space is useless ; 
def power(x, y):
    if (y == 0):
        return 1
    temp = power(x, y // 2)
    if (y % 2 == 0):
        return temp * temp
    else:
        return x * temp * temp


def nthRootSearch(low, high, N, K):
    if (low <= high):
        mid = (low + high) // 2
        if ((power(mid, K) <= N) and (power(mid + 1, K) > N)):
            return mid
        elif (power(mid, K) < N):
            return nthRootSearch(mid + 1, high, N, K)
        else:
            return nthRootSearch(low, mid - 1, N, K)
    return low


N = 16
K = 4
print(nthRootSearch(0, N, N, K))

# Expected output:
2
# count of subsets having sum of min and max element less than k | function that return the count of subset such that min ( s ) + max ( s ) < k ; sorting the array ; ans stores total number of subsets ; add all possible subsets between i and j ; decrease the sum ; 
def get_subset_count(arr, K, N):
    arr .sort()
    left = 0
    right = N - 1
    ans = 0
    while (left <= right):
        if (arr[left] + arr[right] < K):
            ans += 1 << (right - left)
            left += 1
        else:
            right -= 1
    return ans


arr = [2, 4, 5, 7]
K = 8
print(get_subset_count(arr, K, 4))

# Expected output:
4
# minimize the maximum difference of adjacent elements after at most k insertions | python3 program to find the minimum of maximum difference between adjacent elements after at most k insertions ; calculate the maximum adjacent difference ; if the maximum adjacent difference is already zero ; best and worst specifies range of the maximum adjacent difference ; to store the no of insertions required for respective values of mid ; if the number of insertions required exceeds k ; otherwise ; 
def minMaxDiff(arr, n, k):
    max_adj_dif = float('-inf')
    for i in range(n - 1):
        max_adj_dif = max(max_adj_dif, abs(arr[i] - arr[i + 1]))
    if (max_adj_dif == 0):
        return 0
    best = 1
    worst = max_adj_dif
    while (best < worst):
        mid = (best + worst) // 2
        required = 0
        for i in range(n - 1):
            required += (abs(arr[i] - arr[i + 1]) - 1) // mid
        if (required > k):
            best = mid + 1
        else:
            worst = mid
    return worst


arr = [3, 12, 25, 50]
n = len(arr)
k = 7
print(minMaxDiff(arr, n, k))

# Expected output:
5
# check if minimum element in array is less than or equals half of every other element | python3 implementation to check if the minimum element in the array is greater than or equal to half of every other element ; function to check if the minimum element in the array is greater than or equal to half of every other element ; initialise the variables to store smallest and second smallest ; check if current element is smaller than smallest , the current smallest will become secondsmallest and current element will be the new smallest ; check if current element is smaller than secondsmallest simply update the latter ; 

import math


def checkMin(arr, n):
    smallest = math .inf
    secondSmallest = math .inf
    for i in range(n):
        if (arr[i] < smallest):
            secondSmallest = smallest
            smallest = arr[i]
        elif (arr[i] < secondSmallest):
            secondSmallest = arr[i]
    if (2 * smallest <= secondSmallest):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    arr = [2, 3, 4, 5]
    n = len(arr)
    checkMin(arr, n)

# Expected output:
No
# largest and smallest fibonacci numbers in an array | python 3 program to find minimum and maximum fibonacci number in given array ; function to create hash table to check fibonacci numbers ; insert initial two numbers in the hash table ; sum of previous two numbers ; update the variable each time ; function to find minimum and maximum fibonacci number in given array ; find maximum value in the array ; creating a set containing all fibonacci numbers up to maximum value in the array ; for storing the minimum and maximum fibonacci number ; check if current element is a fibonacci number ; update the maximum and minimum accordingly ; 

import sys


def createHash(hash, maxElement):
    prev = 0
    curr = 1
    hash .add(prev)
    hash .add(curr)
    while (curr <= maxElement):
        temp = curr + prev
        hash .add(temp)
        prev = curr
        curr = temp


def fibonacci(arr, n):
    max_val = max(arr)
    hash = set()
    createHash(hash, max_val)
    minimum = sys .maxsize
    maximum = -sys .maxsize - 1
    for i in range(n):
        if (arr[i] in hash):
            minimum = min(minimum, arr[i])
            maximum = max(maximum, arr[i])
    print(minimum, end=", ")
    print(maximum)


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

# Expected output:
1, 5
# longest substring with k unique characters using binary search | function that returns true if there is a sub of length len with <= k unique characters ; size of the ; map to store the characters and their frequency ; update the map for the first sub ; check for the rest of the subs ; add the new character ; remove the first character of the previous window ; update the map ; function to return the length of the longest sub which has k unique characters ; check if the complete contains k unique characters ; size of the ; apply binary search ; 
def isValidLen(s, lenn, k):
    n = len(s)
    mp = dict()
    right = 0
    while (right < lenn):
        mp[s[right]] = mp .get(s[right], 0) + 1
        right += 1
    if (len(mp) <= k):
        return True
    while (right < n):
        mp[s[right]] = mp .get(s[right], 0) + 1
        mp[s[right - lenn]] -= 1
        if (mp[s[right - lenn]] == 0):
            del mp[s[right - lenn]]
        if (len(mp) <= k):
            return True
        right += 1
    return len(mp) <= k


def maxLenSubStr(s, k):
    uni = dict()
    for x in s:
        uni[x] = 1
    if (len(uni) < k):
        return -1
    n = len(s)
    lo = -1
    hi = n + 1
    while (hi - lo > 1):
        mid = lo + hi >> 1
        if (isValidLen(s, mid, k)):
            lo = mid
        else:
            hi = mid
    return lo


s = "aabacbebebe"
k = 3
print(maxLenSubStr(s, k))

# Expected output:
7
# largest area square in an array when elements can be shuffled | function that returns true if it is possible to make a square with side equal to l ; to store the count of elements greater than or equal to l ; increment the count ; if the count becomes greater than or equal to l ; function to return the maximum area of the square that can be obtained ; if square is possible with side length m ; try to find a square with smaller side length ; return the area ; 
def isSquarePossible(arr, n, l):
    cnt = 0
    for i in range(n):
        if arr[i] >= l:
            cnt += 1
        if cnt >= l:
            return True
    return False


def maxArea(arr, n):
    l, r = 0, n
    len = 0
    while l <= r:
        m = l + ((r - l) // 2)
        if isSquarePossible(arr, n, m):
            len = m
            l = m + 1
        else:
            r = m - 1
    return (len * len)


arr = [1, 3, 4, 5, 5]
n = len(arr)
print(maxArea(arr, n))

# Expected output:
9
# check duplicates in a stream of strings | function to insert the names and check whether they appear for the first time ; to store the names of the employees ; if current name is appearing for the first time ; 
def insertNames(arr, n):
    string = set()
    for i in range(n):
        if arr[i]not in string:
            print("No")
            string .add(arr[i])
        else:
            print("Yes")


if __name__ == "__main__":
    arr = ["geeks", "for", "geeks"]
    n = len(arr)
    insertNames(arr, n)

# Expected output:
No
No
Yes
# count the triplets such that a [ i ] < b [ j ] < c [ k ] | function to return the count of elements in arr [ ] which are less than the given key ; modified binary search ; function to return the count of elements in arr [ ] which are greater than the given key ; modified binary search ; function to return the count of the required triplets ; sort all three arrays ; iterate for all the elements of array b ; count of elements in a [ ] which are less than the chosen element from b [ ] ; count of elements in c [ ] which are greater than the chosen element from b [ ] ; update the count ; 
def countLessThan(arr, n, key):
    l = 0
    r = n - 1
    index = -1
    while (l <= r):
        m = (l + r) // 2
        if (arr[m] < key):
            l = m + 1
            index = m
        else:
            r = m - 1
    return (index + 1)


def countGreaterThan(arr, n, key):
    l = 0
    r = n - 1
    index = -1
    while (l <= r):
        m = (l + r) // 2
        if (arr[m] <= key):
            l = m + 1
        else:
            r = m - 1
            index = m
    if (index == -1):
        return 0
    return (n - index)


def countTriplets(n, a, b, c):
    a .sort
    b .sort()
    c .sort()
    count = 0
    for i in range(n):
        current = b[i]
        a_index = -1
        c_index = -1
        low = countLessThan(a, n, current)
        high = countGreaterThan(c, n, current)
        count += (low * high)
    return count


if __name__ == "__main__":
    a = [1, 5]
    b = [2, 4]
    c = [3, 6]
    size = len(a)
    print(countTriplets(size, a, b, c))

# Expected output:
3
# cost to balance the parentheses | python 3 code to calculate the minimum cost to make the given parentheses balanced ; to store absolute count of balanced and unbalanced parenthesis ; o ( open bracket ) stores count of ' ( ' and c ( close bracket ) stores count of ') ; 
def costToBalance(s):
    if (len(s) == 0):
        print(0)
    ans = 0

    o = 0
    c = 0
    for i in range(len(s)):
        if (s[i] == '('):
            o += 1
        if (s[i] == ')'):
            c += 1
    if (o != c):
        return -1
    a = [0 for i in range(len(s))]
    if (s[0] == '('):
        a[0] = 1
    else:
        a[0] = -1
    if (a[0] < 0):
        ans += abs(a[0])
    for i in range(1, len(s)):
        if (s[i] == '('):
            a[i] = a[i - 1] + 1
        else:
            a[i] = a[i - 1] - 1
        if (a[i] < 0):
            ans += abs(a[i])
    return ans


if __name__ == '__main__':
    s = ")))((("
    print(costToBalance(s))
    s = "))(("
    print(costToBalance(s))

# Expected output:
9
4
# middle of three using minimum comparisons | function to find the middle of three number ; x is positive if a is greater than b . x is negative if b is greater than a . ; similar to x ; similar to x and y . ; checking if b is middle ( x and y both are positive ) ; checking if c is middle ( x and z both are positive ) ; 
def middleOfThree(a, b, c):
    x = a - b
    y = b - c
    z = a - c
    if x * y > 0:
        return b
    elif (x * z > 0):
        return
    else:
        return a


a = 20
b = 30
c = 40
print(middleOfThree(a, b, c))

# Expected output:
30
# find four missing numbers in an array containing elements from 1 to n | finds missing 4 numbers in o ( n ) time and o ( 1 ) auxiliary space . ; to keep track of 4 possible numbers greater than length of input array in java , helper is automatically initialized as 0. ; traverse the input array and mark visited elements either by marking them as negative in arr [ ] or in helper [ ] . ; if element is smaller than or equal to length , mark its presence in arr [ ] ; mark presence in helper [ ] ; print all those elements whose presence is not marked . ; 
def missing4(arr):
    helper = [0] * 4
    for i in range(0, len(arr)):
        temp = abs(arr[i])
        if (temp <= len(arr)):
            arr[temp - 1] = arr[temp - 1] * (-1)
        elif (temp > len(arr)):
            if (temp % len(arr)):
                helper[temp % len(arr) - 1] = -1
            else:
                helper[(temp % len(arr)) + len(arr) - 1] = -1
    for i in range(0, len(arr)):
        if (arr[i] > 0):
            print((i + 1), end=" ")
    for i in range(0, len(helper)):
        if (helper[i] >= 0):
            print((len(arr) + i + 1), end=" ")


arr = [1, 7, 3, 12, 5, 10, 8, 4, 9]
missing4(arr)

# Expected output:
2 6 11 13
# permutation present at the middle of lexicographic ordering of permutations of at most length n made up integers up to k | function that finds the middle the lexicographical smallest sequence ; if k is even ; first element is k / 2 ; remaining elements of the sequence are all integer k ; stores the sequence when k is odd ; iterate over the range [ 0 , n / 2 ] ; check if the sequence ends with in 1 or not ; remove the sequence ending in 1 ; if it doesn 't end in 1 ; decrement by 1 ; insert k to the sequence till its size is n ; prthe sequence stored in the vector ; 
def lexiMiddleSmallest(K, N):
    if (K % 2 == 0):
        print(K // 2, end=" ")
        for i in range(N - 1):
            print(K, end=" ")
        print()
        return
    a = [(K + 1) // 2] * (N)
    for i in range(N // 2):
        if (a[-1] == 1):
            del a[-1]
        else:
            a[-1] -= 1
            while (len(a) < N):
                a .append(K)
    for i in a:
        print(i, end=" ")
    print()


if __name__ == '__main__':
    K, N = 2, 4
    lexiMiddleSmallest(K, N)

# Expected output:
1 2 2 2
# remaining array element after repeated removal of the smallest element from pairs with absolute difference of 2 or 0 | function to find the last remaining array element after repeatedly removing the smallest from pairs having absolute difference 2 or 0 ; sort the given array in ascending order ; traverse the array ; if difference between adjacent elements is not equal to 0 or 2 ; if operations can be performed ; 
def findLastElement(arr, N):
    arr .sort()
    i = 0
    for i in range(1, N):
        if (arr[i] - arr[i - 1] != 0 and arr[i] - arr[i - 1] != 2):
            print("-1")
            return
    print(arr[N - 1])


if __name__ == '__main__':
    arr = [2, 4, 6, 8, 0, 8]
    N = len(arr)
    findLastElement(arr, N)

# Expected output:
8
# maximize count of subsets into which the given array can be split such that it satisfies the given condition | function to count maximum subsets into which the given array can be split such that it satisfies the given condition ; sort the array in decreasing order ; stores count of subsets possible ; stores count of elements in current subset ; traverse the array arr [ ] ; update size ; if product of the smallest element present in the current subset and size of current subset is >= k ; update maxsub ; update size ; 
def maxDivisions(arr, N, X):
    arr .sort(reverse=True)
    maxSub = 0
    size = 0
    for i in range(N):
        size += 1
        if (arr[i] * size >= X):
            maxSub += 1
            size = 0
    print(maxSub)


if __name__ == "__main__":
    arr = [1, 3, 3, 7]
    N = len(arr)
    X = 3
    maxDivisions(arr, N, X)

# Expected output:
3
# maximize sum of second minimums in all quadruples of a given array | function to find maximum possible sum of second minimums in each quadruple ; sort the array ; add the second minimum ; print maximum possible sum ; 
def maxPossibleSum(arr, N):
    arr .sort()
    sum = 0
    j = N - 3
    while (j >= 0):
        sum += arr[j]
        j -= 3
    print(sum)


if __name__ == "__main__":
    arr = [7, 4, 5, 2, 3, 1, 5, 9]
    N = 8
    maxPossibleSum(arr, N)

# Expected output:
8
# count pairs ( i , j ) from given array such that i k * arr [ j ] | function to find the count required pairs ; stores count of pairs ; traverse the array ; check if the condition is satisfied or not ; 
def getPairs(arr, N, K):
    count = 0
    for i in range(N):
        for j in range(i + 1, N):
            if (arr[i] > K * arr[i + 1]):
                count += 1
    print(count)


if __name__ == '__main__':
    arr = [5, 6, 2, 1]
    N = len(arr)
    K = 2
    getPairs(arr, N, K)

# Expected output:
2
# count pairs ( i , j ) from given array such that i k * arr [ j ] | function to merge two sorted arrays ; i : index to left subarray ; j : index to right subarray ; stores count of pairs that satisfy the given condition ; traverse to check for the valid conditions ; if condition satisfies ; all elements in the right side of the left subarray also satisfies ; sort the two given arrays and store in the resultant array ; elements which are left in the left subarray ; elements which are left in the right subarray ; return the count obtained ; function to partition array into two halves ; same as ( l + r ) / 2 , but avoids overflow for large l and h ; sort first and second halves ; call the merging function ; function to print the count of required pairs using merge sort ; 
def merge(arr, temp, l, m, r, K):
    i = l
    j = m + 1
    cnt = 0
    for l in range(m + 1):
        found = False
        while (j <= r):
            if (arr[i] >= K * arr[j]):
                found = True
            else:
                break
            j += 1
        if (found):
            cnt += j - (m + 1)
            j -= 1
    k = l
    i = l
    j = m + 1
    while (i <= m and j <= r):
        if (arr[i] <= arr[j]):
            temp[k] = arr[i]
            k += 1
            i += 1
        else:
            temp[k] = arr[j]
            k += 1
            j += 1
    while (i <= m):
        temp[k] = arr[i]
        k += 1
        i += 1
    while (j <= r):
        temp[k] = arr[j]
        k += 1
        j += 1
    for i in range(l, r + 1):
        arr[i] = temp[i]
    return cnt


def mergeSortUtil(arr, temp, l, r, K):
    cnt = 0
    if (l < r):
        m = (l + r) // 2
        cnt += mergeSortUtil(arr, temp, l, m, K)
        cnt += mergeSortUtil(arr, temp, m + 1, r, K)
        cnt += merge(arr, temp, l, m, r, K)
    return cnt


def mergeSort(arr, N, K):
    temp = [0] * N
    print(mergeSortUtil(arr, temp, 0, N - 1, K))


arr = [5, 6, 2, 5]
N = len(arr)
K = 2
mergeSort(arr, N, K)

# Expected output:
2
# minimize consecutive removals of elements of the same type to empty given array | function to count minimum consecutive removals of elements of the same type ; sort the array ; stores the maximum element present in the array ; stores the sum of array ; calculate sum of array ; 
def minRemovals(A, N):
    A .sort()
    mx = A[N - 1]
    sum = 1
    for i in range(0, N):
        sum += A[i]
    if ((sum - mx) >= mx):
        print(0, end="")
    else:
        print(2 * mx - sum, end="")


if __name__ == "__main__":
    A = [3, 3, 2]
    N = len(A)
    minRemovals(A, N)

# Expected output:
0
# rearrange given array such that no array element is same as its index | function to rearrange the array a [ ] such that none of the array elements is same as its index ; sort the array ; traverse the indices [ 0 , n - 2 ] of the given array ; check if the current element is equal to its index ; if found to be true , swap current element with the next element ; check if the last element is same as its index ; if found to be true , swap current element with the previous element ; prthe modified array ; 
def rearrangeArray(a, n):
    a = sorted(a)
    for i in range(n - 1):
        if (a[i] == i + 1):
            a[i], a[i + 1] = a[i + 1], a[i]
    if (a[n - 1] == n):
        a[n - 1], a[n - 2] = a[n - 2], a[n - 1]
    for i in range(n):
        print(a[i], end=" ")


if __name__ == '__main__':
    arr = [1, 5, 3, 2, 4]
    N = len(arr)
    rearrangeArray(arr, N)

# Expected output:
2 1 4 5 3
# count minimum number of moves to front or end to sort an array | function that counts the minimum moves required to covert arr [ ] to brr [ ] ; base case ; if arr [ i ] < arr [ j ] ; include the current element ; otherwise , excluding the current element ; function that counts the minimum moves required to sort the array ; if both the arrays are equal ; no moves required ; otherwise ; print minimum operations required ; 
def minOperations(arr1, arr2, i, j):
    if arr1 == arr2:
        return 0
    if i >= len(arr1) or j >= len(arr2):
        return 0
    if arr1[i] < arr2[j]:
        return 1 + minOperations(arr1, arr2, i + 1, j + 1)
    return max(
        minOperations(
            arr1,
            arr2,
            i,
            j + 1),
        minOperations(
            arr1,
            arr2,
            i + 1,
            j))


def minOperationsUtil(arr):
    brr = sorted(arr)
    if (arr == brr):
        print("0")
    else:
        print(minOperations(arr, brr, 0, 0))


arr = [4, 7, 2, 3, 9]
minOperationsUtil(arr)

# Expected output:
2
# check if a string can be transformed to another by sorting substrings | function to check if str1 can be transformed to t by sorting substrings ; occur [ i ] stores the indices of ( ' a ' + i ) in string s ; idx [ i ] stores the next available index of ( ' a ' + i ) in occur [ i ] ; if this is not available anymore ; conversion not possible ; if one of the smaller characters is available and occurs before ; conversion not possible ; print the answer ; 
def canTransform(s, t):
    n = len(s)
    occur = [[]for i in range(26)]
    for x in range(n):
        ch = ord(s[x]) - ord('a')
        occur[ch].append(x)
    idx = [0] * (26)
    poss = True
    for x in range(n):
        ch = ord(t[x]) - ord('a')
        if (idx[ch] >= len(occur[ch])):
            poss = False
            break
        for small in range(ch):
            if (idx[small] < len(occur[small]) and occur[small]
                    [idx[small]] < occur[ch][idx[ch]]):
                poss = False
                break
        idx[ch] += 1
    if (poss):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    s = "hdecb"
    t = "cdheb"
    canTransform(s, t)

# Expected output:
Yes