giulio98/xlcost-single-prompt huggingface dataset:
# nearest smaller character to a character k from a sorted array | function to return the nearest smaller character ; stores the nearest smaller character ; iterate till starts cross end ; find the mid element ; check if k is found ; check if current character is less than k ; increment the start ; otherwise ; increment end ; return the character ; 
def bs(a, n, ele):
    start = 0
    end = n - 1
    ch = '@'
    while (start <= end):
        mid = start + (end - start) // 2
        if (ar[mid] == ele):
            end = mid - 1
        elif (ar[mid] < ele):
            ch = ar[mid]
            start = mid + 1
        else:
            end = mid - 1
    return ch


if __name__ == '__main__':
    ar = ['e', 'g', 't', 'y']
    n = len(ar)
    K = 'u'
    ch = bs(ar, n, K)
    if (ch == '@'):
        print('-1')
    else:
        print(ch)

# Expected output:
t
# largest possible subset from an array such that no element is k times any other element in the subset | function to find the maximum size of the required subset ; size of the array ; sort the array ; stores which index is included or excluded ; stores the indices of array elements ; count of pairs ; iterate through all the element ; if element is included ; check if a [ i ] * k is present in the array or not ; increase count of pair ; exclude the pair ; 
def findMaxLen(a, k):
    n = len(a)
    a .sort()
    vis = [0] * n
    mp = {}
    for i in range(n):
        mp[a[i]] = i
    c = 0
    for i in range(n):
        if (vis[i] == False):
            check = a[i] * k
            if (check in mp .keys()):
                c += 1
                vis[mp[check]] = True
    return n - c


if __name__ == '__main__':
    K = 3
    arr = [1, 4, 3, 2]
    print(findMaxLen(arr, K))

# Expected output:
3
# minimize length of prefix of string s containing all characters of another string t | python3 program for the above approach ; base case - if t is empty , it matches 0 length prefix ; convert strings to lower case for uniformity ; update dictcount to the letter count of t ; if new character is found , initialize its entry , and increase nunique ; increase count of ch ; iterate from 0 to n ; i - th character ; skip if ch not in targetstr ; decrease count ; if the count of ch reaches 0 , we do not need more ch , and can decrease nunique ; if nunique reaches 0 , we have found required prefix ; otherwise ; 
def getPrefixLength(srcStr, targetStr):
    if (len(targetStr) == 0):
        return 0
    srcStr = srcStr .lower()
    targetStr = targetStr .lower()
    dictCount = dict([])
    nUnique = 0
    for ch in targetStr:
        if (ch not in dictCount):
            nUnique += 1
            dictCount[ch] = 0
        dictCount[ch] += 1
    for i in range(len(srcStr)):
        ch = srcStr[i]
        if (ch not in dictCount):
            continue
        dictCount[ch] -= 1
        if (dictCount[ch] == 0):
            nUnique -= 1
        if (nUnique == 0):
            return (i + 1)
    return -1


if __name__ == "__main__":
    S = "MarvoloGaunt"
    T = "Tom"
    print(getPrefixLength(S, T))

# Expected output:
12
# maximize product of absolute index difference with k | function returns maximum possible value of k ; pointer i make sure that a [ i ] will result in max k ; stores maximum possible k ; possible value of k for current pair ( a [ i ] and a [ j ] ) ; if current value exceeds k ; update the value of k ; update pointer i ; return the maxm possible k ; 
def solve(A, N):
    i = 0
    k = 0
    for j in range(1, N):
        tempK = (min(A[i], A[j]) // (j - i))
        if (tempK > k):
            k = tempK
        if (A[j] >= A[i] // (j - i)):
            i = j
    return k


if __name__ == "__main__":
    A = [10, 5, 12, 15, 8]
    N = len(A)
    print(solve(A, N))

# Expected output:
12
# split array into min number of subsets with difference between each pair greater than 1 | function to split the array into minimum number of subsets with difference strictly > 1 ; sort the array ; traverse through the sorted array ; check the pairs of elements with difference 1 ; if we find even a single pair with difference equal to 1 , then 2 partitions else only 1 partition ; print the count of partitions ; 
def split(arr, n):
    arr .sort()
    count = 1
    for i in range(1, n):
        if (arr[i] - arr[i - 1] == 1):
            count = 2
            break
    print(count)


if __name__ == '__main__':
    arr = [2, 4, 6]
    n = len(arr)
    split(arr, n)

# Expected output:
1
# check if a palindromic string can be formed by concatenating substrings of two given strings | function to check if a palindromic string can be formed from the substring of given strings ; boolean array to mark presence of characters ; check if any of the character of str2 is already marked ; if a common character is found ; if no common character is found ; 
def check(str1, str2):
    mark = [False for i in range(26)]
    n = len(str1)
    m = len(str2)
    for i in range(n):
        mark[ord(str1[i]) - ord('a')] = True
    for i in range(m):
        if (mark[ord(str2[i]) - ord('a')]):
            return True
    return False


if __name__ == "__main__":
    str1 = "abca"
    str2 = "efad"
    if (check(str1, str2)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# generate k co | python3 implementation of the above approach ; function prints the required pairs ; first co - prime pair ; as a pair ( 1 n ) has already been printed ; if i is a factor of n ; since ( i , i ) won 't form  a coprime pair ; 

from math import sqrt


def FindPairs(n, k):
    print(1, n)
    k -= 1
    for i in range(2, int(sqrt(n)) + 1):
        if (n % i == 0):
            print(1, i)
            k -= 1
            if (k == 0):
                break
            if (i != n // i):
                print(1, n // i)
                k -= 1
            if (k == 0):
                break


if __name__ == '__main__':
    N = 100
    K = 5
    FindPairs(N, K)

# Expected output:
1 100
1 2
1 50
1 4
1 25
# count of subarrays which forms a permutation from given array elements | function returns the required count ; store the indices of the elements present in a [ ] . ; store the maximum and minimum index of the elements from 1 to i . ; update maxi and mini , to store minimum and maximum index for permutation of elements from 1 to i + 1 ; if difference between maxi and mini is equal to i ; increase count ; return final count ; 
def PermuteTheArray(A, n):
    arr = [0] * n
    for i in range(n):
        arr[A[i] - 1] = i
    mini = n
    maxi = 0
    count = 0
    for i in range(n):
        mini = min(mini, arr[i])
        maxi = max(maxi, arr[i])
        if (maxi - mini == i):
            count += 1
    return count


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

# Expected output:
4
# find second largest element in an array | set 2 | function to find the largest element in the array arr [ ] ; base condition ; initialize an empty list ; divide the array into two equal length subarrays and recursively find the largest among the two ; store length of compared1 [ ] in the first index ; store the maximum element ; return compared1 which contains the maximum element ; store length of compared2 [ ] in the first index ; store the maximum element ; return compared2 [ ] which contains the maximum element ; function to print the second largest element in the array arr [ ] ; find the largest element in arr [ ] ; find the second largest element in arr [ ] ; print the second largest element ; 
def findLargest(beg, end, arr, n):
    if (beg == end):
        compared = [0] * n
        compared[0] = 1
        compared[1] = arr[beg]
        return compared
    compared1 = findLargest(beg, (beg + end) // 2, arr, n)
    compared2 = findLargest((beg + end) // 2 + 1, end, arr, n)
    if (compared1[1] > compared2[1]):
        k = compared1[0] + 1
        compared1[0] = k
        compared1[k] = compared2[1]
        return compared1
    else:
        k = compared2[0] + 1
        compared2[0] = k
        compared2[k] = compared1[1]
        return compared2


def findSecondLargest(end, arr):
    compared1 = findLargest(0, end - 1, arr, end)
    compared2 = findLargest(2, compared1[0] + 2, compared1, compared1[0])
    print(compared2[1])


N = 10
arr = [20, 1990, 12, 1110, 1, 59, 12, 15, 120, 1110]
findSecondLargest(N, arr)

# Expected output:
1110
# count of reverse bitonic substrings in a given string | function to calculate the number of reverse bitonic substrings ; stores the count ; all possible lengths of substrings ; starting poof a substring ; ending poof a substring ; condition for reverse bitonic substrings of length 1 ; check for decreasing sequence ; if end of substring is reache ; for increasing sequence ; if end of substring is reached ; return the number of bitonic substrings ; 
def CountsubString(strr, n):
    c = 0
    for len in range(n + 1):
        for i in range(n - len):
            j = i + len - 1
            temp = strr[i]
            f = 0
            if (j == i):
                c += 1
                continue
            k = i + 1
            while (k <= j and temp > strr[k]):
                temp = strr[k]
                k += 1
            if (k > j):
                c += 1
                f = 2
            while (k <= j and f != 2 and temp < strr[k]):
                temp = strr[k]
                k += 1
            if (k > j and f != 2):
                c += 1
                f = 0
    return c


if __name__ == '__main__':
    strr = "bade"
    print(CountsubString(strr, len(strr)))

# Expected output:
10
# maximum subsequence sum from a given array which is a perfect square | python3 program to implement the above approach ; if sum is 0 , then answer is true ; if sum is not 0 and arr [ ] is empty , then answer is false ; fill the subset table in bottom up manner ; function to find the sum ; find sum of all values ; return the value ; ; 

import math


def isSubsetSum(arr, n, sum):
    subset = [[True for x in range(sum + 1)]for y in range(n + 1)]
    for i in range(n + 1):
        subset[i][0] = True
    for i in range(1, sum + 1):
        subset[0][i] = False
    for i in range(1, n + 1):
        for j in range(1, sum + 1):
            if (j < arr[i - 1]):
                subset[i][j] = subset[i - 1][j]
            if (j >= arr[i - 1]):
                subset[i][j] = (subset[i - 1][j]
                                or subset[i - 1][j - arr[i - 1]])
    return subset[n][sum]


def findSum(arr, n):
    sum = 0
    for i in range(n):
        sum += arr[i]
    val = int(math .sqrt(sum))
    for i in range(val, -1, -1):
        if (isSubsetSum(arr, n, i * i)):
            return i * i
    return 0


if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    n = len(arr)
    print(findSum(arr, n))

# Expected output:
36
# smallest subarray whose product leaves remainder k when divided by size of the array | function to find the subarray of minimum length ; initialize the minimum subarray size to n + 1 ; generate all possible subarray ; initialize the product ; find the product ; return the minimum size of subarray ; 
def findsubArray(arr, N, K):
    res = N + 1
    for i in range(0, N):
        curr_prad = 1
        for j in range(i, N):
            curr_prad = curr_prad * arr[j]
            if (curr_prad % N == K and res > (j - i + 1)):
                res = min(res, j - i + 1)
                break
    if res == N + 1:
        return 0
    else:
        return res


if __name__ == '__main__':
    arr = [2, 2, 3]
    N = len(arr)
    K = 1
    answer = findsubArray(arr, N, K)
    if (answer != 0):
        print(answer)
    else:
        print(-1)

# Expected output:
2
# count of array elements whose order of deletion precedes order of insertion | python3 program to implement the above approach ; function returns maximum number of required elements ; insert the elements of array b in the queue and set ; stores the answer ; if a [ i ] is already processed ; until we find a [ i ] in the queue ; remove elements from the queue ; increment the count ; remove the current element a [ i ] from the queue and set . ; return total count ; 

import queue


def maximumCount(A, B, n):
    q = queue .Queue()
    s = set()
    for i in range(n):
        s .add(B[i])
        q .put(B[i])
    count = 0
    for i in range(n):
        if (A[i]not in s):
            continue
        while (q .qsize() > 0 and q .queue[0] != A[i]):
            s .remove(q .queue[0])
            q .get()
            count += 1
        if (A[i] == q .queue[0]):
            q .get()
            s .remove(A[i])
        if (q .qsize() == 0):
            break
    print(count)


N = 4
A = [1, 2, 3, 4]
B = [1, 2, 4, 3]
maximumCount(A, B, N)

# Expected output:
1
# check if a matrix is bitonic or not | python3 program to check if a matrix is bitonic or not ; function to check if an array is bitonic or not ; check for increasing sequence ; check for decreasing sequence ; function to check whether given matrix is bitonic or not ; check row wise ; check column wise ; generate an array consisting of elements of current column ; 

N = 3
M = 3


def checkBitonic(arr, n):
    i, j, f = 0, 0, 0
    for i in range(1, n):
        if (arr[i] > arr[i - 1]):
            continue
        if (arr[i] == arr[i - 1]):
            return False
        else:
            f = 1
            break
    if (i == n):
        return True
    for j in range(i + 1, n):
        if (arr[j] < arr[j - 1]):
            continue
        if (arr[i] == arr[i - 1]):
            return False
        else:
            if (f == 1):
                return False
    return True


def check(arr):
    f = 0
    for i in range(N):
        if (not checkBitonic(arr[i], M)):
            print("NO")
            return
    i = 0
    for i in range(N):
        temp = [0] * N
        for j in range(N):
            temp[j] = arr[j][i]
        if (not checkBitonic(temp, N)):
            print("NO")
            return
    print("YES")


if __name__ == '__main__':
    m = [[1, 2, 3], [3, 4, 5], [2, 6, 4]]
    check(m)

# Expected output:
YES
# maximum possible gcd for a pair of integers with product n | python3 program to implement the above approach ; function to return the maximum gcd ; to find all divisors of n ; if i is a factor ; store the pair of factors ; store the maximum gcd ; return the maximum gcd ; 

import sys
import math


def getMaxGcd(N):
    maxGcd = -sys .maxsize - 1
    for i in range(1, int(math .sqrt(N)) + 1):
        if (N % i == 0):
            A = i
            B = N // i
            maxGcd = max(maxGcd, math .gcd(A, B))
    return maxGcd


N = 18
print(getMaxGcd(N))

# Expected output:
3
# maximum of minimum difference of all pairs from subsequences of given size | function to check a subsequence can be formed with min difference mid ; if a subsequence of size b with min diff = mid is possible return true else false ; function to find the maximum of all minimum difference of pairs possible among the subsequence ; sort the array ; stores the boundaries of the search space ; store the answer ; binary search ; if subsequence can be formed with min diff mid and size b ; right half ; left half ; 
def can_place(A, n, B, mid):
    count = 1
    last_position = A[0]
    for i in range(1, n):
        if (A[i] - last_position >= mid):
            last_position = A[i]
            count = count + 1
            if (count == B):
                return bool(True)
    return bool(False)


def find_min_difference(A, n, B):
    A .sort()
    s = 0
    e = A[n - 1] - A[0]
    ans = 0
    while (s <= e):
        mid = (int)((s + e) / 2)
        if (can_place(A, n, B, mid)):
            ans = mid
            s = mid + 1
        else:
            e = mid - 1
    return ans


A = [1, 2, 3, 5]
n = len(A)
B = 3
min_difference = find_min_difference(A, n, B)
print(min_difference)

# Expected output:
2
# count of triplets in an array such that a [ i ] * a [ j ] = a [ k ] and i < j < k | python3 program for the above approach ; returns total number of valid triplets possible ; stores the count ; map to store frequency of array elements ; increment the frequency of a [ j + 1 ] as it can be a valid a [ k ] ; if target exists in the map ; return the final count ; 

from collections import defaultdict


def countTriplets(A, N):
    ans = 0
    map = defaultdict(lambda: 0)
    for j in range(N - 2, 0, -1):
        map[A[j + 1]] += 1
        for i in range(j):
            target = A[i] * A[j]
            if (target in map .keys()):
                ans += map[target]
    return ans


if __name__ == '__main__':
    N = 5
    A = [2, 3, 4, 6, 12]
    print(countTriplets(A, N))

# Expected output:
3
# missing vertex among n axis | python3 program for the above approach ; 

from collections import defaultdict


def MissingPoint(V, N):
    mp = defaultdict(lambda: 0)
    for i in range(len(V)):
        mp[V[i][0]] += 1
    for it in mp .keys():
        if (mp[it] % 2 == 1):
            x = it
            break
    del mp
    mp = defaultdict(lambda: 0)
    for i in range(len(V)):
        mp[V[i][1]] += 1
    for it in mp .keys():
        if (mp[it] % 2 == 1):
            y = it
            break
    print(x, y)


if __name__ == '__main__':
    N = 2
    V = []
    V .append([1, 1])
    V .append([1, 2])
    V .append([4, 6])
    V .append([2, 1])
    V .append([9, 6])
    V .append([9, 3])
    V .append([4, 3])
    MissingPoint(V, N)

# Expected output:
2 2
# longest alternating subsequence with maximum sum | set 2 | function to check the sign of the element ; function to calculate and return the maximum sum of longest alternating subsequence ; iterate through the array ; stores the first element of a sequence of same sign ; traverse until an element with opposite sign is encountered ; update the maximum ; update the maximum sum ; update i ; return the maximum sum ; 
def sign(x):
    if (x > 0):
        return 1
    else:
        return -1


def findMaxSum(arr, size):
    max_sum = 0
    i = 0
    while i < size:
        pres = arr[i]
        j = i
        while (j < size and (sign(arr[i]) == sign(arr[j]))):
            pres = max(pres, arr[j])
            j += 1
        max_sum = max_sum + pres
        i = j - 1
        i += 1
    return max_sum


if __name__ == "__main__":
    arr = [-2, 8, 3, 8, -4, -15, 5, -2, -3, 1]
    size = len(arr)
    print(findMaxSum(arr, size))

# Expected output:
6
# check if an array can be split into subsets of k consecutive elements | python3 program to implement the above approach ; function to check if a given array can be split into subsets of k consecutive elements ; stores the frequencies of array elements ; traverse the map ; check if all its occurrences can be grouped into k subsets ; traverse next k elements ; if the element is not present in the array ; if it cannot be split into required number of subsets ; 

from collections import defaultdict


def groupInKConsecutive(arr, K):
    count = defaultdict(int)
    for h in arr:
        count[h] += 1
    for key, value in count .items():
        cur = key
        n = value
        if (n > 0):
            for i in range(1, K):
                if ((cur + i)not in count):
                    return False
                count[cur + i] -= n
                if (count[cur + i] < 0):
                    return False
    return True


if __name__ == "__main__":
    arr = [1, 2, 3, 6, 2, 3, 4, 7, 8]
    k = 3
    if (groupInKConsecutive(arr, k)):
        print("True")
    else:
        print("False")

# Expected output:
True
# count of substrings of a given binary string with all characters same | function to count number of sub - strings of a given binary string that contains only 1 ; iterate untill l and r cross each other ; check if reached the end of string ; check if encountered '1' then extend window ; check if encountered '0' then add number of strings of current window and change the values for both l and r ; return the answer ; function to flip the bits of string ; function to count number of sub - strings of a given binary string that contains only 0 s & 1 s ; count of substring which contains only 1 s ; flip the character of string s 0 to 1 and 1 to 0 to count the substring with consecutive 0 s ; count of substring which contains only 0 s ; 
def countSubAllOnes(s):
    l, r, ans = 0, 0, 0
    while (l <= r):
        if (r == len(s)):
            ans += ((r - l) * (r - l + 1)) // 2
            break
        if (s[r] == '1'):
            r += 1
        else:
            ans += ((r - l) * (r - l + 1)) // 2
            l = r + 1
            r += 1
    return ans


def flip(s):
    arr = list(s)
    for i in range(len(s)):
        if (arr[i] == '1'):
            arr[i] = '0'
        else:
            arr[i] = '1'
    s = ''.join(arr)
    return s


def countSubAllZerosOnes(s):
    only_1s = countSubAllOnes(s)
    s = flip(s)
    only_0s = countSubAllOnes(s)
    return only_0s + only_1s


if __name__ == "__main__":
    s = "011"
    print(countSubAllZerosOnes(s))

# Expected output:
4
# count of primes in a given range that can be expressed as sum of perfect squares | function to check if a prime number satisfies the condition to be expressed as sum of two perfect squares ; function to check if a number is prime or not ; corner cases ; function to return the count of primes in the range which can be expressed as the sum of two squares ; if i is a prime ; if i can be expressed as the sum of two squares ; return the count ; 
def sumsquare(p):
    return (p - 1) % 4 == 0


def isprime(n):
    if n <= 1:
        return False
    if n <= 3:
        return True
    if (n % 2 == 0) or (n % 3 == 0):
        return False
    i = 5
    while (i * i <= n):
        if ((n % i == 0) or (n % (i + 2) == 0)):
            return False
        i += 6
    return True


def countOfPrimes(L, R):
    count = 0
    for i in range(L, R + 1):
        if (isprime(i)):
            if sumsquare(i):
                count += 1
    return count


if __name__ == '__main__':
    L = 5
    R = 41
    print(countOfPrimes(L, R))

# Expected output:
6
# count of array elements which are greater than all elements on its left | function to return the count of array elements with all elements to its left smaller than it ; stores the count ; stores the maximum ; iterate over the array ; if an element greater than maximum is obtained ; increase count ; update maximum ; 
def count_elements(arr):
    count = 1
    max = arr[0]
    for i in range(1, len(arr)):
        if arr[i] > max:
            count += 1
            max = arr[i]
    return count


arr = [2, 1, 4, 6, 3]
print(count_elements(arr))

# Expected output:
3
# count of bitonic substrings from the given string | function to find all the bitonic sub strings ; pick starting po ; iterate till length of the string ; pick ending pofor string ; substring from i to j is obtained ; substrings of length 1 ; increase count ; for increasing sequence ; check for strictly increasing ; increase count ; check for decreasing sequence ; increase count ; print the result ; 
def subString(str, n):
    c = 0
    for len in range(1, n + 1):
        for i in range(0, n - len + 1):
            j = i + len - 1
            temp = str[i]
            f = 0
            if (j == i):
                c += 1
                continue
            k = i + 1
            while (k <= j and temp < str[k]):
                temp = str[k]
                k += 1
                f = 2
            if (k > j):
                c += 1
                f = 2
            while (k <= j and temp > str[k] and f != 2):
                k += 1
                f = 0
            if (k > j and f != 2):
                c += 1
                f = 0
    print(c)


str = "bade"
subString(str, len(str))

# Expected output:
8