giulio98/xlcost-single-prompt huggingface dataset:
# maximum value at each level in an n | function to find the maximum value at each level of n - ary tree ; stores the adjacency list ; create the adjacency list ; perform level order traversal of nodes at each level ; push the root node ; iterate until queue is empty ; get the size of queue ; iterate for : all the nodes in the queue currently ; dequeue an node from queue ; enqueue the children of dequeued node ; print the result ; 
def maxAtLevel(N, M, Value, Edges):
    adj = [[]for i in range(N)]
    for i in range(M):
        u = Edges[i][0]
        v = Edges[i][1]
        adj[u].append(v)
    q = []
    q .append(0)
    while (len(q)):
        count = len(q)
        maxVal = 0
        while (count):
            temp = q[0]
            q .remove(q[0])
            maxVal = max(maxVal, Value[temp])
            for i in range(len(adj[temp])):
                q .append(adj[temp][i])
            count -= 1
        print(maxVal, end=" ")


if __name__ == '__main__':
    N = 10
    Edges = [
        [
            0, 1], [
            0, 2], [
                0, 3], [
                    1, 4], [
                        1, 5], [
                            3, 6], [
                                6, 7], [
                                    6, 8], [
                                        6, 9]]
    Value = [1, 2, -1, 3, 4, 5, 8, 6, 12, 7]
    maxAtLevel(N, N - 1, Value, Edges)

# Expected output:
1 3 8 12
# rearrange array to maximize count of triplets ( i , j , k ) such that arr [ i ] > arr [ j ] < arr [ k ] and i < j < k | function to rearrange the array to maximize the count of triplets ; sort the given array ; stores the permutations of the given array ; stores the index of the given array ; place the first half of the given array ; place the last half of the given array ; stores the count of triplets ; check the given conditions ; 
def ctTriplets(arr, N):
    arr .sort()
    temp = [0] * N
    index = 0
    for i in range(1, N, 2):
        temp[i] = arr[index]
        index += 1
    for i in range(0, N, 2):
        temp[i] = arr[index]
        index += 1
    ct = 0
    for i in range(N):
        if (i > 0 and i + 1 < N):
            if (temp[i] < temp[i + 1] and temp[i] < temp[i - 1]):
                ct += 1
    print("Count of triplets:", ct)
    print("Array:", end="")
    for i in range(N):
        print(temp[i], end=" ")


arr = [1, 2, 3, 4, 5, 6]
N = len(arr)
ctTriplets(arr, N)

# Expected output:
Count of triplets: 2
Array:4 1 5 2 6 3
# rearrange array to make it non | python3 program for above approach ; function to check if the array can be made non - decreasing ; iterate till n ; find the minimum element ; sort the array ; iterate till n ; check if the element is at its correct position ; return the answer ; 

import sys


def check(a, n):
    b = [None] * n
    minElement = sys .maxsize
    for i in range(0, n):
        b[i] = a[i]
        minElement = min(minElement, a[i])
    b .sort()
    k = 1
    for i in range(0, n):
        if ((a[i] != b[i]) and (a[i] % minElement != 0)):
            k = 0
            break
    if k == 1:
        return True
    else:
        return False


if __name__ == "__main__":
    a = [4, 3, 6, 6, 2, 9]
    n = len(a)
    if check(a, n):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# count 1 s in binary matrix having remaining indices of its row and column filled with 0 s | function to count required 1 s from the given matrix ; stores the dimensions of the mat ; calculate sum of rows ; calculate sum of columns ; stores required count of 1 s ; if current cell is 1 and sum of row and column is 1 ; increment count of 1 s ; return the final count ; 
def numSpecial(mat):
    m = len(mat)
    n = len(mat[0])
    rows = [0] * m
    cols = [0] * n
    i, j = 0, 0
    for i in range(m):
        rows[i] = 0
        for j in range(n):
            rows[i] += mat[i][j]
    for i in range(n):
        cols[i] = 0
        for j in range(m):
            cols[i] += mat[j][i]
    cnt = 0
    for i in range(m):
        for j in range(n):
            if (mat[i][j] == 1 and rows[i] == 1 and cols[j] == 1):
                cnt += 1
    return cnt


if __name__ == '__main__':
    mat = [[1, 0, 0], [0, 0, 1], [0, 0, 0]]
    print(numSpecial(mat))

# Expected output:
2
# find all matrix elements which are minimum in their row and maximum in their column | python3 program for the above approach ; functionto find all the matrix elements which are minimum in its row and maximum in its column ; initialize unordered set ; traverse the matrix ; update the minimum element of current row ; insert the minimum element of the row ; update the maximum element of current column ; checking if it is already present in the unordered_set or not ; 

import sys


def minmaxNumbers(matrix, res):
    s = set()
    for i in range(0, len(matrix), 1):
        minr = sys .maxsize
        for j in range(0, len(matrix[i]), 1):
            minr = min(minr, matrix[i][j])
        s .add(minr)
    for j in range(0, len(matrix[0]), 1):
        maxc = -sys .maxsize - 1
        for i in range(0, len(matrix), 1):
            maxc = max(maxc, matrix[i][j])
        if (maxc in s):
            res .append(maxc)
    return res


if __name__ == '__main__':
    mat = [[1, 10, 4], [9, 3, 8], [15, 16, 17]]
    ans = []
    minmaxNumbers(mat, ans)
    if (len(ans) == 0):
        print("-1")
    for i in range(len(ans)):
        print(ans[i])

# Expected output:
15
# smallest prefix to be deleted such that remaining array can be rearranged to form a sorted array | function to find the minimum length of prefix required to be deleted ; stores index to be returned ; iterate until previous element is <= current index ; decrementing index ; return index ; 
def findMinLength(arr):
    index = len(arr) - 1
    while (index > 0 and arr[index] >= arr[index - 1]):
        index -= 1
    return index


if __name__ == '__main__':
    arr = [7, 8, 5, 0, -1, -1, 0, 1, 2, 3, 4]
    n = len(arr)
    print(findMinLength(arr))

# Expected output:
4
# count array elements exceeding sum of preceding k elements | function to count array elements exceeding sum of preceding k elements ; iterate over the array ; update prefix sum ; check if arr [ k ] > arr [ 0 ] + . . + arr [ k - 1 ] ; increment count ; check if arr [ i ] > arr [ i - k - 1 ] + . . + arr [ i - 1 ] ; increment count ; 
def countPrecedingK(a, n, K):
    prefix = [0] * n
    prefix[0] = a[0]
    for i in range(1, n):
        prefix[i] = prefix[i - 1] + a[i]
    ctr = 0
    if (prefix[K - 1] < a[K]):
        ctr += 1
    for i in range(K + 1, n):
        if (prefix[i - 1] - prefix[i - K - 1] < a[i]):
            ctr += 1
    return ctr


if __name__ == '__main__':
    arr = [2, 3, 8, 10, -2, 7, 5, 5, 9, 15]
    N = len(arr)
    K = 2
    print(countPrecedingK(arr, N, K))

# Expected output:
2
# count minimum moves required to convert a to b | function to find minimum number of moves to obtained b from a ; stores the minimum number of moves ; absolute difference ; k is in range [ 0 , 10 ] ; print the required moves ; 
def convertBfromA(a, b):
    moves = 0
    x = abs(a - b)
    for i in range(10, 0, -1):
        moves += x // i
        x = x % i
    print(moves, end=" ")


A = 188
B = 4
convertBfromA(A, B)

# Expected output:
19
# minimize nth term of an arithmetic progression ( ap ) | python3 program to implement the above approach ; function to find the smallest nth term of an ap possible ; stores the smallest nth term ; check if common difference of ap is an integer ; store the common difference ; store the first term of that ap ; store the nth term of that ap ; check if all elements of an ap are positive ; return the least nth term obtained ; 

import sys


def smallestNth(A, B, N):
    res = sys .maxsize
    for i in range(1, N):
        for j in range(N, i, -1):
            if ((B - A) % (j - i) == 0):
                D = (B - A) // (j - i)
                FirstTerm = A - (i - 1) * D
                NthTerm = FirstTerm + (N - 1) * D
                if (FirstTerm > 0):
                    res = min(res, NthTerm)
    return res


if __name__ == '__main__':
    N = 3
    A = 1
    B = 6
    print(smallestNth(A, B, N))

# Expected output:
11
# minimum characters required to be removed to sort binary string in ascending order | function to find the minimum count of characters to be removed to make the string sorted in ascending order ; length of given string ; stores the first occurrence of '1 ; stores the last occurrence of '0 ; traverse the string to find the first occurrence of '1 ; traverse the string to find the last occurrence of '0 ; return 0 if the str have only one type of character ; initialize count1 and count0 to count '1' s before lastidx0 and '0' s after firstidx1 ; traverse the string to count0 ; traverse the string to count1 ; return the minimum of count0 and count1 ; 
def minDeletion(s):
    n = len(s)

    firstIdx1 = -1

    lastIdx0 = -1
    for i in range(0, n):
        if (str[i] == '1'):
            firstIdx1 = i
            break
    for i in range(n - 1, -1, -1):
        if (str[i] == '0'):
            lastIdx0 = i
            break
    if (firstIdx1 == -1 or
            lastIdx0 == -1):
        return 0

    count1 = 0
    count0 = 0
    for i in range(0, lastIdx0):
        if (str[i] == '1'):
            count1 += 1
    for i in range(firstIdx1 + 1, n):
        if (str[i] == '1'):
            count0 += 1
    return min(count0, count1)


str = "1000101"
print(minDeletion(str))

# Expected output:
2
# maximum score assigned to a subsequence of numerically consecutive and distinct array elements | function to find the maximum score with unique element in the subset ; base case ; check if the previously picked element differs by 1 from the current element ; calculate score by including the current element ; calculate score by excluding the current element ; return maximum of the two possibilities ; 
def maximumSum(a, b, n, index, lastpicked):
    if (index == n):
        return 0
    option1 = 0
    option2 = 0
    if (lastpicked == -1 or a[lastpicked] != a[index]):
        option1 = b[index] + maximumSum(a, b, n, index + 1, index)
    option2 = maximumSum(a, b, n, index + 1, lastpicked)
    return max(option1, option2)


if __name__ == '__main__':
    arr = [1, 2, 3, 3, 3, 1]
    brr = [-1, 2, 10, 20, -10, -9]
    N = len(arr)
    print(maximumSum(arr, brr, N, 0, -1))

# Expected output:
22
# replace every element in a circular array by sum of next k elements | function to print required resultant array ; reverse the array ; traverse the range ; store prefix sum ; find the prefix sum ; store the answer ; calculate the answers ; count of remaining elements ; add the sum of all elements y times ; add the remaining elements ; update ans [ i ] ; if array is reversed print ans in reverse ; 
def sumOfKElements(arr, n, k):
    rev = False
    if (k < 0):
        rev = True
        k *= -1
        l = 0
        r = n - 1
        while (l < r):
            tmp = arr[l]
            arr[l] = arr[r]
            arr[r] = tmp
            l += 1
            r -= 1
    dp = [0] * n
    dp[0] = arr[0]
    for i in range(1, n):
        dp[i] += dp[i - 1] + arr[i]
    ans = [0] * n
    for i in range(n):
        if (i + k < n):
            ans[i] = dp[i + k] - dp[i]
        else:
            x = k - (n - 1 - i)
            y = x // n
            rem = x % n
            ans[i] = (dp[n - 1] - dp[i] + y * dp[n - 1] +
                      (dp[rem - 1]if rem - 1 >= 0 else 0))
    if (rev):
        for i in range(n - 1, -1, -1):
            print(ans[i], end=" ")
    else:
        for i in range(n):
            print(ans[i], end=" ")


if __name__ == '__main__':
    arr = [4, 2, -5, 11]
    N = len(arr)
    K = 3
    sumOfKElements(arr, N, K)

# Expected output:
8 10 17 1
# count subarrays for every array element in which they are the minimum | function to find the boundary of every element within which it is minimum ; perform binary search ; find mid m ; update l ; update r ; inserting the index ; function to required count subarrays ; stores the indices of element ; initialize the output array ; left boundary , till the element is smallest ; right boundary , till the element is smallest ; calculate the number of subarrays based on its boundary ; adding cnt to the ans ; 
def binaryInsert(boundary, i):
    l = 0
    r = len(boundary) - 1
    while l <= r:
        m = (l + r) // 2
        if boundary[m] < i:
            l = m + 1
        else:
            r = m - 1
    boundary .insert(l, i)
    return l


def countingSubarray(arr, n):
    index = {}
    for i in range(n):
        index[arr[i]] = i
    boundary = [-1, n]
    arr .sort()
    ans = [0 for i in range(n)]
    for num in arr:
        i = binaryInsert(boundary, index[num])
        l = boundary[i] - boundary[i - 1] - 1
        r = boundary[i + 1] - boundary[i] - 1
        cnt = l + r + l * r + 1
        ans[index[num]] += cnt
    return ans


N = 5
arr = [3, 2, 4, 1, 5]
print(countingSubarray(arr, N))

# Expected output:
[1, 4, 1, 8, 1]
# check if digit cube limit of an integer arrives at fixed point or a limit cycle | define the limit ; function to get the sum of cube of digits of a number ; convert to string to get sum of the cubes of its digits ; return sum ; function to check if the number arrives at a fixed point or a cycle ; stores the values obtained ; insert n to set s ; get the next number using f ( n ) ; check if the next number is repeated or not ; function to check if digit cube limit of an integer arrives at fixed point or in a limit cycle ; n is a non negative integer ; function call ; if the value received is greater than limit ; if the value received is an armstrong number ; 

LIMIT = 1000000000


def F(N: int) -> int:
    string = str(N)
    sum = 0
    for i in range(len(string)):
        val = int(ord(string[i]) - ord('0'))
        sum += val * val * val
    return sum


def findDestination(N: int) -> int:
    s = set()
    prev = N
    next = 0
    s .add(N)
    while (N <= LIMIT):
        next = F(N)
        if next in s:
            return next
        prev = next
        s .add(prev)
        N = next
    return next


def digitCubeLimit(N: int) -> int:
    if (N < 0):
        print("N cannot be negative")
    else:
        ans = findDestination(N)
        if (ans > LIMIT):
            print("Limit exceeded")
        elif (ans == F(ans)):
            print("{} reaches to a fixed point: {}".format(N, ans))
        else:
            print("{} reaches to a limit cycle: {}".format(N, ans))


if __name__ == "__main__":
    N = 3
    digitCubeLimit(N)

# Expected output:
3 reaches to a fixed point: 153
# count quadruples ( i , j , k , l ) in an array such that i < j < k < l and arr [ i ] = arr [ k ] and arr [ j ] = arr [ l ] | function to count total number of required tuples ; initialize unordered map ; find the pairs ( j , l ) such that arr [ j ] = arr [ l ] and j < l ; elements are equal ; update the count ; add the frequency of arr [ l ] to val ; update the frequency of element arr [ j ] ; return the answer ; 
def countTuples(arr, N):
    ans = 0
    val = 0
    freq = {}
    for j in range(N - 2):
        val = 0
        for l in range(j + 1, N):
            if (arr[j] == arr[l]):
                ans += val
            if arr[l] in freq:
                val += freq[arr[l]]
        freq[arr[j]] = freq .get(arr[j], 0) + 1
    return ans


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

# Expected output:
4
# minimize subarray increments / decrements required to reduce all array elements to 0 | python3 program of the above approach ; function to count the minimum number of operations required ; traverse the array ; if array element is negative ; update minimum negative ; update maximum position ; return minop ; 

import sys


def minOperation(arr):
    minOp = sys .maxsize
    minNeg = 0
    maxPos = 0
    for i in range(len(arr)):
        if (arr[i] < 0):
            if (arr[i] < minNeg):
                minNeg = arr[i]
        else:
            if arr[i] > maxPos:
                maxPos = arr[i]
    return abs(minNeg) + maxPos


if __name__ == "__main__":
    arr = [1, 3, 4, 1]
    print(minOperation(arr))

# Expected output:
4
# pair of integers having least gcd among all given pairs having gcd exceeding k | function to calculate the gcd of two numbers ; function to print the pair having a gcd value just greater than the given integer ; initialize variables ; iterate until low less than equal to high ; calculate mid ; reducing the search space ; print the answer ; 
def GCD(a, b):
    if (b == 0):
        return a
    return GCD(b, a % b)


def GcdPair(arr, k):
    lo = 0
    hi = len(arr) - 1
    ans = [-1, 0]
    while (lo <= hi):
        mid = lo + (hi - lo) // 2
        if (GCD(arr[mid][0], arr[mid][1]) > k):
            ans = arr[mid]
            hi = mid - 1
        else:
            lo = mid + 1
    if (len(ans) == -1):
        print("-1")
    else:
        print("(", ans[0], ",", ans[1], ")")


if __name__ == '__main__':
    arr = [[3, 6], [15, 30], [25, 75], [30, 120]]
    K = 16
    GcdPair(arr, K)

# Expected output:
( 25 , 75 )
# check if array can be sorted by swapping pairs having gcd equal to the smallest element in the array | python3 implementation of the above approach ; function to check if it is possible to sort array or not ; store the smallest element ; copy the original array ; iterate over the given array ; update smallest element ; copy elements of arr to array b ; sort original array ; iterate over the given array ; if the i - th element is not in its sorted place ; not possible to swap ; 

import sys


def isPossible(arr, N):
    mn = sys .maxsize
    B = [0] * N
    for i in range(N):
        mn = min(mn, arr[i])
        B[i] = arr[i]
    arr .sort()
    for i in range(N):
        if (arr[i] != B[i]):
            if (B[i] % mn != 0):
                print("No")
                return
    print("Yes")
    return


if __name__ == '__main__':
    N = 6
    arr = [4, 3, 6, 6, 2, 9]
    isPossible(arr, N)

# Expected output:
Yes
# check if all array elements are present in a given stack or not | function to check if all array elements is present in the stack ; store the frequency of array elements ; loop while the elements in the stack is not empty ; condition to check if the element is present in the stack ; 
def checkArrInStack(s, arr):
    freq = {}
    for ele in arr:
        freq[ele] = freq.get(ele, 0) + 1
    while s:
        poppedEle = s.pop()
        if poppedEle in freq:
            freq[poppedEle] -= 1

            if not freq[poppedEle]:
                del freq[poppedEle]
    if not freq:
        return True
    return False


if __name__ == "__main__":
    s = [10, 20, 30, 40, 50]
    arr = [20, 30]
    if checkArrInStack(s, arr):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# length of longest substring to be deleted to make a string equal to another string | function to prthe length of longest substring to be deleted ; stores the length of string ; store the position of previous matched character of str1 ; store the position of first occurrence of str2 in str1 ; find the position of the first occurrence of str2 ; store the index of str1 ; if both characters not matched ; store the length of the longest deleted substring ; store the position of last occurrence of str2 in str1 ; if both characters not matched ; update res ; update res . ; 
def longDelSub(str1, str2):
    N = len(str1)
    M = len(str2)
    prev_pos = 0
    pos = [0] * M
    for i in range(M):
        index = prev_pos
        while (index < N and str1[index] != str2[i]):
            index += 1
        pos[i] = index
        prev_pos = index + 1
    res = N - prev_pos
    prev_pos = N - 1
    for i in range(M - 1, -1, -1):
        index = prev_pos
        while (index >= 0 and str1[index] != str2[i]):
            index -= 1
        if (i != 0):
            res = max(res, index - pos[i - 1] - 1)
        prev_pos = index - 1
    res = max(res, prev_pos + 1)
    return res


str1 = "GeeksforGeeks"
str2 = "forks"
print(longDelSub(str1, str2))

# Expected output:
5
# maximized partitions of a string such that each character of the string appears in one substring | function to print all the substrings ; stores the substrings ; stores last index of characters of string s ; find the last position of each character in the string ; update the last index ; iterate the 
def print_substring(s):
    n = len(s)
    str = ""
    ans = []
    if (n == 0):
        print("-1")
        return
    last_pos = [-1] * 26
    for i in range(n - 1, -1, -1):
        if (last_pos[ord(s[i]) - ord('a')] == -1):
            last_pos[ord(s[i]) - ord('a')] = i
    minp = -1
    for i in range(n):
        lp = last_pos[ord(s[i]) - ord('a')]
        minp = max(minp, lp)
        if (i == minp):
            str += s[i]
            print(str, end=" ")
            minp = -1
            str = ""
        else:
            str += s[i]


S = "ababcbacadefegdehijhklij"
print_substring(S)

# Expected output:
ababcbaca defegde hijhklij
# lengths of maximized partitions of a string such that each character of the string appears in one substring | function to find the length of all partitions oof a string such that each characters occurs in a single substring ; stores last index of string s ; find the last position of each letter in the string ; update the last index ; iterate the given string ; get the last index of s [ i ] ; extend the current partition characters last pos ; increase len of partition ; if the current pos of character equals the min pos then the end of partition ; store the length ; print all the partition lengths ; 
def partitionString(s):
    n = len(s)
    ans = []
    if (n == 0):
        print("-1")
        return
    last_pos = [-1] * 26
    for i in range(n - 1, -1, -1):
        if (last_pos[ord(s[i]) - ord('a')] == -1):
            last_pos[ord(s[i]) - ord('a')] = i
    minp = -1
    plen = 0
    for i in range(n):
        lp = last_pos[ord(s[i]) - ord('a')]
        minp = max(minp, lp)
        plen += 1
        if (i == minp):
            ans .append(plen)
            minp = -1
            plen = 0
    for i in range(len(ans)):
        print(ans[i], end=" ")


str = "acbbcc"
partitionString(str)

# Expected output:
1 5
# find the maximum occurring character after performing the given operations | function to find the maximum occurring character ; initialize count of zero and one ; iterate over the given string ; count the zeros ; count the ones ; iterate over the given string ; check if character is * then continue ; check if first character after * is x ; add all * to the frequency of x ; set prev to the i - th character ; check if first character after * is y ; set prev to the i - th character ; check if prev character is 1 and current character is 0 ; half of the * will be converted to 0 ; half of the * will be converted to 1 ; check if prev and current are 1 ; all * will get converted to 1 ; no * can be replaced by either 0 or 1 ; prev becomes the ith character ; check if prev and current are 0 ; all * will get converted to 0 ; if frequency of 0 is more ; if frequency of 1 is more ; 
def solve(S):
    count_0 = 0
    count_1 = 0
    prev = -1
    for i in range(len(S)):
        if (S[i] == '0'):
            count_0 += 1
        elif (S[i] == '1'):
            count_1 += 1
    for i in range(len(S)):
        if (S[i] == '*'):
            continue
        elif (S[i] == '0' and prev == -1):
            count_0 = count_0 + i
            prev = i
        elif (S[i] == '1' and prev == -1):
            prev = i
        elif (S[prev] == '1' and S[i] == '0'):
            count_0 = count_0 + (i - prev - 1) / 2
            count_1 = count_1 + (i - prev - 1) // 2
            prev = i
        elif (S[prev] == '1' and S[i] == '1'):
            count_1 = count_1 + (i - prev - 1)
            prev = i
        elif (S[prev] == '0' and S[i] == '1'):
            prev = i
        elif (S[prev] == '0' and S[i] == '0'):
            count_0 = count_0 + (i - prev - 1)
            prev = i
    if (count_0 > count_1):
        print("0")
    elif (count_1 > count_0):
        print("1")
    else:
        print("-1")


str = "**0**1***0"
solve(str)

# Expected output:
0