giulio98/xlcost-single-prompt huggingface dataset:
# minimize cost of placing tiles of dimensions 2 * 1 over a matrix | function to find the minimum cost in placing n tiles in a grid m [ ] [ ] ; stores the minimum profit after placing i tiles ; traverse the grid [ ] [ ] ; update the orig_cost ; traverse over the range [ 2 , n ] ; place tiles horizentally or vertically ; print the answer ; 
def tile_placing(grid, N):
    dp = [0] * (N + 5)
    orig_cost = 0
    for i in range(2):
        for j in range(N):
            orig_cost += grid[i][j]
    dp[0] = 0
    dp[1] = abs(grid[0][0] - grid[1][0])
    for i in range(2, N + 1):
        dp[i] = max(dp[i - 1] + abs(grid[0][i - 1] - grid[1][i - 1]), dp[i - 2] +
                    abs(grid[0][i - 2] - grid[0][i - 1]) + abs(grid[1][i - 2] - grid[1][i - 1]))
    print(orig_cost - dp[N], end="")


if __name__ == "__main__":
    M = [[7, 5, 1, 3], [8, 6, 0, 2]]
    N = len(M[0])
    tile_placing(M, N)

# Expected output:
20
# print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | function to check if array can be split into three equal sum subarrays by removing two elements ; stores sum of all three subarrays ; sum of left subarray ; sum of middle subarray ; sum of right subarray ; check if sum of subarrays are equal ; print the possible pair ; if no pair exists , print - 1 ; 
def findSplit(arr, N):
    for l in range(1, N - 3, 1):
        for r in range(l + 2, N - 1, 1):
            lsum = 0
            rsum = 0
            msum = 0
            for i in range(0, l, 1):
                lsum += arr[i]
            for i in range(l + 1, r, 1):
                msum += arr[i]
            for i in range(r + 1, N, 1):
                rsum += arr[i]
            if (lsum == rsum and rsum == msum):
                print(l, r)
                return
    print(-1)


if __name__ == '__main__':
    arr = [2, 5, 12, 7, 19, 4, 3]
    N = len(arr)
    findSplit(arr, N)

# Expected output:
2 4
# count the number of times a bulb switches its state | python program for the above approach ; function to find the number of times a bulb switches its state ; count of 1 's ; traverse the array ; update the array ; update the status of bulb ; traverse the array q [ ] ; stores previous state of the bulb ; toggle the switch and update the count of 1 's ; if the bulb switches state ; return count ; 

import math


def solve(A, n, Q, q):
    one = 0
    for i in range(0, n):
        if (A[i] == 1):
            one += 1
    glows = 0
    count = 0
    if (one >= int(math .ceil(n / 2))):
        glows = 1
    for i in range(0, q):
        prev = glows
        if (A[Q[i] - 1] == 1):
            one -= 1
        if (A[Q[i] - 1] == 0):
            one += 1
        A[Q[i] - 1] ^= 1
        if (one >= int(math .ceil(n / 2.0))):
            glows = 1
        else:
            glows = 0
        if (prev != glows):
            count += 1
    return count


n = 3
arr = [1, 1, 0]
q = 3
Q = [3, 2, 1]
print(solve(arr, n, Q, q))

# Expected output:
1
# count array elements having sum of digits equal to k | function to calculate the sum of digits of the number n ; stores the sum of digits ; return the sum ; function to count array elements ; store the count of array elements having sum of digits k ; traverse the array ; if sum of digits is equal to k ; increment the count ; prthe count ; given array ; 
def sumOfDigits(N):
    sum = 0
    while (N != 0):
        sum += N % 10
        N //= 10
    return sum


def elementsHavingDigitSumK(arr, N, K):
    count = 0
    for i in range(N):
        if (sumOfDigits(arr[i]) == K):
            count += 1
    print(count)


arr = [23, 54, 87, 29, 92, 62]
K = 11
N = len(arr)
elementsHavingDigitSumK(arr, N, K)

# Expected output:
2
# postfix to infix | python3 program to find infix for a given postfix . ; get infix for a given postfix expression ; push operands ; we assume that input is a valid postfix and expect an operator . ; there must be a single element in stack now which is the required infix . ; 
def isOperand(x):
    return ((x >= 'a' and x <= 'z') or (x >= 'A' and x <= 'Z'))


def getInfix(exp):
    s = []
    for i in exp:
        if (isOperand(i)):
            s .insert(0, i)
        else:
            op1 = s[0]
            s .pop(0)
            op2 = s[0]
            s .pop(0)
            s .insert(0, "(" + op2 + i + op1 + ")")
    return s[0]


if __name__ == '__main__':
    exp = "ab*c+"
    print(getInfix(exp .strip()))

# Expected output:
((a*b)+c)
# next greater element | function to print element and nge pair for all elements of list ; 
def printNGE(arr):
    for i in range(0, len(arr), 1):
        next = -1
        for j in range(i + 1, len(arr), 1):
            if arr[i] < arr[j]:
                next = arr[j]
                break
        print(str(arr[i]) + " -- " + str(next))


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

# Expected output:
11 -- 13
13 -- 21
21 -- -1
3 -- -1
# maximum product of indexes of next greater on left and right | method to find the next greater value in left side ; checking if current element is greater than top ; pop the element till we can 't  get the larger value then  the current value ; else push the element in the stack ; method to find the next greater value in right ; checking if current element is greater than top ; pop the element till we can 't  get the larger value then  the current value ; else push the element in the stack ; for each element storing the index of just greater element in left side ; for each element storing the index of just greater element in right side ; finding the max index product ; 
def nextGreaterInLeft(a):
    left_index = [0] * len(a)
    s = []
    for i in range(len(a)):
        while len(s) != 0 and a[i] >= a[s[-1]]:
            s .pop()
        if len(s) != 0:
            left_index[i] = s[-1]
        else:
            left_index[i] = 0
        s .append(i)
    return left_index


def nextGreaterInRight(a):
    right_index = [0] * len(a)
    s = []
    for i in range(len(a) - 1, -1, -1):
        while len(s) != 0 and a[i] >= a[s[-1]]:
            s .pop()
        if len(s) != 0:
            right_index[i] = s[-1]
        else:
            right_index[i] = 0
        s .append(i)
    return right_index


def LRProduct(arr):
    left = nextGreaterInLeft(arr)
    right = nextGreaterInRight(arr)
    ans = -1
    for i in range(1, len(left) - 1):
        if left[i] == 0 or right[i] == 0:
            ans = max(ans, 0)
        else:
            temp = (left[i] + 1) * (right[i] + 1)
            ans = max(ans, temp)
    return ans


arr = [5, 4, 3, 4, 5]
print(LRProduct(arr))

# Expected output:
8
# the celebrity problem | max ; person with 2 is celebrity ; returns - 1 if celebrity is not present . if present , returns id ( value from 0 to n - 1 ) ; the graph needs not be constructed as the edges can be found by using knows function degree array ; ; query for all edges ; set the degrees ; find a person with indegree n - 1 and out degree 0 ; 

N = 8
MATRIX = [[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 1, 0]]


def knows(a, b):
    return MATRIX[a][b]


def findCelebrity(n):
    indegree = [0 for x in range(n)]
    outdegree = [0 for x in range(n)]
    for i in range(n):
        for j in range(n):
            x = knows(i, j)
            outdegree[i] += x
            indegree[j] += x
    for i in range(n):
        if (indegree[i] == n - 1 and outdegree[i] == 0):
            return i
    return -1


if __name__ == '__main__':
    n = 4
    id_ = findCelebrity(n)
    if id_ == -1:
        print("No celebrity")
    else:
        print("Celebrity ID", id_)

# Expected output:
Celebrity ID 2
# the celebrity problem | max ; person with 2 is celebrity ; returns - 1 if a potential celebrity is not present . if present , returns id ( value from 0 to n - 1 ) . ; base case ; find the celebrity with n - 1 persons ; if there are no celebrities ; if the id knows the nth person then the id cannot be a celebrity , but nth person could be on ; if the id knows the nth person then the id cannot be a celebrity , but nth person could be one ; if there is no celebrity ; returns - 1 if celebrity is not present . if present , returns id ( value from 0 to n - 1 ) . a wrapper over findcelebrity ; find the celebrity ; check if the celebrity found is really the celebrity ; check the id is really the celebrity ; if the person is known to everyone . ; 

N = 8
MATRIX = [[0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 1, 0]]


def knows(a, b):
    return MATRIX[a][b]


def findPotentialCelebrity(n):
    if (n == 0):
        return 0
    id_ = findPotentialCelebrity(n - 1)
    if (id_ == -1):
        return n - 1
    elif knows(id_, n - 1):
        return n - 1
    elif knows(n - 1, id_):
        return id_
    return -1


def Celebrity(n):
    id_ = findPotentialCelebrity(n)
    if (id_ == -1):
        return id_
    else:
        c1 = 0
        c2 = 0
        for i in range(n):
            if (i != id_):
                c1 += knows(id_, i)
                c2 += knows(i, id_)
        if (c1 == 0 and c2 == n - 1):
            return id_
        return -1


if __name__ == '__main__':
    n = 4
    id_ = Celebrity(n)
    if id_ == -1:
        print("No celebrity")
    else:
        print("Celebrity ID", id_)

# Expected output:
Celebrity ID 2
# delete middle element of a stack | deletes middle of stack of size n . curr is current item number ; if stack is empty or all items are traversed ; remove current item ; remove other items ; put all items back except middle ; 

class Stack:
    def __init__(self):
        self .items = []

    def isEmpty(self):
        return self .items == []

    def push(self, item):
        self .items .append(item)

    def pop(self):
        return self .items .pop()

    def peek(self):
        return self .items[len(self .items) - 1]

    def size(self):
        return len(self .items)


def deleteMid(st, n, curr):
    if (st .isEmpty() or curr == n):
        return
    x = st .peek()
    st .pop()
    deleteMid(st, n, curr + 1)
    if (curr != int(n / 2)):
        st .push(x)


st = Stack()
st .push('1')
st .push('2')
st .push('3')
st .push('4')
st .push('5')
st .push('6')
st .push('7')
deleteMid(st, st .size(), 0)
while (st .isEmpty() == False):
    p = st .peek()
    st .pop()
    print(str(p) + " ", end="")

# Expected output:
7 6 5 3 2 1
# sorting array using stacks | this function return the sorted stack ; pop out the first element ; while temporary stack is not empty and top of stack is smaller than temp ; pop from temporary stack and append it to the input stack ; append temp in tempory of stack ; append array elements to stack ; sort the temporary stack ; put stack elements in arrp [ ] ; 
def sortStack(input):
    tmpStack = []
    while (len(input) > 0):
        tmp = input[-1]
        input .pop()
        while (len(tmpStack) > 0 and tmpStack[-1] < tmp):
            input .append(tmpStack[-1])
            tmpStack .pop()
        tmpStack .append(tmp)
    return tmpStack


def sortArrayUsingStacks(arr, n):
    input = []
    i = 0
    while (i < n):
        input .append(arr[i])
        i = i + 1
    tmpStack = sortStack(input)
    i = 0
    while (i < n):
        arr[i] = tmpStack[-1]
        tmpStack .pop()
        i = i + 1
    return arr


arr = [10, 5, 15, 45]
n = len(arr)
arr = sortArrayUsingStacks(arr, n)
i = 0
while (i < n):
    print(arr[i], end=" ")
    i = i + 1

# Expected output:
5 10 15 45
# reverse individual words | reverses individual words of a string ; traverse given string and push all characters to stack until we see a space . ; when we see a space , we print contents of stack . ; since there may not be space after last word . ; 
def reverserWords(string):
    st = list()
    for i in range(len(string)):
        if string[i] != " ":
            st .append(string[i])
        else:
            while len(st) > 0:
                print(st[-1], end="")
                st .pop()
            print(end=" ")
    while len(st) > 0:
        print(st[-1], end="")
        st .pop()


if __name__ == "__main__":
    string = "Geeks for Geeks"
    reverserWords(string)

# Expected output:
skeeG rof skeeG
# count subarrays where second highest lie before highest | python3 program to count number of distinct instance where second highest number lie before highest number in all subarrays . ; finding the next greater element of the array . ; finding the previous greater element of the array . ; wrapper function ; finding previous largest element ; finding next largest element ; 

from typing import List
MAXN = 100005


def makeNext(arr: List[int], n: int, nextBig: List[int]) -> None:
    s = []
    for i in range(n - 1, -1, -1):
        nextBig[i] = i
        while len(s) and s[-1][0] < arr[i]:
            s .pop()
        if len(s):
            nextBig[i] = s[-1][1]
        s .append((arr[i], i))


def makePrev(arr: List[int], n: int, prevBig: List[int]) -> None:
    s = []
    for i in range(n):
        prevBig[i] = -1
        while (len(s) and s[-1][0] < arr[i]):
            s .pop()
        if (len(s)):
            prevBig[i] = s[-1][1]
        s .append((arr[i], i))


def wrapper(arr: List[int], n: int) -> int:
    nextBig = [0] * MAXN
    prevBig = [0] * MAXN
    maxi = [0] * MAXN
    ans = 0
    makePrev(arr, n, prevBig)
    makeNext(arr, n, nextBig)
    for i in range(n):
        if (nextBig[i] != i):
            maxi[nextBig[i] - i] = max(maxi[nextBig[i] - i], i - prevBig[i])
    for i in range(n):
        ans += maxi[i]
    return ans


if __name__ == "__main__":
    arr = [1, 3, 2, 4]
    n = len(arr)
    print(wrapper(arr, n))

# Expected output:
3
# Program for Tower of Hanoi | Recursive Python function to solve tower of hanoi ; Number of disks ; A , C , B are the name of rods
def TowerOfHanoi(n, from_rod, to_rod, aux_rod):
    if n == 1:
        print("Move disk 1 from rod", from_rod, "to rod", to_rod)
        return
    TowerOfHanoi(n - 1, from_rod, aux_rod, to_rod)
    print("Move disk", n, "from rod", from_rod, "to rod", to_rod)
    TowerOfHanoi(n - 1, aux_rod, to_rod, from_rod)


n = 4
TowerOfHanoi(n, 'A', 'C', 'B')

# Expected output:
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
# find maximum of minimum for every window size in a given array | a naive method to find maximum of minimum of all windows of different sizes ; consider all windows of different sizes starting from size 1 ; initialize max of min for current window size k ; traverse through all windows of current size k ; find minimum of current window ; update maxofmin if required ; print max of min for current window size ; 

INT_MIN = -1000000


def printMaxOfMin(arr, n):
    for k in range(1, n + 1):
        maxOfMin = INT_MIN
        for i in range(n - k + 1):
            min = arr[i]
            for j in range(k):
                if (arr[i + j] < min):
                    min = arr[i + j]
            if (min > maxOfMin):
                maxOfMin = min
        print(maxOfMin, end=" ")


arr = [10, 20, 30, 50, 10, 70, 30]
n = len(arr)
printMaxOfMin(arr, n)

# Expected output:
70 30 20 10 10 10 10
# find maximum of minimum for every window size in a given array | an efficient python3 program to find maximum of all minimums of windows of different sizes ; used to find previous and next smaller ; initialize elements of left [ ] and right [ ] ; fill elements of left [ ] using logic discussed on www . geeksforgeeks . org / next - greater - element https : ; empty the stack as stack is going to be used for right [ ] ; fill elements of right [ ] using same logic ; create and initialize answer array ; fill answer array by comparing minimums of all . lengths computed using left [ ] and right [ ] ; length of the interval ; arr [ i ] is a possible answer for this length ' len ' interval , check if arr [ i ] is more than max for 'len   ; some entries in ans [ ] may not be filled yet . fill them by taking values from right side of ans [ ] ; print the result ; 
def printMaxOfMin(arr, n):
    s = []
    left = [-1] * (n + 1)
    right = [n] * (n + 1)
    for i in range(n):
        while (len(s) != 0 and arr[s[-1]] >= arr[i]):
            s .pop()
        if (len(s) != 0):
            left[i] = s[-1]
        s .append(i)
    while (len(s) != 0):
        s .pop()
    for i in range(n - 1, -1, -1):
        while (len(s) != 0 and arr[s[-1]] >= arr[i]):
            s .pop()
        if (len(s) != 0):
            right[i] = s[-1]
        s .append(i)
    ans = [0] * (n + 1)
    for i in range(n + 1):
        ans[i] = 0
    for i in range(n):
        Len = right[i] - left[i] - 1
        ans[Len] = max(ans[Len], arr[i])
    for i in range(n - 1, 0, -1):
        ans[i] = max(ans[i], ans[i + 1])
    for i in range(1, n + 1):
        print(ans[i], end=" ")


if __name__ == '__main__':
    arr = [10, 20, 30, 50, 10, 70, 30]
    n = len(arr)
    printMaxOfMin(arr, n)

# Expected output:
70 30 20 10 10 10 10
# length of the longest valid substring | method to get length of the longest valid ; create a stack and push - 1 as initial index to it . ; initialize result ; traverse all characters of given string ; if opening bracket , push index of it ; if closing bracket ; pop the previous opening bracket 's index ; check if this length formed with base of current valid substring is more than max so far ; if stack is empty . push current index as base for next valid substring ( if any ) ; 
def findMaxLen(string):
    n = len(string)
    stk = []
    stk .append(-1)
    result = 0
    for i in range(n):
        if string[i] == '(':
            stk .append(i)
        else:
            if len(stk) != 0:
                stk .pop()
            if len(stk) != 0:
                result = max(result, i - stk[len(stk) - 1])
            else:
                stk .append(i)
    return result


string = "((()()"
print(findMaxLen(string))
string = "()(()))))"
print(findMaxLen(string))

# Expected output:
4
6
# convert a tree to forest of even nodes | return the number of nodes of subtree having node as a root . ; mark node as visited . ; traverse the adjacency list to find non - visited node . ; finding number of nodes of the subtree of a subtree . ; if nodes are even , increment number of edges to removed . else leave the node as child of subtree . ; return the maximum number of edge to remove to make forest . ; 
def dfs(tree, visit, ans, node):
    num = 0
    temp = 0
    visit[node] = 1
    for i in range(len(tree[node])):
        if (visit[tree[node][i]] == 0):
            temp = dfs(tree, visit, ans, tree[node][i])
            if (temp % 2):
                num += temp
            else:
                ans[0] += 1
    return num + 1


def minEdge(tree, n):
    visit = [0] * (n + 2)
    ans = [0]
    dfs(tree, visit, ans, 1)
    return ans[0]


N = 12
n = 10
tree = [[]for i in range(n + 2)]
tree[1].append(3)
tree[3].append(1)
tree[1].append(6)
tree[6].append(1)
tree[1].append(2)
tree[2].append(1)
tree[3].append(4)
tree[4].append(3)
tree[6].append(8)
tree[8].append(6)
tree[2].append(7)
tree[7].append(2)
tree[2].append(5)
tree[5].append(2)
tree[4].append(9)
tree[9].append(4)
tree[4].append(10)
tree[10].append(4)
print(minEdge(tree, n))

# Expected output:
2
# length of the longest valid substring | python3 program to find length of the longest valid substring ; initialize curmax to zero ; iterate over the string starting from second index ; 
def findMaxLen(s):
    if (len(s) <= 1):
        return 0
    curMax = 0
    longest = [0] * (len(s))
    for i in range(1, len(s)):
        if ((s[i] == ')' and i - longest[i - 1] - 1 >=
                0 and s[i - longest[i - 1] - 1] == '(')):
            longest[i] = longest[i - 1] + 2
            if (i - longest[i - 1] - 2 >= 0):
                longest[i] += (longest[i - longest[i - 1] - 2])
            else:
                longest[i] += 0
            curMax = max(longest[i], curMax)
    return curMax


if __name__ == '__main__':
    Str = "((()()"
    print(findMaxLen(Str))
    Str = "()(()))))"
    print(findMaxLen(Str))

# Expected output:
4
6
# length of the longest valid substring | function to return the length of the longest valid substring ; variables for left and right counter . maxlength to store the maximum length found so far ; iterating the string from left to right ; if " ( " is encountered , then left counter is incremented else right counter is incremented ; whenever left is equal to right , it signifies that the subsequence is valid and ; reseting the counters when the subsequence becomes invalid ; iterating the string from right to left ; if " ( " is encountered , then left counter is incremented else right counter is incremented ; whenever left is equal to right , it signifies that the subsequence is valid and ; reseting the counters when the subsequence becomes invalid ; 
def solve(s, n):
    left = 0
    right = 0
    maxlength = 0
    for i in range(n):
        if (s[i] == '('):
            left += 1
        else:
            right += 1
        if (left == right):
            maxlength = max(maxlength, 2 * right)
        elif (right > left):
            left = right = 0
    left = right = 0
    for i in range(n - 1, -1, -1):
        if (s[i] == '('):
            left += 1
        else:
            right += 1
        if (left == right):
            maxlength = max(maxlength, 2 * left)
        elif (left > right):
            left = right = 0
    return maxlength


print(solve("((()()()()(((())", 16))

# Expected output:
8
# expression contains redundant bracket or not | function to check redundant brackets in a balanced expression ; create a stack of characters ; iterate through the given expression ; if current character is close parenthesis ')   ; if immediate pop have open parenthesis ' ( ' duplicate brackets found ; check for operators in expression ; fetch top element of stack ; if operators not found ; append open parenthesis ' ( ' , ; operators and operands to stack ; function to check redundant brackets ; 
def checkRedundancy(Str):
    st = []
    for ch in Str:
        if (ch == ')'):
            top = st[-1]
            st .pop()
            flag = True
            while (top != '('):
                if (top == '+' or top == '-' or top == '*' or top == '/'):
                    flag = False
                top = st[-1]
                st .pop()
            if (flag):
                return True
        else:
            st .append(ch)
    return False


def findRedundant(Str):
    ans = checkRedundancy(Str)
    if (ans):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    Str = "((a+b))"
    findRedundant(Str)
    Str = "(a+(b)/c)"
    findRedundant(Str)
    Str = "(a+b*(c-d))"
    findRedundant(Str)

# Expected output:
Yes
Yes
No