giulio98/xlcost-single-prompt huggingface dataset:
# length of longest subarray having only k distinct prime numbers | python3 program to implement the above approach ; function to precalculate all the prime up to 10 ^ 6 ; initialize prime to true ; iterate [ 2 , sqrt ( n ) ] ; if p is prime ; mark all multiple of p as true ; function that finds the length of longest subarray k distinct primes ; precompute all prime up to 2 * 10 ^ 6 ; keep track occurrence of prime ; initialize result to - 1 ; if number is prime then increment its count and decrease k ; decrement k ; remove required elements till k become non - negative ; decrease count so that it may appear in another subarray appearing after this present subarray ; increment k ; take the max value as length of subarray ; return the final length ; 

from collections import defaultdict
isprime = [True] * 2000010


def SieveOfEratosthenes(n):
    isprime[1] = False
    p = 2
    while (p * p <= n):
        if (isprime[p]):
            for i in range(p * p, n + 1, p):
                isprime[i] = False
        p += 1


def KDistinctPrime(arr, n, k):
    SieveOfEratosthenes(2000000)
    cnt = defaultdict(lambda: 0)
    result = -1
    j = -1
    for i in range(n):
        x = arr[i]
        if (isprime[x]):
            cnt[x] += 1
            if (cnt[x] == 1):
                k -= 1
    while (k < 0):
        j += 1
        x = arr[j]
        if (isprime[x]):
            cnt[x] -= 1
            if (cnt[x] == 0):
                k += 1
        if (k == 0):
            result = max(result, i - j)
    return result


arr = [1, 2, 3, 3, 4, 5, 6, 7, 8, 9]
K = 3
N = len(arr)
print(KDistinctPrime(arr, N, K))

# Expected output:
8
# nth subset of the sequence consisting of powers of k in increasing order of their sum | python3 program for the above approach ; function to print the required n - th subset ; nearest power of 2 <= n ; now insert k ^ p in the answer ; update n ; print the subset ; 

import math


def printSubset(N, K):
    answer = ""
    while (N > 0):
        p = int(math .log(N, 2))
        answer = str(K ** p) + " " + answer
        N = N % (2 ** p)
    print(answer)


N = 5
K = 4
printSubset(N, K)

# Expected output:
1 16
# count total set bits in all numbers from range l to r | returns position of leftmost set bit the rightmost position is taken as 0 ; function that gives the position of previous leftmost set bit in n ; function that returns count of set bits present in all numbers from 1 to n ; get the position of leftmost set bit in n ; use the position ; function to count the set bits between the two numbers n and m ; base case ; get position of next leftmost set bit ; if n is of the form 2 ^ x - 1 ; update n for next recursive call ; function that counts the set bits between l and r ; 
def getLeftmostBit(n):
    m = 0
    while (n > 1):
        n = n >> 1
        m += 1
    return m


def getNextLeftmostBit(n, m):
    temp = 1 << m
    while (n < temp):
        temp = temp >> 1
        m -= 1
    return m


def countSetBit(n):
    m = getLeftmostBit(n)
    return _countSetBit(n, m)


def _countSetBit(n, m):
    if (n == 0):
        return 0
    m = getNextLeftmostBit(n, m)
    if (n == int(1 << (m + 1)) - 1):
        return int(m + 1) * (1 << m)
    n = n - (1 << m)
    return ((n + 1) + countSetBit(n) + m * (1 << (m - 1)))


def countSetBits(L, R):
    return abs(countSetBit(R) - countSetBit(L - 1))


if __name__ == '__main__':
    L = 3
    R = 5
    print("Total set bit count is ", countSetBits(L, R))

# Expected output:
Total set bit count is  5
# permutation of array such that products of all adjacent elements are even | function to print the required permutation ; push odd elements in ' odd ' and even elements in 'even ; check if it possible to arrange the elements ; else print the permutation ; print remaining odds are even . and even elements ; 
def printPermutation(arr, n):
    odd, even = [], []
    for i in range(n):
        if (arr[i] % 2 == 0):
            even .append(arr[i])
        else:
            odd .append(arr[i])
    size_odd = len(odd)
    size_even = len(even)
    if (size_odd > size_even + 1):
        print(-1)
    else:
        i, j = 0, 0
        while (i < size_odd and j < size_even):
            print(odd[i], end=" ")
            i += 1
            print(even[j], end=" ")
            j += 1
    while (i < size_odd):
        print(odd[i], end=" ")
        i += 1
    while (j < size_even):
        print(even[j], end=" ")
        j += 1


arr = [6, 7, 9, 8, 10, 11]
N = len(arr)
printPermutation(arr, N)

# Expected output:
7 6 9 8 11 10
# maximize gcd of all possible pairs from 1 to n | function to obtain the maximum gcd of all pairs from 1 to n ; print the answer ; 
def find(n):
    print(n // 2)


if __name__ == '__main__':
    n = 5
    find(n)

# Expected output:
2
# count of pairs of array elements which are divisible by k when concatenated | python3 program to count pairs of array elements which are divisible by k when concatenated ; function to calculate and return the count of pairs ; compute power of 10 modulo k ; calculate length of a [ i ] ; increase count of remainder ; calculate ( a [ i ] * 10 ^ lenj ) % k ; calculate ( k - ( a [ i ] * 10 ^ lenj ) % k ) % k ; increase answer by count ; if a pair ( a [ i ] , a [ i ] ) is counted ; return the count of pairs ; 

rem = [[0 for x in range(11)]for y in range(11)]


def countPairs(a, n, k):
    l = [0] * n
    p = [0] * (11)
    p[0] = 1
    for i in range(1, 11):
        p[i] = (p[i - 1] * 10) % k
    for i in range(n):
        x = a[i]
        while (x > 0):
            l[i] += 1
            x //= 10
        rem[l[i]][a[i] % k] += 1
    ans = 0
    for i in range(n):
        for j in range(1, 11):
            r = (a[i] * p[j]) % k
            xr = (k - r) % k
            ans += rem[j][xr]
            if (l[i] == j and (r + a[i] % k) % k == 0):
                ans -= 1
    return ans


a = [4, 5, 2]
n = len(a)
k = 2
print(countPairs(a, n, k))

# Expected output:
4
# count of n digit numbers whose sum of every k consecutive digits is equal | function to count the number of n - digit numbers such that sum of every k consecutive digits are equal ; range of numbers ; extract digits of the number ; store the sum of first k digits ; check for every k - consecutive digits using sliding window ; 
def countDigitSum(N, K):
    l = pow(10, N - 1)
    r = pow(10, N) - 1
    count = 0
    for i in range(1, r + 1):
        num = i
        digits = [0] * (N)
        for j in range(N - 1, 0, -1):
            digits[j] = num % 10
            num //= 10
        sum = 0
        flag = 0
        for j in range(0, K):
            sum += digits[j]
        for j in range(K, N):
            if (sum - digits[j - K] + digits[j] != sum):
                flag = 1
                break
        if (flag == 0):
            count += 1
    return count


if __name__ == '__main__':
    N = 2
    K = 1
    print(countDigitSum(N, K))

# Expected output:
9
# array formed using sum of absolute differences of that element with all other elements | function to return the new array private static list < integer > ; length of the arraylist ; initialize the arraylist ; sum of absolute differences of element with all elements ; initialize sum to 0 ; add the value of sum to ans ; return the final ans ; 
def calculate(arr):
    n = len(arr)
    ans = []
    for i in range(n):
        sum = 0
        for j in range(len(arr)):
            sum += abs(arr[i] - arr[j])
        ans .append(sum)
    return ans


if __name__ == '__main__':
    arr = [2, 3, 5, 6]
    print(calculate(arr))

# Expected output:
[8, 6, 6, 8]
# minimum number of distinct powers of 2 required to express a given binary number | function to return the minimum distinct powers of 2 required to express s ; reverse the string to start from lower powers ; check if the character is 1 ; add in range provided range ; initialize the counter ; check if the character is not 0 ; increment the counter ; print the result ; 
def findMinimum(s):
    n = len(s)
    x = [0] * (n + 1)
    s = s[::-1]
    for i in range(n):
        if (s[i] == '1'):
            if (x[i] == 1):
                x[i + 1] = 1
                x[i] = 0
            elif (i and x[i - 1] == 1):
                x[i + 1] = 1
                x[i - 1] = -1
            else:
                x[i] = 1
    c = 0
    for i in range(n + 1):
        if (x[i] != 0):
            c += 1
    print(c)


if __name__ == '__main__':
    str = "111"
    findMinimum(str)

# Expected output:
2
# split a numeric string into fibonacci sequence | python3 program of the above approach ; function that returns true if fibonacci sequence is found ; base condition : if pos is equal to length of s and seq length is greater than 3 ; return true ; stores current number ; add current digit to num ; avoid integer overflow ; avoid leading zeros ; if current number is greater than last two number of seq ; if seq length is less 2 or current number is is equal to the last two of the seq ; add to the seq ; recur for i + 1 ; remove last added number ; if no sequence is found ; function that prints the fibonacci sequence from the split of string s ; initialize a vector to store the sequence ; call helper function ; if sequence length is greater than 3 ; print the sequence ; if no sequence is found ; print - 1 ; 

import sys


def splitIntoFibonacciHelper(pos, S, seq):
    if (pos == len(S) and (len(seq) >= 3)):
        return True
    num = 0
    for i in range(pos, len(S)):
        num = num * 10 + (ord(S[i]) - ord('0'))
        if (num > sys .maxsize):
            break
        if (ord(S[pos]) == ord('0') and i > pos):
            break
        if (len(seq) > 2 and (num > (seq[-1] + seq[len(seq) - 2]))):
            break
        if (len(seq) < 2 or (num == (seq[-1] + seq[len(seq) - 2]))):
            seq .append(num)
            if (splitIntoFibonacciHelper(i + 1, S, seq)):
                return True
            seq .pop()
    return False


def splitIntoFibonacci(S):
    seq = []
    splitIntoFibonacciHelper(0, S, seq)
    if (len(seq) >= 3):
        for i in seq:
            print(i, end=' ')
    else:
        print(-1, end='')


if __name__ == '__main__':
    S = "11235813"
    splitIntoFibonacci(S)

# Expected output:
1 1 2 3 5 8 13
# count pair of strings whose concatenation has every vowel | function to return the count of all concatenated string with each vowel at least once ; creating a hash array with initial value as 0 ; traversing through each string and getting hash value for each of them ; initializing the weight of each string ; find the hash value for each string ; increasing the count of the hash value ; getting all possible pairs of indexes in hash array ; check if the pair which has hash value 31 and multiplying the count of string and add it strcount ; corner case , for strings which independently has all the vowels ; return thre final count ; 
def good_pairs(Str, N):
    arr = [0 for i in range(32)]
    strCount = 0
    for i in range(N):
        Weight = 0
        for j in range(len(Str[i])):
            switcher = {'a': 1, 'e': 2, 'i': 4, 'o': 8, 'u': 16, }
            Weight = Weight | switcher .get(Str[i][j], 0)
        arr[Weight] += 1
    for i in range(32):
        for j in range(i + 1, 32):
            if ((i | j) == 31):
                strCount += arr[i] * arr[j]
    strCount += int((arr[31] * (arr[31] - 1)) / 2)
    return strCount


Str = ["aaweiolkju", "oxdfgujkmi"]
N = len(Str)
print(good_pairs(Str, N))

# Expected output:
1
# color a grid such that all same color cells are connected either horizontally or vertically | python3 program to color a grid such that all same color cells are connected either horizontally or vertically ; current color ; final grid ; if even row ; traverse from left to right ; if color has been exhausted , move to the next color ; color the grid at this position print ( i , j ) ; reduce the color count ; traverse from right to left for odd rows ; print the grid ; 
def solve(arr, r, c):
    idx = 1
    dp = [[0 for i in range(c)]for i in range(r)]
    for i in range(r):
        if (i % 2 == 0):
            for j in range(c):
                if (arr[idx - 1] == 0):
                    idx += 1
                dp[i][j] = idx
                arr[idx - 1] -= 1
        else:
            for j in range(c - 1, -1, -1):
                if (arr[idx - 1] == 0):
                    idx += 1
                dp[i][j] = idx
                arr[idx - 1] -= 1
    for i in range(r):
        for j in range(c):
            print(dp[i][j], end=" ")
        print()


if __name__ == '__main__':
    r = 3
    c = 5
    n = 5
    arr = [1, 2, 3, 4, 5]
    solve(arr, r, c)

# Expected output:
1 2 2 3 3 
4 4 4 4 3 
5 5 5 5 5
# count of 0 s to be flipped to make any two adjacent 1 s at least k 0 s apart | function to find the count of 0 s to be flipped ; loop traversal to mark k adjacent positions to the right of already existing 1 s . ; loop traversal to mark k adjacent positions to the left of already existing 1 s . ; loop to count the maximum number of 0 s that will be replaced by 1 s ; 
def count(k, s):
    ar = [0] * len(s)
    end = 0
    for i in range(len(s)):
        if s[i] == '1':
            for j in range(i, len(s)):
                if (j <= i + k):
                    ar[j] = -1
                    end = j
            i = end
    end = 0
    for i in range(len(s) - 1, -1, -1):
        if (s[i] == '1'):
            for j in range(i, -1, -1):
                if (j >= i - k):
                    ar[j] = -1
                    end = j
            i = end
    ans = 0
    end = 0
    for j in range(len(s)):
        if (ar[j] == 0):
            ans += 1
            for g in range(j, len(s)):
                if (g <= j + k):
                    ar[g] = -1
                    end = g
            j = end - 1
    return ans


K = 2
s = "000000"
print(count(K, s))

# Expected output:
2
# length of longest connected 1 â €™ s in a binary grid | python3 program for the above approach ; keeps a track of directions that is up , down , left , right ; function to perform the dfs traversal ; mark the current node as visited ; increment length from this node ; update the diameter length ; move to next cell in x - direction ; move to next cell in y - direction ; check if cell is invalid then continue ; perform dfs on new cell ; decrement the length ; function to find the maximum length of connected 1 s in the given grid ; increment the id ; traverse the grid [ ] ; find start point of start dfs call ; dfs traversal from cell ( x , y ) ; print the maximum length ; 

row = 6
col = 7
vis = [[0 for i in range(col + 1)]for j in range(row + 1)]
id = 0
diameter = 0
length = 0
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]


def dfs(a, b, lis, x, y):
    global id, length, diameter
    vis[a][b] = id
    length += 1
    if (length > diameter):
        x = a
        y = b
        diameter = length
    for j in range(4):
        cx = a + dx[j]
        cy = b + dy[j]
        if (cx < 0 or cy < 0 or cx >= row or cy >=
                col or lis[cx][cy] == 0 or vis[cx][cy]):
            continue
        dfs(cx, cy, lis, x, y)
    vis[a][b] = 0
    length -= 1
    return x, y


def findMaximumLength(lis):
    global id, length, diameter
    x = 0
    y = 0
    id += 1
    length = 0
    diameter = 0
    for i in range(row):
        for j in range(col):
            if (lis[i][j] != 0):
                x, y = dfs(i, j, lis, x, y)
                i = row
                break
    id += 1
    length = 0
    diameter = 0
    x, y = dfs(x, y, lis, x, y)
    print(diameter)


if __name__ == "__main__":
    grid = [[0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0], [
        0, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 0, 0, 0]]
    findMaximumLength(grid)

# Expected output:
9
# last two digits of powers of 7 | function to find the last two digits of 7 ^ n ; case 4 ; case 3 ; case 2 ; case 1 ; 
def get_last_two_digit(N):
    if (N % 4 == 0):
        return "01"
    elif (N % 4 == 1):
        return "07"
    elif (N % 4 == 2):
        return "49"
    return "43"


N = 12
print(get_last_two_digit(N))

# Expected output:
01
# subsequence with maximum pairwise absolute difference and minimum size | function to find the subsequence with maximum absolute difference ; to store the resultant subsequence ; first element should be included in the subsequence ; traverse the given array arr [ ] ; if current element is greater than the previous element ; if the current element is not the local maxima then continue ; else push it in subsequence ; if the current element is less then the previous element ; if the current element is not the local minima then continue ; else push it in subsequence ; last element should also be included in subsequence ; print the element ; 
def getSubsequence(ar):
    N = len(ar)
    ans = []
    ans .append(ar[0])
    for i in range(1, N - 1):
        if (ar[i] > ar[i - 1]):
            if (i < N - 1 and ar[i] <= ar[i + 1]):
                continue
            else:
                ans .append(ar[i])
        else:
            if (i < N - 1 and ar[i + 1] < ar[i]):
                continue
            else:
                ans .append(ar[i])
    ans .append(ar[N - 1])
    for it in ans:
        print(it, end=" ")


if __name__ == '__main__':
    arr = [1, 2, 4, 3, 5]
    getSubsequence(arr)

# Expected output:
1 4 3 5
# minimum steps to reach n from 1 by multiplying each step by 2 , 3 , 4 or 5 | function to find a minimum number of steps to reach n from 1 ; check until n is greater than 1 and operations can be applied ; condition to choose the operations greedily ; 
def Minsteps(n):
    ans = 0
    while (n > 1):
        if (n % 5 == 0):
            ans = ans + 1
            n = n / 5
            continue
        elif (n % 4 == 0):
            ans = ans + 1
            n = n / 4
            continue
        elif (n % 3 == 0):
            ans = ans + 1
            n = n / 3
            continue
        elif (n % 2 == 0):
            ans = ans + 1
            n = n / 2
            continue
        return -1
    return ans


n = 10
print(Minsteps(n))

# Expected output:
2
# check if the square of a number is divisible by k or not | python3 implementation to check if the square of x is divisible by k ; function to return if square of x is divisible by k ; finding gcd of x and k ; dividing k by their gcd ; check for divisibility of x by reduced k ; 

from math import gcd


def checkDivisible(x, k):
    g = gcd(x, k)
    k //= g
    if (x % k == 0):
        print("YES")
    else:
        print("NO")


if __name__ == '__main__':
    x = 6
    k = 9
    checkDivisible(x, k)

# Expected output:
YES
# find the minimum value of the given expression over all pairs of the array | python3 program to find the minimum value of the given expression over all pairs of the array ; function to find the minimum value of the expression ; the expression simplifies to finding the minimum xor value pair sort given array ; calculate min xor of consecutive pairs ; 

import sys


def MinimumValue(arr, n):
    arr .sort()
    minXor = sys .maxsize
    val = 0
    for i in range(0, n - 1):
        val = arr[i] ^ arr[i + 1]
        minXor = min(minXor, val)
    return minXor


if __name__ == '__main__':
    N = 6
    A = [12, 3, 14, 5, 9, 8]
    print(MinimumValue(A, N))

# Expected output:
1
# find length of longest substring with at most k normal characters | function to find maximum length of normal substrings ; keeps count of normal characters ; indexes of substring ; maintain length of longest substring with at most k normal characters ; get position of character ; check if current character is normal ; check if normal characters count exceeds k ; update answer with substring length ; get position of character ; check if character is normal then decrement count ; 
def maxNormalSubstring(P, Q, K, N):
    if (K == 0):
        return 0
    count = 0
    left, right = 0, 0
    ans = 0
    while (right < N):
        while (right < N and count <= K):
            pos = ord(P[right]) - ord('a')
            if (Q[pos] == '0'):
                if (count + 1 > K):
                    break
                else:
                    count += 1
            right += 1
            if (count <= K):
                ans = max(ans, right - left)
        while (left < right):
            pos = ord(P[left]) - ord('a')
            left += 1
            if (Q[pos] == '0'):
                count -= 1
            if (count < K):
                break
    return ans


if (__name__ == "__main__"):
    P = "giraffe"
    Q = "01111001111111111011111111"
    K = 2
    N = len(P)
    print(maxNormalSubstring(P, Q, K, N))

# Expected output:
3
# make all the elements of array even with given operations | function to count the total number of operations needed to make all array element even ; traverse the given array ; if an odd element occurs then increment that element and next adjacent element by 1 ; traverse the array if any odd element occurs then return - 1 ; returns the count of operations ; 
def countOperations(arr, n):
    count = 0
    for i in range(n - 1):
        if (arr[i] & 1):
            arr[i] += 1
            arr[i + 1] += 1
            count += 2
    for i in range(n):
        if (arr[i] & 1):
            return -1
    return count


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

# Expected output:
4
# count of pairs with difference at most k with no element repeating | function to count the number of pairs whose difference is atmost k in an array ; sorting the array ; variable to store the count of pairs whose difference is atmost k ; loop to consider the consecutive pairs of the array ; if pair found increment the index by 2 ; 
def countPairs(arr, k):
    arr .sort()
    pair = 0
    index = 0
    while (index < len(arr) - 1):
        if arr[index + 1] - arr[index] <= k:
            pair += 1
            index += 2
        else:
            index += 1
    return pair


if __name__ == "__main__":
    arr = [1, 4, 3, 7, 5]
    k = 2
    count = countPairs(arr, k)
    print(count)

# Expected output:
2
# maximum profit by selling n items at two markets | function to calculate max profit ; prefix sum array for profita [ ] ; suffix sum array for profitb [ ] ; if all the items are sold in market a ; find the maximum profit when the first i items are sold in market a and the rest of the items are sold in market b for all possible values of i ; if all the items are sold in market b ; 
def maxProfit(profitA, profitB, n):
    preSum = [0] * n
    preSum[0] = profitA[0]
    for i in range(1, n):
        preSum[i] = preSum[i - 1] + profitA[i]
    suffSum = [0] * n
    suffSum[n - 1] = profitB[n - 1]
    for i in range(n - 2, -1, -1):
        suffSum[i] = suffSum[i + 1] + profitB[i]
    res = preSum[n - 1]
    for i in range(1, n - 1):
        res = max(res, preSum[i] + suffSum[i + 1])
    res = max(res, suffSum[0])
    return res


if __name__ == "__main__":
    profitA = [2, 3, 2]
    profitB = [10, 30, 40]
    n = len(profitA)
    print(maxProfit(profitA, profitB, n))

# Expected output:
80