giulio98/xlcost-single-prompt huggingface dataset:
# check if given sudoku solution is valid or not | function to check if all elements of the board [ ] [ ] array store value in the range [ 1 , 9 ] ; traverse board [ ] [ ] array ; check if board [ i ] [ j ] lies in the range ; function to check if the solution of sudoku puzzle is valid or not ; check if all elements of board [ ] [ ] stores value in the range [ 1 , 9 ] ; stores unique value from 1 to n ; traverse each row of the given array ; initialize unique [ ] array to false ; traverse each column of current row ; stores the value of board [ i ] [ j ] ; check if current row stores duplicate value ; traverse each column of the given array ; initialize unique [ ] array to false ; traverse each row of current column ; stores the value of board [ j ] [ i ] ; check if current column stores duplicate value ; traverse each block of size 3 * 3 in board [ ] [ ] array ; j stores first column of each 3 * 3 block ; initialize unique [ ] array to false ; traverse current block ; stores row number of current block ; stores column number of current block ; stores the value of board [ x ] [ y ] ; check if current block stores duplicate value ; if all conditions satisfied ; 
def isinRange(board):

    N = 9
    for i in range(0, N):
        for j in range(0, N):
            if ((board[i][j] <= 0) or
                    (board[i][j] > 9)):
                return False

    return True


def isValidSudoku(board):

    N = 9
    if (isinRange(board) == False):
        return False
    unique = [False] * (N + 1)
    for i in range(0, N):
        for m in range(0, N + 1):
            unique[m] = False
        for j in range(0, N):
            Z = board[i][j]
            if (unique[Z] == True):
                return False

            unique[Z] = True
    for i in range(0, N):
        for m in range(0, N + 1):
            unique[m] = False
        for j in range(0, N):
            Z = board[j][i]
            if (unique[Z] == True):
                return False

            unique[Z] = True
    for i in range(0, N - 2, 3):
        for j in range(0, N - 2, 3):
            for m in range(0, N + 1):
                unique[m] = False
            for k in range(0, 3):
                for l in range(0, 3):
                    X = i + k
                    Y = j + l
                    Z = board[X][Y]
                    if (unique[Z] == True):
                        return False

                    unique[Z] = True
    return True


if __name__ == '__main__':

    board = [[7, 9, 2, 1, 5, 4, 3, 8, 6],
             [6, 4, 3, 8, 2, 7, 1, 5, 9],
             [8, 5, 1, 3, 9, 6, 7, 2, 4],
             [2, 6, 5, 9, 7, 3, 8, 4, 1],
             [4, 8, 9, 5, 6, 1, 2, 7, 3],
             [3, 1, 7, 4, 8, 2, 9, 6, 5],
             [1, 3, 6, 7, 4, 8, 5, 9, 2],
             [9, 7, 4, 2, 1, 5, 6, 3, 8],
             [5, 2, 8, 6, 3, 9, 4, 1, 7]]

    if (isValidSudoku(board)):
        print("Valid")
    else:
        print("Not Valid")

# Expected output:
Valid
# subarray of length k whose concatenation forms a palindrome | function to check if a number is palindrome or not here i is the starting index and j is the last index of the subarray ; if the integer at i is not equal to j then the subarray is not palindrome ; otherwise ; all a [ i ] is equal to a [ j ] then the subarray is palindrome ; function to find a subarray whose concatenation forms a palindrome and return its starting index ; iterating over subarray of length k and checking if that subarray is palindrome ; if no subarray is palindrome ; 
def palindrome(a, i, j):
    while (i < j):
        if (a[i] != a[j]):
            return False
        i += 1
        j -= 1
    return True


def findSubArray(arr, k):
    n = len(arr)
    for i in range(n - k + 1):
        if (palindrome(arr, i, i + k - 1)):
            return i
    return -1


arr = [2, 3, 5, 1, 3]
k = 4
ans = findSubArray(arr, k)
if (ans == -1):
    print(-1)
else:
    for i in range(ans, ans + k):
        print(arr[i], end=" ")

# Expected output:
-1
# check if a sequence of path visits any coordinate twice or not | function to check if the man crosses previous visited coordinate or not ; stores the count of crossed vertex ; stores ( x , y ) coordinates ; the coordinates for the origin ; iterate over the string ; condition to increment x or y co - ordinates respectively ; check if ( x , y ) is already visited ; print the result ; 
def isCrossed(path):
    if (len(path) == 0):
        return bool(False)
    ans = bool(False)
    Set = set()
    x, y = 0, 0
    Set .add((x, y))
    for i in range(len(path)):
        if (path[i] == 'N'):
            Set .add((x, y))
            y = y + 1
        if (path[i] == 'S'):
            Set .add((x, y))
            y = y - 1
        if (path[i] == 'E'):
            Set .add((x, y))
            x = x + 1
        if (path[i] == 'W'):
            Set .add((x, y))
            x = x - 1
        if (x, y) in Set:
            ans = bool(True)
            break
    if (ans):
        print("Crossed")
    else:
        print("Not Crossed")


path = "NESW"
isCrossed(path)

# Expected output:
Crossed
# maximum width of an n | python3 program to implement the above approach ; function to find the maximum width of . he tree using level order traversal ; store the edges of the tree ; stores maximum width of the tree ; stores the nodes of each level ; insert root node ; perform level order traversal on the tree ; stores the size of the queue ; update maximum width ; push the nodes of the next level and pop the elements of the current level ; get element from the front the queue ; push all nodes of the next level . ; return the result . ; 

from collections import deque


def maxWidth(N, M, cost, s):
    adj = [[]for i in range(N)]
    for i in range(M):
        adj[s[i][0]].append(s[i][1])
    result = 0
    q = deque()
    q .append(0)
    while (len(q) > 0):
        count = len(q)
        result = max(count, result)
        while (count > 0):
            temp = q .popleft()
            for i in adj[temp]:
                q .append(i)
            count -= 1
    return result


if __name__ == '__main__':
    N = 11
    M = 10
    edges = []
    edges .append([0, 1])
    edges .append([0, 2])
    edges .append([0, 3])
    edges .append([1, 4])
    edges .append([1, 5])
    edges .append([3, 6])
    edges .append([4, 7])
    edges .append([6, 1])
    edges .append([6, 8])
    edges .append([6, 9])
    cost = [1, 2, -1, 3, 4, 5, 8, 2, 6, 12, 7]
    print(maxWidth(N, M, cost, edges))

# Expected output:
4
# minimize sum of prime numbers added to make an array non | pthon3 program to implement the above approach ; stores if an index is a prime / non - prime value ; stores the prime ; function to generate all prime numbers ; if current element is prime ; set all its multiples non - prime ; store all prime numbers ; function to find the closest prime to a particular number ; applying binary search on primes vector ; if the prime added makes the elements equal ; return this as the closest prime ; if the array remains non - decreasing ; search for a bigger prime number ; otherwise ; check if a smaller prime can make array non - decreasing or not ; return closest number ; function to find the minimum cost ; find all primes ; store the result ; iterate over the array ; current element is less than the previous element ; find the closest prime which makes the array non decreasing ; add to overall cost ; update current element ; return the minimum cost ; 

MAX = 10000000
isPrime = [True] * (MAX + 1)
primes = []


def SieveOfEratosthenes():
    global isPrime
    p = 2
    while p * p <= MAX:
        if (isPrime[p]):
            for i in range(p * p, MAX + 1, p):
                isPrime[i] = False
        p += 1
    for p in range(2, MAX + 1):
        if (isPrime[p]):
            primes .append(p)


def prime_search(primes, diff):
    low = 0
    high = len(primes) - 1
    while (low <= high):
        mid = (low + high) // 2
        if (primes[mid] == diff):
            return primes[mid]
        elif (primes[mid] < diff):
            low = mid + 1
        else:
            res = primes[mid]
            high = mid - 1
    return res


def minCost(arr, n):
    SieveOfEratosthenes()
    res = 0
    for i in range(1, n):
        if (arr[i] < arr[i - 1]):
            diff = arr[i - 1] - arr[i]
            closest_prime = prime_search(primes, diff)
            res += closest_prime
            arr[i] += closest_prime
    return res


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

# Expected output:
7
# count ways to split a binary string into three substrings having equal count of zeros | function to return ways to split a string into three parts with the equal number of 0 ; store total count of 0 s ; count total no . of 0 s character in given string ; if total count of 0 character is not divisible by 3 ; initialize map to store frequency of k ; traverse string to find ways to split string ; increment count if 0 appears ; increment result if sum equal to 2 * k and k exists in map ; insert sum in map ; return result ; 
def count(s):
    cnt = 0
    for c in s:
        if c == '0':
            cnt += 1
    if (cnt % 3 != 0):
        return 0
    res = 0
    k = cnt // 3
    sum = 0
    mp = {}
    for i in range(len(s)):
        if s[i] == '0':
            sum += 1
        if (sum == 2 * k and k in mp and i < len(s) - 1 and i > 0):
            res += mp[k]
        if sum in mp:
            mp[sum] += 1
        else:
            mp[sum] = 1
    return res


if __name__ == "__main__":
    st = "01010"
    print(count(st))

# Expected output:
4
# check if a string can be converted to another by swapping of adjacent characters of given type | function to check if it is possible to transform start to end ; check the sequence of a , b in both strings str1 and str2 ; if both the strings are not equal ; traverse the strings ; check for indexes of a and b ; 
def canTransform(str1, str2):
    s1 = ""
    s2 = ""
    for c in str1:
        if (c != 'C'):
            s1 += c
    for c in str2:
        if (c != 'C'):
            s2 += c
    if (s1 != s2):
        return False
    i = 0
    j = 0
    n = len(str1)
    while (i < n and j < n):
        if (str1[i] == 'C'):
            i += 1
        elif (str2[j] == 'C'):
            j += 1
        else:
            if ((str1[i] == 'A' and i < j) or (str1[i] == 'B' and i > j)):
                return False
            i += 1
            j += 1
    return True


if __name__ == '__main__':
    str1 = "BCCABCBCA"
    str2 = "CBACCBBAC"
    if (canTransform(str1, str2)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# longest substring having equal count of vowels and consonants | function to return the length of the longest substring having equal number of vowel and consonant ; generate the array ; initialize variable to store result ; stores the sum of subarray ; map to store indices of the sum ; loop through the array ; if sum is 0 ; count of vowels and consonants are equal ; update the maximum length of substring in hashmap ; store the index of the sum ; return the maximum length of required substring ; 
def maxsubstringLength(S, N):

    arr = [0] * N
    for i in range(N):
        if (S[i] == 'a' or S[i] == 'e' or
           S[i] == 'i' or S[i] == 'o' or
           S[i] == 'u'):
            arr[i] = 1
        else:
            arr[i] = -1
    maxLen = 0
    curr_sum = 0
    hash = {}
    for i in range(N):
        curr_sum += arr[i]
        if (curr_sum == 0):
            maxLen = max(maxLen, i + 1)
        if (curr_sum in hash.keys()):
            maxLen = max(maxLen, i - hash[curr_sum])
        else:
            hash[curr_sum] = i
    return maxLen


S = "geeksforgeeks"
n = len(S)
print(maxsubstringLength(S, n))

# Expected output:
10
# minimum distance from a given cell to all other cells of a matrix | python3 program to implement the above approach ; stores the accessible directions ; function to find the minimum distance from a given cell to all other cells in the matrix ; stores the accessible cells from current cell ; insert pair ( x , y ) ; iterate untill queue is empty ; extract the pair ; pop them ; checking boundary condition ; if the cell is not visited ; assign the minimum distance ; insert the traversed neighbour into the queue ; 

mat = [[0 for x in range(1001)]for y in range(1001)]
dx = [0, -1, -1, -1, 0, 1, 1, 1]
dy = [1, 1, 0, -1, -1, -1, 0, 1]


def FindMinimumDistance():
    global x, y, r, c
    q = []
    q .append([x, y])
    mat[x][y] = 0
    while (len(q) != 0):
        x = q[0][0]
        y = q[0][1]
        q .pop(0)
        for i in range(8):
            a = x + dx[i]
            b = y + dy[i]
            if (a < 0 or a >= r or b >= c or b < 0):
                continue
            if (mat[a][b] == 0):
                mat[a][b] = mat[x][y] + 1
                q .append([a, b])


r = 5
c = 5
x = 1
y = 1
t = x
l = y
mat[x][y] = 0
FindMinimumDistance()
mat[t][l] = 0
for i in range(r):
    for j in range(c):
        print(mat[i][j], end=" ")
    print()

# Expected output:
1 1 1 2 3 
1 0 1 2 3 
1 1 1 2 3 
2 2 2 2 3 
3 3 3 3 3
# minimum flips required to convert given string into concatenation of equal substrings of length k | function that returns the minimum number of flips to convert the s into a concatenation of k - length sub - string ; stores the result ; iterate through string index ; stores count of 0 s & 1 s ; iterate making k jumps ; count 0 's ; count 1 's ; add minimum flips for index i ; return minimum number of flips ; 
def minOperations(S, K):
    ans = 0
    for i in range(K):
        zero, one = 0, 0
        for j in range(i, len(S), K):
            if (S[j] == '0'):
                zero += 1
            else:
                one += 1
        ans += min(zero, one)
    return ans


if __name__ == '__main__':
    s = "110100101"
    K = 3
    print(minOperations(s, K))

# Expected output:
2
# find the missing number in unordered arithmetic progression | function to get the missing element ; for maximum element in the array ; for minimum element in the array ; for xor of all elements ; common difference of ap series ; find maximum and minimum element ; calculating common difference ; calculate the xor of all elements ; perform xor with actual ap series resultant x will be the ans ; return the missing element ; 
def missingElement(arr, n):
    max_ele = arr[0]
    min_ele = arr[0]
    x = 0
    d = 0
    for i in range(n):
        if (arr[i] > max_ele):
            max_ele = arr[i]
        if (arr[i] < min_ele):
            min_ele = arr[i]
    d = (max_ele - min_ele) // n
    for i in range(n):
        x = x ^ arr[i]
    for i in range(n + 1):
        x = x ^ (min_ele + (i * d))
    return x


if __name__ == '__main__':
    arr = [12, 3, 6, 15, 18]
    n = len(arr)
    element = missingElement(arr, n)
    print(element)

# Expected output:
9
# given a string and an integer k , find the kth sub | function to prints kth sub - string ; total sub - strings possible ; if k is greater than total number of sub - strings ; to store number of sub - strings starting with ith character of the string ; compute the values ; substring [ i - 1 ] is added to store the cumulative sum ; binary search to find the starting index of the kth sub - string ; to store the ending index of the kth sub - string ; print the sub - string ; 
def Printksubstring(str1, n, k):
    total = int((n * (n + 1)) / 2)
    if (k > total):
        print("-1")
        return
    substring = [0 for i in range(n + 1)]
    substring[0] = 0
    temp = n
    for i in range(1, n + 1, 1):
        substring[i] = substring[i - 1] + temp
        temp -= 1
    l = 1
    h = n
    start = 0
    while (l <= h):
        m = int((l + h) / 2)
        if (substring[m] > k):
            start = m
            h = m - 1
        elif (substring[m] < k):
            l = m + 1
        else:
            start = m
            break
    end = n - (substring[start] - k)
    for i in range(start - 1, end):
        print(str1[i], end="")


if __name__ == '__main__':
    str1 = "abc"
    k = 4
    n = len(str1)
    Printksubstring(str1, n, k)

# Expected output:
b
# lower insertion point | function to return the lower insertion point of an element in a sorted array ; base cases ; final check for the remaining elements which are < x ; 
def LowerInsertionPoint(arr, n, X):
    if (X < arr[0]):
        return 0
    elif (X > arr[n - 1]):
        return n
    lowerPnt = 0
    i = 1
    while (i < n and arr[i] < X):
        lowerPnt = i
        i = i * 2
    while (lowerPnt < n and arr[lowerPnt] < X):
        lowerPnt += 1
    return lowerPnt


if __name__ == "__main__":
    arr = [2, 3, 4, 4, 5, 6, 7, 9]
    n = len(arr)
    X = 4
    print(LowerInsertionPoint(arr, n, X))

# Expected output:
2
# number of positions with same address in row major and column major order | returns count of required positions ; horizontal 1d array ; vertical 1d array ; iterating for all possible i ; checking if j is integer ; checking if j lies b / w 1 to n ; iterating for all possible j ; checking if i is integer ; checking if i lies b / w 1 to m ; 
def getCount(M, N):
    count = 0
    if (M == 1):
        return N
    if (N == 1):
        return M
    if (N > M):
        for i in range(1, M + 1):
            numerator = N * i - N + M - i
            denominator = M - 1
            if (numerator % denominator == 0):
                j = numerator / denominator
                if (j >= 1 and j <= N):
                    count += 1
    else:
        for j in range(1, N + 1):
            numerator = M * j - M + N - j
            denominator = N - 1
            if (numerator % denominator == 0):
                i = numerator / denominator
                if (i >= 1 and i <= M):
                    count += 1
    return count


if __name__ == '__main__':
    M, N = 3, 5
    print(getCount(M, N))

# Expected output:
3
# maximum in an array that can make another array sorted | python3 program to make array sorted ; function to check whether there is any swappable element present to make the first array sorted ; wrongidx is the index of the element which is making the first array unsorted ; find the maximum element which satisfies the above mentioned neighboring conditions ; if res is true then swap the element and make the first array sorted ; function to print the sorted array if elements are swapped . ; 

import sys


def swapElement(arr1, arr2, n):
    wrongIdx = 0
    for i in range(1, n):
        if (arr1[i] < arr1[i - 1]):
            wrongIdx = i
    maximum = -(sys .maxsize - 1)
    maxIdx = -1
    res = False
    for i in range(n):
        if (arr2[i] > maximum and arr2[i] >= arr1[wrongIdx - 1]):
            if (wrongIdx + 1 <= n - 1 and arr2[i] <= arr1[wrongIdx + 1]):
                maximum = arr2[i]
                maxIdx = i
                res = True
    if (res):
        (arr1[wrongIdx], arr2[maxIdx]) = (arr2[maxIdx], arr1[wrongIdx])
    return res


def getSortedArray(arr1, arr2, n):
    if (swapElement(arr1, arr2, n)):
        for i in range(n):
            print(arr1[i], end=" ")
    else:
        print("Not Possible")


if __name__ == "__main__":
    arr1 = [1, 3, 7, 4, 10]
    arr2 = [2, 1, 6, 8, 9]
    n = len(arr1)
    getSortedArray(arr1, arr2, n)

# Expected output:
1 3 7 9 10
# middle of three using minimum comparisons | function to find the middle of three numbers ; compare each three number to find middle number . enter only if a > b ; decided a is not greater than b . ; 
def middleOfThree(a, b, c):
    if a > b:
        if (b > c):
            return b
        elif (a > c):
            return c
        else:
            return a
    else:
        if (a > c):
            return a
        elif (b > c):
            return c
        else:
            return b


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

# Expected output:
30
# sort the matrix column | function to find the transpose of the matrix mat [ ] ; stores the transpose of matrix mat [ ] [ ] ; traverse each row of the matrix ; traverse each column of the matrix ; transpose matrix elements ; function to sort the given matrix in row wise manner ; traverse the row ; row - wise sorting ; function to print the matrix in column wise sorted manner ; function call to find transpose of the the matrix mat [ ] [ ] ; sorting the matrix row - wise ; calculate transpose of b [ ] [ ] ; print the matrix mat [ ] [ ] ; 
def transpose(mat, row, col):
    tr = [[0 for i in range(row)]for i in range(col)]
    for i in range(row):
        for j in range(col):
            tr[j][i] = mat[i][j]
    return tr


def RowWiseSort(B):
    for i in range(len(B)):
        B[i] = sorted(B[i])
    return B


def sortCol(mat, N, M):
    B = transpose(mat, N, M)
    B = RowWiseSort(B)
    mat = transpose(B, M, N)
    for i in range(N):
        for j in range(M):
            print(mat[i][j], end=" ")
        print()


if __name__ == '__main__':
    mat = [[1, 6, 10], [8, 5, 9], [9, 4, 15], [7, 3, 60]]
    N = len(mat)
    M = len(mat[0])
    sortCol(mat, N, M)

# Expected output:
1 3 9 
7 4 10 
8 5 15 
9 6 60
# largest area possible after removal of a series of horizontal & vertical bars | function to find the largest area when a series of horizontal & vertical bars are removed ; stores all bars ; insert horizontal bars ; insert vertictal bars ; remove horizontal separators from s1 ; remove vertical separators from s2 ; stores left out horizontal and vertical separators ; sort both list in ascending order ; find maximum difference of neighbors of list1 ; find max difference of neighbors of list2 ; print largest volume ; 
def largestArea(N, M, H, V, h, v):
    s1 = set([])
    s2 = set([])
    for i in range(1, N + 2):
        s1 .add(i)
    for i in range(1, M + 2):
        s2 .add(i)
    for i in range(h):
        s1 .remove(H[i])
    for i in range(v):
        s2 .remove(V[i])
    list1 = [0] * len(s1)
    list2 = [0] * len(s2)
    i = 0
    for it1 in s1:
        list1[i] = it1
        i += 1
    i = 0
    for it2 in s2:
        list2[i] = it2
        i += 1
    list1 .sort()
    list2 .sort()
    maxH = 0
    p1 = 0
    maxV = 0
    p2 = 0
    for j in range(len(s1)):
        maxH = max(maxH, list1[j] - p1)
        p1 = list1[j]
    for j in range(len(s2)):
        maxV = max(maxV, list2[j] - p2)
        p2 = list2[j]
    print((maxV * maxH))


if __name__ == "__main__":
    N = 3
    M = 3
    H = [2]
    V = [2]
    h = len(H)
    v = len(V)
    largestArea(N, M, H, V, h, v)

# Expected output:
4
# check if an array can be sorted by swapping pairs from indices consisting of unequal elements in another array | function to check if array , a [ ] can be converted into sorted array by swapping ( a [ i ] , a [ j ] ) if b [ i ] not equal to b [ j ] ; stores if array a [ ] is sorted in descending order or not ; traverse the array a [ ] ; if a [ i ] is greater than a [ i + 1 ] ; update flag ; if array is sorted in ascending order ; count = 2 : check if 0 s and 1 s both present in the b [ ] ; traverse the array ; if current element is 0 ; update count ; traverse the array b [ ] ; if current element is 1 ; if both 0 s and 1 s are present in the array ; input array a [ ] ; 
def checkifSorted(A, B, N):
    flag = False
    for i in range(N - 1):
        if (A[i] > A[i + 1]):
            flag = True
            break
    if (not flag):
        return True
    count = 0
    for i in range(N):
        if (B[i] == 0):
            count += 1
            break
    for i in range(N):
        if B[i]:
            count += 1
            break
    if (count == 2):
        return True

    return False


A = [3, 1, 2]
B = [0, 1, 1]
N = len(A)
check = checkifSorted(A, B, N)
if (check):
    print("YES")
else:
    print("NO")

# Expected output:
YES