giulio98/xlcost-single-prompt huggingface dataset:
# check if a binary string can be converted to another by reversing substrings consisting of even number of 1 s | function to check if string a can be transformed to string b by reversing substrings of a having even number of 1 s ; store the size of string a ; store the size of string b ; store the count of 1 s in a and b ; stores cnta for string a and cntb for string b ; traverse the string a ; if current character is 1 ; increment 1 s count ; otherwise , update odd1a or even1a depending whether count1a is odd or even ; traverse the string b ; if current character is 1 ; increment 1 s count ; otherwise , update odd1b or even1b depending whether count1b is odd or even ; if the condition is satisfied ; if true , pryes ; otherwise , prno ; 
def canTransformStrings(A, B):
    n1 = len(A)
    n2 = len(B)
    count1A = 0
    count1B = 0
    odd1A = 0
    odd1B = 0
    even1A = 0
    even1B = 0
    for i in range(n1):
        if (A[i] == '1'):
            count1A += 1
        else:
            if ((count1A & 1) == 1):
                odd1A += 1
            else:
                even1A += 1
    for i in range(n2):
        if (B[i] == '1'):
            count1B += 1
        else:
            if ((count1B & 1) == 1):
                odd1B += 1
            else:
                even1B += 1
    if (count1A == count1B and odd1A == odd1B and even1A == even1B):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    A = "10011"
    B = "11100"
    canTransformStrings(A, B)

# Expected output:
Yes
# smallest element present in every subarray of all possible lengths | function to print the common elements for all subarray lengths ; function to find and store the minimum element present in all subarrays of all lengths from 1 to n ; skip lengths for which answer [ i ] is - 1 ; initialize minimum as the first element where answer [ i ] is not - 1 ; updating the answer array ; if answer [ i ] is - 1 , then minimum can be substituted in that place ; find minimum answer ; function to find the minimum number corresponding to every subarray of length k , for every k from 1 to n ; stores the minimum common elements for all subarray lengths initialize with - 1. ; find for every element , the minimum length such that the number is present in every subsequence of that particular length or more ; to store first occurence and gaps between occurences ; to cover the distance between last occurence and the end of the array ; to find the distance between any two occurences ; update and store the answer ; print the required answer ; function to find the smallest element common in all subarrays for every possible subarray lengths ; initializing indices array ; store the numbers present in the array ; push the index in the indices [ a [ i ] ] and also store the numbers in set to get the numbers present in input array ; function call to calculate length of subarray for which a number is present in every subarray of that length ; 
def printAnswer(answer, N):
    for i in range(N + 1):
        print(answer[i], end=" ")


def updateAnswerArray(answer, N):
    i = 0
    while (answer[i] == -1):
        i += 1
    minimum = answer[i]
    while (i <= N):
        if (answer[i] == -1):
            answer[i] = minimum
        else:
            answer[i] = min(minimum, answer[i])
        minimum = min(minimum, answer[i])
        i += 1


def lengthOfSubarray(indices, st, N):
    answer = [-1 for i in range(N + 1)]
    for itr in st:
        start = -1
        gap = -1
        indices[itr].append(N)
        for i in range(len(indices[itr])):
            gap = max(gap, indices[itr][i] - start)
            start = indices[itr][i]
        if (answer[gap] == -1):
            answer[gap] = itr
    updateAnswerArray(answer, N)
    printAnswer(answer, N)


def smallestPresentNumber(arr, N):
    indices = [[]for i in range(N + 1)]
    elements = []
    for i in range(N):
        indices[arr[i]].append(i)
        elements .append(arr[i])
    elements = list(set(elements))
    lengthOfSubarray(indices, elements, N)


arr = [2, 3, 5, 3, 2, 3, 1, 3, 2, 7]
N = len(arr)
smallestPresentNumber(arr, N)

# Expected output:
-1 -1 -1 3 2 2 2 1 1 1 1
# minimize remaining array element by removing pairs and replacing them by their absolute difference | function to find the smallest element left in the array by the given operations ; base case ; if this subproblem has occurred previously ; including i - th array element into the first subset ; if i - th array element is not selected ; update dp [ i ] [ sum ] ; utility function to find smallest element left in the array by the given operations ; stores sum of the array elements ; traverse the array ; update total ; stores overlapping subproblems ; 
def smallestLeft(arr, total, sum, i, dp):
    if (i == 0):
        return abs(total - 2 * sum)
    if (dp[i][sum] != -1):
        return dp[i][sum]
    X = smallestLeft(arr, total, sum + arr[i - 1], i - 1, dp)
    Y = smallestLeft(arr, total, sum, i - 1, dp)
    dp[i][sum] = min(X, Y)
    return dp[i][sum]


def UtilSmallestElement(arr, N):
    total = 0
    for i in range(0, N):
        total += arr[i]
    dp = [[-1 for y in range(total)]for x in range(N + 1)]
    print(smallestLeft(arr, total, 0, N, dp))


arr = [2, 7, 4, 1, 8, 1]
N = len(arr)
UtilSmallestElement(arr, N)

# Expected output:
1
# minimize remaining array element by removing pairs and replacing them by their absolute difference | function to find minimize the remaining array element by removing pairs and replacing them by their absolute difference ; stores sum of array elements ; traverse the array ; update totalsum ; stores half of totalsum ; dp [ i ] : true if sum i can be obtained as a subset sum ; base case ; stores closest sum that can be obtained as a subset sum ; traverse the array ; iterate over all possible value of sum ; update dp [ j ] ; if sum i can be obtained from array elements ; update reach ; 
def SmallestElementLeft(arr, N):
    totalSum = 0
    for i in range(N):
        totalSum += arr[i]
    req = totalSum // 2
    dp = [False for i in range(req + 1)]
    dp[0] = True
    reach = 0
    for i in range(N):
        j = req
        while j >= arr[i]:
            dp[j] = dp[j] or dp[j - arr[i]]
            if (dp[j]):
                reach = max(reach, j)
            j -= 1
    return totalSum - (2 * reach)


if __name__ == '__main__':
    arr = [2, 2, 2]
    N = len(arr)
    print(SmallestElementLeft(arr, N))

# Expected output:
2
# replace even | function to count the minimum number of substrings of str1 such that replacing even - indexed characters of those substrings converts the str1 to str2 ; stores length of str1 ; stores minimum count of operations to convert str1 to str2 ; traverse both the given string ; if current character in both the strings are equal ; stores current index of the string ; if current character in both the strings are not equal ; replace str1 [ ptr ] by str2 [ ptr ] ; update ptr ; update cntop ; 
def minOperationsReq(str11, str22):
    str1 = list(str11)
    str2 = list(str22)
    N = len(str1)
    cntOp = 0
    for i in range(N):
        if (str1[i] == str2[i]):
            continue
        ptr = i
        while (ptr < N and str1[ptr] != str2[ptr]):
            str1[ptr] = str2[ptr]
            ptr += 2
        cntOp += 1
    return cntOp


str1 = "abcdef"
str2 = "ffffff"
print(minOperationsReq(str1, str2))

# Expected output:
2
# check if gcd of all composite numbers in an array divisible by k is a fibonacci number or not | python3 program for the above approach ; function to check if a number is composite or not ; corner cases ; check if the number is divisible by 2 or 3 or not ; check if n is a multiple of any other prime number ; function to check if a number is a perfect square or not ; function to check if a number is a fibonacci number or not ; if 5 * n ^ 2 + 4 or 5 * n ^ 2 - 4 or both are perfect square ; function to check if gcd of composite numbers from the array a [ ] which are divisible by k is a fibonacci number or not ; traverse the array ; if array element is composite and divisible by k ; calculate gcd of all elements in compositeset ; if gcd is fibonacci ; 

import math


def isComposite(n):
    if n <= 1:
        return False
    if n <= 3:
        return False
    if n % 2 == 0 or n % 3 == 0:
        return True
    i = 5
    while i * i <= n:
        if ((n % i == 0) or (n % (i + 2) == 0)):
            return True
        i += 6
    return False


def isPerfectSquare(x):
    s = int(math .sqrt(x))
    return (s * s == x)


def isFibonacci(n):
    return (isPerfectSquare(5 * n * n + 4) or isPerfectSquare(5 * n * n - 4))


def ifgcdFibonacci(a, n, k):
    compositeset = []
    for i in range(n):
        if (isComposite(a[i]) and a[i] % k == 0):
            compositeset .append(a[i])
    gcd = compositeset[0]
    for i in range(1, len(compositeset), 1):
        gcd = math .gcd(gcd, compositeset[i])
        if gcd == 1:
            break
    if (isFibonacci(gcd)):
        print("Yes")
        return
    print("No")
    return


if __name__ == "__main__":
    arr = [34, 2, 4, 8, 5, 7, 11]
    n = len(arr)
    k = 2
    ifgcdFibonacci(arr, n, k)

# Expected output:
Yes
# longest subarray in which all elements are a factor of k | function to find the length of the longest subarray in which all elements are a factor of k ; stores length of the longest subarray in which all elements are a factor of k ; stores length of the current subarray ; traverse the array arr [ ] ; if a [ i ] is a factor of k ; update len ; update maxlen ; if a [ i ] is not a factor of k ; reset len ; 
def find_longest_subarray(A, N, K):
    MaxLen = 0
    Len = 0
    for i in range(N):
        if (K % A[i] == 0):
            Len += 1
            MaxLen = max(MaxLen, Len)
        else:
            Len = 0
    return MaxLen


A = [2, 8, 3, 10, 6, 7, 4, 9]
N = len(A)
K = 60
print(find_longest_subarray(A, N, K))

# Expected output:
3
# length of smallest meeting that can be attended | python3 program to implement the above approach ; function to find the minimum time to attend exactly one meeting ; stores minimum time to attend exactly one meeting ; sort entrance [ ] array ; sort exit [ ] time ; traverse meeting [ ] [ ] ; stores start time of current meeting ; stores end time of current meeting ; find just greater value of u in entrance [ ] ; find just greater or equal value of u in entrance [ ] ; stores enter time to attend the current meeting ; stores exist time after attending the meeting ; update start lies in range [ 0 , m - 1 ] and end lies in the range [ 0 , p - 1 ] ; update ans ; return answer ; 

from bisect import bisect_left, bisect_right
import sys


def minTime(meeting, n, entrance, m, exit, p):
    ans = sys .maxsize
    entrance = sorted(entrance)
    exit = sorted(exit)
    for i in range(n):
        u = meeting[i][0]
        v = meeting[i][1]
        it1 = bisect_right(entrance, u)
        it2 = bisect_left(exit, v)
        start = it1 - 1
        end = it2
        if (start >= 0 and start < m and end >= 0 and end < p):
            ans = min(ans, exit[end] - entrance[start])
    if ans >= sys .maxsize:
        ans = -1
    return ans


if __name__ == '__main__':
    meeting = [[15, 19], [5, 10], [7, 25]]
    entrance = [4, 13, 25, 2]
    exit = [10, 25]
    n = len(meeting)
    m = len(entrance)
    p = len(exit)
    print(minTime(meeting, n, entrance, m, exit, p))

# Expected output:
6
# divide array into two arrays which does not contain any pair with sum k | function to split the given array into two separate arrays satisfying given condition ; stores resultant arrays ; traverse the array ; if a [ i ] is smaller than or equal to k / 2 ; print first array ; print second array ; 
def splitArray(a, n, k):
    first = []
    second = []
    for i in range(n):
        if (a[i] <= k // 2):
            first .append(a[i])
        else:
            second .append(a[i])
    for i in range(len(first)):
        print(first[i], end=" ")
    print("",  end="")
    for i in range(len(second)):
        print(second[i], end=" ")


if __name__ == '__main__':
    k = 5
    a = [0, 1, 3, 2, 4, 5, 6, 7, 8, 9, 10]
    n = len(a)
    splitArray(a, n, k)

# Expected output:
0 1 2 3 4 5 6 7 8 9 10
# maximum number of perfect numbers present in a subarray of size k | function to check a number is perfect number or not ; stores sum of divisors ; find all divisors and add them ; if sum of divisors is equal to n ; function to return maximum sum of a subarray of size k ; if k is greater than n ; compute sum of first window of size k ; compute sums of remaining windows by removing first element of previous window and adding last element of current window ; return the answer ; function to find all the perfect numbers in the array ; the given array is converted into binary array ; 
def isPerfect(N):
    sum = 1
    for i in range(2, N):
        if i * i > N:
            break
        if (N % i == 0):
            if (i == N // i):
                sum += i
            else:
                sum += i + N // i
    if (sum == N and N != 1):
        return 1
    return 0


def maxSum(arr, N, K):
    if (N < K):
        print("Invalid")
        return -1
    res = 0
    for i in range(K):
        res += arr[i]
    curr_sum = res
    for i in range(K, N):
        curr_sum += arr[i] - arr[i - K]
        res = max(res, curr_sum)
    return res


def max_PerfectNumbers(arr, N, K):
    for i in range(N):
        if isPerfect(arr[i]):
            arr[i] = 1
        else:
            arr[i] = 0
    return maxSum(arr, N, K)


if __name__ == '__main__':
    arr = [28, 2, 3, 6, 496, 99, 8128, 24]
    K = 4
    N = len(arr)
    print(max_PerfectNumbers(arr, N, K))

# Expected output:
3
# count greater elements on the left side of every array element | function to print the count of greater elements on left of each array element ; function to get the count of greater elements on left of each array element ; store distinct array elements in sorted order ; stores the count of greater elements on the left side ; traverse the array ; insert array elements into the set ; find previous greater element ; find the distance between the previous greater element of arr [ i ] and last element of the set ; 
def display(countLeftGreater, N):
    for i in range(N):
        print(countLeftGreater[i], end=" ")


def countGreater(arr, N):
    St = set()
    countLeftGreater = [0] * (N)
    for i in range(N):
        St .add(arr[i])
        it = 0
        for st in St:
            if (arr[i] < st):
                break
            it += 1
        countLeftGreater[i] = abs(it - len(St))
    display(countLeftGreater, N)


if __name__ == '__main__':
    arr = [12, 1, 2, 3, 0, 11, 4]
    N = len(arr)
    countGreater(arr, N)

# Expected output:
0 1 1 1 4 1 2
# count characters to be shifted from the start or end of a string to obtain another string | function to find the minimum cost to convert string a to string b ; length of string ; initialize maxlen as 0 ; traverse the string a ; stores the length of substrings of string a ; traversing string b for each character of a ; shift i pointer towards right and increment length , if a [ i ] equals b [ j ] ; if traverse till end ; update maxlen ; return minimum cost ; 
def minCost(A, B):
    n = len(A)
    i = 0
    maxlen = 0
    while (i < n):
        length = 0
        for j in range(0, n):
            if (A[i] == B[j]):
                i += 1
                length += 1
                if (i == n):
                    break
        maxlen = max(maxlen, length)
    return n - maxlen


if __name__ == '__main__':
    A = "edacb"
    B = "abcde"
    print(minCost(A, B))

# Expected output:
3
# lexicographic rank of a string among all its substrings | function to find lexicographic rank of among all its substring ; length of string ; traverse the given string and store the indices of each character ; extract the index ; store it in the vector ; traverse the alphaindex array lesser than the index of first character of given string ; if alphaindex [ i ] size exceeds 0 ; traverse over the indices ; add count of substring equal to n - alphaindex [ i ] [ j ] ; store all substrings in a vector strr starting with the first character of the given string ; insert the current character to substring ; store the subformed ; sort the substring in the lexicographical order ; find the rank of given string ; increase the rank until the given is same ; if substring is same as the given string ; add 1 to rank of the given string ; 
def lexicographicRank(s):
    n = len(s)
    alphaIndex = [[]for i in range(26)]
    for i in range(len(s)):
        x = ord(s[i]) - ord('a')
        alphaIndex[x].append(i)
    rank = -1
    for i in range(26):
        if ord('a') + i >= ord(s[0]):
            break
        if len(alphaIndex[i]) > 0:
            for j in range(len(alphaIndex[i])):
                rank = rank + (n - alphaIndex[i][j])
    strr = []
    for i in range(len(alphaIndex[ord(s[0]) - ord('a')])):
        substring = []
        jj = alphaIndex[ord(s[0]) - ord('a')][i]
        for j in range(jj, n):
            substring .append(s[j])
            strr .append(substring)
    strr = sorted(strr)
    for i in range(len(strr)):
        if (strr[i] != s):
            rank += 1
        else:
            break
    return rank + 1


if __name__ == '__main__':
    strr = "enren"
    print(lexicographicRank(strr))

# Expected output:
7
# Find H | Function to find the H - index ; Set the range for binary search ; Check if current citations is possible ; Check to the right of mid ; Update h - index ; Since current value is not possible , check to the left of mid ; Print the h - index ; citations
def hIndex(citations, n):
    hindex = 0
    low = 0
    high = n - 1
    while (low <= high):
        mid = (low + high) // 2
        if (citations[mid] >= (mid + 1)):
            low = mid + 1
            hindex = mid + 1
        else:
            high = mid - 1
    print(hindex)
    return hindex


n = 5
citations = [5, 3, 3, 2, 2]
hIndex(citations, n)

# Expected output:
3
# check if all strings of an array can be made same by interchanging characters | function to check if all strings are equal after swap operations ; stores the frequency of characters ; stores the length of string ; traverse the array ; traverse each string ; check if frequency of character is divisible by n ; 
def checkEqual(arr, N):
    hash = [0] * 256
    M = len(arr[0])
    for i in range(N):
        for j in range(M):
            hash[ord(arr[i][j])] += 1
    for i in range(256):
        if (hash[i] % N != 0):
            return False
    return True


arr = ["fdd", "fhh"]
N = len(arr)
if (checkEqual(arr, N)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# maximize sum of remaining elements after every removal of the array half with greater sum | function to find the maximum sum ; base case ; create a key to map the values ; check if mapped key is found in the dictionary ; traverse the array ; store left prefix sum ; store right prefix sum ; compare the left and right values ; store the value in dp array ; return the final answer ; function to print maximum sum ; stores prefix sum ; store results of subproblems ; traversing the array ; add prefix sum of array ; print the answer ; 
def maxweight(s, e, pre, dp):
    if s == e:
        return 0
    key = (s, e)
    if key in dp:
        return dp[key]
    ans = 0
    for i in range(s, e):
        left = pre[i] - pre[s - 1]
        right = pre[e] - pre[i]
        if left < right:
            ans = max(ans, left + maxweight(s, i, pre, dp))
        if left == right:
            ans = max(ans, left + maxweight(s, i, pre, dp),
                      right + maxweight(i + 1, e, pre, dp))
        if left > right:
            ans = max(ans, right + maxweight(i + 1, e, pre, dp))
        dp[key] = ans
    return dp[key]


def maxSum(arr):
    pre = {-1: 0, 0: arr[0]}
    dp = {}
    for i in range(1, len(arr)):
        pre[i] = pre[i - 1] + arr[i]
    print(maxweight(0, len(arr) - 1, pre, dp))


arr = [6, 2, 3, 4, 5, 5]
maxSum(arr)

# Expected output:
18
# find k smallest leaf nodes from a given binary tree | binary tree node ; function to create new node ; utility function which calculates smallest three nodes of all leaf nodes ; check if current root is a leaf node ; traverse the left and right subtree ; function to find the k smallest nodes of the binary tree ; sorting the leaf nodes array ; loop to print the k smallest leaf nodes of the array ; 

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

    def __init__(self, data):
        self .data = data
        self .left = None
        self .right = None


def storeLeaf(root: Node, arr: list) -> None:
    if (not root):
        return
    if (not root .left and not root .right):
        arr .append(root .data)
        return
    storeLeaf(root .left, arr)
    storeLeaf(root .right, arr)


def KSmallest(root: Node, k: int) -> None:
    arr = []
    storeLeaf(root, arr)
    arr .sort()
    for i in range(k):
        if (i < len(arr)):
            print(arr[i], end=" ")
        else:
            break


if __name__ == "__main__":
    root = Node(1)
    root .left = Node(2)
    root .left .left = Node(4)
    root .left .left .left = Node(21)
    root .left .right = Node(5)
    root .left .right .right = Node(8)
    root .right = Node(3)
    root .right .left = Node(6)
    root .right .right = Node(7)
    root .right .right .right = Node(19)
    KSmallest(root, 3)

# Expected output:
6 8 19
# check if all the pairs of an array are coprime with each other | python3 implementation of the above approach ; function to check if all the pairs of the array are coprime with each other or not ; check if gcd of the pair is not equal to 1 ; all pairs are non - coprime return false ;  ; 
def gcd(a, b):
    if (b == 0):
        return a
    else:
        return gcd(b, a % b)


def allCoprime(A, n):
    all_coprime = True
    for i in range(n):
        for j in range(i + 1, n):
            if gcd(A[i], A[j]) != 1:
                all_coprime = False
                break
    return all_coprime


if __name__ == "__main__":
    A = [3, 5, 11, 7, 19]
    arr_size = len(A)
    if (allCoprime(A, arr_size)):
        print('Yes')
    else:
        print('No')

# Expected output:
Yes
# smallest power of 2 consisting of n digits | python3 program of the above approach ; function to return smallest power of 2 with n digits ; 

from math import log2, ceil


def smallestNum(n):
    power = log2(10)
    print(power)
    return ceil((n - 1) * power)


n = 4
print(smallestNum(n))

# Expected output:
3.321928094887362
10
# find a valid parenthesis sequence of length k from a given valid parenthesis sequence | function to find the subsequence of length k forming valid sequence ; stores the resultant string ; check whether character at index i is visited or not ; traverse the string ; push index of open bracket ; pop and mark visited ; increment count by 2 ; append the characters and create the resultant string ; return the resultant string ; 
def findString(s, k):
    n = len(s)
    ans = ""
    st = []
    vis = [False] * n
    count = 0
    for i in range(n):
        if (s[i] == '('):
            st .append(i)
        if (count < k and s[i] == ')'):
            vis[st[-1]] = 1
            del st[-1]
            vis[i] = True
            count += 2
    for i in range(n):
        if (vis[i]):
            ans += s[i]
    return ans


if __name__ == '__main__':
    s = "()()()"
    K = 2
    print(findString(s, K))

# Expected output:
()
# maximum sum path in a matrix from top | function to find the maximum sum path in the grid ; dimensions of grid [ ] [ ] ; stores maximum sum at each cell sum [ i ] [ j ] from cell sum [ 0 ] [ 0 ] ; iterate to compute the maximum sum path in the grid ; update the maximum path sum ; return the maximum sum ; 
def MaximumPath(grid):
    N = len(grid)
    M = len(grid[0])
    sum = [[0 for i in range(M + 1)]for i in range(N + 1)]
    for i in range(1, N + 1):
        for j in range(1, M + 1):
            sum[i][j] = (max(sum[i - 1][j], sum[i][j - 1]) +
                         grid[i - 1][j - 1])
    return sum[N][M]


if __name__ == '__main__':
    grid = [[1, 2], [3, 5]]
    print(MaximumPath(grid))

# Expected output:
9