giulio98/xlcost-single-prompt huggingface dataset:
# total time required to travel a path denoted by a given string | function to calculate time taken to travel the path ; stores total time ; initial position ; stores visited segments ; check whether segment is present in the set ; increment the value of time by 2 ; insert segment into the set ; print the value of time ; 
def calcTotalTime(path):
    time = 0
    x = 0
    y = 0
    s = set([])
    for i in range(len(path)):
        p = x
        q = y
        if (path[i] == 'N'):
            y += 1
        elif (path[i] == 'S'):
            y -= 1
        elif (path[i] == 'E'):
            x += 1
        elif (path[i] == 'W'):
            x -= 1
        if (p + x, q + y)not in s:
            time += 2
            s .add((p + x, q + y))
        else:
            time += 1
    print(time)


if __name__ == "__main__":
    path = "NSE"
    calcTotalTime(path)

# Expected output:
5
# cost required to make all array elements equal to 1 | function to calculate the cost required to make all array elements equal to 1 ; stores the total cost ; traverse the array arr [ ] ; if current element is 0 ; convert 0 to 1 ; add the cost ; return the total cost ; 
def findCost(A, N):
    totalCost = 0
    for i in range(N):
        if (A[i] == 0):
            A[i] = 1
            totalCost += i
    return totalCost


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

# Expected output:
9
# find the peak index of a given array | function to find the peak index for the given array ; base case ; check for strictly increasing array ; if the strictly increasing condition is violated , then break ; stores the value of i , which is a potential peak index ; second traversal , for strictly decreasing array ; when the strictly decreasing condition is violated , then break ; if i = n - 1 , it means that ans is the peak index ; otherwise , peak index doesn 't exist ; 
def peakIndex(arr):
    N = len(arr)
    if (len(arr) < 3):
        return -1
    i = 0
    while (i + 1 < N):
        if (arr[i + 1] < arr[i] or arr[i] == arr[i + 1]):
            break
        i += 1
    if (i == 0 or i == N - 1):
        return -1
    ans = i
    while (i < N - 1):
        if (arr[i] < arr[i + 1] or arr[i] == arr[i + 1]):
            break
        i += 1
    if (i == N - 1):
        return ans
    return -1


if __name__ == '__main__':
    arr = [0, 1, 0]
    print(peakIndex(arr))

# Expected output:
1
# given an array a [ ] and a number x , check for pair in a [ ] with sum as x | set 2 | function to check if the array has 2 elements whose sum is equal to the given value ; sort the array in increasing order ; traverse the array , nums [ ] ; store the required number to be found ; perform binary search ; store the mid value ; if nums [ mid ] is greater than x , then update high to mid - 1 ; if nums [ mid ] is less than x , then update low to mid + 1 ; otherwise ; if mid is equal i , check mid - 1 and mid + 1 ; otherwise , prthe pair and return ; if no such pair is found , then pr - 1 ; 
def hasArrayTwoPairs(nums, n, target):
    nums = sorted(nums)
    for i in range(n):
        x = target - nums[i]
        low, high = 0, n - 1
        while (low <= high):
            mid = low + ((high - low) // 2)
            if (nums[mid] > x):
                high = mid - 1
            elif (nums[mid] < x):
                low = mid + 1
            else:
                if (mid == i):
                    if ((mid - 1 >= 0) and nums[mid - 1] == x):
                        print(nums[i], end=", ")
                        print(nums[mid - 1])
                        return
                    if ((mid + 1 < n) and nums[mid + 1] == x):
                        print(nums[i], end=", ")
                        print(nums[mid + 1])
                        return
                    break
                else:
                    print(nums[i], end=", ")
                    print(nums[mid])
                    return
    print(-1)


if __name__ == '__main__':
    A = [0, -1, 2, -3, 1]
    X = -2
    N = len(A)
    hasArrayTwoPairs(A, N, X)

# Expected output:
-3, 1
# smallest divisor of n closest to x | python3 program for the above approach ; function to find the divisor of n closest to the target ; iterate till square root of n ; check if divisors are equal ; check if i is the closest ; check if i is the closest ; check if n / i is the closest ; prthe closest value ; 

from math import sqrt, floor, ceil


def findClosest(N, target):
    closest = -1
    diff = 10 ** 18
    for i in range(1, ceil(sqrt(N)) + 1):
        if (N % i == 0):
            if (N // i == i):
                if (abs(target - i) < diff):
                    diff = abs(target - i)
                    closest = i
            else:
                if (abs(target - i) < diff):
                    diff = abs(target - i)
                    closest = i
                if (abs(target - N // i) < diff):
                    diff = abs(target - N // i)
                    closest = N // i
    print(closest)


if __name__ == '__main__':
    N, X = 16, 5
    findClosest(N, X)

# Expected output:
4
# find a pair ( a , b ) such that aa + bb = n | function to calculate the minimum power of a and b greater than n ; stores the power of a which is greater than n ; increment count by 1 ; divide n by a ; function to find a pair ( a , b ) such that a ^ a + b ^ b = n ; calculate the minimum power of a greater than n ; calculate the minimum power of b greater than n ; make copy of a and b ; traverse for every pair ( i , j ) ; check if b ^ j + a ^ i = n to overcome the overflow problem use b = n - a rather than b + a = n ; increment power b by 1 ; increment power a by 1 ; finally pr - 1 if no pair is found ; 
def power(A, N):
    count = 0
    if (A == 1):
        return 0
    while (N > 0):
        count += 1
        N //= A
    return int(count)


def Pairs(N, A, B):
    powerA, powerB = 0, 0
    powerA = power(A, N)
    powerB = power(B, N)
    intialB = B
    intialA = A
    A = 1
    for i in range(powerA + 1):
        B = 1
        for j in range(powerB + 1):
            if (B == N - A):
                print(i, " ", j)
                return
            B *= intialB
        A *= intialA
    print("-1")
    return


if __name__ == '__main__':
    N = 106
    A = 3
    B = 5
    Pairs(N, A, B)

# Expected output:
4   2
# count numbers from a given range that are not divisible by any of the array elements | function to find the non - multiples till k ; stores all unique multiples ; iterate the array ; for finding duplicates only once ; inserting all multiples into the set ; returning only the count of numbers that are not divisible by any of the array elements ; function to count the total values in the range [ l , r ] ; count all values in the range using exclusion principle ; 
def findNonMultiples(arr, n, k):
    multiples = set([])
    for i in range(n):
        if (arr[i]not in multiples):
            for j in range(1, k // arr[i] + 1):
                multiples .add(arr[i] * j)
    return k - len(multiples)


def countValues(arr, N, L, R):
    return (findNonMultiples(arr, N, R) - findNonMultiples(arr, N, L - 1))


if __name__ == "__main__":
    arr = [2, 3, 4, 5, 6]
    N = len(arr)
    L = 1
    R = 20
    print(countValues(arr, N, L, R))

# Expected output:
6
# minimum number of coins to be collected per hour to empty n piles in at most h hours | function to find the minimum number of coins to be collected per hour to empty n piles in h hours ; stores the minimum coins to be removed per hour ; find the maximum array element ; perform binary search ; store the mid value of the range in k ; find the total time taken to empty n piles by removing k coins per hour ; if total time does not exceed h ; otherwise ; prthe required result ; 
def minCollectingSpeed(piles, H):
    ans = -1
    low = 1
    high = max(piles)
    while (low <= high):
        K = low + (high - low) // 2
        time = 0
        for ai in piles:
            time += (ai + K - 1) // K
        if (time <= H):
            ans = K
            high = K - 1
        else:
            low = K + 1
    print(ans)


if __name__ == '__main__':
    arr = [3, 6, 7, 11]
    H = 8
    minCollectingSpeed(arr, H)

# Expected output:
4
# count distinct pairs with given sum | function to count distinct pairs in array whose sum equal to k ; stores count of distinct pairs whose sum equal to k ; sort the array ; stores index of the left pointer ; stores index of the right pointer ; calculate count of distinct pairs whose sum equal to k ; if sum of current pair is equal to k ; remove consecutive duplicate array elements ; update i ; remove consecutive duplicate array elements ; update j ; update cntpairs ; update i ; update j ; if sum of current pair less than k ; update i ; update j ; 
def cntDisPairs(arr, N, K):
    cntPairs = 0
    arr = sorted(arr)
    i = 0
    j = N - 1
    while (i < j):
        if (arr[i] + arr[j] == K):
            while (i < j and arr[i] == arr[i + 1]):
                i += 1
            while (i < j and arr[j] == arr[j - 1]):
                j -= 1
            cntPairs += 1
            i += 1
            j -= 1
        elif (arr[i] + arr[j] < K):
            i += 1
        else:
            j -= 1
    return cntPairs


if __name__ == '__main__':
    arr = [5, 6, 5, 7, 7, 8]
    N = len(arr)
    K = 13
    print(cntDisPairs(arr, N, K))

# Expected output:
2
# count distinct pairs with given sum | function to count distinct pairs in array whose sum equal to k ; stores count of distinct pairs whose sum equal to k ; store frequency of each distinct element of the array ; update frequency of arr [ i ] ; traverse the map ; stores key value of the map ; if i is the half of k ; if frequency of i greater than 1 ; update cntpairs ; update cntpairs ; 
def cntDisPairs(arr, N, K):
    cntPairs = 0
    cntFre = {}
    for i in arr:
        if i in cntFre:
            cntFre[i] += 1
        else:
            cntFre[i] = 1
    for key, value in cntFre .items():
        i = key
        if (2 * i == K):
            if (cntFre[i] > 1):
                cntPairs += 2
        else:
            if (cntFre[K - i]):
                cntPairs += 1
    cntPairs = cntPairs / 2
    return cntPairs


arr = [5, 6, 5, 7, 7, 8]
N = len(arr)
K = 13
print(int(cntDisPairs(arr, N, K)))

# Expected output:
2
# queries to find longest subsequence having no similar adjacent elements with updates | function to find the length of the longest subsequence such that no two adjacent elements are equal ; replace element at index x with y ; since x is 1 - indexed , decrement x by 1 ; keep track of number of elements in subsequence ; if previous element is not same as current element ; print the desired count ; 
def longestSubsequence(N, Q, arr, Queries):
    for i in range(Q):
        x = Queries[i][0]
        y = Queries[i][1]
        arr[x - 1] = y
        count = 1
        for j in range(1, N):
            if (arr[j] != arr[j - 1]):
                count += 1
        print(count, end=' ')


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

# Expected output:
5 3
# queries to find longest subsequence having no similar adjacent elements with updates | python3 program for the above approach ; traverse the array arr [ ] ; if previous element is not same as current element ; traverse the queries ; replace element at index x with y ; recalculate for index x ; subtract contribution of element at index x ; add contribution of y ; recalculate for index x + 1 ; subtract contribution of element at index x + 1 ; adds contribution of y ; replace the element ; 
def longestSubsequence(N, Q, arr, Queries):
    count = 1
    for i in range(1, N):
        if (arr[i] != arr[i - 1]):
            count += 1
    for i in range(Q):
        x = Queries[i][0]
        y = Queries[i][1]
        if (x > 1):
            if (arr[x - 1] != arr[x - 2]):
                count -= 1
            if (arr[x - 2] != y):
                count += 1
        if (x < N):
            if (arr[x] != arr[x - 1]):
                count -= 1
            if (y != arr[x]):
                count += 1
        print(count, end=' ')
        arr[x - 1] = y


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

# Expected output:
5 3
# sum of absolute differences of indices of occurrences of each array element | python3 program for the above approach ; function to find sum of differences of indices of occurrences of each unique array element ; stores indices of each array element ; store the indices ; stores the sums ; traverse the array ; find sum for each element ; iterate over the map ; calculate sum of occurrences of arr [ i ] ; store sum for current element ; print answer for each element ; 

from collections import defaultdict


def sum_i(arr, n):
    mp = defaultdict(lambda: [])
    for i in range(n):
        mp[arr[i]].append(i)
    ans = [0] * n
    for i in range(n):
        sum = 0
        for it in mp[arr[i]]:
            sum += abs(it - i)
            ans[i] = sum
    for i in range(n):
        print(ans[i], end=" ")


if __name__ == '__main__':
    arr = [1, 3, 1, 1, 2]
    n = len(arr)
    sum_i(arr, n)

# Expected output:
5 0 3 4 0
# convert vowels into upper case character in a given string | function to convert vowels into uppercase ; stores the length of str ; 
def conVowUpp(str):
    N = len(str)
    str1 = ""
    for i in range(N):
        if (str[i] == 'a' or str[i] == 'e' or str[i]
                == 'i' or str[i] == 'o' or str[i] == 'u'):
            c = (str[i]).upper()
            str1 += c
        else:
            str1 += str[i]
    print(str1)


if __name__ == '__main__':
    str = "eutopia"
    conVowUpp(str)

# Expected output:
EUtOpIA
# maximize number of days for which p chocolates can be distributed consecutively to n people | stores the frequency of each type of chocolate ; function to check if chocolates can be eaten for ' mid ' no . of days ; if cnt exceeds n , return true ; function to find the maximum number of days for which chocolates can be eaten ; store the frequency of each type of chocolate ; initialize start and end with 0 and p respectively ; calculate mid ; check if chocolates can be distributed for mid days ; check if chocolates can be distributed for more than mid consecutive days ; 

mp = {}
N, P = 0, 0


def helper(mid):
    cnt = 0
    for i in mp:
        temp = mp[i]
        while (temp >= mid):
            temp -= mid
            cnt += 1
    return cnt >= N


def findMaximumDays(arr):
    for i in range(P):
        mp[arr[i]] = mp .get(arr[i], 0) + 1
    start = 0
    end = P
    ans = 0
    while (start <= end):
        mid = start + ((end - start) // 2)
        if (mid != 0 and helper(mid)):
            ans = mid
            start = mid + 1
        elif (mid == 0):
            start = mid + 1
        else:
            end = mid - 1
    return ans


if __name__ == '__main__':
    N = 3
    P = 10
    arr = [1, 2, 2, 1, 1, 3, 3, 3, 2, 4]
    print(findMaximumDays(arr))

# Expected output:
3
# count subarrays having sum modulo k same as the length of the subarray | function that counts the subarrays having sum modulo k equal to the length of subarray ; stores the count of subarrays ; stores prefix sum of the array ; calculate prefix sum array ; generate all the subarrays ; check if this subarray is a valid subarray or not ; total count of subarrays ; given arr [ ] ; size of the array ; 
def countSubarrays(a, n, k):
    ans = 0
    pref = []
    pref .append(0)
    for i in range(n):
        pref .append((a[i] + pref[i]) % k)
    for i in range(1, n + 1, 1):
        for j in range(i, n + 1, 1):
            if ((pref[j] - pref[i - 1] + k) % k == j - i + 1):
                ans += 1
    print(ans, end=' ')


arr = [2, 3, 5, 3, 1, 5]
N = len(arr)
K = 4
countSubarrays(arr, N, K)

# Expected output:
5
# count subarrays having sum modulo k same as the length of the subarray | function that counts the subarrays s . t . sum of elements in the subarray modulo k is equal to size of subarray ; stores the count of ( pref [ i ] - i ) % k ; stores the count of subarray ; stores prefix sum of the array ; find prefix sum array ; base condition ; remove the index at present after k indices from the current index ; update the answer for subarrays ending at the i - th index ; add the calculated value of current index to count ; print the count of subarrays ; given arr [ ] ; size of the array ; 
def countSubarrays(a, n, k):
    cnt = {}
    ans = 0
    pref = []
    pref .append(0)
    for i in range(n):
        pref .append((a[i] + pref[i]) % k)
    cnt[0] = 1
    for i in range(1, n + 1):
        remIdx = i - k
        if (remIdx >= 0):
            if ((pref[remIdx] - remIdx % k + k) % k in cnt):
                cnt[(pref[remIdx] - remIdx % k + k) % k] -= 1
            else:
                cnt[(pref[remIdx] - remIdx % k + k) % k] = -1
        if (pref[i] - i % k + k) % k in cnt:
            ans += cnt[(pref[i] - i % k + k) % k]
        if (pref[i] - i % k + k) % k in cnt:
            cnt[(pref[i] - i % k + k) % k] += 1
        else:
            cnt[(pref[i] - i % k + k) % k] = 1
    print(ans, end=' ')


arr = [2, 3, 5, 3, 1, 5]
N = len(arr)
K = 4
countSubarrays(arr, N, K)

# Expected output:
5
# check if all substrings of length k of a binary string has equal count of 0 s and 1 s | function to check if the substring of length k has equal 0 and 1 ; traverse the string ; check if every k - th character is the same or not ; traverse substring of length k ; if current character is 0 ; increment count ; otherwise ; decrement count ; check for equal 0 s and 1 s ; 
def check(s, k):
    n = len(s)
    for i in range(k):
        for j in range(i, n, k):
            if (s[i] != s[j]):
                return False
    c = 0
    for i in range(k):
        if (s[i] == '0'):
            c += 1
        else:
            c -= 1
    if (c == 0):
        return True
    else:
        return False


s = "101010"
k = 2
if (check(s, k) != 0):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check if characters of a given string can be used to form any n equal strings | python3 program for the above approach ; function to check if the freq of any character is divisible by n ; stores the frequency of characters ; if frequency of a character is not divisible by n ; if no character has frequency at least n ; 

from collections import defaultdict


def isSame(str, n):
    mp = defaultdict(lambda: 0)
    for i in range(len(str)):
        mp[ord(str[i]) - ord('a')] += 1
    for it in mp .keys():
        if (mp[it] >= n):
            return True
    return False


str = "ccabcba"
n = 4
if (isSame(str, n)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# find the root of given non decreasing function between a and b | python3 program for the above approach ; given function ; function to find the root of the given non - decreasing function ; to get the minimum possible answer for the root ; find mid ; search in [ low , x ] ; search in [ x , high ] ; return the required answer ; function to find the roots of the given equation within range [ a , b ] ; if root doesn 't exists ; else find the root upto 4 decimal places ; 

import math
eps = 1e-6


def func(a, b, c, x):
    return a * x * x + b * x + c


def findRoot(a, b, c, low, high):
    x = -1
    while abs(high - low) > eps:
        x = (low + high) / 2
        if (func(a, b, c, low) * func(a, b, c, x) <= 0):
            high = x
        else:
            low = x
    return x


def solve(a, b, c, A, B):
    if (func(a, b, c, A) * func(a, b, c, B) > 0):
        print("No solution")
    else:
        print("{:.4f}".format(findRoot(a, b, c, A, B)))


if __name__ == '__main__':
    a = 2
    b = -3
    c = -2
    A = 0
    B = 3
    solve(a, b, c, A, B)

# Expected output:
2.0000
# median of difference of all pairs from an array | function check if mid can be median index of the difference array ; size of the array ; total possible no of pair possible ; the index of the element in the difference of all pairs from the array ; count the number of pairs having difference <= mid ; if the difference between end and first element is less then or equal to mid ; checking for the no of element less than or equal to mid is greater than median or not ; function to calculate the median of differences of all pairs from the array ; size of the array ; initialising the low and high ; binary search ; calculate mid ; if mid can be the median of the array ; returning the median of the differences of pairs from the array ; 
def possible(mid, a):
    n = len(a)
    total = (n * (n - 1)) // 2
    need = (total + 1) // 2
    count = 0
    start = 0
    end = 1
    while (end < n):
        if (a[end] - a[start] <= mid):
            end += 1
        else:
            count += (end - start - 1)
            start += 1
    if (end == n and start < end and a[end - 1] - a[start] <= mid):
        t = end - start - 1
        count += (t * (t + 1) // 2)
    if (count >= need):
        return True
    else:
        return False


def findMedian(a):
    n = len(a)
    low = 0
    high = a[n - 1] - a[0]
    while (low <= high):
        mid = (low + high) // 2
        if (possible(mid, a)):
            high = mid - 1
        else:
            low = mid + 1
    return high + 1


if __name__ == "__main__":
    a = [1, 7, 5, 2]
    a .sort()
    print(findMedian(a))

# Expected output:
3
# print all strings from array a [ ] having all strings from array b [ ] as subsequence | function to find strings from a [ ] having all strings in b [ ] as subsequence ; calculate respective sizes ; stores the answer ; stores the frequency of each character in strings of a [ ] ; compute the frequencies of characters of all strings ; stores the frequency of each character in strings of b [ ] each character of a string in b [ ] ; if the frequency of a character in b [ ] exceeds that in a [ ] ; a string exists in b [ ] which is not a proper subset of a [ i ] ; if all strings in b [ ] are proper subset of a [ ] ; push the string in resultant vector ; if any string is found ; print those strings ; otherwise ; 
def UniversalSubset(A, B):
    n1 = len(A)
    n2 = len(B)
    res = []
    A_freq = [[0 for x in range(26)]for y in range(n1)]
    for i in range(n1):
        for j in range(len(A[i])):
            A_freq[i][ord(A[i][j]) - ord('a')] += 1
    B_freq = [0] * 26
    for i in range(n2):
        arr = [0] * 26
        for j in range(len(B[i])):
            arr[ord(B[i][j]) - ord('a')] += 1
            B_freq[ord(B[i][j]) - ord('a')] = max(B_freq[ord(B[i][j]
                                                             ) - ord('a')], arr[ord(B[i][j]) - ord('a')])
    for i in range(n1):
        flag = 0
        for j in range(26):
            if (A_freq[i][j] < B_freq[j]):
                flag = 1
                break
        if (flag == 0):
            res .append(A[i])
    if (len(res)):
        for i in range(len(res)):
            for j in range(len(res[i])):
                print(res[i][j], end="")
    else:
        print(-1, end="")


if __name__ == '__main__':
    A = ["geeksforgeeks", "topcoder", "leetcode"]
    B = ["geek", "ee"]
    UniversalSubset(A, B)

# Expected output:
geeksforgeeks
# closest pair in an array such that one number is multiple of the other | python3 program for the above approach ; function to find the minimum distance pair where one is the multiple of the other ; initialize the variables ; iterate for all the elements ; loop to make pairs ; check for minimum distance ; check if one is a multiple of other ; update the distance ; store indexes ; if no such pair exists ; print the answer ; 

import sys


def findPair(a, n):
    min_dist = sys .maxsize
    index_a = -1
    index_b = -1
    for i in range(n):
        for j in range(i + 1, n):
            if (j - i < min_dist):
                if ((a[i] % a[j] == 0) or (a[j] % a[i] == 0)):
                    min_dist = j - i
                    index_a = i
                    index_b = j
    if (index_a == -1):
        print("-1")
    else:
        print("(", a[index_a], ", ", a[index_b], ")")


a = [2, 3, 4, 5, 6]
n = len(a)
findPair(a, n)

# Expected output:
( 2 ,  4 )