giulio98/xlcost-single-prompt huggingface dataset:
# minimum increment / decrement operations required on array to satisfy given conditions | function to find minimum number of operations to get desired array ; for odd ' i ' , sum of elements till ' i ' is positive ; if i is even and sum is positive , make it negative by subtracting 1 + | s | from a [ i ] ; if i is odd and sum is negative , make it positive by adding 1 + | s | into a [ i ] ; for odd ' i ' , sum of elements till ' i ' is negative ; check if ' i ' is odd and sum is positive , make it negative by subtracting 1 + | s | from a [ i ] ; check if ' i ' is even and sum is negative , make it positive by adding 1 + | s | into a [ i ] ; return the minimum of the two ; 
def minOperations(a, N):
    num_of_ops1 = num_of_ops2 = sum = 0
    for i in range(N):
        sum += a[i]
        if (i % 2 == 0 and sum >= 0):
            num_of_ops1 += (1 + abs(sum))
            sum = -1
        elif (i % 2 == 1 and sum <= 0):
            num_of_ops1 += (1 + abs(sum))
            sum = 1
    sum = 0
    for i in range(N):
        sum += a[i]
        if (i % 2 == 1 and sum >= 0):
            num_of_ops2 += (1 + abs(sum))
            sum = -1
        elif (i % 2 == 0 and sum <= 0):
            num_of_ops2 += (1 + abs(sum))
            sum = 1
    return min(num_of_ops1, num_of_ops2)


if __name__ == "__main__":
    arr = [3, -4, 5, 0, 1]
    N = len(arr)
    print(minOperations(arr, N))

# Expected output:
6
# check if all elements of a circular array can be made equal by increments of adjacent pairs | function to check if all array elements can be made equal ; stores the sum of even and odd array elements ; if index is odd ; 
def checkEquall(arr, N):
    sumEven, sumOdd = 0, 0
    for i in range(N):
        if (i & 1):
            sumOdd += arr[i]
        else:
            sumEven += arr[i]
    if (sumEven == sumOdd):
        return True
    else:
        return False


if __name__ == "__main__":
    arr = [2, 7, 3, 5, 7]
    N = len(arr)
    if (checkEquall(arr, N)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# check if a number can be expressed as sum of two perfect powers | function that returns true if n can be written as a ^ m + b ^ n ; taking issum boolean array for check the sum exist or not ; to store perfect squares ; initially all sums as false ; if sum exist then push that sum into perfect square vector ; mark all perfect powers as false ; traverse each perfectpowers ; calculating sum with perfect powers array ; 
def isSumOfPower(n):
    isSum = [0] * (n + 1)
    perfectPowers = []
    perfectPowers .append(1)
    for i in range(n + 1):
        isSum[i] = False
    for i in range(2, n + 1):
        if (isSum[i]):
            perfectPowers .append(i)
            continue
        j = i * i
        while (j > 0 and j < (n + 1)):
            isSum[j] = True
            j *= i
    for i in range(len(perfectPowers)):
        isSum[perfectPowers[i]] = False
    for i in range(len(perfectPowers)):
        for j in range(len(perfectPowers)):
            sum = (perfectPowers[i] + perfectPowers[j])
            if (sum < (n + 1)):
                isSum[sum] = True
    return isSum[n]


n = 9
if (isSumOfPower(n)):
    print("true")
else:
    print("false")

# Expected output:
true
# minimum increments by index value required to obtain at least two equal array elements | function to update every element adding to it its index value ; function to check if at least two elements are equal or not ; count the frequency of arr [ i ] ; function to calculate the number of increment operations required ; stores the minimum number of steps ; 
def update(arr, N):
    for i in range(N):
        arr[i] += (i + 1)


def check(arr, N):
    f = 0
    for i in range(N):
        count = 0
        for j in range(N):
            if (arr[i] == arr[j]):
                count += 1
        if (count >= 2):
            f = 1
            break
    if (f == 1):
        return True
    else:
        return False


def incrementCount(arr, N):
    min = 0
    while (check(arr, N) != True):
        update(arr, N)
        min += 1
    print(min)


if __name__ == '__main__':
    N = 3
    arr = [12, 8, 4]
    incrementCount(arr, N)

# Expected output:
4
# rearrange array such that all even | function to check if it the array can be rearranged such such that every even indices contains an even element ; stores the count of even elements ; traverse array to count even numbers ; if even_no_count exceeds count of even indices ; 
def checkPossible(a, n):
    even_no_count = 0
    for i in range(n):
        if (a[i] % 2 == 0):
            even_no_count += 1
    if (n // 2 > even_no_count):
        print("No")
        return
    print("Yes")
    j = 0
    for i in range(1, n, 2):
        if (a[i] % 2 == 0):
            continue
        else:
            while (j < n and a[j] % 2 != 0):
                j += 2
            a[i] += a[j]
            a[j] = a[i] - a[j]
            a[i] -= a[j]
    for i in range(n):
        print(a[i], end=" ")


arr = [2, 3, 4, 5, 6, 7]
n = len(arr)
checkPossible(arr, n)

# Expected output:
Yes
3 2 5 4 7 6
# largest number m having bit count of n such that difference between their or and xor value is maximized | python3 program for the above approach ; function to find the largest number m having the same length in binary form as n such that the difference between n | m and n ^ m is maximum ; find the most significant bit of n ; initialize m ; set all the bits of m ; return the answer ; 

import math


def maxORminusXOR(N):
    MSB = int(math .log2(N))
    M = 0
    for i in range(MSB + 1):
        M += (1 << i)
    return M


if __name__ == '__main__':
    N = 10
    print(maxORminusXOR(N))

# Expected output:
15
# maximum count of equilateral triangles that can be formed within given equilateral triangle | function to find the number of equilateral triangle formed within another triangle ; check for the valid condition ; number of triangles having upward peak ; number of inverted triangles ; total no . of k sized triangle ; 
def No_of_Triangle(N, K):
    if (N < K):
        return -1
    else:
        Tri_up = 0
        Tri_up = ((N - K + 1) * (N - K + 2)) // 2
        Tri_down = 0
        Tri_down = ((N - 2 * K + 1) * (N - 2 * K + 2)) // 2
        return Tri_up + Tri_down


if __name__ == '__main__':
    N = 4
    K = 2
    print(No_of_Triangle(N, K))

# Expected output:
7
# check if array forms an increasing | function to check if the given array forms an increasing decreasing sequence or vice versa ; base case ; first subarray is stricly increasing ; check for strictly increasing condition & find the break point ; check for strictly decreasing condition & find the break point ; if i is equal to length of array ; first subarray is strictly decreasing ; check for strictly increasing condition & find the break point ; check for strictly increasing condition & find the break point ; if i is equal to length of array - 1 ; condition if ar [ 0 ] == ar [ 1 ] ; 
def canMake(n, ar):
    if (n == 1):
        return True
    else:
        if (ar[0] < ar[1]):
            i = 1
            while (i < n and ar[i - 1] < ar[i]):
                i += 1
            while (i + 1 < n and ar[i] > ar[i + 1]):
                i += 1
            if (i >= n - 1):
                return True
            else:
                return False
        elif (ar[0] > ar[1]):
            i = 1
            while (i < n and ar[i - 1] > ar[i]):
                i += 1
            while (i + 1 < n and ar[i] < ar[i + 1]):
                i += 1
            if (i >= n - 1):
                return True
            else:
                return False
        else:
            for i in range(2, n):
                if (ar[i - 1] <= ar[i]):
                    return False
            return True


arr = [1, 2, 3, 4, 5]
n = len(arr)
if (canMake(n, arr) == False):
    print("Yes")
else:
    print("No")

# Expected output:
No
# minimum count of bit flips required to make a binary string palindromic | function to calculate the length of the binary string ; length ; right shift of n ; increment the length ; return the length ; function to check if the bit present at i - th position is a set bit or not ; returns true if the bit is set ; function to count the minimum number of bit flips required ; length of the binary form ; number of flips ; pointer to the lsb ; pointer to the msb ; check if the bits are equal ; decrementing the left pointer ; incrementing the right pointer ; returns the number of bits to flip . ; 
def check_length(n):
    ans = 0
    while (n):
        n = n >> 1
        ans += 1
    return ans


def check_ith_bit(n, i):
    if (n & (1 << (i - 1))):
        return True
    else:
        return False


def no_of_flips(n):
    ln = check_length(n)
    ans = 0
    right = 1
    left = ln
    while (right < left):
        if (check_ith_bit(n, right) != check_ith_bit(n, left)):
            ans += 1
        left -= 1
        right += 1
    return ans


n = 12
print(no_of_flips(n))

# Expected output:
2
# split n into two integers whose addition to a and b makes them equal | function to calculate the splitted numbers ; calculate x ; if x is odd ; no pair is possible ; otherwise ; calculate x ; calculate y ; 
def findPair(A, B, N):
    X = N - B + A
    if (X % 2 != 0):
        print("-1")
    else:
        X = X // 2
        Y = N - X
        print(X, Y)


if __name__ == "__main__":
    A = 1
    B = 3
    N = 4
    findPair(A, B, N)

# Expected output:
1 3
# find the amplitude and number of waves for the given array | function to find the amplitude and number of waves for the given array ; check for both sides adjacent elements that both must be less or both must be greater than current element ; update amplitude with max value ; prthe amplitude ; 
def check(a, n):
    ma = a[1] - a[0]
    for i in range(1, n - 1):
        if ((a[i] > a[i - 1] and a[i + 1] < a[i])
                or (a[i] < a[i - 1] and a[i + 1] > a[i])):
            ma = max(ma, abs(a[i] - a[i + 1]))
        else:
            return False
    print("Amplitude = ", ma)
    return True


if __name__ == '__main__':
    a = [1, 2, 1, 5, 0, 7, -6]
    n = len(a)
    wave = (n - 1) // 2
    if (check(a, n)):
        print("Waves = ", wave)
    else:
        print("-1")

# Expected output:
Amplitude =  13
Waves =  3
# find relative rank of each element in array | function to find relative rank for each element in the array a [ ] ; create rank array ; stack to store numbers in non - decreasing order from right ; push last element in stack ; iterate from second last element to first element ; if current element is less than the top of stack and append a [ i ] in stack ; rank is stack size - 1 for current element ; pop elements from stack till current element is greater than the top ; push current element in stack ; rank is stack size - 1 ; print rank of all elements ; 
def findRank(A, N):
    rank = [0] * N
    s = []
    s .append(A[N - 1])
    for i in range(N - 2, -1, -1):
        if (A[i] < s[-1]):
            s .append(A[i])
            rank[i] = len(s) - 1
        else:
            while (len(s) > 0 and A[i] >= s[-1]):
                del s[-1]
            s .append(A[i])
            rank[i] = len(s) - 1
    for i in range(N):
        print(rank[i], end=" ")


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

# Expected output:
3 2 1 0 0
# largest string obtained in dictionary order after deleting k characters | python3 program for the above approach ; function to find the largest string after deleting k characters ; deque dq used to find the largest string in dictionary after deleting k characters ; iterate till the length of the string ; condition for popping characters from deque ; to store the resultant string ; to form resultant string ; return the resultant string ; 

from collections import deque


def largestString(n, k, sc):
    s = [i for i in sc]
    deq = deque()
    for i in range(n):
        while (len(deq) > 0 and deq[-1] < s[i] and k > 0):
            deq .popleft()
            k -= 1
        deq .append(s[i])
    st = ""
    for c in deq:
        st = st + c
    return st


if __name__ == '__main__':
    n = 4
    k = 2
    sc = "ritz"
    result = largestString(n, k, sc)
    print(result)

# Expected output:
tz
# count total set bits in all numbers from range l to r | function that counts the set bits from 0 to n ; to store sum of set bits from 0 - n ; until n >= to 2 ^ i ; this k will get flipped after 2 ^ i iterations ; change is iterator from 2 ^ i to 1 ; this will loop from 0 to n for every bit position ; when change = 1 flip the bit ; again set change to 2 ^ i ; increment the position ; function that counts the set bit in the range ( l , r ) ; return the count ; 
def countSetBit(n):
    i = 0
    ans = 0
    while ((1 << i) <= n):
        k = True
        change = 1 << i
        for j in range(n + 1):
            ans += 0 if k else 1
            if (change == 1):
                k = False if k else True
                change = 1 << i
            else:
                change -= 1
        i += 1
    return ans


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
# count total set bits in all numbers from range l to r | function to count set bit in range ; count variable ; find the set bit in nth number ; if last bit is set ; left sift by one bit ; return count ; 
def countSetBits(L, R):
    count = 0
    for i in range(L, R + 1):
        n = i
        while (n > 0):
            count += (n & 1)
            n = n >> 1
    return count


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

# Expected output:
Total set Bit count is  5
# count total set bits in all numbers from range l to r | function to count set bit in [ l , r ] ; variable for count set bit in range ; count set bit for all number in range ; use inbuilt function ; 
def countSetBit(n):
    count = 0
    while (n):
        count += n & 1
        n >>= 1
    return count


def countSetBits(L, R):
    count = 0
    for i in range(L, R + 1):
        count += countSetBit(i)
    return count


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

# Expected output:
Total set bit count is  5
# make max elements in b [ ] equal to that of a [ ] by adding / subtracting integers in range [ 0 , k ] | function that count the number of integers from array b such that subtracting element in the range [ 0 , k ] given any element in a ; to store the count of element ; traverse the array b ; traverse the array a ; find the difference ; if difference is atmost k then increment the cnt ; print the count ; 
def countElement(A, N, B, M, K):
    cnt = 0
    for i in range(M):
        currentElement = B[i]
        for j in range(N):
            diff = abs(currentElement - A[j])
            if (diff <= K):
                cnt += 1
                break
    print(cnt)


if __name__ == '__main__':
    A = [100, 65, 35, 85, 55]
    B = [30, 60, 75, 95]
    N = len(A)
    M = len(B)
    K = 5
    countElement(A, N, B, M, K)

# Expected output:
3
# generate a string of having n * n distinct non | function to construct a string having n * n non - palindromic substrings ; 
def createString(N):
    for i in range(N):
        print('a', end='')
    for i in range(N):
        print('b', end='')


N = 4
createString(N)

# Expected output:
aaaabbbb
# maximum subset sum possible by negating the entire sum after selecting the first array element | function returns maximum subset sum from the given array = ; case 2 : negate values from a [ 1 ] to a [ n - 1 ] ; include only positives for max subset sum ; return max sum obtained ; function to return maximum of the maximum subset sum calculated for the two cases ; case 1 ; case 2 ; modifying the sum ; including first element ; negating again ; return the required answer ; 
def maxSubset(A, flag):
    n = len(A)
    sum = 0
    if (flag):
        for i in range(1, n):
            A[i] = -A[i]
    for i in range(1, n):
        if (A[i] > 0):
            sum += A[i]
    return sum


def findBest(A):
    x = maxSubset(A, 0)
    y = maxSubset(A, 1)
    y = -y
    y += A[0]
    y = -y
    return max(x, y)


if __name__ == "__main__":
    A = [1, 10, 4, -6, 3]
    print(findBest(A))

# Expected output:
17
# construct an array of strings having longest common prefix specified by the given array | function to find the array of strings ; marks the ( n + 1 ) th string ; to generate remaining n strings ; find i - th string using ( i + 1 ) - th string ; check if current character is b ; otherwise ; insert the string ; return the answer ; 
def solve(n, arr):
    s = 'a' * (n)
    ans = []
    ans.append(s)
    for i in range(n - 1,
                   -1, -1):
        if len(s) - 1 >= arr[i]:
            ch = s[arr[i]]
            if (ch == 'b'):
                ch = 'a'
            else:
                ch = 'b'

            p = list(s)
            p[arr[i]] = ch
            s = ''.join(p)
        ans.append(s)
    return ans


if __name__ == "__main__":
    arr = [2, 0, 3]
    n = len(arr)
    ans = solve(n, arr)
    for i in range(len(ans) - 1, -1, -1):
        print(ans[i])

# Expected output:
bab
baa
aaa
aaa
# minimize swaps required to maximize the count of elements replacing a greater element in an array | function to find the minimum number of swaps required ; sort the array in ascending order ; iterate until a greater element is found ; keep incrementing ind ; if a greater element is found ; increase count of swap ; increment ind ; if end of array is reached ; return the answer ; 
def countSwaps(A, n):
    A .sort()
    ind, res = 1, 0
    for i in range(n):
        while (ind < n and A[ind] == A[i]):
            ind += 1
        if (ind < n and A[ind] > A[i]):
            res += 1
            ind += 1
        if (ind >= n):
            break
    return res


A = [4, 3, 3, 2, 5]
print(countSwaps(A, 5))

# Expected output:
3
# minimize swaps required to maximize the count of elements replacing a greater element in an array | function to find the minimum number of swaps required ; stores the frequency of the array elements ; stores maximum frequency ; find the max frequency ; update frequency ; update maximum frequency ; 
def countSwaps(A, n):
    mp = {}
    max_frequency = 0
    for i in range(n):
        if A[i] in mp:
            mp[A[i]] += 1
        else:
            mp[A[i]] = 1
        max_frequency = max(max_frequency, mp[A[i]])
    return n - max_frequency


if __name__ == "__main__":
    A = [6, 5, 4, 3, 2, 1]
    print(countSwaps(A, 6))

# Expected output:
5
# minimum number of steps required to obtain the given array by the given operations | function to calculate the minimum steps to obtain the desired array ; initialize variable ; iterate over the array arr [ ] ; check if i > 0 ; update the answer ; return the result ; 
def min_operation(a, n):
    ans = 0
    for i in range(n):
        if (i > 0):
            ans += abs(a[i] - a[i - 1])
        else:
            ans += abs(a[i])
    return ans


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

# Expected output:
4
# construct a matrix with no element exceeding x and sum of two adjacent elements not exceeding y | function to print the required matrix ; for 1 * 1 matrix ; greater number ; smaller number ; sets / resets for alternate filling of the matrix ; print the matrix ; if end of row is reached ; 
def FindMatrix(n, m, x, y):
    if (n * m == 1):
        if (x > y):
            print(y)
        else:
            print(x)
        return
    a = min(x, y)
    b = min(2 * x, y) - a
    flag = True
    for i in range(n):
        for j in range(m):
            if (flag):
                print(a, end=" ")
            else:
                print(b, end=" ")
            flag = not flag
        if (((n % 2 != 0 and m % 2 == 0) or (n % 2 == 0 and m % 2 == 0))):
            flag = not flag
        print()


N = 3
M = 3
X = 5
Y = 3
FindMatrix(N, M, X, Y)

# Expected output:
3 0 3 
0 3 0 
3 0 3
# count distinct elements after adding each element of first array with second array | function to find occurrence of each element from 1 to 2 * max ; initialise max ; count vector to store count of each element from 1 to 2 * max count = new int [ 2 * max + 1 ] ; ; size of arr1 and arr2 ; find the elements of arr3 and increase count of element by 1 ; prthe result ; 
def findCount(Arr1, Arr2):
    MAX = max(max(Arr1), max(Arr2))
    Count = [0 for i in range(2 * MAX + 1)]
    n = len(Arr1)
    m = len(Arr2)
    for i in range(n):
        for j in range(m):
            element = Arr1[i] + Arr2[j]
            Count[element] += 1
    for i in range(1, 2 * MAX + 1):
        if (Count[i] > 0):
            print(i, "->", Count[i])


if __name__ == '__main__':
    arr1 = [1, 2]
    arr2 = [1, 2, 1]
    findCount(arr1, arr2)

# Expected output:
2 -> 2
3 -> 3
4 -> 1
# find two numbers with difference and division both same as n | function to find two numbers with difference and division both as n ; condition if the answer is not possible ; calculate a and b ; print the values ; 
def findAandB(N):
    if (N == 1):
        print("No")
        return
    a = N * N / (N - 1)
    b = a / N
    print("a = ", a)
    print("b = ", b)


N = 6
findAandB(N)

# Expected output:
a =  7.2
b =  1.2
# maximize number of elements from array with sum at most k | function to select a maximum number of elements in array whose sum is at most k ; sort the array ; calculate the sum and count while iterating the sorted array ; iterate for all the elements in the array ; add the current element to sum ; increment the count ; return the answer ; 
def maxSelections(A, n, k):
    A .sort()
    sum = 0
    count = 0
    for i in range(n):
        sum = sum + A[i]
        if (sum > k):
            break
        count += 1
    return count


if __name__ == '__main__':
    A = [3, 7, 2, 9, 4]
    k = 15
    n = len(A)
    print(maxSelections(A, n, k))

# Expected output:
3
# pair of integers with difference k having an element as the k | function to find the required pair ; no pair possible ; 
def computePair(K):
    if (K == 1):
        print("No")
        return
    else:
        print(K * K / (K - 1), end=" ")
        print(K / (K - 1))


if __name__ == "__main__":
    K = 6
    computePair(K)

# Expected output:
7.2 1.2
# generate a binary string without any consecutive 0 ' s ▁ and ▁ at ▁ most ▁ k ▁ consecutive ▁ 1' s | function to construct the binary string ; conditions when string construction is not possible ; stores maximum 1 's that  can be placed in between ; place 0 's ; place 1 's in between ; count remaining m 's ; place 1 's at the end ; place 1 's at the beginning ; return the final string ; 
def ConstructBinaryString(N, M, K):
    if (M < (N - 1) or M > K * (N + 1)):
        return '-1'
    ans = ""
    l = min(K, M // (N - 1))
    temp = N
    while (temp):
        temp -= 1
        ans += '0'
        if (temp == 0):
            break
        for i in range(l):
            ans += '1'
    M -= (N - 1) * l
    if (M == 0):
        return ans
    l = min(M, K)
    for i in range(l):
        ans += '1'
    M -= l
    while (M > 0):
        ans = '1' + ans
        M -= 1
    return ans


if __name__ == '__main__':
    N = 5
    M = 9
    K = 2
    print(ConstructBinaryString(N, M, K))

# Expected output:
01101101101101