giulio98/xlcost-single-prompt huggingface dataset:
# minimum substring reversals required to make given binary string alternating | function to count the minimum number of substrings required to be reversed to make the string s alternating ; store count of consecutive pairs ; stores the count of 1 s and 0 s ; traverse through the string ; increment 1 s count ; increment 0 s count ; increment k if consecutive same elements are found ; increment 1 s count ; else : increment 0 s count ; check if it is possible or not ; otherwise , print the number of required operations ; 
def minimumReverse(s, n):
    k = 0
    l = 0
    sum1 = 0
    sum0 = 0
    for i in range(1, n):
        if (s[i] == '1'):
            sum1 += 1
        else:
            sum0 += 1
        if (s[i] == s[i - 1] and s[i] == '0'):
            k += 1
        elif (s[i] == s[i - 1] and s[i] == '1'):
            l += 1
    if (s[0] == '1'):
        sum1 += 1
        sum0 += 1
    if (abs(sum1 - sum0) > 1):
        return -1
    return max(k, l)


if __name__ == '__main__':
    S = "10001"
    N = len(S)
    print(minimumReverse(S, N))

# Expected output:
-1
# count pairs with even product from two given arrays | function to count pairs ( arr [ i ] , brr [ j ] ) whose product is an even number ; stores count of odd numbers in arr [ ] ; stores count of odd numbers in brr [ ] ; traverse the array , arr [ ] ; if arr [ i ] is an odd number ; update cntoddarr ; traverse the array , brr [ ] ; if brr [ i ] is an odd number ; update cntoddarr ; return pairs whose product is an even number ; 
def cntPairsInTwoArray(arr, brr, N, M):
    cntOddArr = 0
    cntOddBrr = 0
    for i in range(N):
        if (arr[i] & 1):
            cntOddArr += 1
    for i in range(M):
        if (brr[i] & 1):
            cntOddBrr += 1
    return (N * M) - (cntOddArr * cntOddBrr)


if __name__ == '__main__':
    arr = [1, 2, 3]
    N = len(arr)
    brr = [1, 2]
    M = len(brr)
    print(cntPairsInTwoArray(arr, brr, N, M))

# Expected output:
4
# maximize count of persons receiving a chocolate | python3 program for the above approach ; function to count the maximum number of persons receiving a chocolate ; initialize count as 0 ; sort the given arrays ; initialize a multiset ; insert b [ ] array values into the multiset ; traverse elements in array a [ ] ; search for the lowest value in b [ ] ; if found , increment count , and delete from set ; return the number of people ; 

from bisect import bisect_left


def countMaxPersons(A, n, B, m, x):
    count = 0
    A = sorted(A)
    B = sorted(B)
    s = []
    for i in range(m):
        s .append(B[i])
    for i in range(n):
        val = A[i] - x
        it = bisect_left(s, val)
        if (it != len(s) and it <= A[i] + x):
            count += 1
            del s[it]
    return count


if __name__ == '__main__':
    A = [90, 49, 20, 39, 49]
    B = [14, 24, 82]
    X = 15
    N = len(A)
    M = len(B)
    print(countMaxPersons(A, N, B, M, X))

# Expected output:
3
# maximize frequency of an element by at most one increment or decrement of all array elements | function to maximize the frequency of an array element by incrementing or decrementing array elements at most once ; stores the largest array element ; stores the smallest array element ; freq [ i ] : stores frequency of ( i + min ) in the array ; traverse the array ; update frequency of arr [ i ] ; stores maximum frequency of an array element by incrementing or decrementing array elements ; iterate all the numbers over the range [ min , max ] ; stores sum of three consecutive numbers ; update maxsum ; print maxsum ; 
def max_freq(arr, N):
    Max = max(arr)
    Min = min(arr)
    freq = [0] * (Max - Min + 1)
    for i in range(N):
        freq[arr[i] - Min] += 1
    maxSum = 0
    for i in range(Max - Min - 1):
        val = freq[i] + freq[i + 1] + freq[i + 2]
        maxSum = max(maxSum, val)
    print(maxSum)


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

# Expected output:
4
# longest increasing subsequence consisting of elements from indices divisible by previously selected indices | function to find length of longest subsequence generated that satisfies the specified conditions ; stores the length of longest subsequences of all lengths ; iterate through the given array ; iterate through the multiples i ; update dp [ j ] as maximum of dp [ j ] and dp [ i ] + 1 ; return the maximum element in dp [ ] as the length of longest subsequence ; 
def findMaxLength(N, arr):
    dp = [1] * (N + 1)
    for i in range(1, N + 1):
        for j in range(2 * i, N + 1, i):
            if (arr[i - 1] < arr[j - 1]):
                dp[j] = max(dp[j], dp[i] + 1)
    return max(dp)


if __name__ == '__main__':
    arr = [2, 3, 4, 5, 6, 7, 8, 9]
    N = len(arr)
    print(findMaxLength(N, arr))

# Expected output:
4
# queries to check if any pair exists in an array having values at most equal to the given pair | function that performs binary search to find value less than or equal to first value of the pair ; perform binary search ; find the mid ; update the high ; else update low ; return the low index ; function to modify the second value of each pair ; start from index 1 ; function to evaluate each query ; find value less than or equal to the first value of pair ; check if we got the required pair or not ; function to find a pair whose values is less than the given pairs in query ; find the size of the vector ; sort the vector based on the first value ; function call to modify the second value of each pair ; traverse each queries ; evaluate each query ; print the result ; 
def binary_search(vec, n, a):
    low, high, mid = 0, 0, 0
    low = 0
    high = n - 1
    while (low < high):
        mid = low + (high - low + 1) // 2
        if (vec[mid][0] > a):
            high = mid - 1
        elif vec[mid][0] <= a:
            low = mid
    return low


def modify_vec(v, n):
    for i in range(n):
        v[i][1] = min(v[i][1], v[i - 1][1])
    return v


def evaluate_query(v, n, m1, m2):
    temp = binary_search(v, n, m1)
    if ((v[temp][0] <= m1) and (v[temp][1] <= m2)):
        return 1
    return 0


def checkPairs(v, queries):
    n = len(v)
    v = sorted(v)
    v = modify_vec(v, n)
    k = len(queries)
    for i in range(k):
        m1 = queries[i][0]
        m2 = queries[i][1]
        result = evaluate_query(v, n, m1, m2)
        if (result > 0):
            print("Yes")
        else:
            print("No")


if __name__ == '__main__':
    arr = [[3, 5], [2, 7], [2, 3], [4, 9]]
    queries = [[3, 4], [3, 2], [4, 1], [3, 7]]
    checkPairs(arr, queries)

# Expected output:
Yes
No
No
Yes
# sort a stream of integers | function to sort a stream of integers ; stores the position of array elements ; traverse through the array ; if any element is found to be greater than the current element ; if an element > num is not present ; otherwise , place the number at its right position ; function to print the sorted stream of integers ; stores the sorted stream of integers ; traverse the array ; function call ; print the array after every insertion ; 
def Sort(ans, num):
    pos = -1
    for i in range(len(ans)):
        if (ans[i] >= num):
            pos = i
            break
    if (pos == -1):
        ans .append(num)
    else:
        ans .insert(pos, num)
    return ans


def sortStream(arr, N):
    ans = list()
    for i in range(N):
        ans = Sort(ans, arr[i])
        for j in range(len(ans)):
            print(ans[j], end=" ")
        print()


if __name__ == '__main__':
    arr = [4, 1, 7, 6, 2]
    N = len(arr)
    sortStream(arr, N)

# Expected output:
4 
1 4 
1 4 7 
1 4 6 7 
1 2 4 6 7
# partition string into two substrings having maximum number of common non | function to count maximum common non - repeating characters that can be obtained by partitioning the string into two non - empty substrings ; stores count of non - repeating characters present in both the substrings ; stores distinct characters in left substring ; stores distinct characters in right substring ; traverse left substring ; insert s [ i ] into ls ; traverse right substring ; insert s [ i ] into rs ; traverse distinct characters of left substring ; if current character is present in right substring ; update cnt ; return count ; function to partition the string into two non - empty substrings in all possible ways ; stores maximum common distinct characters present in both the substring partitions ; traverse the string ; update ans ; print count of maximum common non - repeating characters ; 
def countCommonChar(ind, S):
    cnt = 0
    ls = set()
    rs = set()
    for i in range(ind):
        ls .add(S[i])
    for i in range(ind, len(S)):
        rs .add(S[i])
    for v in ls:
        if v in rs:
            cnt += 1
    return cnt


def partitionStringWithMaxCom(S):
    ans = 0
    for i in range(1, len(S)):
        ans = max(ans, countCommonChar(i, S))
    print(ans)


if __name__ == "__main__":
    string = "aabbca"
    partitionStringWithMaxCom(string)

# Expected output:
2
# longest substring of 1 's after removing one character | function to calculate the length of the longest substring of '1' s that can be obtained by deleting one character ; add '0' at the end ; iterator to traverse the string ; stores maximum length of required substring ; stores length of substring of '1' preceding the current character ; stores length of substring of '1' succeeding the current character ; counts number of '0' s ; traverse the string s ; if current character is '1 ; increase curr_one by one ; otherwise ; increment numberofzeros by one ; count length of substring obtained y concatenating preceding and succeeding substrings of '1 ; store maximum size in res ; assign curr_one to prev_one ; reset curr_one ; if string contains only one '0 ; return the answer ; 
def longestSubarray(s):
    s += '0'
    i = 0
    res = 0
    prev_one = 0
    curr_one = 0
    numberOfZeros = 0
    for i in range(len(s)):
        if (s[i] == '1'):
            curr_one += 1
        else:
            numberOfZeros += 1
            prev_one += curr_one
            res = max(res, prev_one)
            prev_one = curr_one
            curr_one = 0
    if (numberOfZeros == 1):
        res -= 1
    return res


if __name__ == '__main__':

    S = "1101"

    print(longestSubarray(S))

# Expected output:
3
# lexicographically smallest string possible by inserting given character | function to obtain lexicographically smallest string possible by inserting character c in the string s ; traverse the string ; check if current character is greater than the 
def SmallestString(s, c):
    i = 0
    while (i < len(s)):
        if s[i] > c:
            s = s[:i] + c + s[i:]
            return s
        i = i + 1
    s = s + c
    return s


S = 'abd'
C = 'c'
print(SmallestString(S, C))

# Expected output:
abcd
# largest non | python program to implement the above approach ; function to find the largest unique element of the array ; store frequency of each distinct element of the array ; traverse the array ; update frequency of arr [ i ] ; stores largest non - repeating element present in the array ; stores index of the largest non - repeating array element ; traverse the array ; if frequency of arr [ i ] is equal to 1 and arr [ i ] exceeds lnrelem ; update ind ; update lnrelem ; if no array element is found with frequency equal to 1 ; prlargest non - repeating element ; 

import sys


def LarUnEl(arr, N):
    map = dict .fromkeys(arr, 0)
    for i in range(N):
        map[arr[i]] += 1
    LNRElem = -sys .maxsize
    ind = -1
    for i in range(N):
        if (map .get(arr[i]) == 1 and arr[i] > LNRElem):
            ind = i
            LNRElem = arr[i]
    if (ind == -1):
        print(ind)
        return
    print(arr[ind])


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

# Expected output:
4
# minimum shifts of substrings of 1 s required to group all 1 s together in a given binary string | function to count indices substrings of 1 s need to be shifted such that all 1 s in the string are grouped together ; stores first occurrence of '1 ; stores last occurrence of '1 ; count of 0 s between firstone and lastone ; traverse the string to find the first and last occurrences of '1 ; count number of 0 s present between firstone and lastone ; print minimum operations ; 
def countShifts(str):

    firstOne = -1

    lastOne = -1
    count = 0

    for i in range(len(str)):
        if (str[i] == '1'):
            if (firstOne == -1):
                firstOne = i
            lastOne = i
    if ((firstOne == -1) or (firstOne == lastOne)):
        print(0)
        return
    for i in range(firstOne, lastOne + 1, 1):
        if (str[i] == '0'):
            count += 1
    print(count)


str = "00110111011"
countShifts(str)

# Expected output:
2
# check if a non | utility function to check whether a subsequence same as the given subarray exists or not ; check if first element of the subarray is also present before ; check if last element of the subarray is also present later ; if above two conditions are not satisfied , then no such subsequence exists ; function to check and prif a subsequence which is same as the given subarray is present or not ; 
def checkSubsequenceUtil(arr, L, R, N):
    for i in range(L):
        if (arr[i] == arr[L]):
            return True
    for i in range(R + 1, N, 1):
        if (arr[i] == arr[R]):
            return True
    return False


def checkSubsequence(arr, L, R, N):
    if (checkSubsequenceUtil(arr, L, R, N)):
        print("YES")
    else:
        print("NO")


arr = [1, 7, 12, 1, 7, 5, 10, 11, 42]
N = len(arr)
L = 3
R = 6
checkSubsequence(arr, L, R, N)

# Expected output:
YES
# longest subarray in which all elements are smaller than k | function to find the length of the longest subarray with all elements smaller than k ; stores the length of maximum consecutive sequence ; stores maximum length of subarray ; iterate through the array ; check if array element smaller than k ; store the maximum of length and count ; reset the counter ; print the maximum length ; 
def largestSubarray(arr, N, K):
    count = 0
    length = 0
    for i in range(N):
        if (arr[i] < K):
            count += 1
        else:
            length = max(length, count)
            count = 0

    if (count):
        length = max(length, count)
    print(length, end="")


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

    K = 6
    largestSubarray(arr, N, K)

# Expected output:
5
# smallest pair of indices with product of subarray co | function to calculate gcd of two integers ; recursively calculate gcd ; function to find the lexicographically smallest pair of indices whose product is co - prime with the product of the subarrays on its left and right ; stores the suffix product of array elements ; set 0 / 1 if pair satisfies the given condition or not ; initialize array right_prod ; update the suffix product ; stores product of all elements ; stores the product of subarray in between the pair of indices ; iterate through every pair of indices ( i , j ) ; store product of a [ i , j ] ; check if product is co - prime to product of either the left or right subarrays ; if no such pair is found , then pr - 1 ; 
def gcd(a, b):
    if (b == 0):
        return a
    return gcd(b, a % b)


def findPair(A, N):
    right_prod = [0] * N
    flag = 0
    right_prod[N - 1] = A[N - 1]
    for i in range(N - 2, 0, -1):
        right_prod[i] = right_prod[i + 1] * A[i]
    total_prod = right_prod[0]
    product = 1
    for i in range(1, N - 1):
        product = 1
        for j in range(i, N - 1):
            product *= A[j]
            if (gcd(product,
                    right_prod[j + 1]) == 1 or gcd(product,
                                                   total_prod / right_prod[i]) == 1):
                flag = 1
                print("(", (i - 1), ", ", (j + 1), ")")
                break
        if (flag == 1):
            break
    if (flag == 0):
        print(-1)


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

# Expected output:
( 0 ,  2 )
# count binary strings of length same as given string after removal of substrings "01" and "00" that consists of at least one '1' | function to count the strings consisting of at least 1 set bit ; initialize count ; iterate through string ; the answer is 2 ^ n - 1 ; 
def countString(S):
    count = 0
    for i in S:
        if (i == '0' and count > 0):
            count -= 1
        else:
            count += 1
    print((1 << count) - 1)


if __name__ == "__main__":
    S = "1001"
    countString(S)

# Expected output:
3
# append digits to the end of duplicate strings to make all strings in an array unique | function to replace duplicate strings by alphanumeric strings to make all strings in the array unique ; store the frequency of strings ; iterate over the array ; for the first occurrence , update the frequency count ; otherwise ; append frequency count to end of the string ; print the modified array ; 
def replaceDuplicates(names):
    hash = {}
    for i in range(0, len(names)):
        if names[i]not in hash:
            hash[names[i]] = 1
        else:
            count = hash[names[i]]
            hash[names[i]] += 1
            names[i] += str(count)
    for i in range(0, len(names)):
        print(names[i], end=' ')


if __name__ == '__main__':
    str1 = ["aa", "bb", "cc", "bb", "aa", "aa", "aa"]
    replaceDuplicates(str1)

# Expected output:
aa bb cc bb1 aa1 aa2 aa3
# minimum cost of flipping characters required to convert binary string to 0 s only | function to find the minimum cost to convert given string to 0 s only ; length of string ; stores the index of leftmost '1' in str ; update the index of leftmost '1' in str ; stores the index of rightmost '1' in str ; update the index of rightmost '1' in str ; if str does not contain any '1' s ; no changes required ; stores minimum cost ; iterating through str form left_1 to right_1 ; stores length of consecutive 0 s ; calculate length of consecutive 0 s ; if a substring of 0 s exists ; update minimum cost ; printing the minimum cost ; 
def convert_to_allzeroes(st, a, b):
    length = len(st)
    left_1 = 0
    i = 0
    while (i < length and st[i] == '0'):
        i += 1
    left_1 = i
    right_1 = 0
    i = length - 1
    while (i >= 0 and st[i] == '0'):
        i -= 1
    right_1 = i
    if (left_1 == length and right_1 == -1):
        print(0)
        return
    cost = a
    for i in range(left_1, right_1 + 1):
        zeroes = 0
        while (i < length and st[i] == '0'):
            zeroes += 1
            i += 1
        if (zeroes):
            cost += min(zeroes * b, a)
    print(cost)


if __name__ == "__main__":
    st = "01101110"
    A = 5
    B = 1
    convert_to_allzeroes(st, A, B)

# Expected output:
6
# minimum distance to visit given k points on x | python3 program to implement the above approach ; function to find the minimum distance travelled to visit k point ; stores minimum distance travelled to visit k point ; stores distance travelled to visit points ; traverse the array arr [ ] ; if arr [ i ] and arr [ i + k - 1 ] are positive ; update dist ; update dist ; update res ; 

import sys


def MinDistK(arr, N, K):
    res = sys .maxsize
    dist = 0
    for i in range(N - K + 1):
        if (arr[i] >= 0 and arr[i + K - 1] >= 0):
            dist = max(arr[i], arr[i + K - 1])
        else:
            dist = (abs(arr[i]) + abs(arr[i + K - 1]) +
                    min(abs(arr[i]), abs(arr[i + K - 1])))
        res = min(res, dist)
    return res


if __name__ == '__main__':
    K = 3
    arr = [-30, -10, 10, 20, 50]
    N = len(arr)
    print(MinDistK(arr, N, K))

# Expected output:
40
# maximize the minimum array element by m subarray increments of size s | function to return index of minimum element in the array ; initialize a [ 0 ] as minvalue ; traverse the array ; if a [ i ] < existing minvalue ; return the minimum index ; function that maximize the minimum element of array after incrementing subarray of size s by 1 , m times ; iterating through the array for m times ; find minimum element index ; increment the minimum value ; storing the left index and right index ; incrementing s - 1 minimum elements to the left and right of minvalue ; reached extreme left ; reached extreme right ; left value is minimum ; right value is minimum ; find the minvalue in a [ ] after m operations ; return the minimum value ; 
def min(a, n):
    minIndex = 0
    minValue = a[0]
    for i in range(1, n):
        if (a[i] < minValue):
            minValue = a[i]
            minIndex = i
    return minIndex


def maximizeMin(A, N, S, M):
    minIndex, left, right = 0, 0, 0
    for i in range(M):
        minIndex = min(A, N)
        A[minIndex] += 1
        left = minIndex - 1
        right = minIndex + 1
        for j in range(S - 1):
            if (left == -1):
                A[right] += 1
                right += 1
            elif (right == N):
                A[left] += 1
                left -= 1
            else:
                if (A[left] < A[right]):
                    A[left] += 1
                    left -= 1
                else:
                    A[right] += 1
                    right += 1
    minIndex = min(A, N)
    return A[minIndex]


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

# Expected output:
3
# sum of nodes in the path from root to n | python3 program for the above approach ; function to find sum of all nodes from root to n ; if n is equal to 1 ; if n is equal to 2 or 3 ; stores the number of nodes at ( i + 1 ) - th level ; stores the number of nodes ; stores if the current level is even or odd ; if level is odd ; if level is even ; if level with node n is reached ; push into vector ; compute prefix sums of count of nodes in each level ; stores the level in which node n s present ; stores the required sum ; add temp to the sum ; 

from bisect import bisect_left, bisect


def sumOfPathNodes(N):
    if (N == 1):
        return 1
    elif (N == 2 or N == 3):
        return N + 1
    arr = []
    arr .append(1)
    k = 1
    flag = True
    while (k < N):
        if (flag):
            k *= 2
            flag = False
        else:
            k *= 4
            flag = True
        if (k > N):
            break
        arr .append(k)
    lenn = len(arr)
    prefix = [0] * (lenn)
    prefix[0] = 1
    for i in range(1, lenn):
        prefix[i] = arr[i] + prefix[i - 1]
    it = bisect_left(prefix, N)
    ind = it
    final_ans = 0
    temp = N
    while (ind > 1):
        val = temp - prefix[ind - 1]
        if (ind % 2 != 0):
            temp = prefix[ind - 2] + (val + 1) // 2
        else:
            temp = prefix[ind - 2] + (val + 3) // 4
        ind -= 1
        final_ans += temp
    final_ans += (N + 1)
    return final_ans


if __name__ == '__main__':
    N = 13
    print(sumOfPathNodes(N))

# Expected output:
20
# check if given point lies in range of any of the given towers | python3 program to implement the above approach ; function to check if the point ( x , y ) exists in the towers network - range or not ; traverse the array arr [ ] ; stores distance of the point ( x , y ) from i - th tower ; if dist lies within the range of the i - th tower ; if the point ( x , y ) does not lie in the range of any of the towers ; 

from math import sqrt


def checkPointRange(arr, X, Y, N):
    for i in range(N):
        dist = sqrt((arr[i][0] - X) * (arr[i][0] - X) +
                    (arr[i][1] - Y) * (arr[i][1] - Y))
        if (dist <= arr[i][2]):
            return True
    return False


if __name__ == '__main__':
    arr = [[1, 1, 3], [10, 10, 3], [15, 15, 15]]
    X = 5
    Y = 5
    N = len(arr)
    if (checkPointRange(arr, X, Y, N)):
        print("True")
    else:
        print("False")

# Expected output:
True