giulio98/xlcost-single-prompt huggingface dataset:
# print all the sum pairs which occur maximum number of times | function to find the sum pairs that occur the most ; hash - table ; keep a count of sum pairs ; variables to store maximum occurrence ; iterate in the hash table ; print all sum pair which occur maximum number of times ; 
def findSumPairs(a, n):
    mpp = {i: 0 for i in range(21)}
    for i in range(n - 1):
        for j in range(i + 1, n, 1):
            mpp[a[i] + a[j]] += 1
    occur = 0
    for key, value in mpp .items():
        if (value > occur):
            occur = value
    for key, value in mpp .items():
        if (value == occur):
            print(key)


if __name__ == '__main__':
    a = [1, 8, 3, 11, 4, 9, 2, 7]
    n = len(a)
    findSumPairs(a, n)

# Expected output:
10
11
12
# minimum index i such that all the elements from index i to given index are equal | function to return the minimum required index ; start from arr [ pos - 1 ] ; all elements are equal from arr [ i + 1 ] to arr [ pos ] ; 
def minIndex(arr, n, pos):
    num = arr[pos]
    i = pos - 1
    while (i >= 0):
        if (arr[i] != num):
            break
        i -= 1
    return i + 1


arr = [2, 1, 1, 1, 5, 2]
n = len(arr)
pos = 4
print(minIndex(arr, n, pos))

# Expected output:
4
# count of strings that become equal to one of the two strings after one removal | python3 implementation of the approach ; function to return the count of the required strings ; searching index after longest common prefix ends ; searching index before longest common suffix ends ;  ; if only 1 character is different in both the strings ; checking remaining part of string for equality ; searching in right of string h ( g to h ) ; 

import math as mt


def findAnswer(str1, str2, n):
    l, r = 0, 0
    ans = 2
    for i in range(n):
        if (str1[i] != str2[i]):
            l = i
            break
    for i in range(n - 1, -1, -1):
        if (str1[i] != str2[i]):
            r = i
            break

    if (r < l):
        return 26 * (n + 1)
    elif (l == r):
        return ans
    else:
        for i in range(l + 1, r + 1):
            if (str1[i] != str2[i - 1]):
                ans -= 1
                break
        for i in range(l + 1, r + 1):
            if (str1[i - 1] != str2[i]):
                ans -= 1
                break
        return ans


str1 = "toy"
str2 = "try"
n = len(str1)
print((findAnswer(str1, str2, n)))

# Expected output:
2
# minimize the maximum minimum difference after one removal from array | function to return the minimum required difference ; sort the given array ; when minimum element is removed ; when maximum element is removed ; return the minimum of diff1 and diff2 ; 
def findMinDifference(arr, n):
    arr .sort()
    diff1 = arr[n - 1] - arr[1]
    diff2 = arr[n - 2] - arr[0]
    return min(diff1, diff2)


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

# Expected output:
2
# minimize the maximum minimum difference after one removal from array | function to return the minimum required difference ; if current element is greater than max ; max will become secondmax ; update the max ; if current element is greater than secondmax but smaller than max ; update the secondmax ; if current element is smaller than min ; min will become secondmin ; update the min ; if current element is smaller than secondmin but greater than min ; update the secondmin ; minimum of the two possible differences ; 
def findMinDifference(arr, n):
    if (arr[0] < arr[1]):
        min__ = secondMax = arr[0]
    else:
        min__ = secondMax = arr[1]
    if (arr[0] < arr[1]):
        max__ = secondMin = arr[1]
    else:
        max__ = secondMin = arr[0]
    for i in range(2, n):
        if (arr[i] > max__):
            secondMax = max__
            max__ = arr[i]
        elif (arr[i] > secondMax):
            secondMax = arr[i]
        elif (arr[i] < min__):
            secondMin = min__
            min__ = arr[i]
        elif (arr[i] < secondMin):
            secondMin = arr[i]
    diff = min(max__ - secondMin, secondMax - min__)
    return diff


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

# Expected output:
2
# integers from the range that are composed of a single distinct digit | boolean function to check distinct digits of a number ; take last digit ; check if all other digits are same as last digit ; remove last digit ; function to return the count of integers that are composed of a single distinct digit only ; if i has single distinct digit ; 
def checkDistinct(x):
    last = x % 10
    while (x):
        if (x % 10 != last):
            return False
        x = x // 10
    return True


def findCount(L, R):
    count = 0
    for i in range(L, R + 1):
        if (checkDistinct(i)):
            count += 1
    return count


L = 10
R = 50
print(findCount(L, R))

# Expected output:
4
# smallest pair sum in an array | python3 program to print the sum of the minimum pair ; function to return the sum of the minimum pair from the array ; if found new minimum ; minimum now becomes second minimum ; update minimum ; if current element is > min and < secondmin ; update secondmin ; return the sum of the minimum pair ; 

import sys


def smallest_pair(a, n):
    min = sys .maxsize
    secondMin = sys .maxsize
    for j in range(n):
        if (a[j] < min):
            secondMin = min
            min = a[j]
        elif ((a[j] < secondMin) and a[j] != min):
            secondMin = a[j]
    return (secondMin + min)


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

# Expected output:
3
# longest subarray with elements divisible by k | function to find longest subarray ; this will contain length of longest subarray found ; 
def longestsubarray(arr, n, k):
    current_count = 0
    max_count = 0
    for i in range(0, n, 1):
        if (arr[i] % k == 0):
            current_count += 1
        else:
            current_count = 0
        max_count = max(current_count, max_count)
    return max_count


if __name__ == '__main__':
    arr = [2, 5, 11, 32, 64, 88]
    n = len(arr)
    k = 8
    print(longestsubarray(arr, n, k))

# Expected output:
3
# remove elements that appear strictly less than k times | python3 program to remove the elements which appear strictly less than k times from the array . ; hash map which will store the frequency of the elements of the array . ; incrementing the frequency of the element by 1. ; print the element which appear more than or equal to k times . ; 
def removeElements(arr, n, k):
    mp = dict()
    for i in range(n):
        mp[arr[i]] = mp .get(arr[i], 0) + 1
    for i in range(n):
        if (arr[i] in mp and mp[arr[i]] >= k):
            print(arr[i], end=" ")


arr = [1, 2, 2, 3, 2, 3, 4]
n = len(arr)
k = 2
removeElements(arr, n, k)

# Expected output:
2 2 3 2 3
# check if a string contains a palindromic sub | function to check if two consecutive same characters are present ; 
def check(s):
    for i in range(0, len(s)):
        if (s[i] == s[i + 1]):
            return True
    return False


s = "xzyyz"
if (check(s)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# remove elements from the array which appear more than k times | python 3 program to remove the elements which appear more than k times from the array . ; hash map which will store the frequency of the elements of the array . ; incrementing the frequency of the element by 1. ; print the element which appear less than or equal to k times . ; 
def RemoveElements(arr, n, k):
    mp = {i: 0 for i in range(len(arr))}
    for i in range(n):
        mp[arr[i]] += 1
    for i in range(n):
        if (mp[arr[i]] <= k):
            print(arr[i], end=" ")


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

# Expected output:
1 3 3 4
# find the smallest after deleting given elements | python3 program to find the smallest number from the array after n deletions ; returns maximum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; hash map of the numbers to be deleted ; increment the count of del [ i ] ; initializing the smallestelement ; search if the element is present ; decrement its frequency ; if the frequency becomes 0 , erase it from the map ; else compare it smallestelement ; 

import math as mt


def findSmallestAfterDel(arr, m, dell, n):
    mp = dict()
    for i in range(n):
        if dell[i] in mp .keys():
            mp[dell[i]] += 1
        else:
            mp[dell[i]] = 1
    SmallestElement = 10 ** 9
    for i in range(m):
        if (arr[i] in mp .keys()):
            mp[arr[i]] -= 1
            if (mp[arr[i]] == 0):
                mp .pop(arr[i])
        else:
            SmallestElement = min(SmallestElement, arr[i])
    return SmallestElement


array = [5, 12, 33, 4, 56, 12, 20]
m = len(array)
dell = [12, 4, 56, 5]
n = len(dell)
print(findSmallestAfterDel(array, m, dell, n))

# Expected output:
12
# find the largest after deleting the given elements | python3 program to find the largest number from the array after n deletions ; returns maximum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; hash map of the numbers to be deleted ; increment the count of del [ i ] ; initializing the largestelement ; search if the element is present ; decrement its frequency ; if the frequency becomes 0 , erase it from the map ; else compare it largestelement ; 

import math as mt


def findlargestAfterDel(arr, m, dell, n):
    mp = dict()
    for i in range(n):
        if dell[i] in mp .keys():
            mp[dell[i]] += 1
        else:
            mp[dell[i]] = 1
    largestElement = -10 ** 9
    for i in range(m):
        if (arr[i] in mp .keys()):
            mp[arr[i]] -= 1
            if (mp[arr[i]] == 0):
                mp .pop(arr[i])
        else:
            largestElement = max(largestElement, arr[i])
    return largestElement


array = [5, 12, 33, 4, 56, 12, 20]
m = len(array)
dell = [12, 33, 56, 5]
n = len(dell)
print(findlargestAfterDel(array, m, dell, n))

# Expected output:
20
# number of anomalies in an array | a simple python3 solution to count anomalies in an array . ; 
def countAnomalies(arr, n, k):
    res = 0
    for i in range(0, n):
        j = 0
        while j < n:
            if i != j and abs(arr[i] - arr[j]) <= k:
                break
            j += 1
        if j == n:
            res += 1
    return res


if __name__ == "__main__":
    arr = [7, 1, 8]
    k = 5
    n = len(arr)
    print(countAnomalies(arr, n, k))

# Expected output:
1
# count majority element in a matrix | function to find count of all majority elements in a matrix ; store frequency of elements in matrix ; loop to iteratre through map ; check if frequency is greater than or equal to ( n * m ) / 2 ; 

N = 3
M = 3


def majorityInMatrix(arr):
    mp = {i: 0 for i in range(7)}
    for i in range(len(arr)):
        for j in range(len(arr)):
            mp[arr[i][j]] += 1
    countMajority = 0
    for key, value in mp .items():
        if (value >= (int((N * M) / 2))):
            countMajority += 1
    return countMajority


if __name__ == '__main__':
    mat = [[1, 2, 2], [1, 3, 2], [1, 2, 6]]
    print(majorityInMatrix(mat))

# Expected output:
1
# find pair with maximum difference in any column of a matrix | function to find the column with max difference ; traverse matrix column wise ; insert elements of column to vector ; calculating difference between maximum and minimum ; 

N = 5


def colMaxDiff(mat):
    max_diff = 0
    for i in range(N):
        max_val = mat[0][i]
        min_val = mat[0][i]
        for j in range(1, N):
            max_val = max(max_val, mat[j][i])
            min_val = min(min_val, mat[j][i])
        max_diff = max(max_diff, max_val - min_val)
    return max_diff


if __name__ == "__main__":
    mat = [[1, 2, 3, 4, 5], [5, 3, 5, 4, 0], [
        5, 6, 7, 8, 9], [0, 6, 3, 4, 12], [9, 7, 12, 4, 3]]
    print("Max difference :", colMaxDiff(mat))

# Expected output:
Max difference : 12
# delete array element in given index range [ l | function to delete l to r element ; return size of array after delete element ; 
def deleteElement(A, L, R, N):
    j = 0
    for i in range(N):
        if i <= L or i >= R:
            A[j] = A[i]
            j += 1
    return j


if __name__ == "__main__":
    A = [5, 8, 11, 15, 26, 14, 19, 17, 10, 14]
    L, R = 2, 7
    n = len(A)
    res_size = deleteElement(A, L, R, n)
    for i in range(res_size):
        print(A[i], end=" ")

# Expected output:
5 8 11 17 10 14
# longest subarray having average greater than or equal to x | function to find index in presum list of tuples 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 longest subarray having average greater than or equal to x . ; update array by subtracting x from each element ; length of longest subarray . ; list to store pair of prefix sum and corresponding ending index value . ; to store 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 or equal to 0 , then answer is i + 1 ; if sum is less than 0 , then find if there is a prefix array having sum that needs to be added to current sum to make its value greater than or equal to 0. if yes , then compare length of updated subarray with maximum length found so far ; 
def findInd(preSum, n, val):
    l = 0
    h = 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 LongestSub(arr, n, x):
    for i in range(n):
        arr[i] -= x
    maxlen = 0
    preSum = []
    total = 0
    minInd = [None] * n
    for i in range(n):
        total += arr[i]
        preSum .append((total, i))
    preSum = sorted(preSum)
    minInd[0] = preSum[0][1]
    for i in range(1, n):
        minInd[i] = min(minInd[i - 1], preSum[i][1])
    total = 0
    for i in range(n):
        total += arr[i]
        if total >= 0:
            maxlen = i + 1
        else:
            ind = findInd(preSum, n, total)
            if (ind != -1) & (minInd[ind] < i):
                maxlen = max(maxlen, i - minInd[ind])
    return maxlen


if __name__ == '__main__':
    arr = [-2, 1, 6, -3]
    n = len(arr)
    x = 3
    print(LongestSub(arr, n, x))

# Expected output:
2
# find the only missing number in a sorted array | python 3 program to find the only missing element . ; if this is the first element which is not index + 1 , then missing element is mid + 1 ; if this is not the first missing element search in left side ; if it follows index + 1 property then search in right side ; if no element is missing ; 
def findmissing(ar, N):
    l = 0
    r = N - 1
    while (l <= r):
        mid = (l + r) / 2
        mid = int(mid)
        if (ar[mid] != mid + 1 and ar[mid - 1] == mid):
            return (mid + 1)
        elif (ar[mid] != mid + 1):
            r = mid - 1
        else:
            l = mid + 1
    return (-1)


def main():
    ar = [1, 2, 3, 4, 5, 7, 8]
    N = len(ar)
    res = findmissing(ar, N)
    print(res)


if __name__ == "__main__":
    main()

# Expected output:
6
# find index of first occurrence when an unsorted array is sorted | python3 program to find index of first occurrence of x when array is sorted . ; lower_bound returns iterator pointing to first element that does not compare less to x . ; if x is not present return - 1. ;  ; 

import math


def lowerBound(a, low, high, element):
    while (low < high):
        middle = low + (high - low) // 2
        if (element > a[middle]):
            low = middle + 1
        else:
            high = middle
    return low


def findFirst(arr, n, x):
    arr .sort()
    ptr = lowerBound(arr, 0, n, x)
    return 1 if (ptr != x)else (ptr - arr)


if __name__ == '__main__':
    x = 20
    arr = [10, 30, 20, 50, 20]
    n = len(arr)
    print(findFirst(arr, n, x))

# Expected output:
1
# find index of first occurrence when an unsorted array is sorted | python 3 program to find index of first occurrence of x when array is sorted . ; 
def findFirst(arr, n, x):
    count = 0
    isX = False
    for i in range(n):
        if (arr[i] == x):
            isX = True
        elif (arr[i] < x):
            count += 1
    return -1 if (isX == False)else count


if __name__ == "__main__":
    x = 20
    arr = [10, 30, 20, 50, 20]
    n = len(arr)
    print(findFirst(arr, n, x))

# Expected output:
1
# find duplicate in an array in o ( n ) and by using o ( 1 ) extra space | function to find duplicate ; find the intersection point of the slow and fast . ; find the " entrance " to the cycle . ; 
def findDuplicate(arr):
    slow = arr[0]
    fast = arr[0]
    while True:
        slow = arr[slow]
        fast = arr[arr[fast]]
        if slow == fast:
            break
    ptr1 = arr[0]
    ptr2 = slow
    while ptr1 != ptr2:
        ptr1 = arr[ptr1]
        ptr2 = arr[ptr2]
    return ptr1


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

# Expected output:
1
# number of larger elements on right side in a string | python3 program to count greater characters on right side of every character . ; arrays to store result and character counts . ; start from right side of string ; 

MAX_CHAR = 26


def printGreaterCount(str1):
    len1 = len(str1)
    ans = [0] * len1
    count = [0] * MAX_CHAR
    for i in range(len1 - 1, -1, -1):
        count[ord(str1[i]) - ord('a')] += 1
        for j in range(ord(str1[i]) - ord('a') + 1, MAX_CHAR):
            ans[i] += count[j]
    for i in range(len1):
        print(ans[i], end=" ")


str1 = "abcd"
printGreaterCount(str1)

# Expected output:
3 2 1 0
# print all pairs with given sum | returns number of pairs in arr [ 0. . n - 1 ] with sum equal to sum ; store counts of all elements in a dictionary ; traverse through all the elements ; search if a pair can be formed with arr [ i ] ; 
def printPairs(arr, n, sum):
    mydict = dict()
    for i in range(n):
        temp = sum - arr[i]
        if temp in mydict:
            count = mydict[temp]
            for j in range(count):
                print("(", temp, ", ", arr[i], ")", sep="", end='')
        if arr[i] in mydict:
            mydict[arr[i]] += 1
        else:
            mydict[arr[i]] = 1


if __name__ == '__main__':
    arr = [1, 5, 7, -1, 5]
    n = len(arr)
    sum = 6
    printPairs(arr, n, sum)

# Expected output:
(1, 5)(7, -1)(1, 5)
# maximum product quadruple ( sub | a o ( n ) python 3 program to find maximum quadruple inan array . ; 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 ; initialize maximum , second maximum , third maximum and fourth maximum element ; initialize minimum , second minimum , third minimum and fourth minimum element ; update maximum , second maximum , third maximum and fourth maximum element ; update second maximum , third maximum and fourth maximum element ; update third maximum and fourth maximum element ; update fourth maximum element ; update minimum , second minimum third minimum and fourth minimum element ; update second minimum , third minimum and fourth minimum element ; update third minimum and fourth minimum element ; update fourth minimum element ; return the maximum of x , y and z ; 

import sys


def maxProduct(arr, n):
    if (n < 4):
        return -1
    maxA = -sys .maxsize - 1
    maxB = -sys .maxsize - 1
    maxC = -sys .maxsize - 1
    maxD = -sys .maxsize - 1
    minA = sys .maxsize
    minB = sys .maxsize
    minC = sys .maxsize
    minD = sys .maxsize
    for i in range(n):
        if (arr[i] > maxA):
            maxD = maxC
            maxC = maxB
            maxB = maxA
            maxA = arr[i]
        elif (arr[i] > maxB):
            maxD = maxC
            maxC = maxB
            maxB = arr[i]
        elif (arr[i] > maxC):
            maxD = maxC
            maxC = arr[i]
        elif (arr[i] > maxD):
            maxD = arr[i]
        if (arr[i] < minA):
            minD = minC
            minC = minB
            minB = minA
            minA = arr[i]
        elif (arr[i] < minB):
            minD = minC
            minC = minB
            minB = arr[i]
        elif (arr[i] < minC):
            minD = minC
            minC = arr[i]
        elif (arr[i] < minD):
            minD = arr[i]
    x = maxA * maxB * maxC * maxD
    y = minA * minB * minC * minD
    z = minA * minB * maxA * maxB
    return max(x, max(y, z))


if __name__ == '__main__':
    arr = [1, -4, 3, -6, 7, 0]
    n = len(arr)
    max1 = maxProduct(arr, n)
    if (max1 == -1):
        print("No Quadruple Exists")
    else:
        print("Maximum product is", max1)

# Expected output:
Maximum product is 504
# ways to choose three points with distance between the most distant points <= l | returns the number of triplets with distance between farthest points <= l ; sort to get ordered triplets so that we can find the distance between farthest points belonging to a triplet ; generate and check for all possible triplets : { arr [ i ] , arr [ j ] , arr [ k ] } ; since the array is sorted the farthest points will be a [ i ] and a [ k ] ; ; 
def countTripletsLessThanL(n, L, arr):
    arr .sort()
    ways = 0
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                mostDistantDistance = arr[k] - arr[i]
                if (mostDistantDistance <= L):
                    ways += 1
    return ways


if __name__ == "__main__":
    arr = [1, 2, 3, 4]
    n = len(arr)
    L = 3
    ans = countTripletsLessThanL(n, L, arr)
    print("Total Number of ways =", ans)

# Expected output:
Total Number of ways = 4
# find the one missing number in range | find the missing number in a range ; here we xor of all the number ; xor last number ; 
def missingNum(arr, n):
    minvalue = min(arr)
    xornum = 0
    for i in range(0, n):
        xornum ^= (minvalue) ^ arr[i]
        minvalue = minvalue + 1
    return xornum ^ minvalue


arr = [13, 12, 11, 15]
n = len(arr)
print(missingNum(arr, n))

# Expected output:
14
# Find last index of a character in a string | Returns last index of x if it is present . Else returns - 1. ; String in which char is to be found ; char whose index is to be found
def findLastIndex(str, x):
    index = -1
    for i in range(0, len(str)):
        if str[i] == x:
            index = i
    return index


str = "geeksforgeeks"
x = 'e'
index = findLastIndex(str, x)
if index == -1:
    print("Character not found")
else:
    print('Last index is', index)

# Expected output:
Last index is 10
# find last index of a character in a string | returns last index of x if it is present . else returns - 1. ; traverse from right ; 
def findLastIndex(str, x):
    for i in range(len(str) - 1, -1, -1):
        if (str[i] == x):
            return i
    return -1


str = "geeksforgeeks"
x = 'e'
index = findLastIndex(str, x)
if (index == -1):
    print("Character not found")
else:
    print("Last index is ", index)

# Expected output:
Last index is  10
# smallest number whose set bits are maximum in a given range | returns smallest number whose set bits are maximum in given range . ; 
def countMaxSetBits(left, right):
    while (left | (left + 1)) <= right:
        left |= left + 1
    return left


l = 1
r = 5
print(countMaxSetBits(l, r))
l = 1
r = 10
print(countMaxSetBits(l, r))

# Expected output:
3
7