giulio98/xlcost-single-prompt huggingface dataset:
# find the winner of the game of removing odd or replacing even array elements | function to evaluate the winner of the game ; stores count of odd array elements ; stores count of even array elements ; traverse the array ; if array element is odd ; otherwise ; if count of even is zero ; if count of odd is even ; if count of odd is odd ; if count of odd is odd and count of even is one ; otherwise ; 
def findWinner(arr, N):
    odd = 0
    even = 0
    for i in range(N):
        if (arr[i] % 2 == 1):
            odd += 1
        else:
            even += 1
    if (even == 0):
        if (odd % 2 == 0):
            print("Player 2")
        elif (odd % 2 == 1):
            print("Player 1")
    elif (even == 1 and odd % 2 == 1):
        print("Player 1")
    else:
        print(-1)


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

# Expected output:
Player 2
# rearrange array to maximize count of local minima | function to rearrange array elements to maximize count of local minima in the array ; sort the array in ascending order ; stores index of left pointer ; stores index of right pointer ; traverse the array elements ; if right is less than n ; print array element ; update right ; print array element ; update left ; 
def rearrangeArrMaxcntMinima(arr, N):
    arr .sort()
    left = 0
    right = N // 2
    while (left < N // 2 or right < N):
        if (right < N):
            print(arr[right], end=" ")
            right += 1
        if (left < N // 2):
            print(arr[left], end=" ")
            left += 1


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

# Expected output:
3 1 4 2 5
# minimum jumps required to make a group of persons sit together | python3 program for the above approach ; function to find the minimum jumps required to make the whole group sit adjacently ; store the indexes ; stores the count of occupants ; length of the string ; traverse the seats ; if current place is occupied ; push the current position in the vector ; base case : ; the index of the median element ; the value of the median element ; traverse the position [ ] ; update the ans ; return the final count ; 

MOD = 10 ** 9 + 7


def minJumps(seats):
    position = []
    count = 0
    lenn = len(seats)
    for i in range(lenn):
        if (seats[i] == 'x'):
            position .append(i - count)
            count += 1
    if (count == lenn or count == 0):
        return 0
    med_index = (count - 1) // 2
    med_val = position[med_index]
    ans = 0
    for i in range(len(position)):
        ans = (ans % MOD + abs(position[i] - med_val) % MOD) % MOD
    return ans % MOD


if __name__ == '__main__':
    S = "....x..xx...x.."
    print(minJumps(S))

# Expected output:
5
# count pairs whose product contains single distinct prime factor | function to find a single distinct prime factor of n ; stores distinct prime factors of n ; calculate prime factor of n ; calculate distinct prime factor ; insert i into disprimefact ; update n ; if n is not equal to 1 ; insert n into disprimefact ; if n contains a single distinct prime factor ; return single distinct prime factor of n ; if n contains more than one distinct prime factor ; function to count pairs in the array whose product contains only single distinct prime factor ; stores count of 1 s in the array ; mp [ i ] : stores count of array elements whose distinct prime factor is only i ; traverse the array arr [ ] ; if current element is 1 ; store distinct prime factor of arr [ i ] ; if arr [ i ] contains more than one prime factor ; if arr [ i ] contains a single prime factor ; stores the count of pairs whose product of elements contains only a single distinct prime factor ; traverse the map mp [ ] ; stores count of array elements whose prime factor is ( it . first ) ; update res ; 
def singlePrimeFactor(N):
    disPrimeFact = {}
    for i in range(2, N + 1):
        if i * i > N:
            break
        while (N % i == 0):
            disPrimeFact[i] = 1
            N //= i
    if (N != 1):
        disPrimeFact[N] = 1
    if (len(disPrimeFact) == 1):
        return list(disPrimeFact .keys())[0]
    return -1


def cntsingleFactorPair(arr, N):
    countOf1 = 0
    mp = {}
    for i in range(N):
        if (arr[i] == 1):
            countOf1 += 1
            continue
        factorValue = singlePrimeFactor(arr[i])
        if (factorValue == -1):
            continue
        else:
            mp[factorValue] = mp .get(factorValue, 0) + 1
    res = 0
    for it in mp:
        X = mp[it]
        res += countOf1 * X + (X * (X - 1)) // 2
    return res


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

# Expected output:
4
# minimize replacements or swapping of same indexed characters required to make two given strings palindromic | function to find minimum operations to make both the strings palindromic ; stores index of the left pointer ; stores index of the right pointer ; stores count of minimum operations to make both the strings palindromic ; if str1 [ i ] equal to str1 [ j ] and str2 [ i ] not equal to str2 [ j ] ; update cntop ; if str1 [ i ] not equal to str1 [ j ] and str2 [ i ] equal to str2 [ j ] ; update cntop ; if str1 [ i ] is not equal to str1 [ j ] and str2 [ i ] is not equal to str2 [ j ] ; if str1 [ i ] is equal to str2 [ j ] and str2 [ i ] is equal to str1 [ j ] ; update cntop ; update cntop ; update i and j ; 
def MincntBothPalin(str1, str2, N):
    i = 0
    j = N - 1
    cntOp = 0
    while (i < j):
        if (str1[i] == str1[j] and str2[i] != str2[j]):
            cntOp += 1
        elif (str1[i] != str1[j] and str2[i] == str2[j]):
            cntOp += 1
        elif (str1[i] != str1[j] and str2[i] != str2[j]):
            if (str1[i] == str2[j] and str2[i] == str1[j]):
                cntOp += 1
            else:
                cntOp += 2
        i += 1
        j -= 1
    return cntOp


if __name__ == "__main__":
    str1 = "dbba"
    str2 = "abcd"
    N = len(str1)
    print(MincntBothPalin(str1, str2, N))

# Expected output:
2
# find an integral solution of the non | python3 program to implement the above approach ; function to find the value of power ( x , n ) ; stores the value of ( x ^ n ) ; calculate the value of power ( x , n ) ; if n is odd ; update res ; update x ; update n ; function to find the value of x and y that satisfy the condition ; base case ; stores maximum possible of x ; update xmax ; stores maximum possible of y ; update ymax ; iterate over all possible values of x ; iterate over all possible values of y ; stores value of 2 ^ i ; stores value of 5 ^ j ; if the pair ( i , j ) satisfy the equation ; if no solution exists ; 

from math import log2


def power(x, N):
    res = 1
    while (N > 0):
        if (N & 1):
            res = (res * x)
        x = (x * x)
        N = N >> 1

    return res


def findValX_Y(N):
    if (N <= 1):
        print(-1)
        return
    xMax = 0
    xMax = int(log2(N))
    yMax = 0
    yMax = int(log2(N) / log2(5.0))
    for i in range(1, xMax + 1):
        for j in range(1, yMax + 1):
            a = power(2, i)
            b = power(5, j)
            if (a + b == N):
                print(i, j)
                return
    print(-1)


if __name__ == '__main__':
    N = 129
    findValX_Y(N)

# Expected output:
2 3
# count pairs from two arrays with difference exceeding k | set 2 | python3 program for the above approach ; function to count pairs that satisfy the given conditions ; stores the count of pairs ; if v1 [ ] is smaller than v2 [ ] ; sort the array v1 [ ] ; traverse the array v2 [ ] ; returns the address of the first number which is >= v2 [ j ] - k ; increase the count by all numbers less than v2 [ j ] - k ; otherwise ; sort the array v2 [ ] ; traverse the array v1 [ ] ; returns the address of the first number which is > v1 [ i ] + k ; increase the count by all numbers greater than v1 [ i ] + k ; return the total count of pairs ; 

from bisect import bisect_left, bisect_right


def countPairs(v1, v2, n, m, k):
    count = 0
    if (n <= m):
        v1 = sorted(v1)
        for j in range(m):
            index = bisect_left(v1, v2[j] - k)
            count += index
    else:
        v2 = sorted(v2)
        for i in range(n):
            index = bisect_right(v2, v1[i] + k)
            count += m - index
    return count


if __name__ == '__main__':
    arr = [5, 9, 1, 8]
    brr = [10, 12, 7, 4, 2, 3]
    K = 3
    N = len(arr)
    M = len(brr)
    print(countPairs(arr, brr, N, M, K))

# Expected output:
6
# maximum sum subarray of size k with sum less than x | function to calculate maximum sum among all subarrays of size k with the sum less than x ; initialize sum_k to 0 ; calculate sum of first k elements ; if sum_k is less than x ; initialize maxsum with sum_k ; iterate over the array from ( k + 1 ) - th index ; subtract the first element from the previous k elements and add the next element ; if sum_k is less than x ; update the max_sum ; 
def maxSumSubarr(A, N, K, X):
    sum_K = 0
    for i in range(0, K):
        sum_K += A[i]
    Max_Sum = 0
    if (sum_K < X):
        Max_Sum = sum_K
    for i in range(K, N):
        sum_K -= (A[i - K] - A[i])
        if (sum_K < X):
            Max_Sum = max(Max_Sum, sum_K)
    print(Max_Sum)


arr = [-5, 8, 7, 2, 10, 1, 20, -4, 6, 9]
K = 5
X = 30
N = len(arr)
maxSumSubarr(arr, N, K, X)

# Expected output:
29
# rearrange array to make sum of all subarrays starting from first index non | function to rearrange the array such that sum of all elements of subarrays from the 1 st index is non - zero ; initialize sum of subarrays ; sum of all elements of array ; if sum is 0 , the required array could never be formed ; if sum is non zero , array might be formed ; sort array in ascending order ; when current subarray sum becomes 0 replace it with the largest element ; swap operation ; if largest element is same as element to be replaced , then rearrangement impossible ; if b = 1 , then rearrangement is not possible . hence check with reverse configuration ; sort array in descending order ; when current subarray sum becomes 0 replace it with the smallest element ; swap operation ; if smallest element is same as element to be replaced , then rearrangement impossible ; if neither of the configurations worked then pr " - 1" ; otherwise , print the formed rearrangement ; 
def rearrangeArray(a, N):
    sum = 0
    for i in range(N):
        sum += a[i]
    if (sum == 0):
        print("-1")
        return
    sum = 0
    b = 0
    a = sorted(a)
    for i in range(N):
        sum += a[i]
        if (sum == 0):
            if (a[i] != a[N - 1]):
                sum -= a[i]
                a[i], a[N - 1] = a[N - 1], a[i]
                sum += a[i]
            else:
                b = 1
                break
    if (b == 1):
        b = 0
        sum = 0
        a = sorted(a)
        a = a[::-1]
        for i in range(N - 1, -1, -1):
            sum += a[i]
            if (sum == 0):
                if (a[i] != a[0]):
                    sum -= a[i]
                    a[i], a[0] = a[0], a[i]
                    sum += a[i]
                else:
                    b = 1
                    break
    if (b == 1):
        print("-1")
        return
    for i in range(N):
        print(a[i], end=" ")


if __name__ == '__main__':
    arr = [1, -1, 2, 4, 0]
    N = len(arr)
    rearrangeArray(arr, N)

# Expected output:
-1 0 4 2 1
# length of smallest subarray to be removed to make sum of remaining elements divisible by k | python3 program for the above approach ; function to find the length of the smallest subarray to be removed such that sum of elements is divisible by k ; stores the remainder of each arr [ i ] when divided by k ; stores total sum of elements ; k has been added to each arr [ i ] to handle - ve integers ; update the total sum ; remainder when total_sum is divided by k ; if given array is already divisible by k ; stores curr_remainder and the most recent index at which curr_remainder has occurred ; stores required answer ; add current element to curr_sum and take mod ; update current remainder index ; if mod already exists in map the subarray exists ; if not possible ; print the result ; given array arr [ ] ; size of array ; 

import sys


def removeSmallestSubarray(arr, n, k):
    mod_arr = [0] * n
    total_sum = 0
    for i in range(n):
        mod_arr[i] = (arr[i] + k) % k
        total_sum += arr[i]
    target_remainder = total_sum % k
    if (target_remainder == 0):
        print("0")
        return
    map1 = {}
    map1[0] = -1
    curr_remainder = 0
    res = sys .maxsize
    for i in range(n):
        curr_remainder = (curr_remainder + arr[i] + k) % k
        map1[curr_remainder] = i
        mod = (curr_remainder - target_remainder + k) % k
        if (mod in map1 .keys()):
            res = min(res, i - map1[mod])
    if (res == sys .maxsize or res == n):
        res = -1
    print(res)


arr = [3, 1, 4, 2]
N = len(arr)
K = 6
removeSmallestSubarray(arr, N, K)

# Expected output:
1
# queries to flip characters of a binary string in given range | function to find the binary by performing all the given queries ; stores length of the string ; prefixcnt [ i ] : stores number of times strr [ i ] toggled by performing all the queries ; update prefixcnt [ q [ i ] [ 0 ] ] ; update prefixcnt [ q [ i ] [ 1 ] + 1 ] ; calculate prefix sum of prefixcnt [ i ] ; traverse prefixcnt [ ] array ; if ith element toggled odd number of times ; toggled i - th element of binary string ; 
def toggleQuery(strr, Q, M):
    strr = [i for i in strr]
    N = len(strr)
    prefixCnt = [0] * (N + 1)
    for i in range(M):
        prefixCnt[Q[i][0]] += 1
        prefixCnt[Q[i][1] + 1] -= 1
    for i in range(1, N + 1):
        prefixCnt[i] += prefixCnt[i - 1]
    for i in range(N):
        if (prefixCnt[i] % 2):
            strr[i] = (chr(ord('1') - ord(strr[i]) + ord('0')))
    return "".join(strr)


if __name__ == '__main__':
    strr = "101010"
    Q = [[0, 1], [2, 5], [2, 3], [1, 4], [0, 5]]
    M = len(Q)
    print(toggleQuery(strr, Q, M))

# Expected output:
111000
# maximum length possible by cutting n given woods into at least k pieces | function to check if it is possible to cut woods into k pieces of length len ; stores count of pieces having length equal to k ; traverse wood [ ] array ; update count ; function to find the maximum value of l ; stores minimum possible of l ; stores maximum possible value of l ; apply binary search over the range [ left , right ] ; stores mid value of left and right ; if it is possible to cut woods into k pieces having length of each piece equal to mid ; update left ; update right ; 
def isValid(wood, N, len, K):
    count = 0
    for i in range(N):
        count += wood[i] // len
    return (count >= K)


def findMaxLen(wood, N, K):
    left = 1
    right = max(wood)
    while (left <= right):
        mid = left + (right - left) // 2
        if (isValid(wood, N, mid, K)):
            left = mid + 1
        else:
            right = mid - 1
    return right


if __name__ == '__main__':
    wood = [5, 9, 7]
    N = len(wood)
    K = 4
    print(findMaxLen(wood, N, K))

# Expected output:
4
# count quadruplets with sum k from given array | function to return the number of quadruplets with the given sum ; initialize answer ; all possible first elements ; all possible second elements ; all possible third elements ; all possible fourth elements ; increment counter by 1 if quadruplet sum is s ; return the final count ; 
def countSum(a, n, sum):
    count = 0
    for i in range(n - 3):
        for j in range(i + 1, n - 2):
            for k in range(j + 1, n - 1):
                for l in range(k + 1, n):
                    if (a[i] + a[j] + a[k] + a[l] == sum):
                        count += 1
    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
# minimum adjacent swaps to group similar characters together | function to find minimum adjacent swaps required to make all the same character adjacent ; initialize answer ; create a 2d array of size 26 ; traverse the string ; get character ; append the current index in the corresponding vector ; traverse each character from a to z ; add difference of adjacent index ; return answer ; 
def minSwaps(S, n):
    swaps = 0
    arr = [[]for i in range(26)]
    for i in range(n):
        pos = ord(S[i]) - ord('a')
        arr[pos].append(i)
    for ch in range(ord('a'), ord('z') + 1):
        pos = ch - ord('a')
        for i in range(1, len(arr[pos])):
            swaps += abs(arr[pos][i] - arr[pos][i - 1] - 1)
    return swaps


if __name__ == '__main__':
    S = "abbccabbcc"
    N = len(S)
    print(minSwaps(S, N))

# Expected output:
10
# construct a graph which does not contain any pair of adjacent nodes with same value | function that prints the edges of the generated graph ; first print connections stored in store [ ] ; check if there is more than one occurrence of 1 st unique element ; print all other occurrence of 1 st unique element with second unique element ; function to construct the graph such that the every adjacent nodes have different value ; stores pair of edges formed ; stores first unique occurrence ; check for the second unique occurrence ; store indices of 2 nd unique occurrence ; to check if arr has only 1 unique element or not ; store the connections of all unique elements with node 1 ; if value at node ( i + 1 ) is same as value at node 1 then store its indices ; if count is zero then it 's not  possible to construct the graph ; if more than 1 unique element is present ; print the edges ; 
def printConnections(store, ind, ind1):
    for pr in store:
        print(pr[0], pr[1])
    if (len(ind) != 0):
        for x in ind:
            print(ind1, x + 1)


def constructGraph(arr, N):
    ind = []
    store = []
    x = arr[0]
    count, ind1 = 0, 0
    for i in range(1, N):
        if (arr[i] != x):
            ind1 = i + 1
            count += 1
            store .append([1, i + 1])
        else:
            ind .append(i)
    if count == 0:
        print("Not Possible")
    else:
        print("Possible")
        printConnections(store, ind, ind1)


if __name__ == '__main__':
    N = 5
    arr = ['a', 'b', 'a', 'b', 'c']
    constructGraph(arr, N)

# Expected output:
Possible
1 2
1 4
1 5
5 3
# minimum substring flips required to convert given binary string to another | function that finds the minimum number of operations required such that string a and b are the same ; stores the count of steps ; stores the last index whose bits are not same ; iterate until both string are unequal ; check till end of string to find rightmost unequals bit ; update the last index ; flipping characters up to the last index ; flip the bit ; increasing steps by one ; print the count of steps ; 
def findMinimumOperations(a, b):
    step = 0
    last_index = 0
    while (a != b):
        a = [i for i in a]
        for i in range(len(a)):
            if (a[i] != b[i]):
                last_index = i
        for i in range(last_index + 1):
            if (a[i] == '0'):
                a[i] = '1'
            else:
                a[i] = '0'
        a = "".join(a)
        step += 1
    print(step)


if __name__ == '__main__':
    A = "101010"
    B = "110011"
    findMinimumOperations(A, B)

# Expected output:
4
# count all disjoint pairs having absolute difference at least k from a given array | function to check if it is possible to form m pairs with abs diff at least k ; traverse the array over [ 0 , m ] ; if valid index ; return 1 ; function to count distinct pairs with absolute difference atleasr k ; stores the count of all possible pairs ; initialize left and right ; sort the array ; perform binary search ; find the value of mid ; check valid index ; update ans ; print the answer ; 
def isValid(arr, n, m, d):
    for i in range(m):
        if (abs(arr[n - m + i] - arr[i]) < d):
            return 0
    return 1


def countPairs(arr, N, K):
    ans = 0
    left = 0
    right = N // 2 + 1
    arr .sort(reverse=False)
    while (left < right):
        mid = (left + right) // 2
        if (isValid(arr, N, mid, K)):
            ans = mid
            left = mid + 1
        else:
            right = mid - 1
    print(ans, end="")


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

# Expected output:
2
# minimum common element in subarrays of all possible lengths | function to find maximum distance between every two element ; stores index of last occurence of each array element ; initialize temp [ ] with - 1 ; traverse the array ; if array element has not occurred previously ; update index in temp ; otherwise ; compare temp [ a [ i ] ] with distance from its previous occurence and store the maximum ; compare temp [ i ] with distance of its last occurence from the end of the array and store the maximum ; function to find the minimum common element in subarrays of all possible lengths ; function call to find a the maximum distance between every pair of repetition ; initialize ans [ ] to - 1 ; check if subarray of length temp [ i ] contains i as one of the common elements ; find the minimum of all common elements ; 
def max_distance(a, temp, n):
    mp = {}
    for i in range(1, n + 1):
        temp[i] = -1
    for i in range(n):
        if (a[i]not in mp):
            temp[a[i]] = i + 1
        else:
            temp[a[i]] = max(temp[a[i]], i - mp[a[i]])
        mp[a[i]] = i
    for i in range(1, n + 1):
        if (temp[i] != -1):
            temp[i] = max(temp[i], n - mp[i])


def min_comm_ele(a, ans, temp, n):
    max_distance(a, temp, n)
    for i in range(1, n + 1):
        ans[i] = -1
    for i in range(1, n + 1):
        if (ans[temp[i]] == -1):
            ans[temp[i]] = i
    for i in range(1, n + 1):
        if (i > 1 and ans[i - 1] != -1):
            if (ans[i] == -1):
                ans[i] = ans[i - 1]
            else:
                ans[i] = min(ans[i], ans[i - 1])
        print(ans[i], end=" ")


if __name__ == "__main__":
    N = 6
    a = [1, 3, 4, 5, 6, 7]
    temp = [0] * 100
    ans = [0] * 100
    min_comm_ele(a, ans, temp, N)

# Expected output:
-1 -1 -1 4 3 1
# find a triplet in an array such that arr [ i ] arr [ k ] and i < j < k | function to find a triplet that satisfy the conditions ; traverse the given array ; stores current element ; stores element just before the current element ; stores element just after the current element ; check the given conditions ; print a triplet ; if no triplet found ; 
def FindTrip(arr, N):
    for i in range(1, N - 1):
        p = arr[i - 1]
        q = arr[i]
        r = arr[i + 1]
        if (p < q and q > r):
            print(i - 1, i, i + 1)
            return
    print(-1)


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

# Expected output:
1 2 3
# count subarrays having each distinct element occurring at least twice | python3 program to implement the above approach ; function to get the count of subarrays having each element occurring at least twice ; stores count of subarrays having each distinct element occurring at least twice ; stores count of unique elements in a subarray ; store frequency of each element of a subarray ; traverse the given array ; count frequency and check conditions for each subarray ; update frequency ; check if frequency of arr [ j ] equal to 1 ; update count of unique elements ; update count of unique elements ; if each element of subarray occurs at least twice ; update cntsub ; remove all elements from the subarray ; update cntunique ; 

from collections import defaultdict


def cntSubarrays(arr, N):
    cntSub = 0
    cntUnique = 0
    cntFreq = defaultdict(lambda: 0)
    for i in range(N):
        for j in range(i, N):
            cntFreq[arr[j]] += 1
            if (cntFreq[arr[j]] == 1):
                cntUnique += 1
            elif (cntFreq[arr[j]] == 2):
                cntUnique -= 1
            if (cntUnique == 0):
                cntSub += 1
        cntFreq .clear()
        cntUnique = 0
    return cntSub


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

# Expected output:
6