giulio98/xlcost-single-prompt huggingface dataset:
# count number of triplets with product equal to given number | set 2 | function to count such triplets ; sort the array ; three pointer technique ; calculate the product of a triplet ; check if that product is greater than m , decrement mid ; check if that product is smaller than m , increment start ; check if that product is equal to m , decrement mid , increment start and increment the count of pairs ; 
def countTriplets(arr, n, m):
    count = 0
    arr .sort()
    for end in range(n - 1, 1, -1):
        start = 0
        mid = end - 1
        while (start < mid):
            prod = (arr[end] * arr[start] * arr[mid])
            if (prod > m):
                mid -= 1
            elif (prod < m):
                start += 1
            elif (prod == m):
                count += 1
                mid -= 1
                start += 1
    return count


if __name__ == "__main__":
    arr = [1, 1, 1, 1, 1, 1]
    n = len(arr)
    m = 1
    print(countTriplets(arr, n, m))

# Expected output:
6
# equally divide into two sets such that one set has maximum distinct elements | python3 program to equally divide n elements into two sets such that second set has maximum distinct elements . ; insert all the resources in the set there will be unique resources in the set ; return minimum of distinct resources and n / 2 ; 
def distribution(arr, n):
    resources = set()
    for i in range(n):
        resources .add(arr[i])
    return min(len(resources), n // 2)


if __name__ == '__main__':
    arr = [1, 1, 2, 1, 3, 4]
    n = len(arr)
    print(distribution(arr, n), "")

# Expected output:
3
# sort 3 numbers | python3 program to sort an array of size 3 ; insert arr [ 1 ] ; insert arr [ 2 ] ; 
def sort3(arr):
    if (arr[1] < arr[0]):
        arr[0], arr[1] = arr[1], arr[0]
    if (arr[2] < arr[1]):
        arr[1], arr[2] = arr[2], arr[1]
        if (arr[1] < arr[0]):
            arr[1], arr[0] = arr[0], arr[1]


a = [10, 12, 5]
sort3(a)
for i in range(3):
    print(a[i], end=" ")

# Expected output:
5 10 12
# merge sort with o ( 1 ) extra space merge and o ( n lg n ) time [ unsigned integers only ] | python3 program to sort an array using merge sort such that merge operation takes o ( 1 ) extra space . ; obtaining actual values ; recursive merge sort with extra parameter , naxele ; this functions finds max element and calls recursive merge sort . ; 
def merge(arr, beg, mid, end, maxele):
    i = beg
    j = mid + 1
    k = beg
    while (i <= mid and j <= end):
        if (arr[i] % maxele <= arr[j] % maxele):
            arr[k] = arr[k] + (arr[i] % maxele) * maxele
            k += 1
            i += 1
        else:
            arr[k] = arr[k] + (arr[j] % maxele) * maxele
            k += 1
            j += 1
    while (i <= mid):
        arr[k] = arr[k] + (arr[i] % maxele) * maxele
        k += 1
        i += 1
    while (j <= end):
        arr[k] = arr[k] + (arr[j] % maxele) * maxele
        k += 1
        j += 1
    for i in range(beg, end + 1):
        arr[i] = arr[i] // maxele


def mergeSortRec(arr, beg, end, maxele):
    if (beg < end):
        mid = (beg + end) // 2
        mergeSortRec(arr, beg, mid, maxele)
        mergeSortRec(arr, mid + 1, end, maxele)
        merge(arr, beg, mid, end, maxele)


def mergeSort(arr, n):
    maxele = max(arr) + 1
    mergeSortRec(arr, 0, n - 1, maxele)


if __name__ == '__main__':
    arr = [999, 612, 589, 856, 56, 945, 243]
    n = len(arr)
    mergeSort(arr, n)
    print("Sorted array")
    for i in range(n):
        print(arr[i], end=" ")

# Expected output:
Sorted array
56 243 589 612 856 945 999
# print triplets with sum less than k | python3 program to print triplets with sum smaller than a given value ; sort input array ; every iteration of loop counts triplet with first element as arr [ i ] . ; initialize other two elements as corner elements of subarray arr [ j + 1. . k ] ; use meet in the middle concept ; if sum of current triplet is more or equal , move right corner to look for smaller values ; else move left corner ; this is important . for current i and j , there are total k - j third elements . ; 
def printTriplets(arr, n, sum):
    arr .sort()
    for i in range(n - 2):
        (j, k) = (i + 1, n - 1)
        while (j < k):
            if (arr[i] + arr[j] + arr[k] >= sum):
                k -= 1
            else:
                for x in range(j + 1, k + 1):
                    print(str(arr[i]) + ", " +
                          str(arr[j]) + ", " + str(arr[x]))
                j += 1


if __name__ == "__main__":
    arr = [5, 1, 3, 4, 7]
    n = len(arr)
    sum = 12
    printTriplets(arr, n, sum)

# Expected output:
1, 3, 4
1, 3, 5
1, 3, 7
1, 4, 5
# sort string of characters using stack | function to print the characters in sorted order ; primary stack ; secondary stack ; append first character ; iterate for all character in string ; i - th character ascii ; stack 's top element ascii ; if greater or equal to top element then push to stack ; if smaller , then push all element to the temporary stack ; push all greater elements ; push operation ; push till the stack is not - empty ; push the i - th character ; push the tempstack back to stack ; print the stack in reverse order ; 
def printSorted(s, l):
    stack = []
    tempstack = []
    stack .append(s[0])
    for i in range(1, l):
        a = ord(s[i])
        b = ord(stack[-1])
        if ((a - b) >= 1 or (a == b)):
            stack .append(s[i])
        elif ((b - a) >= 1):
            while ((b - a) >= 1):
                tempstack .append(stack .pop())
                if (len(stack) > 0):
                    b = ord(stack[-1])
                else:
                    break
            stack .append(s[i])
            while (len(tempstack) > 0):
                stack .append(tempstack .pop())
    print(''.join(stack))


s = "geeksforgeeks"
l = len(s)
printSorted(s, l)

# Expected output:
eeeefggkkorss
# check whether an array can be fit into another array rearranging the elements in the array | returns true if the array a can be fit into array b , otherwise false ; sort both the arrays ; iterate over the loop and check whether every array element of a is less than or equal to its corresponding array element of b ; 
def checkFittingArrays(A, B, N):
    A = sorted(A)
    B = sorted(B)
    for i in range(N):
        if (A[i] > B[i]):
            return False
    return True


A = [7, 5, 3, 2]
B = [5, 4, 8, 7]
N = len(A)
if (checkFittingArrays(A, B, N)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# maximise the number of toys that can be purchased with amount k | this functions returns the required number of toys ; sort the cost array ; check if we can buy ith toy or not ; increment the count variable ; 
def maximum_toys(cost, N, K):
    count = 0
    sum = 0
    cost .sort(reverse=False)
    for i in range(0, N, 1):
        if (sum + cost[i] <= K):
            sum = sum + cost[i]
            count += 1
    return count


if __name__ == '__main__':
    K = 50
    cost = [1, 12, 5, 111, 200, 1000, 10, 9, 12, 15]
    N = len(cost)
    print(maximum_toys(cost, N, K))

# Expected output:
6
# find if k bookings possible with given arrival and departure times | python code implementation of the above approach ; 
def areBookingsPossible(A, B, K):
    A .sort()
    B .sort()
    for i in range(len(A)):
        if i + K < len(A) and A[i + K] < B[i]:
            return "No"
    return "Yes"


if __name__ == "__main__":
    arrival = [1, 2, 3]
    departure = [2, 3, 4]
    K = 1
    print(areBookingsPossible(arrival, departure, K))

# Expected output:
Yes
# check if given array is almost sorted ( elements are at | function for checking almost sort ; one by one compare adjacents . ; check whether resultant is sorted or not ; is resultant is sorted return true ; 
def almostSort(A, n):
    i = 0
    while i < n - 1:
        if A[i] > A[i + 1]:
            A[i], A[i + 1] = A[i + 1], A[i]
            i += 1
        i += 1
    for i in range(0, n - 1):
        if A[i] > A[i + 1]:
            return False
    return True


if __name__ == "__main__":
    A = [1, 3, 2, 4, 6, 5]
    n = len(A)
    if almostSort(A, n):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# efficiently merging two sorted arrays with o ( 1 ) extra space | function to find next gap . ; comparing elements in the first array . ; comparing elements in both arrays . ; comparing elements in the second array . ; 
def nextGap(gap):
    if (gap <= 1):
        return 0
    return (gap // 2) + (gap % 2)


def merge(arr1, arr2, n, m):
    gap = n + m
    gap = nextGap(gap)
    while gap > 0:
        i = 0
        while i + gap < n:
            if (arr1[i] > arr1[i + gap]):
                arr1[i], arr1[i + gap] = arr1[i + gap], arr1[i]
            i += 1
        j = gap - n if gap > n else 0
        while i < n and j < m:
            if (arr1[i] > arr2[j]):
                arr1[i], arr2[j] = arr2[j], arr1[i]
            i += 1
            j += 1
        if (j < m):
            j = 0
            while j + gap < m:
                if (arr2[j] > arr2[j + gap]):
                    arr2[j], arr2[j + gap] = arr2[j + gap], arr2[j]
                j += 1
        gap = nextGap(gap)


if __name__ == "__main__":
    a1 = [10, 27, 38, 43, 82]
    a2 = [3, 9]
    n = len(a1)
    m = len(a2)
    merge(a1, a2, n, m)
    print("First Array: ", end="")
    for i in range(n):
        print(a1[i], end=" ")
    print()
    print("Second Array: ", end="")
    for i in range(m):
        print(a2[i], end=" ")
    print()

# Expected output:
First Array: 3 9 10 27 38 
Second Array: 43 82
# merge two sorted arrays | merge arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] into arr3 [ 0. . n1 + n2 - 1 ] ; traverse both array ; check if current element of first array is smaller than current element of second array . if yes , store first array element and increment first array index . otherwise do same with second array ; store remaining elements of first array ; store remaining elements of second array ; 
def mergeArrays(arr1, arr2, n1, n2):
    arr3 = [None] * (n1 + n2)
    i = 0
    j = 0
    k = 0
    while i < n1 and j < n2:
        if arr1[i] < arr2[j]:
            arr3[k] = arr1[i]
            k = k + 1
            i = i + 1
        else:
            arr3[k] = arr2[j]
            k = k + 1
            j = j + 1
    while i < n1:
        arr3[k] = arr1[i]
        k = k + 1
        i = i + 1
    while j < n2:
        arr3[k] = arr2[j]
        k = k + 1
        j = j + 1
    print("Array after merging")
    for i in range(n1 + n2):
        print(str(arr3[i]), end=" ")


arr1 = [1, 3, 5, 7]
n1 = len(arr1)
arr2 = [2, 4, 6, 8]
n2 = len(arr2)
mergeArrays(arr1, arr2, n1, n2)

# Expected output:
Array after merging
1 2 3 4 5 6 7 8
# sort array after converting elements to their squares | function to sort an square array ; first convert each array elements into its square ; sort an array using " inbuild ▁ sort ▁ function " in arrays class ; 
def sortSquare(arr, n):
    for i in range(n):
        arr[i] = arr[i] * arr[i]
    arr .sort()


arr = [-6, -3, -1, 2, 4, 5]
n = len(arr)
print("Before sort")
for i in range(n):
    print(arr[i], end=" ")
print("")
sortSquare(arr, n)
print("After sort")
for i in range(n):
    print(arr[i], end=" ")

# Expected output:
Before sort
-6 -3 -1 2 4 5 
After sort
1 4 9 16 25 36
# sort an array when two halves are sorted | merge two sorted halves of array into single sorted array ; starting index of second half ; temp array store sorted resultant array ; first find the point where array is divide into two half ; if given array is all - ready sorted ; merge two sorted arrays in single sorted array ; copy the remaining elements of a [ i to half_ ! ] ; copy the remaining elements of a [ half_ ! to n ] ; 
def mergeTwoHalf(A, n):
    half_i = 0
    temp = [0 for i in range(n)]
    for i in range(n - 1):
        if (A[i] > A[i + 1]):
            half_i = i + 1
            break
    if (half_i == 0):
        return
    i = 0
    j = half_i
    k = 0
    while (i < half_i and j < n):
        if (A[i] < A[j]):
            temp[k] = A[i]
            k += 1
            i += 1
        else:
            temp[k] = A[j]
            k += 1
            j += 1
    while i < half_i:
        temp[k] = A[i]
        k += 1
        i += 1
    while (j < n):
        temp[k] = A[j]
        k += 1
        j += 1
    for i in range(n):
        A[i] = temp[i]


A = [2, 3, 8, -1, 7, 10]
n = len(A)
mergeTwoHalf(A, n)
print(*A, sep=' ')

# Expected output:
-1 2 3 7 8 10
# chocolate distribution problem | arr [ 0. . n - 1 ] represents sizes of packets m is number of students . returns minimum difference between maximum and minimum values of distribution . ; if there are no chocolates or number of students is 0 ; sort the given packets ; number of students cannot be more than number of packets ; largest number of chocolates ; find the subarray of size m such that difference between last ( maximum in case of sorted ) and first ( minimum in case of sorted ) elements of subarray is minimum . ; 
def findMinDiff(arr, n, m):
    if (m == 0 or n == 0):
        return 0
    arr .sort()
    if (n < m):
        return -1
    min_diff = arr[n - 1] - arr[0]
    for i in range(len(arr) - m + 1):
        min_diff = min(min_diff, arr[i + m - 1] - arr[i])
    return min_diff


if __name__ == "__main__":
    arr = [12, 4, 7, 9, 2, 23, 25, 41, 30, 40, 28, 42, 30, 44, 48, 43, 50]
    n = len(arr)
    m = 7
    print("Minimum difference is", findMinDiff(arr, n, m))

# Expected output:
Minimum difference is 10
# absolute distinct count in a sorted array | this function returns number of distinct absolute values among the elements of the array ; set keeps all unique elements ; 
def distinctCount(arr, n):
    s = set()
    for i in range(n):
        s .add(abs(arr[i]))
    return len(s)


arr = [-2, -1, 0, 1, 1]
n = len(arr)
print("Count of absolute distinct values:", distinctCount(arr, n))

# Expected output:
Count of absolute distinct values: 3
# absolute distinct count in a sorted array | the function returns return number of distinct absolute values among the elements of the array ; initialize count as number of elements ; remove duplicate elements from the left of the current window ( i , j ) and also decrease the count ; remove duplicate elements from the right of the current window ( i , j ) and also decrease the count ; break if only one element is left ; now look for the zero sum pair in current window ( i , j ) ; decrease the count if ( positive , negative ) pair is encountered ; 
def distinctCount(arr, n):
    count = n
    i = 0
    j = n - 1
    sum = 0
    while (i < j):
        while (i != j and arr[i] == arr[i + 1]):
            count = count - 1
            i = i + 1
        while (i != j and arr[j] == arr[j - 1]):
            count = count - 1
            j = j - 1
        if (i == j):
            break
        sum = arr[i] + arr[j]
        if (sum == 0):
            count = count - 1
            i = i + 1
            j = j - 1
        elif (sum < 0):
            i = i + 1
        else:
            j = j - 1
    return count


arr = [-2, -1, 0, 1, 1]
n = len(arr)
print("Count of absolute distinct values : ", distinctCount(arr, n))

# Expected output:
Count of absolute distinct values :  3
# lexicographically smallest numeric string having odd digit counts | function to construct lexicographically smallest numeric string having an odd count of each characters ; stores the resultant string ; if n is even ; otherwise ; 
def genString(N):
    ans = ""
    if (N % 2 == 0):
        ans = "".join("1"for i in range(N - 1))
        ans = ans + "2"
    else:
        ans = "".join("1"for i in range(N))
    return ans


if __name__ == "__main__":
    N = 5
    print(genString(N))

# Expected output:
11111
# count of values chosen for x such that n is reduced to 0 after given operations | function to check if the value of x reduces n to 0 or not ; update the value of n as n - x ; check if x is a single digit integer ; function to find the number of values x such that n can be reduced to 0 after performing the given operations ; number of digits in n ; stores the count of value of x ; iterate over all possible value of x ; check if x follow the conditions ; return the total count ; 
def check(x, N):
    while True:
        N -= x
        if len(str(x)) == 1:
            break
        x = sum(list(map(int, str(x))))
    if len(str(x)) == 1 and N == 0:
        return 1
    return 0


def countNoOfsuchX(N):
    k = len(str(N))
    count = 0
    for x in range(N - k * (k + 1) * 5, N + 1):
        if check(x, N):
            count += 1
    return count


N = 9939
print(countNoOfsuchX(N))

# Expected output:
3
# minimize moves required to make array elements equal by incrementing and decrementing pairs | set 2 | function to find the minimum number of increment and decrement of pairs required to make all array elements equal ; stores the sum of the array ; if sum is not divisible by n ; update sum ; store the minimum number of operations ; iterate while i is less than n ; add absolute difference of current element with k to ans ; increase i bye 1 ; return the value in ans2 ; 
def find(arr, N):
    Sum = sum(arr)
    if Sum % N:
        return -1
    else:
        k = Sum // N
        ans = 0
        i = 0
        while i < N:
            ans = ans + abs(k - arr[i])
            i += 1
        return ans // 2


if __name__ == '__main__':
    arr = [5, 4, 1, 10]
    N = len(arr)
    print(find(arr, N))

# Expected output:
5
# convert a into b by incrementing or decrementing 1 , 2 , or 5 any number of times | function to find minimum number of moves required to convert a into b ; stores the minimum number of moves required ; stores the absolute difference ; find the number of moves ; return cnt ; 
def minimumSteps(a, b):
    cnt = 0
    a = abs(a - b)
    cnt = (a // 5) + (a % 5) // 2 + (a % 5) % 2
    return cnt


A = 3
B = 9
print(minimumSteps(A, B))

# Expected output:
2
# lexicographically smallest string which is not a subsequence of given string | function to find lexicographically smallest string that is not a subsequence of s ; variable to store frequency of a ; calculate frequency of a ; initialize string consisting of freq number of a ; change the last digit to b ; add another ' a ' to the string ; return tha answer string ; 
def smallestNonSubsequence(S, N):
    freq = 0
    for i in range(N):
        if (S[i] == 'a'):
            freq += 1
    ans = ""
    for i in range(freq):
        ans += 'a'
    if (freq == N):
        ans = ans .replace(ans[freq - 1], 'b')
    else:
        ans += 'a'
    return ans


if __name__ == '__main__':
    S = "abcdefghijklmnopqrstuvwxyz"
    N = len(S)
    print(smallestNonSubsequence(S, N))

# Expected output:
aa
# print all numbers that can be obtained by adding a or b to n exactly m times | function to find all possible numbers that can be obtained by adding a or b to n exactly m times ; for maintaining increasing order ; smallest number that can be obtained ; if a and b are equal , then only one number can be obtained , i . e . n + m * a ; for finding others numbers , subtract a from number once and add b to number once ; 
def possibleNumbers(N, M, A, B):
    if (A > B):
        temp = A
        A = B
        B = temp
    number = N + M * A
    print(number, end=" ")
    if (A != B):
        for i in range(M):
            number = number - A + B
            print(number, end=" ")


if __name__ == '__main__':
    N = 5
    M = 3
    A = 4
    B = 6
    possibleNumbers(N, M, A, B)

# Expected output:
17 19 21 23
# maximize number of circular buildings that can be covered by l length wire | python3 program for the above approach ; function to find the maximum number of buildings covered ; store the current sum ; traverse the array ; add the length of wire required for current building to cur_sum ; add extra unit distance 1 ; if curr_sum <= length of wire increment count by 1 ; if curr_sum > length of wire increment start by 1 and decrement count by 1 and update the new curr_sum ; update the max_count ; return the max_count ; 

Pi = 3.141592


def MaxBuildingsCovered(arr, N, L):
    curr_sum = 0
    start = 0
    curr_count = 0
    max_count = 0
    for i in range(N):
        curr_sum = curr_sum + (arr[i] * Pi)
        if (i != 0):
            curr_sum += 1
        if (curr_sum <= L):
            curr_count += 1
        elif (curr_sum > L):
            curr_sum = curr_sum - (arr[start] * Pi)
            curr_sum -= 1
            start += 1
            curr_count -= 1
        max_count = max(curr_count, max_count)
    return max_count


if __name__ == '__main__':
    arr = [4, 1, 6, 2]
    L = 24
    N = len(arr)
    print(MaxBuildingsCovered(arr, N, L))

# Expected output:
2
# count numbers less than n whose bitwise and with n is zero | function to count number of unset bits in the integer n ; stores the number of unset bits in n ; check if n is even ; increment the value of c ; right shift n by 1 ; return the value of count of unset bits ; function to count numbers whose bitwise and with n equal to 0 ; stores the number of unset bits in n ; prthe value of 2 to the power of unsetbits ; 
def countUnsetBits(N):
    c = 0
    while (N):
        if (N % 2 == 0):
            c += 1
        N = N >> 1
    return c


def countBitwiseZero(N):
    unsetBits = countUnsetBits(N)
    print((1 << unsetBits))


if __name__ == '__main__':
    N = 9
    countBitwiseZero(N)

# Expected output:
4
# check if a binary string can be split into disjoint subsequences which are equal to "010" | function to check if the given string can be partitioned into a number of subsequences all of which are equal to "010" ; store the size of the string ; store the count of 0 s and 1 s ; traverse the given string in the forward direction ; if the character is '0' , increment count_0 by 1 ; if the character is '1' increment count_1 by 1 ; if at any point , count_1 > count_0 , return false ; if count_0 is not equal to twice count_1 , return false ; reset the value of count_0 and count_1 ; traverse the string in the reverse direction ; if the character is '0' increment count_0 ; if the character is '1' increment count_1 ; if count_1 > count_0 , return false ; 
def isPossible(s):
    n = len(s)
    count_0, count_1 = 0, 0
    for i in range(n):
        if (s[i] == '0'):
            count_0 += 1
        else:
            count_1 += 1
        if (count_1 > count_0):
            return False
    if (count_0 != (2 * count_1)):
        return False
    count_0, count_1 = 0, 0
    for i in range(n - 1, -1, -1):
        if (s[i] == '0'):
            count_0 += 1
        else:
            count_1 += 1
        if (count_1 > count_0):
            return False
    return True


if __name__ == '__main__':
    s = "010100"
    if (isPossible(s)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimum number of bricks that can be intersected | python 3 program for the above approach ; function to find a line across a wall such that it intersects minimum number of bricks ; declare a hashmap ; store the maximum number of brick ending a point on x - axis ; iterate over all the rows ; initialize width as 0 ; iterate over individual bricks ; add the width of the current brick to the total width ; increment number of bricks ending at this width position ; update the variable , res ; print the answer ; 

from collections import defaultdict


def leastBricks(wall):
    map = defaultdict(int)
    res = 0
    for list in wall:
        width = 0
        for i in range(len(list) - 1):
            width += list[i]
            map[width] += 1
            res = max(res, map[width])
    print(len(wall) - res)


if __name__ == "__main__":
    arr = [[1, 2, 2, 1], [3, 1, 2], [1, 3, 2], [2, 4], [3, 1, 2], [1, 3, 1, 1]]
    leastBricks(arr)

# Expected output:
2
# find an n | function to print the required permutation ; 
def findPermutation(N):
    for i in range(1, N + 1, 1):
        print(i, end=" ")
    print("",  end="")


if __name__ == '__main__':
    N = 5
    findPermutation(N)

# Expected output:
1 2 3 4 5