giulio98/xlcost-single-prompt huggingface dataset:
# longest subsequence such that difference between adjacents is one | set 2 | python3 implementation to find longest subsequence such that difference between adjacents is one ; function to find longest subsequence such that difference between adjacents is one ; hash table to map the array element with the length of the longest subsequence of which it is a part of and is the last element of that subsequence ; to store the longest length subsequence ; traverse the array elements ; / initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in ' um ' and its length of subsequence is greater than 'len   ; f ' arr [ i ] + 1' is in ' um ' and its length of subsequence is greater than ' len ' ; update arr [ i ] subsequence length in ' um ' ; update longest length ; required longest length subsequence ; 

from collections import defaultdict


def longLenSub(arr, n):
    um = defaultdict(lambda: 0)
    longLen = 0
    for i in range(n):
        len1 = 0
        if (arr[i - 1] in um and len1 < um[arr[i] - 1]):
            len1 = um[arr[i] - 1]
        if (arr[i] + 1 in um and len1 < um[arr[i] + 1]):
            len1 = um[arr[i] + 1]
        um[arr[i]] = len1 + 1
        if longLen < um[arr[i]]:
            longLen = um[arr[i]]
    return longLen


arr = [1, 2, 3, 4, 5, 3, 2]
n = len(arr)
print("Longest length subsequence =", longLenSub(arr, n))

# Expected output:
Longest length subsequence = 6
# longest consecutive subsequence | returns length of the longest contiguous subsequence ; sort the array ; insert repeated elements only once in the vector ; find the maximum length by traversing the array ; check if the current element is equal to previous element + 1 ; update the maximum ; 
def findLongestConseqSubseq(arr, n):
    ans = 0
    count = 0
    arr .sort()
    v = []
    v .append(arr[0])
    for i in range(1, n):
        if (arr[i] != arr[i - 1]):
            v .append(arr[i])
    for i in range(len(v)):
        if (i > 0 and v[i] == v[i - 1] + 1):
            count += 1
        else:
            count = 1
        ans = max(ans, count)
    return ans


arr = [1, 2, 2, 3]
n = len(arr)
print(
    "Length of the Longest contiguous subsequence is",
    findLongestConseqSubseq(
        arr,
        n))

# Expected output:
Length of the Longest contiguous subsequence is 3
# count smaller primes on the right of each array element | ''python3 program for the above approach ; ''function to check if a number is prime or not ; ''function to update a binary tree ; ''function to find the sum of all the elements which are less than or equal to index ; ''function to find the number of smaller primes on the right for every array element ; '' iterate the array in backwards ; '' calculating the required  number of primes ; '' if current array  element is prime ; '' update the fenwick tree ; ''

maxn = int(1e6) + 5
BITree = [0] * (maxn)


def is_prime(n):
    if (n <= 1):
        return False
    i = 2
    while (i * i <= n):
        if (n % i == 0):
            return False
        i += 1
    return True


def update_bitree(index, value):
    while (index <= maxn):
        BITree[index] += value
        index += (index & (-index))


def sum_bitree(index):
    s = 0
    while (index > 0):
        s += BITree[index]
        index -= (index & (-index))
    return s


def countSmallerPrimes(ar, N):
    ans = [0] * (N)
    global BITree
    for i in range(N - 1, 0, -1):
        ans[i] = sum_bitree(ar[i])
        if (is_prime(ar[i])):
            update_bitree(ar[i], 1)
    ans[0] = 2
    for i in range(N):
        print(ans[i], end=" ")


if __name__ == '__main__':
    ar = [5, 5, 17, 9, 12, 15, 11, 7, 39, 3]
    N = len(ar)
    countSmallerPrimes(ar, N)

# Expected output:
2 1 3 2 3 3 2 1 1 0
# longest consecutive subsequence | python program to find longest contiguous subsequence ; hash all the array elements ; check each possible sequence from the start then update optimal length ; if current element is the starting element of a sequence ; then check for next elements in the sequence ; update optimal length if this length is more ; 
def findLongestConseqSubseq(arr, n):
    s = set()
    ans = 0
    for ele in arr:
        s .add(ele)
    for i in range(n):
        if (arr[i] - 1)not in s:
            j = arr[i]
            while (j in s):
                j += 1
            ans = max(ans, j - arr[i])
    return ans


if __name__ == '__main__':
    n = 7
    arr = [1, 9, 3, 10, 4, 20, 2]
    print("Length of the Longest contiguous subsequence is ",
          findLongestConseqSubseq(arr, n))

# Expected output:
Length of the Longest contiguous subsequence is  4
# largest increasing subsequence of consecutive integers | python3 implementation of longest continuous increasing subsequence function for lis ; initialize result ; iterate through array and find end index of lis and its size ; print lis size ; print lis after setting start element ; 
def findLIS(A, n):
    hash = dict()
    LIS_size, LIS_index = 1, 0
    hash[A[0]] = 1
    for i in range(1, n):
        if A[i] - 1 not in hash:
            hash[A[i] - 1] = 0
        hash[A[i]] = hash[A[i] - 1] + 1
        if LIS_size < hash[A[i]]:
            LIS_size = hash[A[i]]
            LIS_index = A[i]
    print("LIS_size =", LIS_size)
    print("LIS : ", end="")
    start = LIS_index - LIS_size + 1
    while start <= LIS_index:
        print(start, end=" ")
        start += 1


if __name__ == "__main__":
    A = [2, 5, 3, 7, 4, 8, 5, 13, 6]
    n = len(A)
    findLIS(A, n)

# Expected output:
LIS_size = 5
LIS : 2 3 4 5 6
# count subsets having distinct even numbers | function to count the required subsets ; inserting even numbers in the set ' us ' single copy of each number is retained ; counting distinct even numbers ; total count of required subsets ; 
def countSubSets(arr, n):
    us = set()
    even_count = 0
    for i in range(n):
        if arr[i] % 2 == 0:
            us .add(arr[i])
    even_count = len(us)
    return pow(2, even_count) - 1


arr = [4, 2, 1, 9, 2, 6, 5, 3]
n = len(arr)
print("Numbers of subset=", countSubSets(arr, n))

# Expected output:
Numbers of subset= 7
# count distinct elements in every window of size k | simple python3 program to count distinct elements in every window of size k ; counts distinct elements in window of size k ; traverse the window ; check if element arr [ i ] exists in arr [ 0. . i - 1 ] ; counts distinct elements in all windows of size k ; traverse through every window ; 

import math as mt


def countWindowDistinct(win, k):
    dist_count = 0
    for i in range(k):
        j = 0
        while j < i:
            if (win[i] == win[j]):
                break
            else:
                j += 1
        if (j == i):
            dist_count += 1
    return dist_count


def countDistinct(arr, n, k):
    for i in range(n - k + 1):
        print(countWindowDistinct(arr[i:k + i], k))


arr = [1, 2, 1, 3, 4, 2, 3]
k = 4
n = len(arr)
countDistinct(arr, n, k)

# Expected output:
3
4
4
3
# maximum score assigned to a subsequence of numerically consecutive and distinct array elements | ''function to find the maximum score possible ; '' base case ; '' if previously occurred  subproblem occurred ; '' check if lastpicked element differs  by 1 from the current element ; '' calculate score by including  the current element ; '' calculate score by excluding  the current element ; '' return maximum score from  the two possibilities ; ''function to print maximum score ; '' dp array to store results ; '' function call ; ''
def maximumSum(a, b, n, index, lastpicked, dp):
    if (index == n):
        return 0
    if (dp[index][lastpicked + 1] != -1):
        return dp[index][lastpicked + 1]
    option1, option2 = 0, 0
    if (lastpicked == -1 or a[lastpicked] != a[index]):
        option1 = (b[index] + maximumSum(a, b, n, index + 1, index, dp))
    option2 = maximumSum(a, b, n, index + 1, lastpicked, dp)
    dp[index][lastpicked + 1] = max(option1, option2)
    return dp[index][lastpicked + 1]


def maximumPoints(arr, brr, n):
    index = 0
    lastPicked = -1
    dp = [[-1 for x in range(n + 5)]for y in range(n + 5)]
    print(maximumSum(arr, brr, n, index, lastPicked, dp))


if __name__ == "__main__":
    arr = [1, 2, 3, 3, 3, 1]
    brr = [-1, 2, 10, 20, -10, -9]
    N = len(arr)
    maximumPoints(arr, brr, N)

# Expected output:
22
# maximum possible sum of a window in an array such that elements of same window in other array are unique | function to return maximum sum of window in b [ ] according to given constraints . ; map is used to store elements and their counts . ; initialize result ; calculating the maximum possible sum for each subarray containing unique elements . ; remove all duplicate instances of a [ i ] in current window . ; add current instance of a [ i ] to map and to current sum . ; update result if current sum is more . ; 
def returnMaxSum(A, B, n):
    mp = set()
    result = 0
    curr_sum = curr_begin = 0
    for i in range(0, n):
        while A[i] in mp:
            mp .remove(A[curr_begin])
            curr_sum -= B[curr_begin]
            curr_begin += 1
        mp .add(A[i])
        curr_sum += B[i]
        result = max(result, curr_sum)
    return result


if __name__ == "__main__":
    A = [0, 1, 2, 3, 0, 1, 4]
    B = [9, 8, 1, 2, 3, 4, 5]
    n = len(A)
    print(returnMaxSum(A, B, n))

# Expected output:
20
# length of second longest sequence of consecutive 1 s in a binary array | ''function to find maximum and second maximum length ; '' initialise maximum length ; '' initialise second maximum length ; '' initialise count ; '' iterate over the array ; '' if sequence ends ; '' reset count ; '' otherwise ; '' increase length  of current sequence ; '' update maximum ; '' traverse the given array ; '' if sequence continues ; '' increase length  of current sequence ; '' update second max ; '' reset count when 0 is found ; '' print the result ; ''
def FindMax(arr, N):
    maxi = -1
    maxi2 = -1
    count = 0
    for i in range(N):
        if (arr[i] == 0):
            count = 0
        else:
            count += 1
            maxi = max(maxi, count)
    for i in range(N):
        if (arr[i] == 1):
            count += 1
            if (count > maxi2 and count < maxi):
                maxi2 = count
        if (arr[i] == 0):
            count = 0
    maxi = max(maxi, 0)
    maxi2 = max(maxi2, 0)
    print(maxi2)


if __name__ == '__main__':
    arr = [1, 1, 1, 0, 0, 1, 1]
    N = len(arr)
    FindMax(arr, N)

# Expected output:
2
# minimum distance between any special pair in the given array | ''python3 program for the above approach ; ''function that finds the minimum difference between two vectors ; '' find lower bound of the index ; '' find two adjacent indices  to take difference ; '' return the result ; ''function to find the minimum distance between index of special pairs ; '' stores the index of each element  in the array arr[] ; store the indexes ; get the unique values in list ; '' take adjacent difference  of same values ; '' left index array ; '' right index array ; '' find the minimum gap between  the two adjacent different  values ; ''

import sys


def mindist(left, right):
    res = sys .maxsize
    for i in range(len(left)):
        num = left[i]
        index = right .index(min([i for i in right if num >= i]))
        if (index == 0):
            res = min(res, abs(num - right[index]))
        elif (index == len(right)):
            res = min(res,
                      min(abs(num - right[index - 1]),
                          abs(num - right[index])))
    return res


def specialPairs(nums):
    m = {}
    vals = []
    for i in range(len(nums)):
        m[nums[i]] = i
    for p in m:
        vals .append(p)
    res = sys .maxsize
    for i in range(1, len(vals)):
        vec = [m[vals[i]]]
        for i in range(1, len(vec)):
            res = min(res, abs(vec[i] - vec[i - 1]))
        if (i):
            a = vals[i]
            left = [m[a]]
            b = vals[i - 1]
            right = [m[b]]
            res = min(res, mindist(left, right)) + 1
    return res


if __name__ == "__main__":
    arr = [0, -10, 5, -5, 1]
    print(specialPairs(arr))

# Expected output:
2
# substring of length k having maximum frequency in the given string | ''python3 program for the above approach ; ''function that generates substring of length k that occurs maximum times ; '' store the frequency of substrings ; '' deque to maintain substrings  window size k ; '' update the frequency of the  first subin the map  e="".join(list(d ; '' remove the first character of  the previous k length substring ; '' traverse the string ; '' insert the current character  as last character of  current substring ; '' pop the first character of  previous k length substring ; '' find the subthat occurs  maximum number of times  print(m) ; '' print the substring ; ''

from collections import deque, Counter, defaultdict
import sys


def maximumOccurringString(s, K):
    M = {}
    D = deque()
    for i in range(K):
        D .append(s[i])
    M[str("".join(list(D)))] = M .get(str("".join(list(D))), 0) + 1
    D .popleft()
    for j in range(i, len(s)):
        D .append(s[j])
        M[str("".join(list(D)))] = M .get(str("".join(list(D))), 0) + 1
        D .popleft()
    maxi = -sys .maxsize - 1
    ans = deque()
    for it in M:
        if (M[it] >= maxi):
            maxi = M[it]
            ans = it
    for i in range(len(ans)):
        print(ans[i], end="")


if __name__ == '__main__':
    s = "bbbbbaaaaabbabababa"
    K = 5
    maximumOccurringString(s, K)

# Expected output:
ababa
# count nodes from all lower levels smaller than minimum valued node of current level for every level in a binary tree | ''python3 program of the above approach ; ''stores the nodes to be deleted ; ''structure of a tree node ; ''function to find the min value of node for each level ; '' count is used to diffentiate  each level of the tree ; ''function to check whether the nodes in the level below it are smaller by performing post order traversal ; '' traverse the left subtree ; '' traverse right subtree ; '' check from minimum values  computed at each level ; ''function to print count of nodes from all lower levels having values less than the the nodes in the current level ; '' stores the number of levels ; '' stores the required count  of nodes for each level ; ''

from collections import deque
from sys import maxsize as INT_MAX
mp = dict()


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


def calculateMin(root: Node, levelMin: list) -> None:
    qt = deque()
    qt .append(root)
    count = 1
    min_v = INT_MAX
    while (qt):
        temp = qt .popleft()
        min_v = min(min_v, temp .key)
        if (temp .left):
            qt .append(temp .left)
        if (temp .right):
            qt .append(temp .right)
        count -= 1
        if (count == 0):
            levelMin .append(min_v)
            min_v = INT_MAX
            count = len(qt)


def findNodes(
        root: Node,
        levelMin: list,
        levelResult: list,
        level: int) -> None:
    if (root is None):
        return
    findNodes(root .left, levelMin, levelResult, level + 1)
    findNodes(root .right, levelMin, levelResult, level + 1)
    for i in range(level):
        if (root .key <= levelMin[i]):
            levelResult[i] += 1


def printNodes(root: Node) -> None:
    levelMin = []
    calculateMin(root, levelMin)
    numLevels = len(levelMin)
    levelResult = [0] * numLevels
    findNodes(root, levelMin, levelResult, 0)
    for i in range(numLevels):
        print(levelResult[i], end=" ")


if __name__ == "__main__":
    root = Node(4)
    root .left = Node(3)
    root .right = Node(5)
    root .right .left = Node(3)
    root .right .right = Node(1)
    root .left .left = Node(10)
    root .left .right = Node(2)
    printNodes(root)

# Expected output:
4 3 0
# count subarrays which contains both the maximum and minimum array element | ''function to count subarray containing both maximum and minimum array elements ; '' if the length of the  array is less than 2 ; '' find the index of  maximum element ; '' find the index of  minimum element ; '' if i > j, then swap  the value of i and j ; '' return the answer ; ''function to return max_element index ; ''function to return min_element index ; ''
def max_element(arr):
    idx = 0
    max = arr[0]
    for i in range(1, len(arr)):
        if (max < arr[i]):
            max = arr[i]
            idx = i
    return idx


def min_element(arr):
    idx = 0
    min = arr[0]
    for i in range(1, len(arr)):
        if (arr[i] < min):
            min = arr[i]
            idx = i
    return idx

def countSubArray(arr, n):
    if (n < 2):
        return n
    i = max_element(arr)
    j = min_element(arr)
    if (i > j):
        tmp = arr[i]
        arr[i] = arr[j]
        arr[j] = tmp
    return (i + 1) * (n - j)


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

# Expected output:
3
# split array into subarrays at minimum cost by minimizing count of repeating elements in each subarray | python3 program for the above approach ; function to find the minimum cost of splitting the array into subarrays ; get the maximum element ; dp will store the minimum cost upto index i ; initialize the result array ; initialise the first element ; create the frequency array ; update the frequency ; counting the cost of the duplicate element ; minimum cost of operation from 0 to j ; total cost of the array ; 

import sys


def findMinCost(a, k, n):
    max_ele = max(a)
    dp = [0] * (n + 1)
    for i in range(1, n + 1):
        dp[i] = sys .maxsize
    dp[0] = 0
    for i in range(0, n):
        freq = [0] * (max_ele + 1)
        for j in range(i, n):
            freq[a[j]] += 1
            cost = 0
            for x in range(0, max_ele + 1):
                cost += (0 if (freq[x] == 1)else freq[x])
            dp[j + 1] = min(dp[i] + cost + k, dp[j + 1])
    return dp[n]


if __name__ == '__main__':
    arr = [1, 2, 1, 1, 1]
    K = 2
    n = len(arr)
    print(findMinCost(arr, K, n))

# Expected output:
6
# find subarray with given sum | set 2 ( handles negative numbers ) | function to print subarray with sum as given sum ; create an empty map ; if curr_sum is equal to target sum we found a subarray starting from index 0 and ending at index i ; if curr_sum - sum already exists in map we have found a subarray with target sum ; if value is not present then add to hashmap ; if we reach here , then no subarray exists ; 
def subArraySum(arr, n, Sum):
    Map = {}
    curr_sum = 0
    for i in range(0, n):
        curr_sum = curr_sum + arr[i]
        if curr_sum == Sum:
            print("Sum found between indexes 0 to", i)
            return
        if (curr_sum - Sum) in Map:
            print("Sum found between indexes",
                  Map[curr_sum - Sum] + 1, "to", i)
            return
        Map[curr_sum] = i
    print("No subarray with given sum exists")


if __name__ == "__main__":
    arr = [10, 2, -2, -20, 10]
    n = len(arr)
    Sum = -10
    subArraySum(arr, n, Sum)

# Expected output:
Sum found between indexes 0 to 3
# write code to determine if two trees are identical | a binary tree node has data , pointer to left child and a pointer to right child ; given two trees , return true if they are structurally identical ; 1. both empty ; 2. both non - empty -> compare them ; 3. one empty , one not -- false ; 

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


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


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(2)
root2 .right = Node(3)
root2 .left .left = Node(4)
root2 .left .right = Node(5)
if identicalTrees(root1, root2):
    print("Both trees are identical")
else:
    print("Trees are not identical")

# Expected output:
Both trees are identical
# generate a string from an array of alphanumeric strings based on given conditions | function to generate required string ; to store the result ; split name and number ; stores the maximum number less than or equal to the length of name ; check for number by parsing it to integer if it is greater than max number so far ; check if no such number is found then we append x to the result . ; otherwise ; append max index of the name ; return the final string ; 
def generatePassword(s, T):
    result = []
    for currentString in s:
        person = currentString .split(":")
        name = person[0]
        number = person[1]
        n = len(name)
        max = 0
        for i in range(len(number)):
            temp = int(number[i])
            if (temp > max and temp <= n):
                max = temp
        if max == 0:
            result .append(T)
        else:
            result .append(name[max - 1])
    return result


arr = ["Geeks:89167", "gfg:68795"]
T = 'X'
print(*generatePassword(arr, T), sep="")

# Expected output:
GX
# minimum number of edges required to be removed from an undirected graph to make it acyclic | stores the adjacency list ; stores if a vertex is visited or not ; function to perform dfs traversal to count the number and size of all connected components ; mark the current node as visited ; traverse the adjacency list of the current node ; for every unvisited node ; recursive dfs call ; function to add undirected edge in the graph ; function to calculate minimum number of edges to be removed ; create adjacency list ; iterate over all the nodes ; print the final count ; 
def dfs(node):

    global cc
    vis[node] = True
    for x in vec[node]:
        if (vis[x] == 0):
            cc += 1
            dfs(x)


def addEdge(u, v):

    vec[u].append(v)
    vec[v].append(u)


def minEdgeRemoved(N, M, Edges):

    global cc
    for i in range(M):
        addEdge(Edges[i][0], Edges[i][1])
    k = 0
    for i in range(1, N + 1):
        if (not vis[i]):
            cc = 1
            dfs(i)
            k += 1
    print(M - N + k)


if __name__ == '__main__':
    vec = [[] for i in range(100001)]
    vis = [False] * 100001
    cc = 1
    N = 3
    M = 2

    Edges = [[1, 2], [2, 3]]

    minEdgeRemoved(N, M, Edges)

# Expected output:
0
# group shifted string | total lowercase letter ; method to a difference string for a given string . if string is " adf " then difference string will be " cb " ( first difference3 then difference 2 ) ; representing the difference as char ; this string will be 1 less length than str ; method for grouping shifted string ; map for storing indices of string which are in same group ; iterating through map to print group ; 

ALPHA = 26


def getDiffString(str):
    shift = ""
    for i in range(1, len(str)):
        dif = (ord(str[i]) - ord(str[i - 1]))
        if (dif < 0):
            dif += ALPHA
        shift += chr(dif + ord('a'))
    return shift


def groupShiftedString(str, n):
    groupMap = {}
    for i in range(n):
        diffStr = getDiffString(str[i])
        if diffStr not in groupMap:
            groupMap[diffStr] = [i]
        else:
            groupMap[diffStr].append(i)
    for it in groupMap:
        v = groupMap[it]
        for i in range(len(v)):
            print(str[v[i]], end=" ")
        print()


str = ["acd", "dfg", "wyz", "yab", "mop", "bdfh", "a", "x", "moqs"]
n = len(str)
groupShiftedString(str, n)

# Expected output:
acd dfg wyz yab mop 
bdfh moqs 
a x