giulio98/xlcost-single-prompt huggingface dataset:
# maximize sum of count of distinct prime factors of k array elements | python 3 program for the above approach ; function to find the maximum sum of count of distinct prime factors of k array elements ; stores the count of distinct primes ; stores 1 and 0 at prime and non - prime indices respectively ; initialize the count of factors to 0 ; sieve of eratosthenes ; count of factors of a prime number is 1 ; increment countdistinct of all multiples of i ; mark its multiples non - prime ; stores the maximum sum of distinct prime factors of k array elements ; stores the count of all distinct prime factors ; traverse the array to find count of all array elements ; maximum sum of k prime factors of array elements ; check for the largest prime factor ; increment sum ; decrement its count and k ; print the maximum sum ; 

MAX = 1000000


def maxSumOfDistinctPrimeFactors(arr, N, K):
    CountDistinct = [0] * (MAX + 1)
    prime = [False] * (MAX + 1)
    for i in range(MAX + 1):
        CountDistinct[i] = 0
        prime[i] = True
    for i in range(2, MAX + 1):
        if (prime[i]):
            CountDistinct[i] = 1
            for j in range(i * 2, MAX + 1, i):
                CountDistinct[j] += 1
                prime[j] = False
    sum = 0
    PrimeFactor = [0] * 20
    for i in range(N):
        PrimeFactor[CountDistinct[arr[i]]] += 1
    for i in range(19, 0, -1):
        while (PrimeFactor[i] > 0):
            sum += i
            PrimeFactor[i] -= 1
            K -= 1
            if (K == 0):
                break
        if (K == 0):
            break
    print(sum)


if __name__ == "__main__":
    arr = [6, 9, 12]
    N = len(arr)
    K = 2
    maxSumOfDistinctPrimeFactors(arr, N, K)

# Expected output:
4
# minimum replacements such that no palindromic substring of length exceeding 1 is present in the given string | function to count the changes required such that no palindromic subof length exceeding 1 is present in the string ;  ; stores the count ; iterate over the string ; palindromic subof length 2 ; replace the next character ; increment changes ; palindromic subof length 3 ; replace the next character ; increment changes ; 
def maxChange(str):
    str = [i for i in str]
    if (len(str) <= 1):
        return 0
    minChanges = 0
    for i in range(len(str) - 1):
        if (str[i] == str[i + 1]):
            str[i + 1] = 'N'
            minChanges += 1
        elif (i > 0 and str[i - 1] == str[i + 1]):
            str[i + 1] = 'N'
            minChanges += 1
    return minChanges


if __name__ == '__main__':
    str = "bbbbbbb"
    print(maxChange(str))

# Expected output:
4
# smallest positive integer k such that all array elements can be made equal by incrementing or decrementing by at most k | function to find smallest integer k such that incrementing or decrementing each element by k at most once makes all elements equal ; store distinct array elements ; traverse the array , a [ ] ; count elements into the set ; iterator to store first element of b ; if m is greater than 3 ; if m is equal to 3 ; stores the first smallest element ; stores the second smallest element ; stores the largest element ; if difference between b_2 and b_1 is equal to b_3 and b_2 ; if m is equal to 2 ; stores the smallest element ; stores the largest element ; if difference is an even ; if m is equal to 1 ; 
def findMinKToMakeAllEqual(N, A):
    B = {}
    for i in range(N):
        B[A[i]] = 1
    M = len(B)
    itr, i = list(B .keys()), 0
    if (M > 3):
        print("-1")
    elif (M == 3):
        B_1, i = itr[i], i + 1
        B_2, i = itr[i], i + 1
        B_3, i = itr[i], i + 1
        if (B_2 - B_1 == B_3 - B_2):
            print(B_2 - B_1)
        else:
            print("-1")
    elif (M == 2):
        B_1, i = itr[i], i + 1
        B_2, i = itr[i], i + 1
        if ((B_2 - B_1) % 2 == 0):
            print((B_2 - B_1) // 2)
        else:
            print(B_2 - B_1)
    else:
        print(0)


if __name__ == '__main__':
    A = [1, 3, 5, 1]
    N = len(A)
    findMinKToMakeAllEqual(N, A)

# Expected output:
2
# maximum number of times a given string needs to be concatenated to form a substring of another string | function to find lps [ ] for given pattern pat [ 0. . m - 1 ] ; length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; iterate string to calculate lps [ i ] ; if the current character of the pattern matches ; otherwise ; otherwise ; function to implement kmp algorithm ; stores the longest prefix and suffix values for pattern ; preprocess the pattern and find the lps [ ] array ; index for txt [ ] ; index for pat [ ] ; if pattern is found return 1 ; mismatch after j matches ; don 't match lps[0, lps[j - 1]]  characters they will  match anyway ; return 0 if the pattern is not found ; function to find the maximum value k for which s2 concatenated k times is a subof s1 ; store the required maximum number ; create a temporary to store word ; store the maximum number of times s2 can occur in s1 ; traverse in range [ 0 , numwords - 1 ] ; if curword is found in sequence ; concatenate word to curword ; increment rescount by 1 ; otherwise break the loop ; print the answer ; 
def computeLPSArray(pat, M, lps):
    lenn = 0
    lps[0] = 0
    i = 1
    while (i < M):
        if (pat[i] == pat[lenn]):
            lenn += 1
            lps[i] = lenn
            i += 1
        else:
            if (lenn != 0):
                lenn = lps[lenn - 1]
            else:
                lps[i] = 0
                i += 1


def KMPSearch(pat, txt):
    M = len(pat)
    N = len(txt)
    lps = [0 for i in range(M)]
    computeLPSArray(pat, M, lps)
    i = 0
    j = 0
    while (i < N):
        if (pat[j] == txt[i]):
            j += 1
            i += 1
        if (j == M):
            return 1
            j = lps[j - 1]
        elif (i < N and pat[j] != txt[i]):
            if (j != 0):
                j = lps[j - 1]
            else:
                i = i + 1
    return 0


def maxRepeating(seq, word):
    resCount = 0
    curWord = word
    numWords = len(seq) // len(word)
    for i in range(numWords):
        if (KMPSearch(curWord, seq)):
            curWord += word
            resCount += 1
        else:
            break
    print(resCount)


if __name__ == '__main__':
    S1, S2 = "ababc", "ab"
    maxRepeating(S1, S2)

# Expected output:
2
# count all possible strings that can be generated by placing spaces | function to count the number of strings that can be generated by placing spaces between pair of adjacent characters ; length of the string ; count of positions for spaces ; count of possible strings ; 
def countNumberOfStrings(s):
    length = len(s)
    n = length - 1
    count = 2 ** n
    return count


if __name__ == "__main__":
    S = "ABCD"
    print(countNumberOfStrings(S))

# Expected output:
8
# minimum time required to reach a given score | function to calculate minimum time required to achieve given score target ; store the frequency of elements ; traverse the array p [ ] ; update the frequency ; stores the minimim time required ; store the current score at any time instant t ; iterate until sum is at least equal to target ; increment time with every iteration ; traverse the map ; increment the points ; prthe time required ; 
def findMinimumTime(p, n, target):
    um = {}
    for i in range(n):
        um[p[i]] = um .get(p[i], 0) + 1
    time = 0
    sum = 0
    while (sum < target):
        sum = 0
        time += 1
        for it in um:
            sum += um[it] * (time // it)
    print(time)


if __name__ == '__main__':
    arr = [1, 3, 3, 4]
    N = len(arr)
    target = 10
    findMinimumTime(arr, N, target)

# Expected output:
6
# construct mex array from the given array | python3 program for the above approach ; function to construct array b [ ] that stores mex of array a [ ] excluding a [ i ] ; stores elements present in arr [ ] ; mark all values 1 , if present ; initialize variable to store mex ; find mex of arr [ ] ; stores mex for all indices ; traverse the given array ; update mex ; mex default ; prthe array b ; 

MAXN = 100001


def constructMEX(arr, N):
    hash = [0] * MAXN
    for i in range(N):
        hash[arr[i]] = 1
    MexOfArr = 0
    for i in range(1, MAXN):
        if (hash[i] == 0):
            MexOfArr = i
            break
    B = [0] * N
    for i in range(N):
        if (arr[i] < MexOfArr):
            B[i] = arr[i]
        else:
            B[i] = MexOfArr
    for i in range(N):
        print(B[i], end=" ")


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

# Expected output:
2 1 4 3
# minimize remaining array element by repeatedly replacing pairs by half of one more than their sum | function to print smallest element left in the array and the pairs by given operation ; stores array elements and return the minimum element of arr [ ] in o ( 1 ) ; stores all the pairs that can be selected by the given operations ; traverse the array arr [ ] ; traverse pq while count of elements left in pq greater than 1 ; stores top element of pq ; pop top element of pq ; stores top element of pq ; pop top element of pq ; insert ( x + y + 1 ) / 2 in pq ; insert the pair ( x , y ) in pairsarr [ ] ; print element left in pq by performing the given operations ; stores count of elements in pairsarr [ ] ; print the pairs that can be selected in given operations ; if i is the first index of pairsarr [ ] ; print pairs of pairsarr [ ] ; if i is not the last index of pairsarr [ ] ; if i is the last index of pairsarr [ ] ; 
def smallestNumberLeftInPQ(arr, N):
    pq = []
    pairsArr = []
    for i in range(N):
        pq .append(arr[i])
    pq = sorted(pq)
    while (len(pq) > 1):
        X = pq[-1]
        del pq[-1]
        Y = pq[-1]
        del pq[-1]
        pq .append((X + Y + 1) // 2)
        pairsArr .append([X, Y])
        pq = sorted(pq)
    print("{", pq[-1], "}, ", end="")
    sz = len(pairsArr)
    for i in range(sz):
        if (i == 0):
            print("{ ", end="")
        print("(", pairsArr[i][0], ",", pairsArr[i][1], ")", end="")
        if (i != sz - 1):
            print(end=", ")
        if (i == sz - 1):
            print(end=" }")


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

# Expected output:
{ 2 }, { ( 3 , 2 ), ( 3 , 1 ) }
# move weighting scale alternate under given constraints | dfs method to traverse among states of weighting scales ; if we reach to more than required steps , return true ; try all possible weights and choose one which returns 1 afterwards ; try this weight only if it is greater than current residueand not same as previous chosen weight ; assign this weight to array and recur for next state ; if any weight is not possible , return false ; method prints weights for alternating scale and if not possible prints ' not ▁ possible ' ; call dfs with current residue as 0 and current steps as 0 ; 
def dfs(residue, curStep, wt, arr, N, steps):
    if (curStep >= steps):
        return True
    for i in range(N):
        if (arr[i] > residue and arr[i] != wt[curStep - 1]):
            wt[curStep] = arr[i]
            if (dfs(arr[i] - residue, curStep + 1, wt, arr, N, steps)):
                return True
    return False


def printWeightsOnScale(arr, N, steps):
    wt = [0] * (steps)
    if (dfs(0, 0, wt, arr, N, steps)):
        for i in range(steps):
            print(wt[i], end=" ")
    else:
        print("Not possible")


if __name__ == '__main__':
    arr = [2, 3, 5, 6]
    N = len(arr)
    steps = 10
    printWeightsOnScale(arr, N, steps)

# Expected output:
2 3 2 3 5 6 5 3 2 3
# minimum removals required such that sum of remaining array modulo m is x | python3 program for the above approach ; function to find the minimum elements having sum x ; initialize dp table ; pre - compute subproblems ; if mod is smaller than element ; minimum elements with sum j upto index i ; return answer ; function to find minimum number of removals to make sum % m in remaining array is equal to x ; sum of all elements ; sum to be removed ; print answer ; 

import sys


def findSum(S, n, x):
    table = [[0 for x in range(x + 1)]for y in range(n + 1)]
    for i in range(1, x + 1):
        table[0][i] = sys .maxsize - 1
    for i in range(1, n + 1):
        for j in range(1, x + 1):
            if (S[i - 1] > j):
                table[i][j] = table[i - 1][j]
            else:
                table[i][j] = min(table[i - 1][j], table[i][j - S[i - 1]] + 1)
    if (table[n][x] > n):
        return -1
    return table[n][x]


def minRemovals(arr, n, m, x):
    sum = 0
    for i in range(n):
        sum += arr[i]
    requied_Sum = 0
    if (sum % m < x):
        requied_Sum = m + sum % m - x
    else:
        requied_Sum = sum % m - x
    print(findSum(arr, n, requied_Sum))


if __name__ == "__main__":
    arr = [3, 2, 1, 2]
    n = len(arr)
    m = 4
    x = 2
    minRemovals(arr, n, m, x % m)

# Expected output:
1
# count minimum character replacements required such that given string satisfies the given conditions | function that finds the minimum count of steps required to make the string special ; stores the frequency of the left & right half of string ; find frequency of left half ; find frequency of left half ; make all characters equal to character c ; case 1 : for s [ i ] < s [ j ] ; subtract all the characters on left side that are <= d ; adding all characters on the right side that same as d ; find minimum value of count ; similarly for case 2 : s [ i ] > s [ j ] ; return the minimum changes ; 
def minChange(s, n):
    L = [0] * 26
    R = [0] * 26
    for i in range(0, n // 2):
        ch = s[i]
        L[ord(ch) - ord('a')] += 1
    for i in range(n // 2, n):
        ch = s[i]
        R[ord(ch) - ord('a')] += 1
    count = n
    for ch in range(ord('a'), ord('z')):
        count = min(count, n - L[ch - ord('a')] - R[ch - ord('a')])
    change = n / 2
    for d in range(0, 25):
        change -= L[d]
        change += R[d]
        count = min(count, change)
    change = n / 2
    for d in range(0, 25):
        change -= R[d]
        change += L[d]
        count = min(change, count)
    return int(count)


if __name__ == '__main__':
    S = "aababc"
    N = len(S)
    print(minChange(S, N))

# Expected output:
2
# rearrange string to obtain longest palindromic substring | function to rearrange the string to get the longest palindromic substring ; stores the length of str ; store the count of occurrence of each character ; traverse the string , str ; count occurrence of each character ; store the left half of the longest palindromic substring ; store the right half of the longest palindromic substring ; traverse the array , hash [ ] ; append half of the characters to res1 ; append half of the characters to res2 ; reverse string res2 to make res1 + res2 palindrome ; store the remaining characters ; check if any odd character appended to the middle of the resultant string or not ; append all the character which occurs odd number of times ; if count of occurrence of characters is odd ; 
def longestPalinSub(st):
    N = len(st)
    hash1 = [0] * 256
    for i in range(N):
        hash1[ord(st[i])] += 1
    res1 = ""
    res2 = ""
    for i in range(256):
        for j in range(hash1[i] // 2):
            res1 += chr(i)
        for j in range((hash1[i] + 1) // 2, hash1[i]):
            res2 += chr(i)
    p = list(res2)
    p .reverse()
    res2 = ''.join(p)
    res3 = ""
    f = False
    for i in range(256):
        if (hash1[i] % 2):
            if (not f):
                res1 += chr(i)
                f = True
            else:
                res3 += chr(i)
    return (res1 + res2 + res3)


if __name__ == "__main__":
    st = "geeksforgeeks"
    print(longestPalinSub(st))

# Expected output:
eegksfskgeeor
# maximize subsequences having array elements not exceeding length of the subsequence | python3 program for the above approach ; function to calculate the number of subsequences that can be formed ; stores the number of subsequences ; iterate over the map ; count the number of subsequences that can be formed from x . first ; number of occurrences of x . first which are left ; return the number of subsequences ; function to create the maximum count of subsequences that can be formed ; stores the frequency of arr [ ] ; update the frequency ; print the number of subsequences ; 

from collections import defaultdict


def No_Of_subsequences(mp):
    count = 0
    left = 0
    for x in mp:
        mp[x] += left
        count += (mp[x] // x)
        left = mp[x] % x
    return count


def maximumsubsequences(arr, n):
    mp = defaultdict(int)
    for i in range(n):
        mp[arr[i]] += 1
    print(No_Of_subsequences(mp))


if __name__ == "__main__":
    arr = [1, 1, 1, 1]
    N = len(arr)
    maximumsubsequences(arr, N)

# Expected output:
4
# check if concatenation of any permutation of given list of arrays generates the given array | python3 program for the above approach ; function to check if it is possible to obtain array by concatenating the arrays in list pieces [ ] ; stores the index of element in the given array arr [ ] ; traverse over the list pieces ; if item size is 1 and exists in map ; if item contains > 1 element then check order of element ; if end of the array ; check the order of elements ; if order is same as the array elements ; increment idx ; if order breaks ; otherwise ; return false if the first element doesn 't exist in m ; return true ; 

from array import *


def check(arr, pieces):
    m = {}
    for i in range(0, len(arr)):
        m[arr[i]] = i + 1
    for i in range(0, len(pieces)):
        if (len(pieces[i]) == 1 and m[pieces[i][0]] != 0):
            continue
        elif (len(pieces[i]) > 1 and m[pieces[i][0]] != 0):
            idx = m[pieces[i][0]] - 1
            idx = idx + 1
            if idx >= len(arr):
                return False
            for j in range(1, len(pieces[i])):
                if arr[idx] == pieces[i][j]:
                    idx = idx + 1
                    if (idx >= len(arr) and j < len(pieces[i]) - 1):
                        return False
                else:
                    return False
        else:
            return False
    return True


if __name__ == "__main__":
    arr = [1, 2, 4, 3]
    pieces = [[1], [4, 3], [2]]
    if check(arr, pieces):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# modify given array to make sum of odd and even indexed elements same | function to modify array to make sum of odd and even indexed elements equal ; stores the count of 0 s , 1 s ; stores sum of odd and even indexed elements respectively ; count 0 s ; count 1 s ; calculate odd_sum and even_sum ; if both are equal ; print the original array ; otherwise ; print all the 0 s ; for checking even or odd ; update total count of 1 s ; print all 1 s ; 
def makeArraySumEqual(a, N):
    count_0 = 0
    count_1 = 0
    odd_sum = 0
    even_sum = 0
    for i in range(N):
        if (a[i] == 0):
            count_0 += 1
        else:
            count_1 += 1
        if ((i + 1) % 2 == 0):
            even_sum += a[i]
        elif ((i + 1) % 2 > 0):
            odd_sum += a[i]
    if (odd_sum == even_sum):
        for i in range(N):
            print(a[i], end=" ")
    else:
        if (count_0 >= N / 2):
            for i in range(count_0):
                print("0", end=" ")
        else:
            is_Odd = count_1 % 2
            count_1 -= is_Odd
            for i in range(count_1):
                print("1", end=" ")


arr = [1, 1, 1, 0]
N = len(arr)
makeArraySumEqual(arr, N)

# Expected output:
1 1
# minimum replacement of pairs by their lcm required to reduce given array to its lcm | python3 program for the above approach ; boolean array to set or unset prime non - prime indices ; stores the prefix sum of the count of prime numbers ; function to check if a number is prime or not from 0 to n ; if p is a prime ; set its multiples as non - prime ; function to store the count of prime numbers ; function to count the operations to reduce the array to one element by replacing each pair with its lcm ; generating prime number ; corner case ; 

maxm = 10001
prime = [True] * (maxm + 1)
prime_number = [0] * (maxm + 1)


def SieveOfEratosthenes():
    for p in range(2, (int(maxm ** 1 / 2))):
        if (prime[p]):
            for i in range(p * p, maxm, p):
                prime[i] = False
    prime[0] = False
    prime[1] = False


def num_prime():
    prime_number[0] = 0
    for i in range(1, maxm + 1):
        tmp = -1
        if (prime[i]):
            tmp = 1
        else:
            tmp = 0
        prime_number[i] = prime_number[i - 1] + tmp


def min_steps(arr, n):
    SieveOfEratosthenes()
    num_prime()
    if (n == 1):
        print("0")
    elif (n == 2):
        print("1")
    else:
        print(prime_number[n] - 1 + (n - 2))


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

# Expected output:
5
# find the winner of a game of removing any number of stones from the least indexed non | function to find the winner of game between a and b ; win = 1 means b is winner win = 0 means a is winner ; if size is even , winner is b ; if size is odd , winner is a ; stone will be removed by b ; b will take n - 1 stones from current pile having n stones and force a to pick 1 stone ; stone will be removed by a ; a will take n - 1 stones from current pile having n stones and force b to pick 1 stone ; print the winner accordingly ; 
def findWinner(a, n):
    win = 0
    if (n % 2 == 0):
        win = 1
    else:
        win = 0
    for i in range(n - 2, -1, -1):
        if (i % 2 == 1):
            if (win == 0 and a[i] > 1):
                win = 1
        else:
            if (win == 1 and a[i] > 1):
                win = 0
    if (win == 0):
        print("A")
    else:
        print("B")


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

# Expected output:
B
# check if a destination is reachable from source with two movements allowed | set 2 | check if ( x2 , y2 ) can be reached from ( x1 , y1 ) ; reduce x2 by y2 until it is less than or equal to x1 ; reduce y2 by x2 until it is less than or equal to y1 ; if x2 is reduced to x1 ; check if y2 can be reduced to y1 or not ; if y2 is reduced to y1 ; check if x2 can be reduced to x1 or not ; 
def isReachable(x1, y1, x2, y2):
    while (x2 > x1 and y2 > y1):
        if (x2 > y2):
            x2 %= y2
        else:
            y2 %= x2
    if (x2 == x1):
        return (y2 - y1) >= 0 and (y2 - y1) % x1 == 0
    elif (y2 == y1):
        return (x2 - x1) >= 0 and (x2 - x1) % y1 == 0
    else:
        return 0


source_x = 2
source_y = 10
dest_x = 26
dest_y = 12
if (isReachable(source_x, source_y, dest_x, dest_y)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# find the player who wins the game by removing the last of given n cards | function to check which player can win the game ; 
def checkWinner(N, K):
    if (N % (K + 1)):
        print("A")
    else:
        print("B")


N = 50
K = 10
checkWinner(N, K)

# Expected output:
A