giulio98/xlcost-single-prompt huggingface dataset:
# check if ceil of number divided by power of two exist in sorted array | function to find there exist a number or not in the array ; loop to check if there exist a number by divided by power of 2 ; binary search ; condition to check the number is found in the array or not ; otherwise divide the number by increasing the one more power of 2 ; 
def findNumberDivByPowerofTwo(ar, k, n):
    found = -1
    m = k
    while (m > 0):
        l = 0
        r = n - 1
        while (l <= r):
            mid = (l + r) // 2
            if (ar[mid] == m):
                found = m
                break
            elif (ar[mid] > m):
                r = mid - 1
            elif (ar[mid] < m):
                l = mid + 1
        if (found != -1):
            break
        m = m // 2
    return found


arr = [3, 5, 7, 8, 10]
k = 4
n = 5
print(findNumberDivByPowerofTwo(arr, k, n))

# Expected output:
-1
# largest subset having with sum less than equal to sum of respective indices | function to find the length of the longest subset ; stores the sum of differences between elements and their respective index ; stores the size of the subset ; iterate over the array ; if an element which is smaller than or equal to its index is encountered ; increase count and sum ; store the difference with index of the remaining elements ; sort the differences in increasing order ; include the differences while sum remains positive or ; return the size ; 
def findSubset(a, n):
    sum = 0
    cnt = 0
    v = []
    for i in range(1, n + 1):
        if (a[i - 1] - i <= 0):
            sum += a[i - 1] - i
            cnt += 1
        else:
            v .append(a[i - 1] - i)
    v .sort()
    ptr = 0
    while (ptr < len(v) and sum + v[ptr] <= 0):
        cnt += 1
        ptr += 1
        sum += v[ptr]
    return cnt


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

# Expected output:
3
# queries for count of array elements with values in given range with updates | python3 code for queries for number of elements that lie in range [ l , r ] ( with updates ) ; function to set arr [ index ] = x ; function to get count of elements that lie in range [ l , r ] ; traverse array ; if element lies in the range [ l , r ] ; increase count ; function to solve each query ; 

from typing import Generic, List, TypeVar
T = TypeVar('T')
V = TypeVar('V')


class Pair (Generic[V, T]):
    def __init__(self, first: V, second: T) -> None:
        self .first = first
        self .second = second


def setElement(arr: List[int], n: int, index: int, x: int) -> None:
    arr[index] = x


def getCount(arr: List[int], n: int, l: int, r: int) -> int:
    count = 0
    for i in range(n):
        if (arr[i] >= l and arr[i] <= r):
            count += 1
    return count


def SolveQuery(arr: List[int], n: int, Q: List[Pair[int, Pair[int, int]]]):
    x = 0
    for i in range(len(Q)):
        if (Q[i].first == 1):
            x = getCount(arr, n, Q[i].second .first, Q[i].second .second)
            print(x, end=" ")
        else:
            setElement(arr, n, Q[i].second .first, Q[i].second .second)


if __name__ == "__main__":
    arr = [1, 2, 2, 3, 4, 4, 5, 6]
    n = len(arr)
    Q = [
        Pair(
            1, Pair(
                3, 5)), Pair(
            1, Pair(
                2, 4)), Pair(
            1, Pair(
                1, 2)), Pair(
            2, Pair(
                1, 7)), Pair(
            1, Pair(
                1, 2))]
    SolveQuery(arr, n, Q)

# Expected output:
4 5 3 2
# construct a sequence from given frequencies of n consecutive integers with unit adjacent difference | function generates the sequence ; map to store the frequency of numbers ; sum of all frequencies ; try all possibilities for the starting element ; if the frequency of current element is non - zero ; vector to store the answer ; copy of the map for every possible starting element ; decrement the frequency ; push the starting element to the vector ; the last element inserted is i ; try to fill the rest of the positions if possible ; if the frequency of last - 1 is non - zero ; decrement the frequency of last - 1 ; insert it into the sequence ; update last number added to sequence ; break from the inner loop ; if the size of the sequence vector is equal to sum of total frequqncies ; return sequence ; if no such sequence if found return empty sequence ; function call to print the sequence ; the required sequence ; if the size of sequence if zero it means no such sequence was found ; otherwise print the sequence ; 
def generateSequence(freq, n):
    m = {}
    total = 0
    for i in range(n):
        m[i] = freq[i]
        total += freq[i]
    for i in range(n):
        if (m[i]):
            sequence = []
            mcopy = {}
            for j in m:
                mcopy[j] = m[j]
            mcopy[i] -= 1
            sequence .append(i)
            last = i
            for j in range(total - 1):
                if ((last - 1) in mcopy and mcopy[last - 1] > 0):
                    mcopy[last - 1] -= 1
                    sequence .append(last - 1)
                    last -= 1
                elif (mcopy[last + 1]):
                    mcopy[last + 1] -= 1
                    sequence .append(last + 1)
                    last += 1
                else:
                    break
            if (len(sequence) == total):
                return sequence
    return []


def PrintSequence(freq, n):
    sequence = generateSequence(freq, n)
    if (len(sequence) == 0):
        print("-1")
    else:
        for i in range(len(sequence)):
            print(sequence[i], end=" ")


if __name__ == '__main__':
    freq = [2, 2, 2, 3, 1]
    N = 5
    PrintSequence(freq, N)

# Expected output:
0 1 0 1 2 3 2 3 4 3
# minimum distance between any most frequent and least frequent element of an array | python3 implementation of the approach ; function to find the minimum distance between any two most and least frequent element ; initialize sets to store the least and the most frequent elements ; initialize variables to store max and min frequency ; initialize hashmap to store frequency of each element ; loop through the array ; store the count of each element ; store the least and most frequent elements in the respective sets ; store count of current element ; if count is equal to max count ; store in max set ; if count is greater then max count ; empty max set ; update max count ; store in max set ; if count is equal to min count ; store in min set ; if count is less then max count ; empty min set ; update min count ; store in min set ; initialize a variable to store the minimum distance ; initialize a variable to store the last index of least frequent element ; traverse array ; if least frequent element ; update last index of least frequent element ; if most frequent element ; update minimum distance ; traverse array from the end ; if least frequent element ; update last index of least frequent element ; if most frequent element ; update minimum distance ; print the minimum distance ; 

import sys


def getMinimumDistance(a, n):
    min_set = {}
    max_set = {}
    max, min = 0, sys .maxsize + 1
    frequency = {}
    for i in range(n):
        frequency[a[i]] = frequency .get(a[i], 0) + 1
    for i in range(n):
        count = frequency[a[i]]
        if (count == max):
            max_set[a[i]] = 1
        elif (count > max):
            max_set .clear()
            max = count
            max_set[a[i]] = 1
        if (count == min):
            min_set[a[i]] = 1
        elif (count < min):
            min_set .clear()
            min = count
            min_set[a[i]] = 1
    min_dist = sys .maxsize + 1
    last_min_found = -1
    for i in range(n):
        if (a[i] in min_set):
            last_min_found = i
        if ((a[i] in max_set) and last_min_found != -1):
            if i - last_min_found < min_dist:
                min_dist = i - last_min_found
    last_min_found = -1
    for i in range(n - 1, -1, -1):
        if (a[i] in min_set):
            last_min_found = i
        if ((a[i] in max_set) and last_min_found != -1):
            if min_dist > last_min_found - i:
                min_dist = last_min_found - i
    print(min_dist)


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

# Expected output:
1
# construct a string that has exactly k subsequences from given string | python3 program for the above approach ; function that computes the string s ; length of the given string str ; list that stores all the prime factors of given k ; find the prime factors ; initialize the count of each character position as 1 ; loop until the list becomes empty ; increase the character count by multiplying it with the prime factor ; if we reach end then again start from beginning ; store output ; print the string ; 

import math


def printSubsequenceString(st, k):
    n = len(st)
    factors = []
    sqt = (int(math .sqrt(k)))
    for i in range(2, sqt + 1):
        while (k % i == 0):
            factors .append(i)
            k //= i
    if (k > 1):
        factors .append(k)
    count = [1] * n
    index = 0
    while (len(factors) > 0):
        count[index] *= factors[-1]
        factors .pop()
        index += 1
        if (index == n):
            index = 0
    s = ""
    for i in range(n):
        while (count[i] > 0):
            s += st[i]
            count[i] -= 1
    print(s)


if __name__ == "__main__":
    st = "code"
    k = 20
    printSubsequenceString(st, k)

# Expected output:
cccccoodde
# replace each element of array with it 's corresponding rank | function to assign rank to array elements ; copy input array into newarray ; sort newarray [ ] in ascending order ; dictionary to store the rank of the array element ; update rank of element ; assign ranks to elements ; 
def changeArr(input1):
    newArray = sorted(input1 .copy())
    ranks = {}
    rank = 1
    for index in range(len(newArray)):
        element = newArray[index]
        if element not in ranks:
            ranks[element] = rank
            rank += 1
    for index in range(len(input1)):
        element = input1[index]
        input1[index] = ranks[input1[index]]


if __name__ == "__main__":
    arr = [100, 2, 70, 2]
    changeArr(arr)
    print(arr)

# Expected output:
[3, 1, 2, 1]
# find pairs in array whose sum does not exist in array | function to print all pairs with sum not present in the array ; corner case ; stores the distinct array elements ; generate all possible pairs ; calculate sum of current pair ; check if the sum exists in the hashset or not ; 
def findPair(arr, n):
    if (n < 2):
        print("-1")
    hashMap = []
    for k in arr:
        hashMap .append(k)
    for i in range(n - 1):
        for j in range(i + 1, n):
            sum = arr[i] + arr[j]
            if sum not in hashMap:
                print("(", arr[i], ", ", arr[j], ")")


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

# Expected output:
( 2 ,  6 )
( 4 ,  6 )
( 2 ,  6 )
# largest subset with m as smallest missing number | function to find and return the length of the longest subset whose smallest missing value is m ; initialize a set ; if array element is not equal to m ; insert into set ; increment frequency ; stores minimum missing number ; iterate to find the minimum missing integer ; if minimum obtained is less than m ; update answer ; return answer ; 
def findLengthOfMaxSubset(arr, n, m):
    s = []
    answer = 0
    for i in range(n):
        tmp = arr[i]
        if (tmp != m):
            s .append(tmp)
            answer += 1
    min = 1
    while (s .count(min)):
        min += 1
    if (min != m):
        answer = -1
    return answer


if __name__ == "__main__":
    arr = [1, 2, 4]
    N = len(arr)
    M = 3
    print(findLengthOfMaxSubset(arr, N, M))

# Expected output:
3
# count of submatrix with sum x in a given matrix | size of a column ; function to find the count of submatrix whose sum is x ; copying arr to dp and making it indexed 1 ; precalculate and store the sum of all rectangles with upper left corner at ( 0 , 0 ) ; ; calculating sum in a 2d grid ; stores the answer ; minimum length of square ; maximum length of square ; flag to set if sub - square with sum x is found ; calculate lower right index if upper right corner is at { i , j } ; calculate the sum of elements in the submatrix with upper left column { i , j } and lower right column at { ni , nj } ; ; if sum x is found ; if sum > x , then size of the square with sum x must be less than mid ; if sum < x , then size of the square with sum x must be greater than mid ; if found , increment count by 1 ; ; 

m = 5


def countSubsquare(arr, n, X):
    dp = [[0 for x in range(m + 1)]for y in range(n + 1)]
    for i in range(n):
        for j in range(m):
            dp[i + 1][j + 1] = arr[i][j]
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            dp[i][j] += (dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1])
    cnt = 0
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            lo = 1
            hi = min(n - i, m - j) + 1
            found = False
            while (lo <= hi):
                mid = (lo + hi) // 2
                ni = i + mid - 1
                nj = j + mid - 1
                sum = (dp[ni][nj] - dp[ni][j - 1] -
                       dp[i - 1][nj] + dp[i - 1][j - 1])
                if (sum >= X):
                    if (sum == X):
                        found = True
                    hi = mid - 1
                else:
                    lo = mid + 1
            if (found):
                cnt += 1
    return cnt


if __name__ == "__main__":
    N, X = 4, 10
    arr = [[2, 4, 3, 2, 10], [3, 1, 1, 1, 5], [1, 1, 2, 1, 4], [2, 1, 1, 1, 3]]
    print(countSubsquare(arr, N, X))

# Expected output:
3
# check if two arrays can be made equal by reversing any subarray once | function to check whether two arrays can be made equal by reversing a sub - array only once ; integer variable for storing the required starting and ending indices in the array ; finding the smallest index for which a [ i ] != b [ i ] i . e the starting index of the unequal sub - array ; finding the largest index for which a [ i ] != b [ i ] i . e the ending index of the unequal sub - array ; reversing the sub - array a [ start ] , a [ start + 1 ] . . a [ end ] ; checking whether on reversing the sub - array a [ start ] ... a [ end ] makes the arrays equal ; if any element of the two arrays is unequal print no and return ; print yes if arrays are equal after reversing the sub - array ; 
def checkArray(A, B, N):
    start = 0
    end = N - 1
    for i in range(N):
        if (A[i] != B[i]):
            start = i
            break
    for i in range(N - 1, -1, -1):
        if (A[i] != B[i]):
            end = i
            break
    A[start:end + 1] = reversed(A[start:end + 1])
    for i in range(N):
        if (A[i] != B[i]):
            print("No")
            return
    print("Yes")


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

# Expected output:
Yes
# count of substrings having all distinct characters | function to count total number of valid substrings ; stores the count of substrings ; stores the frequency of characters ; initialised both pointers to beginning of the string ; if all characters in substring from index i to j are distinct ; increment count of j - th character ; add all substring ending at j and starting at any index between i and j to the answer ; increment 2 nd pointer ; if some characters are repeated or j pointer has reached to end ; decrement count of j - th character ; increment first pointer ; return the final count of substrings ; 
def countSub(Str):
    n = len(Str)
    ans = 0
    cnt = 26 * [0]
    i, j = 0, 0
    while (i < n):
        if (j < n and (cnt[ord(Str[j]) - ord('a')] == 0)):
            cnt[ord(Str[j]) - ord('a')] += 1
            ans += (j - i + 1)
            j += 1
        else:
            cnt[ord(Str[i]) - ord('a')] -= 1
            i += 1
    return ans


Str = "gffg"
print(countSub(Str))

# Expected output:
6
# find largest factor of n such that n / f is less than k | function to find the largest factor of n which is less than or equal to k ; initialise the variable to store the largest factor of n <= k ; loop to find all factors of n ; check if j is a factor of n or not ; check if j <= k if yes , then store the larger value between ans and j in ans ; check if n / j <= k if yes , then store the larger value between ans and j in ans ; since max value is always stored in ans , the maximum value divisible by n less than or equal to k will be returned . ; 
def solve(n, k):
    ans = 0
    for j in range(1, n + 1):
        if (j * j > n):
            break
        if (n % j == 0):
            if (j <= k):
                ans = max(ans, j)
            if (n // j <= k):
                ans = max(ans, n // j)
    return ans


if __name__ == '__main__':
    N = 8
    K = 7
    print((N // solve(N, K)))

# Expected output:
2
# maximum sum subarray of size range [ l , r ] | python3 program to find maximum sum subarray of size between l and r . ; function to find maximum sum subarray of size between l and r ; calculating prefix sum ; maintain 0 for initial values of i upto r once i = r , then we need to erase that 0 from our multiset as our first index of subarray cannot be 0 anymore . ; we maintain flag to counter if that initial 0 was erased from set or not . ; erase 0 from multiset once i = b ; insert pre [ i - l ] ; find minimum value in multiset . ; erase pre [ i - r ] ; 

import sys


def max_sum_subarray(arr, L, R):
    n = len(arr)
    pre = n * [0]
    pre[0] = arr[0]
    for i in range(1, n):
        pre[i] = pre[i - 1] + arr[i]
    s1 = []
    s1 .append(0)
    ans = -sys .maxsize - 1
    ans = max(ans, pre[L - 1])
    flag = 0
    for i in range(L, n):
        if (i - R >= 0):
            if (flag == 0):
                s1 .remove(0)
                flag = 1
        if (i - L >= 0):
            s1 .append(pre[i - L])
        ans = max(ans, pre[i] - s1[0])
        if (i - R >= 0):
            s1 .remove(pre[i - R])
    print(ans)


if __name__ == "__main__":
    L = 1
    R = 3
    arr = [1, 2, 2, 1]
    max_sum_subarray(arr, L, R)

# Expected output:
5
# check if the count of inversions of two given types on an array are equal or not | python3 program to implement the above approach ; function to check if the count of inversion of two types are same or not ; if maximum value is found to be greater than a [ j ] , then that pair of indices ( i , j ) will add extra value to inversion of type 1 ; update max ; 

import sys


def solve(a, n):
    mx = -sys .maxsize - 1
    for j in range(1, n):
        if (mx > a[j]):
            return False
        mx = max(mx, a[j - 1])
    return True


a = [1, 0, 2]
n = len(a)
possible = solve(a, n)
if (possible != 0):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# How to validate an IP address using ReGex | Python3 program to validate IP address using Regex ; Function for Validating IP ; Regex expression for validating IPv4 ; Regex expression for validating IPv6 ; Checking if it is a valid IPv4 addresses ; Checking if it is a valid IPv6 addresses ; Return Invalid ; IP addresses to validate

import re


def Validate_It(IP):
    regex = "(([0-9] [1-9][0-9] 1[0-9][0-9] 2[0-4][0-9] 25[0-5])\.){3}" "([0-9] [1-9][0-9] 1[0-9][0-9] 2[0-4][0-9] 25[0-5])"
    regex1 = "((([0-9a-fA-F]){1,4})\:){7}"
    p = re .compile(regex)
    p1 = re .compile(regex1)
    if (re .search(p, IP)):
        return "Valid IPv4"
    elif (re .search(p1, IP)):
        return "Valid IPv6"
    return "Invalid IP"


IP = "203.120.223.13"
print(Validate_It(IP))
IP = "fffe:3465:efab:23fe:2235:6565:aaab:0001"
print(Validate_It(IP))
IP = "2F33:12a0:3Ea0:0302"
print(Validate_It(IP))

# Expected output:
Invalid IP
Valid IPv6
Invalid IP
# count of elements which is product of a pair or an element square | python3 program to implement the above approach ; stores all factors a number ; function to calculate and store in a vector ; function to return the count of array elements which are a product of two array elements ; copy elements into a a duplicate array ; sort the duplicate array ; store the count of elements ; if the factors are not calculated already ; traverse its factors ; if a pair of factors is found ; 

import math
v = [[]for i in range(100000)]


def div(n):
    global v
    for i in range(2, int(math .sqrt(n)) + 1):
        if (n % i == 0):
            v[n].append(i)


def prodof2elements(arr, n):
    arr2 = sorted(arr .copy())
    ans = 0
    for i in range(n):
        if (len(v[arr[i]]) == 0):
            div(arr[i])
        for j in v[arr[i]]:
            if j in arr2:
                if int(arr[i] / j) in arr2:
                    ans += 1
                    break
    return ans


arr = [2, 1, 8, 4, 32, 18]
N = len(arr)
print(prodof2elements(arr, N))

# Expected output:
3
# largest subarray with frequency of all elements same | function to find maximum subarray size ; generating all subarray i -> starting index j -> end index ; map 1 to hash frequency of all elements in subarray ; map 2 to hash frequency of all frequencies of elements ; finding previous frequency of arr [ j ] in map 1 ; increasing frequency of arr [ j ] by 1 ; check if previous frequency is present in map 2 ; delete previous frequency if hash is equal to 1 ; decrement the hash of previous frequency ; incrementing hash of new frequency in map 2 ; check if map2 size is 1 and updating answer ; return the maximum size of subarray ; 
def max_subarray_size(N, arr):
    ans = 0
    for i in range(N):
        map1 = {}
        map2 = {}
        for j in range(i, N):
            if (arr[j]not in map1):
                ele_count = 0
            else:
                ele_count = map1[arr[j]]
            if arr[j] in map1:
                map1[arr[j]] += 1
            else:
                map1[arr[j]] = 1
            if (ele_count in map2):
                if (map2[ele_count] == 1):
                    del map2[ele_count]
                else:
                    map2[ele_count] -= 1
            if ele_count + 1 in map2:
                map2[ele_count + 1] += 1
            else:
                map2[ele_count + 1] = 1
            if (len(map2) == 1):
                ans = max(ans, j - i + 1)
    return ans


arr = [1, 2, 2, 5, 6, 5, 6]
N = len(arr)
print(max_subarray_size(N, arr))

# Expected output:
6
# longest substring consisting of vowels using binary search | function to check if a character is vowel or not ; 0 - a 1 - b 2 - c and so on 25 - z ; function to check if any substring of length k exists which contains only vowels ; applying sliding window to get all substrings of length k ; remove the occurence of ( i - k + 1 ) th character ; function to perform binary search ; doing binary search on the lengths ; 
def vowel(vo):
    if (vo == 0 or vo == 4 or vo == 8 or vo == 14 or vo == 20):
        return True
    else:
        return False


def check(s, k):
    cnt = [0] * 26
    for i in range(k - 1):
        cnt[ord(s[i]) - ord('a')] += 1
    for i in range(k - 1, len(s)):
        cnt[ord(s[i]) - ord('a')] += 1
        flag1 = 0
        for j in range(26):
            if (vowel(j) == False and cnt[j] > 0):
                flag1 = 1
                break
        if (flag1 == 0):
            return True
        cnt[ord(s[i - k + 1]) - ord('a')] -= 1
    return False


def longestSubstring(s):
    l = 1
    r = len(s)
    maxi = 0
    while (l <= r):
        mid = (l + r) // 2
        if (check(s, mid)):
            l = mid + 1
            maxi = max(maxi, mid)
        else:
            r = mid - 1
    return maxi


if __name__ == "__main__":
    s = "sedrewaefhoiu"
    print(longestSubstring(s))

# Expected output:
3