giulio98/xlcost-single-prompt huggingface dataset:
# count pairs made up of an element divisible by the other from an array consisting of powers of 2 | function to count the number of pairs as per the given conditions ; initialize array set_bits as 0 ; store the total number of required pairs ; traverse the array arr [ ] ; store arr [ i ] in x ; store the position of the leftmost set bit in arr [ i ] ; increase bit position ; divide by 2 to shift bits in right at each step ; count of pairs for index i till its set bit position ; increasing count of set bit position of current elelement ; prthe answer ; 
def numberOfPairs(arr, N):
    set_bits = [0] * 31
    count = 0
    for i in range(N):
        x = arr[i]
        bitpos = -1
        while (x > 0):
            bitpos += 1
            x //= 2
        for j in range(bitpos + 1):
            count += set_bits[j]
        set_bits[bitpos] += 1
    print(count)


if __name__ == '__main__':
    arr = [4, 16, 8, 64]
    N = len(arr)
    numberOfPairs(arr, N)

# Expected output:
5
# queries to find minimum sum of array elements from either end of an array | function to calculate the minimum sum from either end of the arrays for the given queries ; traverse the query [ ] array ; stores sum from start and end of the array ; calculate distance from start ; calculate distance from end ; 
def calculateQuery(arr, N, query, M):
    for i in range(M):
        X = query[i]
        sum_start = 0
        sum_end = 0
        for j in range(N):
            sum_start += arr[j]
            if (arr[j] == X):
                break
        for j in range(N - 1, -1, -1):
            sum_end += arr[j]
            if (arr[j] == X):
                break
        print(min(sum_end, sum_start), end=" ")


if __name__ == "__main__":
    arr = [2, 3, 6, 7, 4, 5, 30]
    queries = [6, 5]
    N = len(arr)
    M = len(queries)
    calculateQuery(arr, N, queries, M)

# Expected output:
11 27
# queries to find minimum sum of array elements from either end of an array | function to find the minimum sum for the given queries ; stores prefix and suffix sums ; stores pairs of prefix and suffix sums ; traverse the array ; add element to prefix ; store prefix for each element ; traverse the array in reverse ; add element to suffix ; storing suffix for each element ; traverse the array queries [ ] ; minimum of suffix and prefix sums ; 
def calculateQuery(arr, N, query, M):
    prefix = 0
    suffix = 0
    mp = {}
    for i in range(N):
        prefix += arr[i]
        mp[arr[i]] = [prefix, 0]
    for i in range(N - 1, -1, -1):
        suffix += arr[i]
        mp[arr[i]] = [mp[arr[i]][0], suffix]
    for i in range(M):
        X = query[i]
        print(min(mp[X][0], mp[X][1]), end=" ")


arr = [2, 3, 6, 7, 4, 5, 30]
queries = [6, 5]
N = len(arr)
M = len(queries)
calculateQuery(arr, N, queries, M)

# Expected output:
11 27
# queries to find the maximum array element after removing elements from a given range | function to find the maximum element after removing elements in range [ l , r ] ; store prefix maximum element ; store suffix maximum element ; prefix max till first index is first index itself ; traverse the array to fill prefix max array ; store maximum till index i ; suffix max till last index is last index itself ; traverse the array to fill suffix max array ; store maximum till index i ; traverse all queries ; store the starting and the ending index of the query ; edge cases ; otherwise ; 
def findMaximum(arr, N, Q, queries):
    prefix_max = [0] * (N + 1)
    suffix_max = [0] * (N + 1)
    prefix_max[0] = arr[0]
    for i in range(1, N):
        prefix_max[i] = max(prefix_max[i - 1], arr[i])
    suffix_max[N - 1] = arr[N - 1]
    for i in range(N - 2, -1, -1):
        suffix_max[i] = max(suffix_max[i + 1], arr[i])
    for i in range(Q):
        l = queries[i][0]
        r = queries[i][1]
        if (l == 0 and r == (N - 1)):
            print("0")
        elif (l == 0):
            print(suffix_max[r + 1])
        elif (r == (N - 1)):
            print(prefix_max[l - 1])
        else:
            print(max(prefix_max[l - 1], suffix_max[r + 1]))


if __name__ == '__main__':
    arr = [5, 6, 8, 10, 15]
    N = len(arr)
    queries = [[0, 1], [0, 2], [1, 4]]
    Q = len(queries)
    findMaximum(arr, N, Q, queries)

# Expected output:
15
15
5
# queries to find first occurrence of a character in a given range | python3 implementation for the above approach ; function to find the first occurence for a given range ; n = length of string ; m = length of queries ; stores the indices of a character ; traverse the string ; push the index i into the vector [ s [ i ] ] ; traverse the query ; stores the value l ; stores the value r ; stores the character c ; find index >= l in the vector v ; if there is no index of c >= l ; stores the value at idx ; if idx > r ; otherwise ; 

from bisect import bisect_left


def firstOccurence(s, Q):
    N = len(s)
    M = len(Q)
    v = [[]for i in range(26)]
    for i in range(N):
        v[ord(s[i]) - ord('a')].append(i)
    for i in range(M):
        left = Q[i][0]
        right = Q[i][1]
        c = Q[i][2]
        if (len(v[ord(c) - ord('a')]) == 0):
            print("-1")
            continue
        idx = bisect_left(v[ord(c) - ord('a')], left)
        if (idx == len(v[ord(c) - ord('a')])):
            print("-1 ")
            continue
        idx = v[ord(c) - ord('a')][idx]
        if (idx > right):
            print("-1 ")
        else:
            print(idx, end=" ")


if __name__ == '__main__':
    S = "abcabcabc"
    Q = [[0, 3, 'a'], [0, 2, 'b'], [2, 4, 'z']]
    firstOccurence(S, Q)

# Expected output:
0 1 -1
# find index of the element differing in parity with all other array elements | function to prthe element which differs in parity ; stores the count of odd and even array elements encountered ; stores the indices of the last odd and even array elements encountered ; traverse the array ; if array element is even ; otherwise ; if only one odd element is present in the array ; if only one even element is present in the array ; 
def oddOneOut(arr, N):
    odd = 0
    even = 0
    lastOdd = 0
    lastEven = 0
    for i in range(N):
        if (arr[i] % 2 == 0):
            even += 1
            lastEven = i
        else:
            odd += 1
            lastOdd = i
    if (odd == 1):
        print(lastOdd)
    else:
        print(lastEven)


arr = [2, 4, 7, 8, 10]
N = len(arr)
oddOneOut(arr, N)

# Expected output:
2
# reduce a string to a valid email address of minimum length by replacing specified substrings | function to find the minimum length by replacing at with @ and dot with ' . ' such that the string is valid email ; stores string by replacing at with @ and dot with ' . ' such that the string is valid email ; append first character ; stores index ; check if at ( @ ) already included or not ; iterate over characters of the string ; at can be replaced at most once ; update ans ; update i ; update notat ; if current substring found dot ; update ans ; update i ; update ans ; update i ; 
def minEmail(email):
    ans = ''
    ans += email[0]
    i = 1
    notAt = True
    while i < len(email):
        if (i < len(email) - 3 and notAt and email[i:i + 2] == 'at'):
            ans += '@'
            i += 1
            notAt = False
        elif i < len(email) - 4 and email[i:i + 3] == 'dot':
            ans += '.'
            i += 2
        else:
            ans += email[i]
        i += 1
    return ans


if __name__ == '__main__':
    email = 'geeksforgeeksatgmaildotcom'
    print(minEmail(email))

# Expected output:
geeksforgeeks@gmail.com
# find the smallest value of n such that sum of first n natural numbers is â ‰¥ x | function to check if sum of first n natural numbers is >= x ; finds minimum value of n such that sum of first n natural number >= x ; check if sum of first i natural number >= x ; 
def isGreaterEqual(N, X):
    return (N * (N + 1) // 2) >= X


def minimumPossible(X):
    for i in range(1, X + 1):
        if (isGreaterEqual(i, X)):
            return i


if __name__ == '__main__':
    X = 14
    print(minimumPossible(X))

# Expected output:
5
# queries to count numbers from given range which are divisible by all its digits | function to check if a number is divisible by all of its non - zero digits or not ; stores the number ; iterate over the digits of the numbers ; if digit of number is non - zero ; if number is not divisible by its current digit ; update n ; function to count of numbers which are divisible by all of its non - zero digits in the range [ 1 , i ] ; stores count of numbers which are divisible by all of its non - zero digits in the range [ 1 , i ] ; iterate over the range [ 1 , max ] ; update ; traverse the array , arr [ ] ; 
def CheckDivByAllDigits(number):
    n = number
    while (n > 0):
        if (n % 10):
            if (number % (n % 10)):
                return False
        n //= 10
    return True


def cntNumInRang(arr, N):
    global Max
    prefCntDiv = [0] * Max
    for i in range(1, Max):
        prefCntDiv[i] = prefCntDiv[i - 1] + (CheckDivByAllDigits(i))
    for i in range(N):
        print(prefCntDiv[arr[i][1]] - prefCntDiv[arr[i][0] - 1], end=" ")


if __name__ == '__main__':
    arr = [[1, 5], [12, 14]]
    Max = 1000005
    N = len(arr)
    cntNumInRang(arr, N)

# Expected output:
5 1
# longest subset of nested elements from a given array | function to find length of longest subset such that subset { arr [ i ] , arr [ arr [ i ] ] , . . } ; stores length of the longest subset that satisfy the condition ; traverse in the array , arr [ ] ; if arr [ i ] equals to i ; update res ; count of elements in a subset ; stores index of elements in the current subset ; calculate length of a subset that satisfy the condition ; make visited the current index ; update curr_index ; update count ; update res ; 
def arrayNesting(arr):
    res = 0
    for i in range(len(arr)):
        if arr[i] == i:
            res = max(res, 1)
        else:
            count = 0
            curr_index = i
            while arr[curr_index] != curr_index:
                next_index = arr[curr_index]
                arr[curr_index] = curr_index
                curr_index = next_index
                count += 1
        res = max(res, count)
    return res


if __name__ == "__main__":
    arr = [5, 4, 0, 3, 1, 6, 2]
    res = arrayNesting(arr)
    print(res)

# Expected output:
4
# minimize remaining array sizes by removing equal pairs of first array elements | function to count the remaining elements in the arrays ; stores the count of 1 s in l1 ; store the count of 0 s in l2 ; traverse the array l1 ; if condition is true ; increment one by 1 ; increment zero by 1 ; stores the index after which no further removals are possible ; traverse the array l2 ; if condition is true ; decrement one by 1 ; if one < 0 , then break out of the loop ; decrement zero by 1 ; if zero < 0 , then break out of loop ; print the answer ; 
def countRemainingElements(L1, L2, n):
    one = 0
    zero = 0
    for i in range(n):
        if (L1[i] == 1):
            one += 1
        else:
            zero += 1
    ans = n
    for i in range(n):
        if (L2[i] == 1):
            one -= 1
            if (one < 0):
                ans = i
                break
        else:
            zero -= 1
            if (zero < 0):
                ans = i
                break
    print(n - ans)


if __name__ == '__main__':
    L1 = [1, 1, 0, 0]
    L2 = [0, 0, 0, 1]
    N = len(L1)
    countRemainingElements(L1, L2, N)

# Expected output:
2
# count pairs of similar rectangles possible from a given array | function to calculate the count of similar rectangles ; 
def getCount(rows, columns, A):
    res = 0
    for i in range(rows):
        for j in range(i + 1, rows, 1):
            if (A[i][0] * A[j][1] == A[i][1] * A[j][0]):
                res += 1
    return res


if __name__ == '__main__':
    A = [[4, 8], [10, 20], [15, 30], [3, 6]]
    columns = 2
    rows = len(A)
    print(getCount(rows, columns, A))

# Expected output:
6
# find the index with minimum score from a given array | function to find the index with minimum score ; stores the score of current index ; traverse the array in reverse ; update minimum score ; print the index with minimum score ; 
def Min_Score_Index(N, A):
    Score = [0] * N
    for i in range(N - 1, -1, -1):
        if A[i] + i < N:
            Score[i] = A[i] * Score[A[i] + i]
        else:
            Score[i] = A[i]
    min_value = min(Score)
    ind = Score .index(min_value)
    print(ind)


if __name__ == "__main__":
    N = 5
    A = [1, 2, 3, 4, 5]
    Min_Score_Index(N, A)

# Expected output:
2
# minimize length of a string by removing occurrences of another string from it as a substring | function to minimize length of string s after removing all occurrences of string t as substring ; count of characters required to be removed ; iterate over the string ; insert the current character to temp ; check if the last m characters forms t or not ; getting the last m characters . if they are equal to t then remove the last m characters from the temp string ; incrementing subtract by m ; removing last m characters from the string ; prthe final answer ; 
def minLength(S, T, N, M):
    temp = ""
    subtract = 0
    for i in range(N):
        temp += S[i]
        if (len(temp) >= M):
            if (T == (temp[len(temp) - M:len(temp)])):
                subtract += M
                cnt = 0
                while (cnt != M):
                    temp = temp[0:len(temp) - 1]
                    cnt += 1
    print((N - subtract))


if __name__ == '__main__':
    S = "aabcbcbd"
    T = "abc"
    N = len(S)
    M = len(T)
    minLength(S, T, N, M)

# Expected output:
2
# minimize swaps between two arrays such that sum of the first array exceeds sum of the second array | function to find the minimum count of swaps required between the two arrays to make the sum of arr1 [ ] greater than that of arr2 [ ] ; stores the sum of the two arrays ; calculate sum of arr1 [ ] ; calculate sum of arr2 [ ] ; sort the arrays arr1 [ ] and arr2 [ ] ; traverse the array arr [ ] ; if the sum1 is less than or equal to sum2 ; swapping the elements ; update the sum1 and sum2 ; increment the count ; return the final count ; 
def maximumCount(arr1, arr2, s1, s2):
    sum1 = 0
    sum2 = 0
    for i in range(s1):
        sum1 += arr1[i]
    for j in range(s2):
        sum2 += arr2[j]
    len = 0
    if (s1 >= s2):
        lenn = s2
    else:
        lenn = s1
    arr1 .sort()
    arr2 .sort()
    j = 0
    k = s2 - 1
    count = 0
    for i in range(lenn):
        if (sum1 <= sum2):
            if (arr2[k] >= arr1[i]):
                dif1 = arr1[j]
                dif2 = arr2[k]
                sum1 -= dif1
                sum1 += dif2
                sum2 -= dif2
                sum2 += dif1
                j += 1
                k -= 1
                count += 1
            else:
                break
        else:
            break
    return count


arr1 = [1, 3, 2, 4]
arr2 = [6, 7, 8]
N = len(arr1)
M = len(arr2)
print(maximumCount(arr1, arr2, N, M))

# Expected output:
1
# count array elements whose all distinct digits appear in k | function to check a digit occurs in the digit of k or not ; iterate over all possible digits of k ; if current digit equal to digit ; update k ; function to find the count of array elements whose distinct digits are a subset of digits of k ; stores count of array elements whose distinct digits are subset of digits of k ; traverse the array , [ ] arr ; stores the current element ; check if all the digits arr [ i ] is a subset of the digits of k or not ; iterate over all possible digits of arr [ i ] ; stores current digit ; if current digit does not appear in k ; update flag ; update no ; if all the digits arr [ i ] appear in k ; update count ; finally print count ; 
def isValidDigit(digit, K):
    while (K != 0):
        if (K % 10 == digit):
            return True
        K = K // 10
    return False


def noOfValidNumbers(K, arr, n):
    count = 0
    for i in range(n):
        no = arr[i]
        flag = True
        while (no != 0):
            digit = no % 10
            if (not isValidDigit(digit, K)):
                flag = False
                break
            no = no // 10
        if (flag):
            count += 1
    return count


if __name__ == "__main__":
    K = 12
    arr = [1, 12, 1222, 13, 2]
    n = len(arr)
    print(noOfValidNumbers(K, arr, n))

# Expected output:
4
# queries to find the minimum index in given array having at least value x | python3 program to implement the above approachf ; function to find the smallest index of an array element whose value is less than or equal to q [ i ] ; stores size of array ; stores coun of queries ; store array elements along with the index ; store smallest index of an array element whose value is greater than or equal to i ; traverse the array ; insert { arr [ i ] , i } into storearridx [ ] ; sort the array ; sort the storearridx ; stores index of arr [ n - 1 ] in sorted order ; traverse the array storearridx [ ] ; update minidx [ i ] ; traverse the array q [ ] ; store the index of lower_bound of q [ i ] ; if no index found whose value greater than or equal to arr [ i ] ; prsmallest index whose value greater than or equal to q [ i ] ; 

from bisect import bisect_left


def minimumIndex(arr, Q):
    N = len(arr)
    M = len(Q)
    storeArrIdx = []
    minIdx = [0] * (N)
    for i in range(N):
        storeArrIdx .append([arr[i], i])
    arr = sorted(arr)
    storeArrIdx = sorted(storeArrIdx)
    minIdx[N - 1] = storeArrIdx[N - 1][1]
    for i in range(N - 2, -1, -1):
        minIdx[i] = min(minIdx[i + 1], storeArrIdx[i][1])
    for i in range(M):
        pos = bisect_left(arr, Q[i])
        if (pos == N):
            print(-1, end=" ")
            continue
        print(minIdx[pos], end=" ")


if __name__ == '__main__':
    arr = [1, 9]
    Q = [7, 10, 0]
    minimumIndex(arr, Q)

# Expected output:
1 -1 0
# find a k | utility function to check if subarray of size k exits whose xor of elements equal to xor ofremaning array elements ; find xor of whole array ; find xor of first k elements ; adding xor of next element ; removing xor of previous element ; check if xor of current subarray matches with the xor of remaining elements or not ; function to check if subarray of size k exits whose xor of elements equal to xor ofremaning array elements ; 
def isSubarrayExistUtil(arr, K, N):
    totalXOR = 0
    SubarrayXOR = 0
    for i in range(N):
        totalXOR ^= arr[i]
    for i in range(K):
        SubarrayXOR ^= arr[i]
    if (SubarrayXOR == (totalXOR ^ SubarrayXOR)):
        return True
    for i in range(K, N):
        SubarrayXOR ^= arr[i]
        SubarrayXOR ^= arr[i - 1]
        if (SubarrayXOR == (totalXOR ^ SubarrayXOR)):
            return True
    return False


def isSubarrayExist(arr, K, N):
    if (isSubarrayExistUtil(arr, K, N)):
        print("YES")
    else:
        print("NO")


if __name__ == '__main__':
    arr = [2, 3, 3, 5, 7, 7, 3, 4]
    N = len(arr)
    K = 5
    isSubarrayExist(arr, K, N)

# Expected output:
YES
# count pairs from a given range having even sum | function to find the count of ordered pairs having even sum ; stores count of even numbers in the range [ l , r ] ; if l is even ; update count_even ; update count_odd ; stores count of odd numbers in the range [ l , r ] ; update count_odd ; update count_odd ; stores count of pairs whose sum is even and both elements of the pairs are also even ; stores count of pairs whose sum is even and both elements of the pairs are odd ; print total ordered pairs whose sum is even ; 
def countPairs(L, R):
    count_even = 0
    if (L % 2 == 0):
        count_even = ((R // 2) - (L // 2) + 1)
    else:
        count_even = ((R // 2) - (L // 2))
    count_odd = 0
    if (L % 2 == 0):
        count_odd = (((R + 1) // 2) - ((L + 1) // 2))
    else:
        count_odd = (((R + 1) // 2) - ((L + 1) // 2) + 1)
    count_even *= count_even
    count_odd *= count_odd
    print(count_even + count_odd)


if __name__ == '__main__':
    L, R = 1, 3
    countPairs(L, R)

# Expected output:
5
# count of array elements that can be found using randomized binary search on every array element | python3 program for the above approach ; function to find minimum count of array elements found by repeatedly applying randomized binary search ; stores count of array elements ; smallestright [ i ] : stores the smallest array element on the right side of i ; update smallestright [ 0 ] ; traverse the array from right to left ; update smallestright [ i ] ; stores the largest element upto i - th index ; stores the minimum count of elements found by repeatedly applying randomized binary search ; if largest element on left side is less than smallest element on right side ; update ans ; update mn ; 

import sys


def getDefiniteFinds(arr):
    n = len(arr)
    smallestRight = [0] * (n + 1)
    smallestRight[n] = sys .maxsize
    for i in range(n - 1, -1, -1):
        smallestRight[i] = min(smallestRight[i + 1], arr[i])
    mn = -sys .maxsize - 1
    ans = 0
    for i in range(n):
        if (mn < arr[i] and arr[i] < smallestRight[i + 1]):
            ans += 1
        mn = max(arr[i], mn)
    return ans


arr = [5, 4, 9]
print(getDefiniteFinds(arr))

# Expected output:
1
# count numbers from a given range having same first and last digits in their binary representation | function to count numbers in range [ l , r ] having same first and last digit in the binary representation ; 
def Count_numbers(L, R):
    count = (R - L) // 2
    if (R % 2 != 0 or L % 2 != 0):
        count += 1
    print(count)


L = 6
R = 30
Count_numbers(L, R)

# Expected output:
12
# find the index having sum of elements on its left equal to reverse of the sum of elements on its right | function to check if a number is equal to the reverse of digits of other number ; stores reverse of digits of rightsum ; stores rightsum ; calculate reverse of digits of temp ; update rev ; update temp ; if reverse of digits of rightsum equal to leftsum ; function to find the index that satisfies the condition ; stores sum of array elements on right side of each index ; stores sum of array elements on left side of each index ; traverse the array ; update rightsum ; traverse the array ; update rightsum ; if leftsum equal to reverse of digits of rightsum ; update leftsum ; 
def checkReverse(leftSum, rightSum):
    rev = 0
    temp = rightSum
    while (temp != 0):
        rev = (rev * 10) + (temp % 10)
        temp //= 10
    if (rev == leftSum):
        return True
    return False


def findIndex(arr, N):
    rightSum = 0
    leftSum = 0
    for i in range(N):
        rightSum += arr[i]
    for i in range(N):
        rightSum -= arr[i]
        if (checkReverse(leftSum, rightSum)):
            return i
        leftSum += arr[i]
    return -1


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

# Expected output:
2
# print distinct absolute differences of all possible pairs from a given array | python3 program for the above approach ; function to find all distinct absolute difference of all possible pairs of the array ; bset [ i ] : check if i is present in the array or not ; diff [ i ] : check if there exists a pair whose absolute difference is i ; traverse the array , arr [ ] ; iterate over the range [ 0 , max ] ; if i - th bit is set ; insert the absolute difference of all possible pairs whose first element is arr [ i ] ; stores count of set bits ; if there is at least one duplicate element in arr [ ] ; printing the distinct absolute differences of all possible pairs ; if i - th bit is set ; 

Max = 100005


def printUniqDif(n, a):
    bset = [0 for i in range(33)]
    diff = 0
    for i in range(n):
        bset[a[i]] = 1
    d = 0
    for i in range(1, 33):
        d = d | (bset[i] << i)
    for i in range(33):
        if (bset[i]):
            diff = diff | d >> i
    X, Y = bset .count(1), str(bin(diff)[2:])
    if (X != n):
        print(0, end=" ")
    for i in range(1, len(Y)):
        if (Y[i] == '1'):
            print(i, end=" ")


if __name__ == '__main__':
    a = [1, 4, 6]
    n = len(a)
    printUniqDif(n, a)

# Expected output:
2 3 5