giulio98/xlcost-single-prompt huggingface dataset:
# maximum sum of products of two arrays by toggling adjacent bits | python3 program to find the maximum sop of two arrays by toggling adjacent bits in the second array ; function to return max sum ; intialparity and finalparity are 0 if total no . of 1 's is even else 1 ; minpositive and maxnegative will store smallest positive and smallest negative integer respectively . ; count of initial parity ; if arr1 [ i ] is positive then add 1 in finalparity to get 1 at arr2 [ i ] ; if both parity are odd or even then return sum ; else add one more 1 or remove 1 ; if minpositive > maxnegative , put 1 at maxnegative and add it to our sum ; else remove minpositive no . ; 

import sys


def maxSum(arr1, arr2, n):
    initialParity, finalParity = 0, 0
    sum = 0
    minPositive = sys .maxsize
    maxNegative = -sys .maxsize - 1
    for i in range(n):
        initialParity += arr2[i]
        if (arr1[i] >= 0):
            finalParity += 1
            sum += arr1[i]
            minPositive = min(minPositive, arr1[i])
        else:
            maxNegative = max(maxNegative, arr1[i])
    if (initialParity % 2 == finalParity % 2):
        return sum
    else:
        if (minPositive + maxNegative >= 0):
            return sum + maxNegative
        else:
            return sum - minPositive


arr1 = [2, -4, 5, 3]
arr2 = [0, 1, 0, 1]
n = len(arr1)
print(maxSum(arr1, arr2, n))

# Expected output:
8
# minimum number to be added to all digits of x to make x > y | function to check if x is lexicographically larger y ; it is lexicographically larger ; utility function to check minimum value of d ; if x is already larger do not need to add anything ; adding d to all elements of x ; if x is larger now print d ; else print d + 1 ; 
def IsLarger(X, Y, n):
    for i in range(n):
        if (X[i] < Y[i]):
            return False
    return True


def solve(X, Y, n):
    ans = 0
    if (IsLarger(X, Y, n)):
        ans = 0
    else:
        d = Y[0] - X[0]
        for i in range(n):
            X[i] += d
        if (IsLarger(X, Y, n)):
            ans = d
        else:
            ans = d + 1
    return ans


if __name__ == "__main__":
    X = [2, 3, 6, 9]
    Y = [3, 4, 8, 1]
    n = len(X)
    print(solve(X, Y, n))

# Expected output:
2
# maximum possible bitwise or of the two numbers from the range [ l , r ] | function to return the maximum bitwise or of any pair from the given range ; converting l to its binary representation ; converting r to its binary representation ; in order to make the number of bits of l and r same ; push 0 to the msb ; when ith bit of r is 1 and ith bit of l is 0 ; from msb side set all bits of l to be 1 ; from ( i + 1 ) th bit , all bits of l changed to be 1 ; 
def max_bitwise_or(L, R):
    v1 = []
    v2 = []
    v3 = []
    z = 0
    i = 0
    ans = 0
    cnt = 1
    while (L > 0):
        v1 .append(L % 2)
        L = L // 2
    while (R > 0):
        v2 .append(R % 2)
        R = R // 2
    while (len(v1) != len(v2)):
        v1 .append(0)
    for i in range(len(v2) - 1, -1, -1):
        if (v2[i] == 1 and v1[i] == 0 and z == 0):
            z = 1
            continue
        if (z == 1):
            v1[i] = 1
    for i in range(len(v2)):
        v3 .append(v2[i] | v1[i])
    for i in range(len(v2)):
        if (v3[i] == 1):
            ans += cnt
        cnt *= 2
    return ans


L = 10
R = 20
print(max_bitwise_or(L, R))

# Expected output:
31
# find the minimum value of x for an expression | function to calculate value of x ; check for both possibilities ; 
def valueofX(ar, n):
    summ = sum(ar)
    if (summ % n == 0):
        return summ // n
    else:
        A = summ // n
        B = summ // n + 1
        ValueA = 0
        ValueB = 0
        for i in range(n):
            ValueA += (ar[i] - A) * (ar[i] - A)
            ValueB += (ar[i] - B) * (ar[i] - B)
        if (ValueA < ValueB):
            return A
        else:
            return B


n = 7
arr = [6, 9, 1, 6, 1, 3, 7]
print(valueofX(arr, n))

# Expected output:
5
# minimum halls required for class scheduling | python3 implementation of the approach ; function to return the minimum number of halls required ; array to store the number of lectures ongoing at time t ; for every lecture increment start point s decrement ( end point + 1 ) ; perform prefix sum and update the ans to maximum ; 

MAX = 100001


def minHalls(lectures, n):
    prefix_sum = [0] * MAX
    for i in range(n):
        prefix_sum[lectures[i][0]] += 1
        prefix_sum[lectures[i][1] + 1] -= 1
    ans = prefix_sum[0]
    for i in range(1, MAX):
        prefix_sum[i] += prefix_sum[i - 1]
        ans = max(ans, prefix_sum[i])
    return ans


if __name__ == "__main__":
    lectures = [[0, 5], [1, 2], [1, 10]]
    n = len(lectures)
    print(minHalls(lectures, n))

# Expected output:
3
# find the minimum capacity of the train required to hold the passengers | function to return the minimum capacity required ; to store the minimum capacity ; to store the current capacity of the train ; for every station ; add the number of people entering the train and subtract the number of people exiting the train to get the current capacity of the train ; update the minimum capacity ; 
def minCapacity(enter, exit, n):
    minCap = 0
    currCap = 0
    for i in range(n):
        currCap = currCap + enter[i] - exit[i]
        minCap = max(minCap, currCap)
    return minCap


if __name__ == '__main__':
    enter = [3, 5, 2, 0]
    exit = [0, 2, 4, 4]
    n = len(enter)
    print(minCapacity(enter, exit, n))

# Expected output:
6
# count of numbers in the range [ l , r ] which satisfy the given conditions | python3 implementation of the approach ; maximum possible valid number ; to store all the required number from the range [ 1 , max ] ; function that returns true if x satisfies the given conditions ; to store the digits of x ; if current digit appears more than once ; if current digit is greater than 5 ; put the digit in the map ; function to generate all the required numbers in the range [ 1 , max ] ; insert first 5 valid numbers ; inserting 0 externally because 0 cannot be the leading digit in any number ; if x satisfies the given conditions ; cannot append anymore digit as adding a digit will repeat one of the already present digits ; append all the valid digits one by one and append the new generated number to the queue ; append the digit ; push the newly generated number to the queue ; function to copmpare two strings which represent a numerical value ; function to return the count of valid numbers in the range [ l , r ] ; generate all the valid numbers in the range [ 1 , max ] ; to store the count of numbers in the range [ l , r ] ; for every valid number in the range [ 1 , max ] ; if current number is within the required range ; if number is equal to either l or r ; 

from collections import deque
MAX = 543210
ans = []


def isValidNum(x):
    mp = dict()
    for i in range(len(x)):
        if (ord(x[i]) - ord('0') in mp .keys()):
            return False
        elif (ord(x[i]) - ord('0') > 5):
            return False
        else:
            mp[ord(x[i]) - ord('0')] = 1
    return True


def generate():
    q = deque()
    q .append("1")
    q .append("2")
    q .append("3")
    q .append("4")
    q .append("5")
    flag = True
    ans .append("0")
    while (len(q) > 0):
        x = q .popleft()
        if (isValidNum(x)):
            ans .append(x)
        if (len(x) == 6):
            continue
        for i in range(6):
            z = str(i)
            temp = x + z
            q .append(temp)


def comp(a, b):
    if (len(a) == len(b)):
        if a < b:
            return True
    else:
        return len(a) < len(b)


def findcount(l, r):
    generate()
    count = 0
    for i in range(len(ans)):
        a = ans[i]
        if (comp(l, a) and comp(a, r)):
            count += 1
        elif (a == l or a == r):
            count += 1
    return count


l = "1"
r = "1000"
print(findcount(l, r))

# Expected output:
130
# find permutation with maximum remainder sum | function to find the permutation ; put n at the first index 1 ; put all the numbers from 2 to n sequentially ; 
def Findpermutation(n):
    a = [0] * (n + 1)
    a[1] = n
    for i in range(2, n + 1):
        a[i] = i - 1
    return a


if __name__ == "__main__":
    n = 8
    v = Findpermutation(n)
    for i in range(1, n + 1):
        print(v[i], end=' ')

# Expected output:
8 1 2 3 4 5 6 7
# lexicographically smallest string of length n and sum k | function to return the lexicographically smallest string of length n that satisfies the given condition ; iteration from the last position in the array ; if k is a positive integer ; ' z ' needs to be inserted ; add the required character ; 
def lexo_small(n, k):
    arr = ""
    for i in range(n):
        arr += 'a'
    for i in range(n - 1, -1, -1):
        k -= i
        if (k >= 0):
            if (k >= 26):
                arr = arr[:i] + 'z' + arr[i + 1:]
                k -= 26
            else:
                c = (k + 97 - 1)
                arr = arr[:i] + chr(c) + arr[i + 1:]
                k -= ord(arr[i]) - ord('a') + 1
        else:
            break
        k += i
    return arr


if __name__ == '__main__':
    n = 5
    k = 42
    arr = lexo_small(n, k)
    print(arr)

# Expected output:
aaamz
# check if string can be rearranged so that every odd length substring is palindrome | function to check is it possible to rearrange the string such that every odd length substring is palindrome ; length of the string ; to count number of distinct character in string ; to count frequency of each character ; inserting into set ; incrementing the frequency ; all characters in the string are same ; there are more than 2 different character in string ; currently there is 2 different character in string ; get the frequencies of the characters that present in string ; difference between their count is less than or equal to 1 ; 
def IsPossible(s):
    n = len(s)
    count = set()
    map = dict .fromkeys(s, 0)
    for i in range(n):
        count .add(s[i])
        map[s[i]] += 1
    if (len(count) == 1):
        return True
    if (len(count) > 2):
        return False
    j = 0
    it = list(count)[j]
    x = 0
    y = 0
    x = map[it]
    j += 1
    it = list(count)[j]
    y = map[it]
    if (abs(x - y) <= 1):
        return True
    return False


if __name__ == "__main__":
    s = "aaaddad"
    if (IsPossible(s)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# minimum element left from the array after performing given operations | function to return the minimum possible value of the last element left after performing the given operations ; 
def getMin(arr, n):
    minVal = min(arr)
    return minVal


if __name__ == "__main__":
    arr = [5, 3, 1, 6, 9]
    n = len(arr)
    print(getMin(arr, n))

# Expected output:
1
# largest substring with same characters | function to find largest sub with same characters ; traverse the string ; if character is same as previous increment temp value ; return the required answer ; 
def Substring(s):
    ans, temp = 1, 1
    for i in range(1, len(s)):
        if (s[i] == s[i - 1]):
            temp += 1
        else:
            ans = max(ans, temp)
            temp = 1
    ans = max(ans, temp)
    return ans


s = "abcdddddeff"
print(Substring(s))

# Expected output:
5
# number of balanced parenthesis substrings | function to find number of balanced parenthesis sub strings ; to store required answer ; vector to stores the number of balanced brackets at each depth . ; d stores checks the depth of our sequence for example level of ( ) is 1 and that of ( ( ) ) is 2. ; if open bracket increase depth ; if closing bracket ; return the required answer ; 
def Balanced_Substring(s, n):
    ans = 0
    arr = [0] * (int(n / 2) + 1)
    d = 0
    for i in range(n):
        if (s[i] == '('):
            d += 1
        else:
            if (d == 1):
                j = 2
                while (j <= n // 2 + 1 and arr[j] != 0):
                    arr[j] = 0
            ans += 1
            ans += arr[d]
            arr[d] += 1
            d -= 1
    return ans


s = "()()()"
n = len(s)
print(Balanced_Substring(s, n))

# Expected output:
6
# count ways to divide circle using n non | function to calculate x ^ y % mod efficiently ; initialize the answer ; if power is odd ; update the answer ; square the base and half the exponent ; return the value ; function to calculate ncr % mod efficiently ; initialize the answer ; calculate ncr in o ( r ) ; multiply with the numerator factor ; calculate the inverse of factor of denominator ; multiply with inverse value ; return answer value ; function to return the number of non intersecting chords ; define mod value ; value of c ( 2 n , n ) ; modulo inverse of ( n + 1 ) ; multiply with modulo inverse ; return the answer ; 
def power(x, y, mod):
    res = 1
    while (y):
        if (y & 1):
            res = (res * x) % mod
        x = (x * x) % mod
        y = (y >> 1)
    return (res % mod)


def ncr(n, r, mod):
    res = 1
    for i in range(1, r + 1):
        res = (res * (n - i + 1)) % mod
        inv = power(i, mod - 2, mod)
        res = (res * inv) % mod
    return (res % mod)


def NoOfChords(A):
    mod = 10 ** 9 + 7
    ans = ncr(2 * A, A, mod)
    inv = power(A + 1, mod - 2, mod)
    ans = (ans * inv) % mod
    return (ans % mod)


N = 2
print(NoOfChords(N))

# Expected output:
2
# longest subarray having strictly positive xor | function to return the length of the longest sub - array having positive xor ; to store the xor of all the elements ; to check if all the elements of the array are 0 s ; take xor of all the elements ; if any positive value is found the make the checkallzero false ; if complete array is the answer ; if all elements are equal to zero ; initialize l and r ; first positive value of the array ; last positive value of the array ; maximum length among these two subarrays ; 
def StrictlyPositiveXor(A, N):
    allxor = 0
    checkallzero = True
    for i in range(N):
        allxor ^= A[i]
        if (A[i] > 0):
            checkallzero = False
    if (allxor != 0):
        return N
    if (checkallzero):
        return -1
    l = N
    r = -1
    for i in range(N):
        if (A[i] > 0):
            l = i + 1
            break
    for i in range(N - 1, -1, -1):
        if (A[i] > 0):
            r = i + 1
            break
    return max(N - l, r - 1)


if __name__ == "__main__":
    A = [1, 0, 0, 1]
    N = len(A)
    print(StrictlyPositiveXor(A, N))

# Expected output:
3
# find minimum length sub | python3 implementation of the approach ; function to return the minimum length of a sub - array which contains 0 , 1 , 2 , 3 , 4 as a sub - sequence ; to store the indices where 0 , 1 , 2 , 3 and 4 are present ; to store if there exist a valid prefix of sequence in array ; base case ; if current element is 0 ; update the count of 0 s till now ; push the index of the new 0 ; to check if previous element of the given sequence is found till now ; if it is the end of sequence ; iterate for other elements of the sequence ; binary search to find closest occurrence less than equal to starting point ; update the starting point ; 

MAX_INT = 1000000


def solve(Array, N):
    pos = [[]for i in range(5)]
    pref = [0 for i in range(5)]
    if (Array[0] == 0):
        pref[0] = 1
        pos[0].append(0)
    ans = MAX_INT
    for i in range(N):
        if (Array[i] == 0):
            pref[0] += 1
            pos[0].append(i)
        else:
            if (pref[Array[i] - 1] > 0):
                pref[Array[i]] += 1
                pos[Array[i]].append(i)
                if (Array[i] == 4):
                    end = i
                    start = i
                    for j in range(3, -1, -1):
                        s = 0
                        e = len(pos[j]) - 1
                        temp = -1
                        while (s <= e):
                            m = (s + e) // 2
                            if (pos[j][m] <= start):
                                temp = pos[j][m]
                                s = m + 1
                            else:
                                e = m - 1
                        start = temp
                    ans = min(ans, end - start + 1)
    return ans


Array = [0, 1, 2, 3, 4, 2, 0, 3, 4]
N = len(Array)
print(solve(Array, N))

# Expected output:
5
# find optimal weights which can be used to weigh all the weights in the range [ 1 , x ] | function to find the optimal weights ; number of weights required ; finding the value of required powers of 3 ; optimal weights are powers of 3 ; 
def findWeights(X):
    sum = 0
    power = 0
    while (sum < X):
        sum = pow(3, power + 1) - 1
        sum //= 2
        power += 1
    ans = 1
    for i in range(1, power + 1):
        print(ans, end=" ")
        ans = ans * 3


X = 2
findWeights(X)

# Expected output:
1 3
# order of indices which is lexicographically smallest and sum of elements is <= x | python3 implementation of the approach ; function to return the chosen indices ; maximum indices chosen ; try to replace the first element in ans by i , making the order lexicographically smaller ; if no further replacement possible return ; if found an index smaller than ind and sum not exceeding x then remove index of smallest value from ans and then add index i to ans ; 

import sys


def solve(X, A):
    minimum = sys .maxsize
    ind = -1
    for i in range(len(A)):
        if (A[i] < minimum):
            minimum = A[i]
            ind = i
    maxIndChosen = X // minimum
    ans = []
    if (maxIndChosen == 0):
        return ans
    for i in range(maxIndChosen):
        ans .append(ind)
    temp = maxIndChosen
    sum = maxIndChosen * A[ind]
    for i in range(ind):
        if (sum - X == 0 or temp == 0):
            break
        while ((sum - A[ind] + A[i]) <= X and temp != 0):
            del (ans[0])
            ans .append(i)
            temp -= 1
            sum += (A[i] - A[ind])
    ans .sort()
    return ans


if __name__ == "__main__":
    A = [5, 6, 4, 8]
    X = 18
    ans = solve(X, A)
    for i in range(len(ans)):
        print(ans[i], end=" ")

# Expected output:
0 0 2 2
# find if a binary matrix exists with given row and column sums | function to check if matrix exists ; store sum of rowsums , max of row sum number of non zero row sums ; store sum of column sums , max of column sum number of non zero column sums ; check condition 1 , 2 , 3 ; 
def matrix_exist(row, column, r, c):
    row_sum = 0
    column_sum = 0
    row_max = -1
    column_max = -1
    row_non_zero = 0
    column_non_zero = 0
    for i in range(r):
        row_sum += row[i]
        row_max = max(row_max, row[i])
        if (row[i]):
            row_non_zero = row_non_zero + 1
    for i in range(c):
        column_sum = column_sum + column[i]
        column_max = max(column_max, column[i])
        if (column[i]):
            column_non_zero = column_non_zero + 1
    if ((row_sum != column_sum) or (row_max > column_non_zero)
            or (column_max > row_non_zero)):
        return False
    return True


if __name__ == '__main__':
    row = [2, 2, 2, 2, 2]
    column = [5, 5, 0, 0]
    r = len(row)
    c = len(column)
    if matrix_exist(row, column, r, c):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# length of longest sub | function to find maximum distance between unequal elements ; calculate maxmean ; iterate over array and calculate largest subarray with all elements greater or equal to maxmean ; 
def longestSubarray(arr, n):
    maxMean = 0
    for i in range(1, n):
        maxMean = max(maxMean, (arr[i] + arr[i - 1]) // 2)
    ans = 0
    subarrayLength = 0
    for i in range(n):
        if (arr[i] >= maxMean):
            subarrayLength += 1
            ans = max(ans, subarrayLength)
        else:
            subarrayLength = 0
    return ans


arr = [4, 3, 3, 2, 1, 4]
n = len(arr)
print(longestSubarray(arr, n))

# Expected output:
3
# maximum distance between two unequal elements | function to return the maximum distance between two unequal elements ; if first and last elements are unequal they are maximum distance apart ; fix first element as one of the elements and start traversing from the right ; break for the first unequal element ; to store the distance from the first element ; fix last element as one of the elements and start traversing from the left ; break for the first unequal element ; to store the distance from the last element ; maximum possible distance ; 
def maxDistance(arr, n):
    if (arr[0] != arr[n - 1]):
        return (n - 1)
    i = n - 1
    while (i > 0):
        if (arr[i] != arr[0]):
            break
        i -= 1
    distFirst = -1 if (i == 0)else i
    i = 0
    while (i < n - 1):
        if (arr[i] != arr[n - 1]):
            break
        i += 1
    distLast = -1 if (i == n - 1)else (n - 1 - i)
    maxDist = max(distFirst, distLast)
    return maxDist


arr = [4, 4, 1, 2, 1, 4]
n = len(arr)
print(maxDistance(arr, n))

# Expected output:
4
# minimum number of pairs required to make two strings same | python3 implementation of the approach ; function which will check if there is a path between a and b by using bfs ; function to return the minimum number of pairs ; to store the count of pairs ; iterating through the strings ; check if we can add an edge in the graph ; return the count of pairs ; 

from collections import defaultdict, deque


def Check_Path(a, b, G):
    visited = defaultdict(bool)
    queue = deque()
    queue .append(a)
    visited[a] = True
    while queue:
        n = queue .popleft()
        if n == b:
            return True
        for i in list(G[n]):
            if not visited[i]:
                queue .append(i)
                visited[i] = True
    return False


def countPairs(s1, s2, G):
    name = defaultdict(bool)
    count = 0
    for i in range(x):
        a = s1[i]
        b = s2[i]
        if a in G and b not in G and a != b:
            G[a].append(b)
            G[b].append(a)
            count += 1
        elif b in G and a not in G and a != b:
            G[b].append(a)
            G[a].append(b)
            count += 1
        elif a not in G and b not in G and a != b:
            G[a].append(b)
            G[b].append(a)
            count += 1
        else:
            if not Check_Path(a, b, G) and a != b:
                G[a].append(b)
                G[b].append(a)
                count += 1
    return count


if __name__ == "__main__":
    s1 = "abb"
    s2 = "dad"
    x = len(s1)
    G = defaultdict(list)
    print(countPairs(s1, s2, G))

# Expected output:
2
# generate an array of k elements such that sum of elements is n and the condition a [ i ] < a [ i + 1 ] <= 2 * a [ i ] is met | set 2 | function that print the desired array which satisfies the given conditions ; if the lowest filling condition is void , then it is not possible to generate the required array ; increase all the elements by cnt ; start filling from the back till the number is a [ i + 1 ] <= 2 * a [ i ] ; get the number to be filled ; if it is less than the remaining numbers to be filled ; less than remaining numbers to be filled ; get the sum of the array ; if this condition is void at any stage during filling up , then print - 1 ; else add it to the sum ; if the sum condition is not satisified , then print - 1 ; print the generated array ; 
def solve(n, k):
    mini = 0
    x1 = 1
    a = [0 for i in range(k)]
    for i in range(1, k + 1):
        mini += x1
        a[i - 1] = x1
        x1 += 1
    if (n < mini):
        print("-1", end="")
        return
    rem = n - mini
    cnt = int(rem / k)
    rem = rem % k
    for i in range(k):
        a[i] += cnt
    i = k - 1
    while (i > 0 and rem > 0):
        xx = a[i - 1] * 2
        left = xx - a[i]
        if (rem >= left):
            a[i] = xx
            rem -= left
        else:
            a[i] += rem
            rem = 0
        i -= 1
    sum = a[0]
    for i in range(1, k):
        if (a[i] > 2 * a[i - 1]):
            print("-1", end="")
            return
        sum += a[i]
    if (sum != n):
        print("-1", end="")
        return
    for i in range(k):
        print(a[i], end=" ")


if __name__ == '__main__':
    n = 26
    k = 6
    solve(n, k)

# Expected output:
1 2 3 4 6 10