giulio98/xlcost-single-prompt huggingface dataset:
# minimum moves required to come out of a grid safely | ''stores size of the grid ; ''function to check valid cells of the grid ; ''checks for the border sides ; ''function to find shortest distance between two cells of the grid ; '' rows of the grid ; '' column of the grid ; '' stores possible move  of the person ; '' store possible cells visited  by the person ; '' store possible cells which  are burning ; '' traverse the grid ; '' if current cell is  burning ; '' if person is in  the current cell ; '' stores shortest distance  between two cells ; '' check if a cell is visited  by the person or not ; '' while pq is not empty ; '' update depth ; '' popped all the cells from  pq and mark all adjacent cells  of as visited ; '' front element of  the queue pq ; '' remove front element of  the queue pq ; '' if current cell is burning ; '' find all adjacent cells ; '' stores row number of  adjacent cell ; '' stores column number  of adjacent cell ; '' checks if current cell  is valid ; '' mark the cell as visited ; '' enqueue the cell ; '' checks the escape condition ; '' burn all the adjacent cells  of burning cells ; '' front element of  the queue fq ; '' delete front element of  the queue fq ; '' find adjacent cells of  burning cell ; '' stores row number of  adjacent cell ; '' stores column number  of adjacent cell ; '' checks if current  cell is valid ; '' burn all the adjacent  cells of current cell ; ''

m = 0
n = 0


def valid(x, y):
    global n
    global m
    return (x >= 0 and x < m and y >= 0 and y < n)


def border(x, y):
    global n
    global m
    return (x == 0 or x == m - 1 or y == 0 or y == n - 1)


def minStep(mat):
    global n
    global m
    m = len(mat)
    n = len(mat[0])
    dx = [1, -1, 0, 0]
    dy = [0, 0, 1, -1]
    pQ = []
    fQ = []
    for i in range(m):
        for j in range(n):
            if (mat[i][j] == 2):
                fQ .append([i, j])
            elif (mat[i][j] == 1):
                if (border(i, j)):
                    return 0
                pQ .append([i, j])
    depth = 0
    visited = [[0 for i in range(m)]for j in range(n)]
    while (len(pQ) > 0):
        depth += 1
        i = len(pQ)
        while (i > 0):
            pos = pQ[0]
            pQ .remove(pQ[0])
            if (mat[pos[0]][pos[1]] == 2):
                continue
            for j in range(4):
                x = pos[0] + dx[j]
                y = pos[1] + dy[j]
                if (valid(x, y) and mat[x][y] != 2 and visited[x][y] == 0):
                    visited[x][y] = 1
                    pQ .append([x, y])
                    if (border(x, y)):
                        return depth
            i -= 1
        i = len(fQ)
        while (i > 0):
            pos = fQ[0]
            fQ .remove(fQ[0])
            for j in range(4):
                x = pos[0] + dx[j]
                y = pos[1] + dy[j]
                if (valid(x, y) and mat[x][y] != 2):
                    mat[x][y] = 2
                    fQ .append([x, y])
            i -= 1
    return -1


if __name__ == '__main__':
    grid = [[0, 0, 0, 0], [2, 0, 0, 0], [2, 1, 0, 0], [2, 2, 0, 0]]
    print(minStep(grid))

# Expected output:
2
# find sum of non | find the sum of all non - repeated elements in an array ; sort all elements of array ; 
def findSum(arr, n):
    arr .sort()
    sum = arr[0]
    for i in range(0, n - 1):
        if (arr[i] != arr[i + 1]):
            sum = sum + arr[i + 1]
    return sum


def main():
    arr = [1, 2, 3, 1, 1, 4, 5, 6]
    n = len(arr)
    print(findSum(arr, n))


if __name__ == '__main__':
    main()

# Expected output:
21
# length of the longest subsequence such that xor of adjacent elements is equal to k | ''function to find maximum length of subsequence having xor of adjacent elements equal to k ; '' store maximum length of subsequence ; '' stores the dp-states ; '' base case ; '' iterate over the range [1, n-1] ; '' iterate over the range [0, i - 1] ; '' if arr[i]^arr[j] == k ; '' update the dp[i] ; '' update the maximum subsequence length ; '' if length of longest subsequence  is less than 2 then return 0 ; ''
def xorSubsequence(a, n, k):
    ans = 0
    dp = [0] * n
    dp[0] = 1
    for i in range(1, n):
        for j in range(i - 1, -1, -1):
            if ((a[i] ^ a[j]) == k):
                dp[i] = max(dp[i], dp[j] + 1)
        ans = max(ans, dp[i])
        dp[i] = max(1, dp[i])
    return ans if ans >= 2 else 0


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

# Expected output:
3
# check if a binary tree contains duplicate subtrees of size 2 or more | python3 program to find if there is a duplicate sub - tree of size 2 or more separator node ; structure for a binary tree node ; this function returns empty if tree contains a duplicate subtree of size 2 or more . ; if current node is none , return marker ; if left subtree has a duplicate subtree . ; do same for right subtree ; serialize current subtree ; if current subtree already exists in hash table . [ note that size of a serialized tree with single node is 3 as it has two marker nodes . ; 

MARKER = '$'


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


subtrees = {}


def dupSubUtil(root):
    global subtrees
    s = ""
    if (root is None):
        return s + MARKER
    lStr = dupSubUtil(root .left)
    if (s in lStr):
        return s
    rStr = dupSubUtil(root .right)
    if (s in rStr):
        return s
    s = s + root .key + lStr + rStr
    if (len(s) > 3 and s in subtrees):
        return ""
    subtrees[s] = 1
    return s


if __name__ == '__main__':
    root = Node('A')
    root .left = Node('B')
    root .right = Node('C')
    root .left .left = Node('D')
    root .left .right = Node('E')
    root .right .right = Node('B')
    root .right .right .right = Node('E')
    root .right .right .left = Node('D')
    str = dupSubUtil(root)
    if "" in str:
        print(" Yes ")
    else:
        print(" No ")

# Expected output:
 Yes
# count pairs of similar rectangles possible from a given array | ''python 3 program for the hashmap approach ; ''get the count of all pairs of similar rectangles ; '' initialize the result value and  map to store the ratio to the rectangles ; '' calculate the rectangular ratio and save them ; '' calculate pairs of similar rectangles from its common ratio ; ''

from collections import defaultdict


def getCount(rows, columns, sides):
    ans = 0
    umap = defaultdict(int)
    for i in range(rows):
        ratio = sides[i][0] / sides[i][1]
        umap[ratio] += 1
    for x in umap:
        value = umap[x]
        if (value > 1):
            ans += (value * (value - 1)) / 2
    return ans


if __name__ == "__main__":
    sides = [[4, 8], [10, 20], [15, 30], [3, 6]]
    rows = 4
    columns = 2
    print(int(getCount(rows, columns, sides)))

# Expected output:
6
# non | python3 program to find first non - repeating element . ; 
def firstNonRepeating(arr, n):
    for i in range(n):
        j = 0
        while (j < n):
            if (i != j and arr[i] == arr[j]):
                break
            j += 1
        if (j == n):
            return arr[i]
    return -1


arr = [9, 4, 9, 6, 7, 4]
n = len(arr)
print(firstNonRepeating(arr, n))

# Expected output:
6
# non | efficient python3 program to find first non - repeating element . ; insert all array elements in hash table ; traverse array again and return first element with count 1. ; 

from collections import defaultdict


def firstNonRepeating(arr, n):
    mp = defaultdict(lambda: 0)
    for i in range(n):
        mp[arr[i]] += 1
    for i in range(n):
        if mp[arr[i]] == 1:
            return arr[i]
    return -1


arr = [9, 4, 9, 6, 7, 4]
n = len(arr)
print(firstNonRepeating(arr, n))

# Expected output:
6
# non | efficient python program to print all non - repeating elements . ; insert all array elements in hash table ; traverse through map only and ; 
def firstNonRepeating(arr, n):
    mp = {}
    for i in range(n):
        if arr[i]not in mp:
            mp[arr[i]] = 0
        mp[arr[i]] += 1
    for x in mp:
        if (mp[x] == 1):
            print(x, end=" ")


arr = [9, 4, 9, 6, 7, 4]
n = len(arr)
firstNonRepeating(arr, n)

# Expected output:
6 7
# minimum substring removals required to make all remaining characters of a string same | ''python3 program to implement the above approach ; ''function to count minimum operations required to make all characters equal by repeatedly removing substring ; '' remove consecutive duplicate  characters from str ; '' stores length of the string ; '' stores frequency of each distinct  characters of the string str ; '' iterate over all the characters  of the string str ; '' update frequency of str[i] ; '' decrementing the frequency  of the string str[0] ; '' decrementing the frequency  of the ord(string ord(str[n - 1] ; '' stores the required count ; '' iterate over all characters  of the string str ; '' update ans ; ''

import re
import sys


def minOperationNeeded(s):
    d = {}
    str_ = re .sub("(.) + ", '', s)
    N = len(str_)
    res = [0 for i in range(256)]
    for i in range(N):
        res[ord(str_[i])] += 1
    res[ord(str_[0])] -= 1
    res[ord(str_[N - 1])] -= 1
    ans = sys .maxsize
    for i in range(N):
        ans = min(ans, res[ord(str_[i])])
    print((ans + 1))


if __name__ == '__main__':
    str = "ABCDABCDABCDA"
    minOperationNeeded(str)

# Expected output:
3
# print all root to leaf paths of an n | ''structure of an n ary tree node ; ''function to print the root to leaf path of the given n-ary tree ; '' print elements in the vector ; ''utility function to print all root to leaf paths of an nary tree ; '' if root is null ; ' ' ▁ insert ▁ current ▁ node ' s data into the vector ; '' if current node is a leaf node ; '' print the path ; '' pop the leaf node  and return ; '' recur for all children of  the current node ; '' recursive function call ; ''function to print root to leaf path ; '' if root is null, return ; '' utility function call ; ''

class Node:
    def __init__(self, x):
        self .data = x
        self .child = []


def printPath(vec):
    for ele in vec:
        print(ele, end=" ")
    print()


def printAllRootToLeafPaths(root):
    global vec
    if (not root):
        return
    vec .append(root .data)
    if (len(root .child) == 0):
        printPath(vec)
        vec .pop()
        return
    for i in range(len(root .child)):
        printAllRootToLeafPaths(root .child[i])
    vec .pop()


def printRootToLeafPaths(root):
    global vec
    if (not root):
        return
    printAllRootToLeafPaths(root)


if __name__ == '__main__':
    vec = []
    root = Node(1)
    root .child .append(Node(2))
    root .child .append(Node(3))
    root .child[0].child .append(Node(4))
    root .child[1].child .append(Node(5))
    root .child[1].child .append(Node(6))
    root .child[1].child[1].child .append(Node(7))
    root .child[1].child[1].child .append(Node(8))
    printRootToLeafPaths(root)

# Expected output:
1 2 4 
1 3 5 
1 3 6 7 
1 3 6 8
# pairs of positive negative values in an array | print pair with negative and positive value ; for each element of array . ; try to find the negative value of arr [ i ] from i + 1 to n ; if absolute values are equal print pair . ; if size of vector is 0 , therefore there is no element with positive negative value , print "0" ; sort the vector ; print the pair with negative positive value . ; 
def printPairs(arr, n):
    v = []
    for i in range(n):
        for j in range(i + 1, n):
            if (abs(arr[i]) == abs(arr[j])):
                v .append(abs(arr[i]))
    if (len(v) == 0):
        return
    v .sort()
    for i in range(len(v)):
        print(-v[i], "", v[i], end=" ")


if __name__ == "__main__":
    arr = [4, 8, 9, -4, 1, -1, -8, -9]
    n = len(arr)
    printPairs(arr, n)

# Expected output:
-1  1 -4  4 -8  8 -9  9
# check if an array can be divided into pairs whose sum is divisible by k | python3 program to check if arr [ 0. . n - 1 ] can be divided in pairs such that every pair is divisible by k . ; returns true if arr [ 0. . n - 1 ] can be divided into pairs with sum divisible by k . ; an odd length array cannot be divided into pairs ; create a frequency array to count occurrences of all remainders when divided by k . ; count occurrences of all remainders ; traverse input array and use freq [ ] to decide if given array can be divided in pairs ; remainder of current element ; if remainder with current element divides k into two halves . ; then there must be even occurrences of such remainder ; if remainder is 0 , then there must be two elements with 0 remainde ; then there must be even occurrences of such remainder ; else number of occurrences of remainder must be equal to number of occurrences of k - remainder ; 

from collections import defaultdict


def canPairs(arr, n, k):
    if (n & 1):
        return 0
    freq = defaultdict(lambda: 0)
    for i in range(0, n):
        freq[((arr[i] % k) + k) % k] += 1
    for i in range(0, n):
        rem = ((arr[i] % k) + k) % k
        if (2 * rem == k):
            if (freq[rem] % 2 != 0):
                return 0
        elif (rem == 0):
            if (freq[rem] & 1):
                return 0
        elif (freq[rem] != freq[k - rem]):
            return 0
    return 1


arr = [92, 75, 65, 48, 45, 35]
k = 10
n = len(arr)
if (canPairs(arr, n, k)):
    print("True")
else:
    print("False")

# Expected output:
True
# subarray with no pair sum divisible by k | function to find the subarray with no pair sum divisible by k ; hash table to store the remainders obtained on dividing by k ; s : starting index of the current subarray , e : ending index of the current subarray , maxs : starting index of the maximum size subarray so far , maxe : ending index of the maximum size subarray so far ; insert the first element in the set ; removing starting elements of current subarray while there is an element in set which makes a pair with mod [ i ] such that the pair sum is divisible . ; include the current element in the current subarray the ending index of the current subarray increments by one ; compare the size of the current subarray with the maximum size so far ; 
def subarrayDivisibleByK(arr, n, k):
    mp = [0] * 1000
    s = 0
    e = 0
    maxs = 0
    maxe = 0
    mp[arr[0] % k] = mp[arr[0] % k] + 1
    for i in range(1, n):
        mod = arr[i] % k
        while (mp[k - mod] != 0 or (mod == 0 and mp[mod] != 0)):
            mp[arr[s] % k] = mp[arr[s] % k] - 1
            s = s + 1
        mp[mod] = mp[mod] + 1
        e = e + 1
        if ((e - s) > (maxe - maxs)):
            maxe = e
            maxs = s
    print("The maximum size is {} and the ".format((maxe - maxs + 1)))
    for i in range(maxs, maxe + 1):
        print("{} ".format(arr[i]), end="")


k = 3
arr = [5, 10, 15, 20, 25]
n = len(arr)
subarrayDivisibleByK(arr, n, k)

# Expected output:
The maximum size is 2 and the 
10 15
# find three element from different three arrays such that a + b + c = sum | function to check if there is an element from each array such that sum of the three elements is equal to given sum . ; 
def findTriplet(a1, a2, a3, n1, n2, n3, sum):
    for i in range(0, n1):
        for j in range(0, n2):
            for k in range(0, n3):
                if (a1[i] + a2[j] + a3[k] == sum):
                    return True
    return False


a1 = [1, 2, 3, 4, 5]
a2 = [2, 3, 6, 1, 2]
a3 = [3, 2, 4, 5, 6]
sum = 9
n1 = len(a1)
n2 = len(a2)
n3 = len(a3)
print("Yes")if findTriplet(a1, a2, a3, n1, n2, n3, sum)else print("No")

# Expected output:
Yes
# find three element from different three arrays such that a + b + c = sum | function to check if there is an element from each array such that sum of the three elements is equal to given sum . ; store elements of first array in hash ; sum last two arrays element one by one ; consider current pair and find if there is an element in a1 [ ] such that these three form a required triplet ; 
def findTriplet(a1, a2, a3, n1, n2, n3, sum):
    s = set()
    for i in range(n1):
        s .add(a1[i])
    for i in range(n2):
        for j in range(n3):
            if sum - a2[i] - a3[j] in s:
                return True
    return False


a1 = [1, 2, 3, 4, 5]
a2 = [2, 3, 6, 1, 2]
a3 = [3, 24, 5, 6]
n1 = len(a1)
n2 = len(a2)
n3 = len(a3)
sum = 9
if findTriplet(a1, a2, a3, n1, n2, n3, sum):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# count quadruplets with sum k from given array | ''function to return the number of quadruplets having given sum ; '' initialize answer ; '' all possible first elements ; '' all possible second element ; '' use map to find the  fourth element ; '' all possible third elements ; '' calculate number of valid  4th elements ; '' update the twice_count ; '' unordered pairs ; '' return answer ; ''
def countSum(a, n, sum):
    count = 0
    for i in range(n - 3):
        for j in range(i + 1, n - 2, 1):
            req = sum - a[i] - a[j]
            m = {}
            for k in range(j + 1, n, 1):
                m[a[k]] = m .get(a[k], 0) + 1
            twice_count = 0
            for k in range(j + 1, n, 1):
                twice_count += m .get(req - a[k], 0)
                if (req - a[k] == a[k]):
                    twice_count -= 1
            count += twice_count // 2
    return count


if __name__ == '__main__':
    arr = [4, 5, 3, 1, 2, 4]
    S = 13
    N = len(arr)
    print(countSum(arr, N, S))

# Expected output:
3
# find four elements a , b , c and d in an array such that a + b = c + d | function to find a , b , c , d such that ( a + b ) = ( c + d ) ; create an empty hashmap to store mapping from sum to pair indexes ; traverse through all possible pairs of arr [ ] ; sum already present in hash ; 
def find_pair_of_sum(arr: list, n: int):
    map_ = {}
    for i in range(n):
        for j in range(i + 1, n):
            sum_ = arr[i] + arr[j]
            if sum_ in map_:
                print(map_[sum_], arr[i], arr[j])
                return
            else:
                map_[sum_] = (arr[i], arr[j])


if __name__ == "__main__":
    arr = [3, 4, 7, 1, 2, 9, 8]
    n = len(arr)
    find_pair_of_sum(arr, n)

# Expected output:
(3, 8) 4 7
# check if all subarrays contains at least one unique element | ''function to check if all subarrays have at least one unique element ; '' generate all subarray ; ' ' ▁ store ▁ frequency ▁ of ▁ ▁ subarray ' s elements ; '' traverse the array over  the range [i, n] ; '' update frequency of  current subarray in map ; '' increment count ; '' decrement count ; '' if all subarrays have at  least 1 unique element ; ''
def check(arr, n):
    for i in range(n):
        hm = {}
        count = 0
        for j in range(i, n):
            hm[arr[j]] = hm .get(arr[j], 0) + 1
            if (hm[arr[j]] == 1):
                count += 1
            if (hm[arr[j]] == 2):
                count -= 1
            if (count == 0):
                return "No"
    return "Yes"


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

# Expected output:
Yes
# count all disjoint pairs having absolute difference at least k from a given array | ''function to count distinct pairs with absolute difference atleast k ; '' track the element that  have been paired ; '' stores count of distinct pairs ; '' pick all elements one by one ; '' if already visited ; '' if already visited ; '' if difference is at least k ; '' mark element as visited and  increment the count ; '' print the final count ; ''
def countPairsWithDiffK(arr, N, K):
    vis = [0] * N
    count = 0
    for i in range(N):
        if (vis[i] == 1):
            continue
        for j in range(i + 1, N):
            if (vis[j] == 1):
                continue
            if (abs(arr[i] - arr[j]) >= K):
                count += 1
                vis[i] = 1
                vis[j] = 1
                break
    print(count)


if __name__ == '__main__':
    arr = [1, 3, 3, 5]
    N = len(arr)
    K = 2
    countPairsWithDiffK(arr, N, K)

# Expected output:
2
# check if two trees are mirror | a binary tree node ; given two trees , return true if they are mirror of each other ; base case : both empty ; if only one is empty ; both non - empty , compare them recursively . note that in recursive calls , we pass left of one tree and right of other tree ; 

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


def areMirror(a, b):
    if a is None and b is None:
        return True
    if a is None or b is None:
        return False
    return (
        a .data == b .data and areMirror(
            a .left,
            b .right) and areMirror(
            a .right,
            b .left))


root1 = Node(1)
root2 = Node(1)
root1 .left = Node(2)
root1 .right = Node(3)
root1 .left .left = Node(4)
root1 .left .right = Node(5)
root2 .left = Node(3)
root2 .right = Node(2)
root2 .right .left = Node(5)
root2 .right .right = Node(4)
if areMirror(root1, root2):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# find the length of largest subarray with 0 sum | returns the maximum length ; note : dictonary in python in implemented as hash maps create an empty hash map ( dictionary ) ; initialize sum of elements ; initialize result ; traverse through the 
def maxLen(arr):
    hash_map = {}
    curr_sum = 0
    max_len = 0
    for i in range(len(arr)):
        curr_sum += arr[i]
        if arr[i] is 0 and max_len is 0:
            max_len = 1
        if curr_sum is 0:
            max_len = i + 1
        if curr_sum in hash_map:
            max_len = max(max_len, i - hash_map[curr_sum])
        else:
            hash_map[curr_sum] = i
    return max_len


arr = [15, -2, 2, -8, 1, 7, 10, 13]
print("Length of the longest 0 sum subarray is % d" % maxLen(arr))

# Expected output:
Length of the longest 0 sum subarray is  5
# print alternate elements of an array | ''function to print alternate elements of the given array ; '' print elements  at odd positions ; '' print elements of array ; ''
def printAlter(arr, N):
    for currIndex in range(0, N, 2):
        print(arr[currIndex], end=" ")


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

# Expected output:
1 3 5
# longest increasing consecutive subsequence | python program to find length of the longest increasing subsequence whose adjacent element differ by 1 ; function that returns the length of the longest increasing subsequence whose adjacent element differ by 1 ; create hashmap to save latest consequent number as " key " and its length as " value " ; stores the length of the longest subsequence that ends with a [ i ] ; iterate for all element ; if a [ i ] - 1 is present before i - th index ; last index of a [ i ] - 1 ; 

from collections import defaultdict
import sys


def longestSubsequence(a, n):
    mp = defaultdict(lambda: 0)
    dp = [0 for i in range(n)]
    maximum = -sys .maxsize
    for i in range(n):
        if a[i] - 1 in mp:
            lastIndex = mp[a[i] - 1] - 1
            dp[i] = 1 + dp[lastIndex]
        else:
            dp[i] = 1
        mp[a[i]] = i + 1
        maximum = max(maximum, dp[i])
    return maximum


a = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12]
n = len(a)
print(longestSubsequence(a, n))

# Expected output:
6