giulio98/xlcost-single-prompt huggingface dataset:
# count pairs in an array such that frequency of one is at least value of other | python3 program to find the number of ordered pairs ; function to find count of ordered pairs ; initialize pairs to 0 ; store frequencies ; count total ordered_pairs ; 

from collections import defaultdict


def countOrderedPairs(A, n):
    orderedPairs = 0
    m = defaultdict(lambda: 0)
    for i in range(0, n):
        m[A[i]] += 1
    for X, Y in m .items():
        for j in range(1, Y + 1):
            if m[j] >= X:
                orderedPairs += 1
    return orderedPairs


if __name__ == "__main__":
    A = [1, 1, 2, 2, 3]
    n = len(A)
    print(countOrderedPairs(A, n))

# Expected output:
4
# longest subarray with elements having equal modulo k | function to find longest sub - array whose elements gives same remainder when divided with k ; iterate in the array ; check if array element greater then x or not ; 
def LongestSubarray(arr, n, k):
    count = 1
    max_lenght = 1
    prev_mod = arr[0] % k
    for i in range(1, n):
        curr_mod = arr[i] % k
        if curr_mod == prev_mod:
            count += 1
        else:
            max_lenght = max(max_lenght, count)
            count = 1
            prev_mod = curr_mod
    return max(max_lenght, count)


arr = [4, 9, 7, 18, 29, 11]
n = len(arr)
k = 11
print(LongestSubarray(arr, n, k))

# Expected output:
3
# search in a sorted 2d matrix ( stored in row major order ) | python 3 program to find whether a given element is present in the given 2 - d matrix ; basic binary search to find an element in a 1 - d array ; if element found return true ; if middle less than k then skip the left part of the array else skip the right part ; if not found return false ; function to search an element in a matrix based on divide and conquer approach ; if the element lies in the range of this row then call 1 - d binary search on this row ; if the element is less then the starting element of that row then search in upper rows else search in the lower rows ; if not found ; 

M = 3
N = 4


def binarySearch1D(arr, K):
    low = 0
    high = N - 1
    while (low <= high):
        mid = low + int((high - low) / 2)
        if (arr[mid] == K):
            return True
        if (arr[mid] < K):
            low = mid + 1
        else:
            high = mid - 1
    return False


def searchMatrix(matrix, K):
    low = 0
    high = M - 1
    while (low <= high):
        mid = low + int((high - low) / 2)
        if (K >= matrix[mid][0] and K <= matrix[mid][N - 1]):
            return binarySearch1D(matrix[mid], K)
        if (K < matrix[mid][0]):
            high = mid - 1
        else:
            low = mid + 1
    return False


if __name__ == '__main__':
    matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
    K = 3
    if (searchMatrix(matrix, K)):
        print("Found")
    else:
        print("Not found")

# Expected output:
Found
# program to find nth term divisible by a or b | python 3 program to find nth term divisible by a or b ; function to return gcd of a and b ; function to calculate how many numbers from 1 to num are divisible by a or b ; calculate number of terms divisible by a and by b then , remove the terms which are divisible by both a and b ; binary search to find the nth term divisible by a or b ; set low to 1 and high to max ( a , b ) * n , here we have taken high as 10 ^ 18 ; if the current term is less than n then we need to increase low to mid + 1 ; if current term is greater than equal to n then high = mid ; 

import sys


def gcd(a, b):
    if a == 0:
        return b
    return gcd(b % a, a)


def divTermCount(a, b, lcm, num):
    return num // a + num // b - num // lcm


def findNthTerm(a, b, n):
    low = 1
    high = sys .maxsize
    lcm = (a * b) // gcd(a, b)
    while low < high:
        mid = low + (high - low) // 2
        if divTermCount(a, b, lcm, mid) < n:
            low = mid + 1
        else:
            high = mid
    return low


a = 2
b = 5
n = 10
print(findNthTerm(a, b, n))

# Expected output:
16
# replace all occurrences of pi with 3.14 in a given string | function to replace all occurrences of pi in a given with 3.14 ; iterate through second last element of the string ; if current and current + 1 alphabets form the word ' pi ' append 3.14 to output ; append the current letter ; return the output string ; 
def replacePi(input):
    output = ""
    size = len(input)
    for i in range(size):
        if (i + 1 < size and input[i] == 'p' and input[i + 1] == 'i'):
            output += "3.14"
            i += 1
        else:
            output += input[i]
    return output


input = "2 * pi + 3 * pi = 5 * pi"
print(replacePi(input))

# Expected output:
2 * 3.14i + 3 * 3.14i = 5 * 3.14i
# number of elements that can be seen from right side | python3 program to find number of elements that can be seen from right side ; 
def numberOfElements(height, n):
    max_so_far = 0
    coun = 0
    for i in range(n - 1, -1, -1):
        if height[i] > max_so_far:
            max_so_far = height[i]
            coun = coun + 1
    return coun


if __name__ == '__main__':
    n = 6
    height = [4, 8, 2, 0, 0, 5]
    print(numberOfElements(height, n))

# Expected output:
2
# largest element in the array that is repeated exactly k times | function that finds the largest element which is repeated ' k ' times ; sort the array ; if the value of ' k ' is 1 and the largest appears only once in the array ; counter to count the repeated elements ; check if the element at index ' i ' is equal to the element at index ' i + 1' then increase the count ; else set the count to 1 to start counting the frequency of the new number ; if the count is equal to k and the previous element is not equal to this element ; if there is no such element ; 
def solve(arr, n, k):
    arr .sort()
    if (k == 1 and arr[n - 2] != arr[n - 1]):
        print(arr[n - 1])
        return
    count = 1
    for i in range(n - 2, -1, -1):
        if (arr[i] == arr[i + 1]):
            count += 1
        else:
            count = 1
        if (count == k and (i == 0 or (arr[i - 1] != arr[i]))):
            print(arr[i])
            return
    print("No such element")


if __name__ == "__main__":
    arr = [1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6]
    k = 2
    n = len(arr)
    solve(arr, n, k)

# Expected output:
5
# largest element in the array that is repeated exactly k times | python implementation of above approach ; function that finds the largest element that occurs exactly ' k ' times ; store the frequency of each element ; to store the maximum element ; if current element has frequency ' k ' and current maximum hasn 't been set ; set the current maximum ; if current element has frequency ' k ' and it is greater than the current maximum ; change the current maximum ; if there is no element with frequency 'k ; print the largest element with frequency 'k ; 

import sys


def solve(arr, n, k):
    m = {}

    for i in range(0, n - 1):
        if (arr[i] in m.keys()):
            m[arr[i]] += 1
        else:
            m[arr[i]] = 1
        i += 1
    max = sys.maxsize

    for i in range(0, n - 1):
        if (m[arr[i]] == k and
                max == sys.maxsize):
            max = arr[i]
        elif (m[arr[i]] == k and max < arr[i]):
            max = arr[i]
        i += 1
    if (max == sys.maxsize):
        print("No such element")
    else:
        print(max)


arr = [1, 1, 2, 3, 3, 4,
       5, 5, 6, 6, 6]
k = 4
n = len(arr)
solve(arr, n, k)

# Expected output:
No such element
# count the number of pop operations on stack to get each element of the array | function to find the count ; hashmap to store all the elements which are popped once . ; check if the number is present in the hashmap or in other words been popped out from the stack before . ; keep popping the elements while top is not equal to num ; pop the top ie . equal to num ; print the number of elements popped . ; 
def countEle(s, a, N):
    mp = {}
    for i in range(0, N):
        num = a[i]
        if num in mp:
            print("0", end=" ")
        else:
            cnt = 0
            while s[-1] != num:
                mp[s .pop()] = True
                cnt += 1
            s .pop()
            cnt += 1
            print(cnt, end=" ")


if __name__ == "__main__":
    N = 5
    s = []
    s .append(1)
    s .append(2)
    s .append(3)
    s .append(4)
    s .append(6)
    a = [6, 3, 4, 1, 2]
    countEle(s, a, N)

# Expected output:
1 2 0 2 0
# count characters with same neighbors | function to count the characters with same adjacent characters ; if length is less than 3 then return length as there will be only two characters ; traverse the string ; increment the count if the previous and next character is same ; return count ; 
def countChar(str):
    n = len(str)
    if (n <= 2):
        return n
    count = 2
    for i in range(1, n - 1):
        if (str[i - 1] == str[i + 1]):
            count += 1
    return count


if __name__ == '__main__':
    str = "egeeksk"
    print(countChar(str))

# Expected output:
4
# first strictly smaller element in a sorted array in java | python3 program to find first element that is strictly smaller than given target ; minimum size of the array should be 1 ; if target lies beyond the max element , than the index of strictly smaller value than target should be ( end - 1 ) ; move to the left side if target is smaller ; move right side ; 
def next(arr, target):
    start = 0
    end = len(arr) - 1
    if (end == 0):
        return -1
    if (target > arr[end]):
        return end
    ans = -1
    while (start <= end):
        mid = (start + end) // 2
        if (arr[mid] >= target):
            end = mid - 1
        else:
            ans = mid
            start = mid + 1
    return ans


if __name__ == '__main__':
    arr = [1, 2, 3, 5, 8, 12]
    print(next(arr, 5))

# Expected output:
2
# first strictly greater element in a sorted array in java | python program to find first element that is strictly greater than given target . ; move to right side if target is greater . ; move left side . ; 
def next(arr, target):
    start = 0
    end = len(arr) - 1
    ans = -1
    while (start <= end):
        mid = (start + end) // 2
        if (arr[mid] <= target):
            start = mid + 1
        else:
            ans = mid
            end = mid - 1
    return ans


if __name__ == '__main__':
    arr = [1, 2, 3, 5, 8, 12]
    print(next(arr, 8))

# Expected output:
5
# reallocation of elements based on locality of reference | a function to perform sequential search . ; linearly search the element ; if not found ; shift elements before one position ; 
def search(arr, n, x):
    res = -1
    for i in range(0, n, 1):
        if (x == arr[i]):
            res = i
    if (res == -1):
        return False
    temp = arr[res]
    i = res
    while (i > 0):
        arr[i] = arr[i - 1]
        i -= 1
    arr[0] = temp
    return True


if __name__ == '__main__':
    arr = [12, 25, 36, 85, 98, 75, 89, 15, 63, 66, 64, 74, 27, 83, 97]
    q = [63, 63, 86, 63, 78]
    n = len(arr)
    m = len(q)
    for i in range(0, m, 1):
        if (search(arr, n, q[i])):
            print("Yes", end=" ")
        else:
            print("No", end=" ")

# Expected output:
Yes Yes No Yes No
# probability of a key k present in array | function to find the probability ; find probability upto 2 decimal places ; 
def kPresentProbability(a, n, k):
    count = a .count(k)
    return round(count / n, 2)


if __name__ == "__main__":
    A = [4, 7, 2, 0, 8, 7, 5]
    K = 2
    N = len(A)
    print(kPresentProbability(A, N, K))

# Expected output:
0.14
# largest subarray having sum greater than k | comparison function used to sort presum vector . ; function to find index in presum vector upto which all prefix sum values are less than or equal to val . ; starting and ending index of search space . ; to store required index value . ; if middle value is less than or equal to val then index can lie in mid + 1. . n else it lies in 0. . mid - 1. ; function to find largest subarray having sum greater than or equal to k . ; length of largest subarray . ; vector to store pair of prefix sum and corresponding ending index value . ; to store the current value of prefix sum . ; to store minimum index value in range 0. . i of presum vector . ; insert values in presum vector . ; update minind array . ; if sum is greater than k , then answer is i + 1. ; if sum is less than or equal to k , then find if there is a prefix array having sum that needs to be added to current sum to make its value greater than k . if yes , then compare length of updated subarray with maximum length found so far . ; 
def compare(a, b):
    if a[0] == b[0]:
        return a[1] < b[1]
    return a[0] < b[0]


def findInd(preSum, n, val):
    l, h = 0, n - 1
    ans = -1
    while l <= h:
        mid = (l + h) // 2
        if preSum[mid][0] <= val:
            ans = mid
            l = mid + 1
        else:
            h = mid - 1
    return ans


def largestSub(arr, n, k):
    maxlen = 0
    preSum = []
    Sum = 0
    minInd = [None] * (n)
    for i in range(0, n):
        Sum = Sum + arr[i]
        preSum .append([Sum, i])
    preSum .sort()
    minInd[0] = preSum[0][1]
    for i in range(1, n):
        minInd[i] = min(minInd[i - 1], preSum[i][1])
    Sum = 0
    for i in range(0, n):
        Sum = Sum + arr[i]
        if Sum > k:
            maxlen = i + 1
        else:
            ind = findInd(preSum, n, Sum - k - 1)
            if ind != -1 and minInd[ind] < i:
                maxlen = max(maxlen, i - minInd[ind])
    return maxlen


if __name__ == "__main__":
    arr = [-2, 1, 6, -3]
    n = len(arr)
    k = 5
    print(largestSub(arr, n, k))

# Expected output:
2
# find the slope of the given number | function to find slope of a number ; to store slope of the given number 'num ; loop from the 2 nd digit up to the 2 nd last digit of the given number 'num ; if the digit is a maxima ; if the digit is a minima ; required slope ; 
def slopeOfNum(num, n):

    slope = 0

    for i in range(1, n - 1):

        if (num[i] > num[i - 1] and
                num[i] > num[i + 1]):
            slope += 1
        elif (num[i] < num[i - 1] and
              num[i] < num[i + 1]):
            slope += 1

    return slope


if __name__ == "__main__":

    num = "1213321"
    n = len(num)
    print("Slope =", slopeOfNum(num, n))

# Expected output:
Slope = 2
# sudo placement | beautiful pairs | python3 code for finding required pairs ; the function to check if beautiful pair exists ; set for hashing ; traversing the first array ; traversing the second array to check for every j corresponding to single i ; x + y = z = > x = y - z ; if such x exists then we return true ; hash to make use of it next time ; no pair exists ; 

from typing import List


def pairExists(arr1: List[int], m: int, arr2: List[int], n: int) -> bool:
    s = set()
    for i in range(m):
        for j in range(n):
            if (arr2[2] - arr1[2])not in s:
                return True
        s .add(arr1[i])
    return False


if __name__ == "__main__":
    arr1 = [1, 5, 10, 8]
    arr2 = [2, 20, 13]
    if (pairExists(arr1, 4, arr2, 3)):
        print(1)
    else:
        print(0)

# Expected output:
1
# sudo placement | placement tour | python program to find the optimal number of elements such that the cumulative value should be less than given number ; this function returns true if the value cumulative according to received integer k is less than budget b , otherwise returns false ; initialize a temporary array which stores the cumulative value of the original array ; sort the array to find the smallest k values ; check if the value is less than budget ; this function prints the optimal number of elements and respective cumulative value which is less than the given number ; initialize answer as zero as optimal value may not exists ; if the current mid value is an optimal value , then try to maximize it ; call again to set the corresponding cumulative value for the optimal ans ; 

value = 0


def canBeOptimalValue(K: int, arr: list, N: int, B: int) -> bool:
    global value

    tmp = [0] * N

    for i in range(N):
        tmp[i] = (arr[i] + K * (i + 1))
    tmp.sort()

    value = 0
    for i in range(K):
        value += tmp[i]
    return value <= B


def findNoOfElementsandValue(arr: list, N: int, B: int):
    global value
    start = 0

    end = N
    ans = 0

    value = 0
    while start <= end:
        mid = (start + end) // 2
        if canBeOptimalValue(mid, arr, N, B):
            ans = mid
            start = mid + 1
        else:
            end = mid - 1
    canBeOptimalValue(ans, arr, N, B)

    print(ans, value)


if __name__ == "__main__":
    arr = [1, 2, 5, 6, 3]
    N = len(arr)
    B = 90
    findNoOfElementsandValue(arr, N, B)

# Expected output:
4 54
# previous greater element | python 3 program previous greater element a naive solution to print previous greater element for every element in an array . ; previous greater for first element never exists , so we print - 1. ; let us process remaining elements . ; find first element on left side that is greater than arr [ i ] . ; if all elements on left are smaller . ; 
def prevGreater(arr, n):
    print("-1", end=", ")
    for i in range(1, n):
        flag = 0
        for j in range(i - 1, -1, -1):
            if arr[i] < arr[j]:
                print(arr[j], end=", ")
                flag = 1
                break
        if j == 0 and flag == 0:
            print("-1", end=", ")


if __name__ == "__main__":
    arr = [10, 4, 2, 20, 40, 12, 30]
    n = len(arr)
    prevGreater(arr, n)

# Expected output:
-1, 10, 4, -1, -1, 40, 40,
# previous greater element | python3 program to print previous greater element an efficient solution to print previous greater element for every element in an array . ; create a stack and push index of first element to it ; previous greater for first element is always - 1. ; traverse remaining elements ; pop elements from stack while stack is not empty and top of stack is smaller than arr [ i ] . we always have elements in decreasing order in a stack . ; if stack becomes empty , then no element is greater on left side . else top of stack is previous greater . ; 

import math as mt


def prevGreater(arr, n):
    s = list()
    s .append(arr[0])
    print("-1, ", end="")
    for i in range(1, n):
        while (len(s) > 0 and s[-1] < arr[i]):
            s .pop()
        if len(s) == 0:
            print("-1, ", end="")
        else:
            print(s[-1], ", ", end="")
        s .append(arr[i])


arr = [10, 4, 2, 20, 40, 12, 30]
n = len(arr)
prevGreater(arr, n)

# Expected output:
-1, 10 , 4 , -1, -1, 40 , 40 ,
# duplicates in an array in o ( n ) time and by using o ( 1 ) extra space | set | function to find repeating elements ; flag variable used to represent whether repeating element is found or not . ; check if current element is repeating or not . if it is repeating then value will be greater than or equal to n . ; check if it is first repetition or not . if it is first repetition then value at index arr [ i ] is less than 2 * n . print arr [ i ] if it is first repetition . ; add n to index arr [ i ] to mark presence of arr [ i ] or to mark repetition of arr [ i ] . ; if flag variable is not set then no repeating element is found . so print - 1. ; 
def printDuplicates(arr, n):
    fl = 0
    for i in range(0, n):
        if (arr[arr[i] % n] >= n):
            if (arr[arr[i] % n] < 2 * n):
                print(arr[i] % n, end=" ")
                fl = 1
        arr[arr[i] % n] += n
    if (fl == 0):
        print("-1")


arr = [1, 6, 3, 1, 3, 6, 6]
arr_size = len(arr)
printDuplicates(arr, arr_size)

# Expected output:
1 3 6
# find the smallest positive number missing from an unsorted array | set 2 | function to find smallest positive missing number . ; to store next array element in current traversal ; if value is negative or greater than array size , then it cannot be marked in array . so move to next element . ; traverse the array until we reach at an element which is already marked or which could not be marked . ; find first array index which is not marked which is also the smallest positive missing number . ; if all indices are marked , then smallest missing positive number is array_size + 1. ; 
def findMissingNo(arr, n):
    for i in range(n):
        if (arr[i] <= 0 or arr[i] > n):
            continue
        val = arr[i]
        while (arr[val - 1] != val):
            nextval = arr[val - 1]
            arr[val - 1] = val
            val = nextval
            if (val <= 0 or val > n):
                break
    for i in range(n):
        if (arr[i] != i + 1):
            return i + 1
    return n + 1


if __name__ == "__main__":
    arr = [2, 3, 7, 6, 8, -1, -10, 15]
    arr_size = len(arr)
    missing = findMissingNo(arr, arr_size)
    print("The smallest positive", "missing number is ", missing)

# Expected output:
The smallest positive missing number is  1
# print all triplets with given sum | prints all triplets in arr [ ] with given sum ; 
def findTriplets(arr, n, sum):
    for i in range(0, n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
                if (arr[i] + arr[j] + arr[k] == sum):
                    print(arr[i], " ", arr[j], " ", arr[k], sep="")


arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n, -2)

# Expected output:
0 -3 1
-1 2 -3
# print all triplets with given sum | python3 program to find triplets in a given array whose sum is equal to given sum . ; function to print triplets with given sum ; find all pairs with sum equals to " sum - arr [ i ] " ; 

import math as mt


def findTriplets(arr, n, Sum):
    for i in range(n - 1):
        s = dict()
        for j in range(i + 1, n):
            x = Sum - (arr[i] + arr[j])
            if x in s .keys():
                print(x, arr[i], arr[j])
            else:
                s[arr[j]] = 1


arr = [0, -1, 2, -3, 1]
Sum = -2
n = len(arr)
findTriplets(arr, n, Sum)

# Expected output:
-3 0 1
2 -1 -3
# maximum product quadruple ( sub | python3 program to find a maximum product of a quadruple in array of integers ; function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; will contain max product ; 

import sys


def maxProduct(arr, n):
    if (n < 4):
        return -1
    max_product = -sys .maxsize
    for i in range(n - 3):
        for j in range(i + 1, n - 2):
            for k in range(j + 1, n - 1):
                for l in range(k + 1, n):
                    max_product = max(
                        max_product, arr[i] * arr[j] * arr[k] * arr[l])
    return max_product


arr = [10, 3, 5, 6, 20]
n = len(arr)
max = maxProduct(arr, n)
if (max == -1):
    print("No Quadruple Exists")
else:
    print("Maximum product is", max)

# Expected output:
Maximum product is 6000
# maximum product quadruple ( sub | function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; sort the array in ascending order ; return the maximum of x , y and z ; 
def maxProduct(arr, n):
    if (n < 4):
        return -1
    arr .sort()
    x = (arr[n - 1] * arr[n - 2] * arr[n - 3] * arr[n - 4])
    y = arr[0] * arr[1] * arr[2] * arr[3]
    z = (arr[0] * arr[1] * arr[n - 1] * arr[n - 2])
    return max(x, max(y, z))


if __name__ == "__main__":
    arr = [-10, -3, 5, 6, -20]
    n = len(arr)
    max = maxProduct(arr, n)
    if (max == -1):
        print("No Quadruple Exists")
    else:
        print("Maximum product is", max)

# Expected output:
Maximum product is 6000
# minimum value of " max ▁ + ▁ min " in a subarray | python 3 program to find sum of maximum and minimum in any subarray of an array of positive numbers . ; 
def maxSum(arr, n):
    if (n < 2):
        return -1
    ans = arr[0] + arr[1]
    for i in range(1, n - 1, 1):
        ans = min(ans, (arr[i] + arr[i + 1]))
    return ans


if __name__ == '__main__':
    arr = [1, 12, 2, 2]
    n = len(arr)
    print(maxSum(arr, n))

# Expected output:
4