giulio98/xlcost-single-prompt huggingface dataset:
# longest substring where all the characters appear at least k times | set 3 | function to find the length of the longest substring ; store the required answer ; create a frequency map of the characters of the string ; store the length of the string ; traverse the string , s ; increment the frequency of the current character by 1 ; stores count of unique characters ; find the number of unique characters in string ; iterate in range [ 1 , unique ] ; 
def longestSubstring(s, k):
    ans = 0
    freq = [0] * 26
    n = len(s)
    for i in range(n):
        freq[ord(s[i]) - ord('a')] += 1
    unique = 0
    for i in range(26):
        if (freq[i] != 0):
            unique += 1
    for curr_unique in range(1, unique + 1):
        Freq = [0] * 26
        start, end = 0, 0
        cnt, count_k = 0, 0
        while (end < n):
            if (cnt <= curr_unique):
                ind = ord(s[end]) - ord('a')
                if (Freq[ind] == 0):
                    cnt += 1
                Freq[ind] += 1
                if (Freq[ind] == k):
                    count_k += 1
                end += 1
            else:
                ind = ord(s[start]) - ord('a')
                if (Freq[ind] == k):
                    count_k -= 1
                Freq[ind] -= 1
                if (Freq[ind] == 0):
                    cnt -= 1
                start += 1
            if ((cnt == curr_unique) and (count_k == curr_unique)):
                ans = max(ans, end - start)
    print(ans)


S = "aabbba"
K = 3
longestSubstring(S, K)

# Expected output:
6
# print matrix elements using dfs traversal | direction vectors ; function to check if current position is valid or not ; check if the cell is out of bounds ; check if the cell is visited or not ; utility function to prmatrix elements using dfs traversal ; mark the current cell visited ; print element at the cell ; traverse all four adjacent cells of the current element ; check if x and y is valid index or not ; function to print matrix elementsdef ; function call to prmatrix elements by dfs traversal ; 

dRow = [-1, 0, 1, 0]
dCol = [0, 1, 0, -1]


def isValid(row, col, COL, ROW):
    global vis
    if (row < 0 or col < 0 or col > COL - 1 or row > ROW - 1):
        return False
    if (vis[row][col]):
        return False
    return True


def DFSUtil(row, col, grid, M, N):
    global vis
    vis[row][col] = True
    print(grid[row][col], end=" ")
    for i in range(4):
        x = row + dRow[i]
        y = col + dCol[i]
        if (isValid(x, y, M, N)):
            DFSUtil(x, y, grid, M, N)


def DFS(row, col, grid, M, N):
    global vis
    DFSUtil(0, 0, grid, M, N)


if __name__ == '__main__':
    grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
    M = len(grid)
    N = len(grid[0])
    vis = [[False for i in range(M)]for i in range(N)]
    DFS(0, 0, grid, M, N)

# Expected output:
1 2 3 4 8 12 16 15 11 7 6 10 14 13 9 5
# print matrix elements using dfs traversal | direction vectors ; function to check if curruent position is valid or not ; check if the cell is out of bounds ; check if the cell is visited ; function to print the matrix elements ; stores if a position in the matrix been visited or not ; initialize stack to implement dfs ; push the first position of grid [ ] [ ] in the stack ; mark the cell ( 0 , 0 ) visited ; stores top element of stack ; delete the top ( ) element of stack ; print element at the cell ; traverse in all four adjacent sides of current positions ; check if x and y is valid position and then push the position of current cell in the stack ; push the current cell ; mark current cell visited ; 

dRow = [-1, 0, 1, 0]
dCol = [0, 1, 0, -1]
vis = []


def isValid(row, col, COL, ROW):
    global vis
    if (row < 0 or col < 0 or col > COL - 1 or row > ROW - 1):
        return False
    if (vis[row][col]):
        return False
    return True


def DFS_iterative(grid, M, N):
    global vis
    vis = []
    for i in range(M + 5):
        vis .append([])
        for j in range(N + 5):
            vis[i].append(False)
    st = []
    st .append([0, 0])
    vis[0][0] = True
    while (len(st) > 0):
        p = st[-1]
        st .pop()
        row = p[0]
        col = p[1]
        print(grid[row][col], "", end="")
        for i in range(4):
            x = row + dRow[i]
            y = col + dCol[i]
            if (isValid(x, y, M, N)):
                st .append([x, y])
                vis[x][y] = True


grid = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
M = len(grid)
N = len(grid[0])
DFS_iterative(grid, M, N)

# Expected output:
1 5 9 13 14 15 16 12 8 7 3 4 11 10 6 2
# segregate 1 s and 0 s in separate halves of a binary string | function to count the minimum number of operations required to segregate all 1 s and 0 s in a binary string ; stores the count of unequal pair of adjacent characters ; if an unequal pair of adjacent characters occurs ; for odd count ; for even count ; 
def minOps(s, N):
    ans = 0
    for i in range(1, N):
        if (s[i] != s[i - 1]):
            ans += 1
    if (ans % 2 == 1):
        print((ans - 1) // 2)
        return
    print(ans // 2)


str = "01011100"
N = len(str)
minOps(str, N)

# Expected output:
2
# find index of the element differing in parity with all other array elements | function to print the array element which differs in parity with the remaining array elements ; multimaps to store even and odd numbers along with their indices ; traverse the array ; if array element is even ; otherwise ; if only one even element is present in the array ; if only one odd element is present in the array ;  ; 
def OddOneOut(arr, N):
    e, o = {}, {}
    for i in range(N):
        if (arr[i] % 2 == 0):
            e[arr[i]] = i
        else:
            o[arr[i]] = i
    if (len(e) == 1):
        print(list(e .values())[0])
    else:
        print(list(o .values())[0])


arr = [2, 4, 7, 8, 10]
N = len(arr)
OddOneOut(arr, N)

# Expected output:
2
# count indices where the maximum in the prefix array is less than that in the suffix array | function to print the count of indices in which the maximum in prefix arrays is less than that in the suffix array ; if size of array is 1 ; pre [ ] : prefix array suf [ ] : suffix array ; stores the required count ; find the maximum in prefix array ; find the maximum in suffix array ; traverse the array ; if maximum in prefix array is less than maximum in the suffix array ; print the answer ; 
def count(a, n):
    if (n == 1):
        print(0)
        return
    pre = [0] * (n - 1)
    suf = [0] * (n - 1)
    max = a[0]
    ans = 0
    pre[0] = a[0]
    for i in range(n - 1):
        if (a[i] > max):
            max = a[i]
        pre[i] = max
    max = a[n - 1]
    suf[n - 2] = a[n - 1]
    for i in range(n - 2, 0, -1):
        if (a[i] > max):
            max = a[i]
        suf[i - 1] = max
    for i in range(n - 1):
        if (pre[i] < suf[i]):
            ans += 1
    print(ans)


arr = [2, 3, 4, 8, 1, 4]
N = len(arr)
count(arr, N)

# Expected output:
3
# length of the longest subsequence such that xor of adjacent elements is equal to k | function to find maximum length of subsequence ; stores maximum length of subsequence ; hashmap to store the longest length of subsequence ending at an integer , say x ; stores the maximum length of subsequence ending at index i ; base case ; iterate over the range [ 1 , n - 1 ] ; if dpj is not null ; update dp [ i ] ; update ans ; update the maximum length of subsequence ending at element is a [ i ] in hashmap ; return the ans if ans >= 2. otherwise , return 0 ; 
def xorSubsequence(a, n, k):
    ans = 0
    map = {}
    dp = [0] * n
    map[a[0]] = 1
    dp[0] = 1
    for i in range(1, n):
        if (a[i] ^ k in map):
            dp[i] = max(dp[i], map[a[i] ^ k] + 1)
        ans = max(ans, dp[i])
        if a[i] in map:
            map[a[i]] = max(map[a[i]], dp[i])
        else:
            map[a[i]] = max(1, dp[i])
    if ans >= 2:
        return ans
    return 0


if __name__ == "__main__":
    arr = [3, 2, 4, 3, 5]
    N = len(arr)
    K = 1
    print(xorSubsequence(arr, N, K))

# Expected output:
3
# minimum time required to fill given n slots | function to return the minimum time to fill all the slots ; stores visited slots ; checks if a slot is visited or not ; insert all filled slots ; iterate until queue is not empty ; iterate through all slots in the queue ; front index ; if previous slot is present and not visited ; if next slot is present and not visited ; increment the time at each level ; print the answer ; 
def minTime(arr, N, K):
    q = []
    vis = [False] * (N + 1)
    time = 0
    for i in range(K):
        q .append(arr[i])
        vis[arr[i]] = True
    while (len(q) > 0):
        for i in range(len(q)):
            curr = q[0]
            q .pop(0)
            if (curr - 1 >= 1 and vis[curr - 1] == 0):
                vis[curr - 1] = True
                q .append(curr - 1)
            if (curr + 1 <= N and vis[curr + 1] == 0):
                vis[curr + 1] = True
                q .append(curr + 1)
        time += 1
    print(time - 1)


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

# Expected output:
2
# count of integers having difference with its reverse equal to d | maximum digits in n ; utility function to find count of n such that n + d = reverse ( n ) ; if d is a multiple of 9 , no such value n found ; divide d by 9 check reverse of number and its sum ; b [ i ] : stores power of ( 10 , i ) ; calculate power ( 10 , i ) ; update b [ i ] ; stores count of n such that n + d = reverse ( n ) ; iterate over the range [ 1 , maxl ] ; update ans ; function to find count of possible values of n such that n + d = reverse ( n ) ; base case ; if d is not qual to 0 ; stores count of possible values of n such that n + d = reverse ( n ) ; update ans ; if l is even ; update ans ; stores count of possible values of n such that n + d = reverse ( n ) ; iterae over the range [ - 9 , 9 ] ; update ans ; 

MAXL = 17
N = 0
v = 0


def count(D, l, t, x):
    global N
    global v
    if (t == N):
        if (D != 0):
            return 0
        ans = 1
        for i in range(N):
            ans *= (9 if i == 0 else 10) - abs(x[i])
        if (l % 2 == 0):
            ans *= 10
        return ans
    ans = 0
    for m in range(-9, 10):
        if (-v[t] < D + v[t] * m and D + v[t] * m < v[t]):
            x[t] = m
            ans += count(D + v[t] * m, l, t + 1, x)
    return ans

def findN(D):
    global N
    global v
    if (D % 9 != 0):
        return 0
    D //= 9
    B = [0] * MAXL
    B[0] = 1
    for i in range(1, MAXL):
        B[i] = B[i - 1] * 10
    ans = 0
    for i in range(1, MAXL + 1):
        N = (i + 1) // 2
        v = [0] * N
        for j in range(N):
            for k in range(j, i - j):
                v[j] += B[k]
        temp = [0] * N
        ans += count(D, i, 0, temp)
        return ans


if __name__ == '__main__':
    D = 63
    print(findN(D))

# Expected output:
2
# search for an element in a mountain array | function to find the index of the peak element in the array ; stores left most index in which the peak element can be found ; stores right most index in which the peak element can be found ; stores mid of left and right ; if element at mid is less than element at ( mid + 1 ) ; update left ; update right ; function to perform binary search in an a subarray if elements of the subarray are in an ascending order ; stores mid of left and right ; if x found at mid ; if x is greater than mid ; update left ; update right ; function to perform binary search in an a subarray if elements of the subarray are in an ascending order ; stores mid of left and right ; if x found at mid ; update right ; update left ; function to find the smallest index of x ; stores index of peak element in array ; stores index of x in the array ; if x greater than or equal to first element of array and less than the peak element ; update res ; if element not found on left side of peak element ; update res ; print res ; 
def findPeak(arr):
    left = 0
    right = len(arr) - 1
    while (left < right):
        mid = left + (right - left) // 2
        if (arr[mid] < arr[(mid + 1)]):
            left = mid + 1
        else:
            right = mid
    return left


def BS(X, left, right, arr):
    while (left <= right):
        mid = left + (right - left) // 2
        if (arr[mid] == X):
            return mid
        elif (X > arr[mid]):
            left = mid + 1
        else:
            right = mid - 1
    return -1


def reverseBS(X, left, right, arr):
    while (left <= right):
        mid = left + (right - left) // 2
        if (arr[mid] == X):
            return mid
        elif (X > arr[mid]):
            right = mid - 1
        else:
            left = mid + 1
    return -1


def findInMA(X, mountainArr):
    peakIndex = findPeak(mountainArr)
    res = -1
    if (X >= mountainArr[0] and X <= mountainArr[peakIndex]):
        res = BS(X, 0, peakIndex, mountainArr)
    if (res == -1):
        res = reverseBS(X, peakIndex + 1, mountainArr .size() - 1, mountainArr)
    print(res)


if __name__ == "__main__":
    X = 3
    arr = [1, 2, 3, 4, 5, 3, 1]
    findInMA(X, arr)

# Expected output:
2
# rearrange given array to obtain positive prefix sums at exactly x indices | function to rearrange the array according to the given condition ; using 2 nd operation making all values positive ; sort the array ; assign k = n - k ; count number of zeros ; if number of zeros if greater ; using 2 nd operation convert it into one negative ; using 2 nd operation convert it into one negative ; print array ; 
def rearrange(a, n, x):
    for i in range(n):
        a[i] = abs(a[i])
    a = sorted(a)
    x = n - x
    z = a .count(0)
    if (x > n - z):
        print("-1")
        return
    for i in range(0, n, 2):
        if x <= 0:
            break
        a[i] = -a[i]
        x -= 1
    for i in range(n - 1, -1, -1):
        if x <= 0:
            break
        if (a[i] > 0):
            a[i] = -a[i]
            x -= 1
    for i in range(n):
        print(a[i], end=" ")


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

# Expected output:
0 2 -3 4 5
# maximize product of a strictly increasing or decreasing subarray | function to find the maximum product of subarray in the array , arr [ ] ; maximum positive product ending at the i - th index ; minimum negative product ending at the current index ; maximum product up to i - th index ; check if an array element is positive or not ; traverse the array ; if current element is positive ; update max_ending_here ; update min_ending_here ; update flag ; if current element is 0 , reset the start index of subarray ; update max_ending_here ; update min_ending_here ; if current element is negative ; stores max_ending_here ; update max_ending_here ; update min_ending_here ; update max_so_far , if needed ; if no array elements is positive and max_so_far is 0 ; function to find the maximum product of either increasing subarray or the decreasing subarray ; stores start index of either increasing subarray or the decreasing subarray ; initially assume maxprod to be 1 ; traverse the array ; store the longest either increasing subarray or the decreasing subarray whose start index is i ; check for increasing subarray ; insert elements of increasing subarray ; check for decreasing subarray ; insert elements of decreasing subarray ; stores maximum subarray product of current increasing or decreasing subarray ; update maxprod ; update i ; finally prmaxprod ; 
def maxSubarrayProduct(arr, n):
    max_ending_here = 1
    min_ending_here = 1
    max_so_far = 0
    flag = 0
    for i in range(n):
        if (arr[i] > 0):
            max_ending_here = max_ending_here * arr[i]
            min_ending_here = min(min_ending_here * arr[i], 1)
            flag = 1
        elif (arr[i] == 0):
            max_ending_here = 1
            min_ending_here = 1
        else:
            temp = max_ending_here
            max_ending_here = max(min_ending_here * arr[i], 1)
            min_ending_here = temp * arr[i]
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here
    if (flag == 0 and max_so_far == 0):
        return 0
    return max_so_far


def findMaxProduct(a, n):
    i = 0
    maxProd = -10 ** 9
    while (i < n):
        v = []
        v .append(a[i])
        if i < n - 1 and a[i] < a[i + 1]:
            while (i < n - 1 and a[i] < a[i + 1]):
                v .append(a[i + 1])
                i += 1
        elif (i < n - 1 and a[i] > a[i + 1]):
            while (i < n - 1 and a[i] > a[i + 1]):
                v .append(a[i + 1])
                i += 1
        prod = maxSubarrayProduct(v, len(v))
        maxProd = max(maxProd, prod)
        i += 1
    return maxProd


if __name__ == '__main__':
    arr = [1, 2, 10, 8, 1, 100, 101]
    N = len(arr)
    print(findMaxProduct(arr, N))

# Expected output:
10100
# number of connected components of a graph ( using disjoint set union ) | stores the parent of each vertex ; function to find the topmost parent of vertex a ; if current vertex is the topmost vertex ; otherwise , set topmost vertex of its parent as its topmost vertex ; function to connect the component having vertex a with the component having vertex b ; connect edges ; function to find unique top most parents ; traverse all vertices ; insert all topmost vertices obtained ; print count of connected components ; function to print answer ; setting parent to itself ; traverse all edges ; print answer ; given n ; 

parent = [0] * (1000000)


def root(a):
    if (a == parent[a]):
        return a
    parent[a] = root(parent[a])
    return parent[a]


def connect(a, b):
    a = root(a)
    b = root(b)
    if (a != b):
        parent[b] = a


def connectedComponents(n):
    s = set()
    for i in range(n):
        s .add(root(parent[i]))
    print(len(s))


def printAnswer(N, edges):
    for i in range(N + 1):
        parent[i] = i
    for i in range(len(edges)):
        connect(edges[i][0], edges[i][1])
    connectedComponents(N)


N = 6
edges = [[1, 0], [2, 3], [1, 2], [4, 5]]
printAnswer(N, edges)

# Expected output:
2
# remove all zero | function to remove the rows or columns from the matrix which contains all 0 s elements ; stores count of rows ; col [ i ] : stores count of 0 s in current column ; row [ i ] : stores count of 0 s in current row ; traverse the matrix ; stores count of 0 s in current row ; update col [ j ] ; update count ; update row [ i ] ; traverse the matrix ; if all elements of current row is 0 ; if all elements of current column is 0 ; 
def removeZeroRowCol(arr):
    n = len(arr)
    col = [0] * (n + 1)
    row = [0] * (n + 1)
    for i in range(n):
        count = 0
        for j in range(n):
            col[j] += (arr[i][j] == 1)
            count += (arr[i][j] == 1)
        row[i] = count
    for i in range(n):
        if (row[i] == 0):
            continue
        for j in range(n):
            if (col[j] != 0):
                print(arr[i][j], end="")
        print()


arr = [[1, 1, 0, 1], [0, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 1]]
removeZeroRowCol(arr)

# Expected output:
111
111
011
# find a pair of overlapping intervals from a given set | function to find a pair ( i , j ) such that i - th interval lies within the j - th interval ; store interval and index of the interval in the form of { { l , r } , index } ; traverse the array , arr [ ] [ ] ; stores l - value of the interval ; stores r - value of the interval ; push current interval and index into tup ; sort the vector based on l - value of the intervals ; stores r - value of current interval ; stores index of current interval ; traverse the vector , tup [ ] ; stores l - value of previous interval ; stores l - value of current interval ; if q and r are equal ; print the index of interval ; stores r - value of current interval ; if t is less than or equal to curr ; update curr ; update currpos ; if such intervals found ; given l - value of segments ; given r - value of segments ; 
def findOverlapSegement(N, a, b):
    tup = []
    for i in range(N):
        x = a[i]
        y = b[i]
        tup .append(((x, y), i))
    tup .sort()
    curr = tup[0][0][1]
    currPos = tup[0][1]
    for i in range(1, N):
        Q = tup[i - 1][0][0]
        R = tup[i][0][0]
        if Q == R:
            if tup[i - 1][0][1] < tup[i][0][1]:
                print(tup[i - 1][1], tup[i][1])
            else:
                print(tup[i][1], tup[i - 1][1])
            return
        T = tup[i][0][1]
        if (T <= curr):
            print(tup[i][1], currPos)
            return
        else:
            curr = T
            currPos = tup[i][1]
    print("-1", "-1", end="")


a = [1, 2, 3, 2, 2]
b = [5, 10, 10, 2, 15]
N = len(a)
findOverlapSegement(N, a, b)

# Expected output:
3 0
# count maximum concatenation of pairs from given array that are divisible by 3 | function to count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; stores count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; check if an element present in any pair or not ; generate all possible pairs ; if the element already present in a pair ; if the element already present in a pair ; if concatenation of elements is divisible by 3 ; update ans ; mark i is true ; mark j is true ; 
def countDivBy3InArray(arr):
    ans = 0
    taken = [False] * len(arr)
    for i in range(len(arr)):
        if taken[i]:
            continue
        for j in range(i + 1, len(arr)):
            if taken[j]:
                continue
            if (not int(str(arr[i]) + str(arr[j])) %
                    3 or not int(str(arr[j]) + str(arr[i])) % 3):
                ans += 1
                taken[i] = True
                taken[j] = True
    return ans


arr = [5, 3, 2, 8, 7]
print(countDivBy3InArray(arr))

# Expected output:
1
# maximum average of subtree values in a given binary tree | structure of the tree node ; stores the result ; function for finding maximum subtree average ; checks if current node is not none and doesn 't have any children ; stores sum of its subtree in index 0 and count number of nodes in index 1 ; traverse all children of the current node ; recursively calculate max average of subtrees among its children ; increment sum by sum of its child 's subtree ; increment number of nodes by its child 's node ; increment sum by current node 's value ; increment number of nodes by one ; take maximum of ans and current node 's average ; finally return pair of { sum , count } ; 

class TreeNode:
    def __init__(self, val):
        self .val = val
        self .children = []


ans = 0.0


def MaxAverage(root):
    global ans
    if (root is not None and len(root .children) == 0):
        ans = max(ans, (root .val))
        return [root .val, 1]
    childResult = [0 for i in range(2)]
    for child in root .children:
        childTotal = MaxAverage(child)
        childResult[0] = childResult[0] + childTotal[0]
        childResult[1] = childResult[1] + childTotal[1]
    sum = childResult[0] + root .val
    count = childResult[1] + 1
    ans = max(ans, sum / count)
    return [sum, count]


if __name__ == '__main__':
    root = TreeNode(20)
    left = TreeNode(12)
    right = TreeNode(18)
    root .children .append(left)
    root .children .append(right)
    left .children .append(TreeNode(11))
    left .children .append(TreeNode(3))
    right .children .append(TreeNode(15))
    right .children .append(TreeNode(8))
    MaxAverage(root)
    print(ans * 1.0)

# Expected output:
15.0