giulio98/xlcost-single-prompt huggingface dataset:
# maximize minimum distance between repetitions from any permutation of the given array | python3 program to implement the above approach ; size of the array ; stores the frequency of array elements ; find the highest frequency in the array ; increase count of max frequent element ; if no repetition is present ; find the maximum distance ; return the max distance ; 

import sys


def findMaxLen(a):
    n = len(a)
    freq = [0] * (n + 1)
    for i in range(n):
        freq[a[i]] += 1
    maxFreqElement = -sys .maxsize - 1
    maxFreqCount = 1
    for i in range(1, n + 1):
        if (freq[i] > maxFreqElement):
            maxFreqElement = freq[i]
            maxFreqCount = 1
        elif (freq[i] == maxFreqElement):
            maxFreqCount += 1
    if (maxFreqElement == 1):
        ans = 0
    else:
        ans = ((n - maxFreqCount) // (maxFreqElement - 1))
    return ans


a = [1, 2, 1, 2]
print(findMaxLen(a))

# Expected output:
2
# find number of pairs in an array such that their xor is 0 | function to calculate the count ; sorting the list using built in function ; traversing through the elements ; counting frequncy of each elements ; adding the contribution of the frequency to the answer ; 
def calculate(a):
    a .sort()
    count = 1
    answer = 0
    for i in range(1, len(a)):
        if a[i] == a[i - 1]:
            count += 1
        else:
            answer = answer + count * (count - 1) // 2
            count = 1
    answer = answer + count * (count - 1) // 2
    return answer


if __name__ == '__main__':
    a = [1, 2, 1, 2, 4]
    print(calculate(a))

# Expected output:
2
# find number of pairs in an array such that their xor is 0 | function to calculate the answer ; finding the maximum of the array ; creating frequency array with initial value 0 ; traversing through the array ; counting frequency ; traversing through the frequency array ; calculating answer ; 
def calculate(a):
    maximum = max(a)
    frequency = [0 for x in range(maximum + 1)]
    for i in a:
        frequency[i] += 1
    answer = 0
    for i in frequency:
        answer = answer + i * (i - 1) // 2
    return answer


a = [1, 2, 1, 2, 4]
print(calculate(a))

# Expected output:
2
# largest subarray with equal number of 0 s and 1 s | this function prints the starting and ending indexes of the largest subarray with equal number of 0 s and 1 s . also returns the size of such subarray . ; pick a starting point as i ; consider all subarrays starting from i ; if this is a 0 sum subarray , then compare it with maximum size subarray calculated so far ; 
def findSubArray(arr, n):
    sum = 0
    maxsize = -1
    for i in range(0, n - 1):
        sum = -1 if (arr[i] == 0)else 1
        for j in range(i + 1, n):
            sum = sum + (-1)if (arr[j] == 0)else sum + 1
            if (sum == 0 and maxsize < j - i + 1):
                maxsize = j - i + 1
                startindex = i
    if (maxsize == -1):
        print("No such subarray")
    else:
        print(startindex, "to", startindex + maxsize - 1)
    return maxsize


arr = [1, 0, 0, 1, 0, 1, 1]
size = len(arr)
findSubArray(arr, size)

# Expected output:
0 to 5
# maximum element in a sorted and rotated array | function to return the maximum element ; if there is only one element left ; find mid ; check if mid reaches 0 , it is greater than next element or not ; check if mid itself is maximum element ; decide whether we need to go to the left half or the right half ; 
def findMax(arr, low, high):
    if (high == low):
        return arr[low]
    mid = low + (high - low) // 2
    if (mid == 0 and arr[mid] > arr[mid + 1]):
        return arr[mid]
    if (mid < high and arr[mid + 1] < arr[mid]
            and mid > 0 and arr[mid] > arr[mid - 1]):
        return arr[mid]
    if (arr[low] > arr[mid]):
        return findMax(arr, low, mid - 1)
    else:
        return findMax(arr, mid + 1, high)


arr = [6, 5, 4, 3, 2, 1]
n = len(arr)
print(findMax(arr, 0, n - 1))

# Expected output:
6
# Ternary Search | Function to perform Ternary Search ; Find mid1 and mid2 ; Check if key is at any mid ; Since key is not present at mid , Check in which region it is present Then repeat the search operation in that region ; key lies between l and mid1 ; key lies between mid2 and r ; key lies between mid1 and mid2 ; key not found ; Get the list Sort the list if not sorted ; Starting index ; Length of list ; Key to be searched in the list ; Search the key using ternary search ; Print the result ; Key to be searched in the list ; Search the key using ternary search ; Print the result
def ternarySearch(l, r, key, ar):
    while r >= l:
        mid1 = l + (r - l) // 3
        mid2 = r - (r - l) // 3
        if key == ar[mid1]:
            return mid1
        if key == mid2:
            return mid2
        if key < ar[mid1]:
            r = mid1 - 1
        elif key > ar[mid2]:
            l = mid2 + 1
        else:
            l = mid1 + 1
            r = mid2 - 1
    return -1


ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l = 0
r = 9
key = 5
p = ternarySearch(l, r, key, ar)
print("Index of", key, "is", p)
key = 50
p = ternarySearch(l, r, key, ar)
print("Index of", key, "is", p)

# Expected output:
Index of 5 is 4
Index of 50 is -1
# majority element | set | function to print the majoritynumber ; 
def majorityNumber(nums):
    num_count = {}
    for num in nums:
        if num in num_count:
            num_count[num] += 1
        else:
            num_count[num] = 1
    for num in num_count:
        if num_count[num] > len(nums) / 2:
            return num
    return -1


a = [2, 2, 1, 1, 1, 2, 2]
print(majorityNumber(a))

# Expected output:
2
# search an element in a sorted and rotated array | returns index of key in arr [ l . . h ] if key is present , otherwise returns - 1 ; if arr [ l ... mid ] is sorted ; as this subarray is sorted , we can quickly check if key lies in half or other half ; if key not lies in first half subarray , divide other half into two subarrays , such that we can quickly check if key lies in other half ; if arr [ l . . mid ] is not sorted , then arr [ mid ... r ] must be sorted ; 
def search(arr, l, h, key):
    if l > h:
        return -1
    mid = (l + h) // 2
    if arr[mid] == key:
        return mid
    if arr[l] <= arr[mid]:
        if key >= arr[l] and key <= arr[mid]:
            return search(arr, l, mid - 1, key)
        return search(arr, mid + 1, h, key)
    if key >= arr[mid] and key <= arr[h]:
        return search(a, mid + 1, h, key)
    return search(arr, l, mid - 1, key)


arr = [4, 5, 6, 7, 8, 9, 1, 2, 3]
key = 6
i = search(arr, 0, len(arr) - 1, key)
if i != -1:
    print("Index: % d" % i)
else:
    print("Key not found")

# Expected output:
Index:  2
# find the minimum element in a sorted and rotated array | python program to find minimum element in a sorted and rotated array ; this condition is needed to handle the case when array is not rotated at all ; if there is only one element left ; find mid ; check if element ( mid + 1 ) is minimum element . consider the cases like [ 3 , 4 , 5 , 1 , 2 ] ; check if mid itself is minimum element ; decide whether we need to go to left half or right half ; 
def findMin(arr, low, high):
    if high < low:
        return arr[0]
    if high == low:
        return arr[low]
    mid = int((low + high) / 2)
    if mid < high and arr[mid + 1] < arr[mid]:
        return arr[mid + 1]
    if mid > low and arr[mid] < arr[mid - 1]:
        return arr[mid]
    if arr[high] > arr[mid]:
        return findMin(arr, low, mid - 1)
    return findMin(arr, mid + 1, high)


arr1 = [5, 6, 1, 2, 3, 4]
n1 = len(arr1)
print("The minimum element is " + str(findMin(arr1, 0, n1 - 1)))
arr2 = [1, 2, 3, 4]
n2 = len(arr2)
print("The minimum element is " + str(findMin(arr2, 0, n2 - 1)))
arr3 = [1]
n3 = len(arr3)
print("The minimum element is " + str(findMin(arr3, 0, n3 - 1)))
arr4 = [1, 2]
n4 = len(arr4)
print("The minimum element is " + str(findMin(arr4, 0, n4 - 1)))
arr5 = [2, 1]
n5 = len(arr5)
print("The minimum element is " + str(findMin(arr5, 0, n5 - 1)))
arr6 = [5, 6, 7, 1, 2, 3, 4]
n6 = len(arr6)
print("The minimum element is " + str(findMin(arr6, 0, n6 - 1)))
arr7 = [1, 2, 3, 4, 5, 6, 7]
n7 = len(arr7)
print("The minimum element is " + str(findMin(arr7, 0, n7 - 1)))
arr8 = [2, 3, 4, 5, 6, 7, 8, 1]
n8 = len(arr8)
print("The minimum element is " + str(findMin(arr8, 0, n8 - 1)))
arr9 = [3, 4, 5, 1, 2]
n9 = len(arr9)
print("The minimum element is " + str(findMin(arr9, 0, n9 - 1)))

# Expected output:
The minimum element is 1
The minimum element is 1
The minimum element is 1
The minimum element is 1
The minimum element is 1
The minimum element is 1
The minimum element is 1
The minimum element is 1
The minimum element is 1
# find the minimum element in a sorted and rotated array | function to find minimum element ; 
def findMin(arr, low, high):
    while (low < high):
        mid = low + (high - low) // 2
        if (arr[mid] == arr[high]):
            high -= 1
        elif (arr[mid] > arr[high]):
            low = mid + 1
        else:
            high = mid
    return arr[high]


if __name__ == '__main__':
    arr1 = [5, 6, 1, 2, 3, 4]
    n1 = len(arr1)
    print("The minimum element is ", findMin(arr1, 0, n1 - 1))
    arr2 = [1, 2, 3, 4]
    n2 = len(arr2)
    print("The minimum element is ", findMin(arr2, 0, n2 - 1))
    arr3 = [1]
    n3 = len(arr3)
    print("The minimum element is ", findMin(arr3, 0, n3 - 1))
    arr4 = [1, 2]
    n4 = len(arr4)
    print("The minimum element is ", findMin(arr4, 0, n4 - 1))
    arr5 = [2, 1]
    n5 = len(arr5)
    print("The minimum element is ", findMin(arr5, 0, n5 - 1))
    arr6 = [5, 6, 7, 1, 2, 3, 4]
    n6 = len(arr6)
    print("The minimum element is ", findMin(arr6, 0, n6 - 1))
    arr7 = [1, 2, 3, 4, 5, 6, 7]
    n7 = len(arr7)
    print("The minimum element is ", findMin(arr7, 0, n7 - 1))
    arr8 = [2, 3, 4, 5, 6, 7, 8, 1]
    n8 = len(arr8)
    print("The minimum element is ", findMin(arr8, 0, n8 - 1))
    arr9 = [3, 4, 5, 1, 2]
    n9 = len(arr9)
    print("The minimum element is ", findMin(arr9, 0, n9 - 1))

# Expected output:
The minimum element is  1
The minimum element is  1
The minimum element is  1
The minimum element is  1
The minimum element is  1
The minimum element is  1
The minimum element is  1
The minimum element is  1
The minimum element is  1
# k | python3 program to find k - th absolute difference between two elements ; returns number of pairs with absolute difference less than or equal to mid . ; upper bound returns pointer to position of next higher number than a [ i ] + mid in a [ i . . n - 1 ] . we subtract ( a + i + 1 ) from this position to count ; returns k - th absolute difference ; sort array ; minimum absolute difference ; maximum absolute difference ; do binary search for k - th absolute difference ; 

from bisect import bisect as upper_bound


def countPairs(a, n, mid):
    res = 0
    for i in range(n):
        res += upper_bound(a, a[i] + mid)
    return res


def kthDiff(a, n, k):
    a = sorted(a)
    low = a[1] - a[0]
    for i in range(1, n - 1):
        low = min(low, a[i + 1] - a[i])
    high = a[n - 1] - a[0]
    while (low < high):
        mid = (low + high) >> 1
        if (countPairs(a, n, mid) < k):
            low = mid + 1
        else:
            high = mid
    return low


k = 3
a = [1, 2, 3, 4]
n = len(a)
print(kthDiff(a, n, k))

# Expected output:
1
# find the smallest and second smallest elements in an array | python program to find smallest and second smallest elements ; function to print first smallest and second smallest elements ; there should be atleast two elements ; if current element is smaller than first then update both first and second ; if arr [ i ] is in between first and second then update second ; 

import sys


def print2Smallest(arr):
    arr_size = len(arr)
    if arr_size < 2:
        print("Invalid Input")
        return
    first = second = sys .maxsize
    for i in range(0, arr_size):
        if arr[i] < first:
            second = first
            first = arr[i]
        elif (arr[i] < second and arr[i] != first):
            second = arr[i]
    if (second == sys .maxsize):
        print("No second smallest element")
    else:
        print('The smallest element is', first,
              'and' ' second smallest element is', second)


arr = [12, 13, 1, 10, 34, 1]
print2Smallest(arr)

# Expected output:
The smallest element is 1 and second smallest element is 10
# count possible decoding of a given digit sequence with hidden characters | python program for the above approach ; check the first character of the string if it is ' * ' then 9 ways ; traverse the string ; if s [ i ] = = ' * ' there can be 9 possible values of * ; if previous character is 1 then words that can be formed are k ( 11 ) , l ( 12 ) , m ( 13 ) , n ( 14 ) o ( 15 ) , p ( 16 ) , q ( 17 ) , r ( 18 ) , s ( 19 ) ; if previous character is 2 then the words that can be formed are u ( 21 ) , v ( 22 ) , w ( 23 ) , x ( 24 ) y ( 25 ) , z ( 26 ) ; if the previous digit is * then all 15 2 - digit characters can be formed ; taking the value from previous step ; if previous character is 1 then the i - 1 th character and ith character can be decoded in a single character therefore , adding dp [ i - 1 ] . ; if previous character is 2 and ith character is less than 6 then the i - 1 th character and ith character can be decoded in a single character therefore , adding dp [ i - 1 ] . ; if previous character is * then it will contain the above 2 cases ; 

M = 1000000007


def waysOfDecoding(s):
    dp = [0] * (len(s) + 1)
    dp[0] = 1
    if s[0] == '*':
        dp[1] = 9
    elif s[0] == '0':
        dp[1] = 0
    else:
        dp[1] = 1
    for i in range(len(s)):
        if (s[i] == '*'):
            dp[i + 1] = 9 * dp[i]
            if (s[i - 1] == '1'):
                dp[i + 1] = (dp[i + 1] + 9 * dp[i - 1]) % M
            elif (s[i - 1] == '2'):
                dp[i + 1] = (dp[i + 1] + 6 * dp[i - 1]) % M
            elif (s[i - 1] == '*'):
                dp[i + 1] = (dp[i + 1] + 15 * dp[i - 1]) % M
        else:
            if s[i] != '0':
                dp[i + 1] = dp[i]
            else:
                dp[i + 1] = 0
            if (s[i - 1] == '1'):
                dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M
            elif (s[i - 1] == '2' and s[i] <= '6'):
                dp[i + 1] = (dp[i + 1] + dp[i - 1]) % M
            elif (s[i - 1] == '*'):
                if (s[i] <= '6'):
                    dp[i + 1] = dp[i + 1] + 2 * dp[i - 1]
                else:
                    dp[i + 1] = dp[i + 1] + 1 * dp[i - 1]
                dp[i + 1] = dp[i + 1] % M
    return dp[len(s)]


if __name__ == "__main__":
    s = "12"
    print(waysOfDecoding(s))

# Expected output:
2
# count ways to split array into two subsets having difference between their sum equal to k | function to count the number of ways to divide the array into two subsets and such that the difference between their sums is equal to diff ; store the sum of the set s1 ; initializing the matrix ; number of ways to get sum using 0 elements is 0 ; number of ways to get sum 0 using i elements is 1 ; traverse the 2d array ; if the value is greater than the sum store the value of previous state ; return the result ; 
def countSubset(arr, n, diff):
    sum = 0
    for i in range(n):
        sum += arr[i]
    sum += diff
    sum = sum // 2
    t = [[0 for i in range(sum + 1)]for i in range(n + 1)]
    for j in range(sum + 1):
        t[0][j] = 0
    for i in range(n + 1):
        t[i][0] = 1
    for i in range(1, n + 1):
        for j in range(1, sum + 1):
            if (arr[i - 1] > j):
                t[i][j] = t[i - 1][j]
            else:
                t[i][j] = t[i - 1][j] + t[i - 1][j - arr[i - 1]]
    return t[n][sum]


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

# Expected output:
3
# probability that the sum of all numbers obtained on throwing a dice n times lies between two given integers | python3 program for above approach ; function to calculate probability that the sum of numbers on n throws of dice lies between a and b ; base case ; add the probability for all the numbers between a and b ; 

dp = [[0 for i in range(605)]for j in range(105)]


def find(N, a, b):
    probability = 0.0
    for i in range(1, 7):
        dp[1][i] = 1.0 / 6
    for i in range(2, N + 1):
        for j in range(i, (6 * i) + 1):
            for k in range(1, 7):
                dp[i][j] = dp[i][j] + dp[i - 1][j - k] / 6
    for Sum in range(a, b + 1):
        probability = probability + dp[N][Sum]
    return probability


N, a, b = 4, 13, 17
probability = find(N, a, b)
print('%.6f' % probability)

# Expected output:
0.505401
# maximum sum from a tree with adjacent levels not allowed | python3 code for max sum with adjacent levels not allowed ; a bst node ; recursive function to find the maximum sum returned for a root node and its grandchildren ; returns maximum sum with adjacent levels not allowed . this function mainly uses getsumalternate ( ) ; we compute sum of alternate levels starting first level and from second level . and return maximum of two values . ; 

from collections import deque as queue


class Node:
    def __init__(self, x):
        self .data = x
        self .left = None
        self .right = None


def getSumAlternate(root):
    if (root is None):
        return 0
    sum = root .data
    if (root .left is not None):
        sum += getSum(root .left .left)
        sum += getSum(root .left .right)
    if (root .right is not None):
        sum += getSum(root .right .left)
        sum += getSum(root .right .right)
    return sum


def getSum(root):
    if (root is None):
        return 0
    return max(
        getSumAlternate(root),
        (getSumAlternate(
            root .left) +
            getSumAlternate(
            root .right)))


if __name__ == '__main__':
    root = Node(1)
    root .left = Node(2)
    root .right = Node(3)
    root .right .left = Node(4)
    root .right .left .right = Node(5)
    root .right .left .right .left = Node(6)
    print(getSum(root))

# Expected output:
11
# subset sum problem in o ( sum ) space | returns true if there exists a subset with given sum in arr [ ] ; the value of subset [ i % 2 ] [ j ] will be true if there exists a subset of sum j in arr [ 0 , 1 , ... . , i - 1 ] ; a subset with sum 0 is always possible ; if there exists no element no sum is possible ; 
def isSubsetSum(arr, n, sum):
    subset = [[False for j in range(sum + 1)]for i in range(3)]
    for i in range(n + 1):
        for j in range(sum + 1):
            if (j == 0):
                subset[i % 2][j] = True
            elif (i == 0):
                subset[i % 2][j] = False
            elif (arr[i - 1] <= j):
                subset[i %
                       2][j] = subset[(i + 1) %
                                      2][j - arr[i - 1]] or subset[(i + 1) %
                                                                   2][j]
            else:
                subset[i % 2][j] = subset[(i + 1) % 2][j]
    return subset[n % 2][sum]


arr = [6, 2, 5]
sum = 7
n = len(arr)
if (isSubsetSum(arr, n, sum)):
    print("There exists a subset with given sum")
else:
    print("No subset exists with given sum")

# Expected output:
There exists a subset with given sum
# maximum equlibrium sum in an array | python 3 program to find maximum equilibrium sum . ; function to find maximum equilibrium sum . ; 

import sys


def findMaxSum(arr, n):
    res = -sys .maxsize - 1
    for i in range(n):
        prefix_sum = arr[i]
        for j in range(i):
            prefix_sum += arr[j]
        suffix_sum = arr[i]
        j = n - 1
        while (j > i):
            suffix_sum += arr[j]
            j -= 1
        if (prefix_sum == suffix_sum):
            res = max(res, prefix_sum)
    return res


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

# Expected output:
7
# maximum equlibrium sum in an array | function to find maximum equilibrium sum . ; array to store prefix sum . ; array to store suffix sum . ; variable to store maximum sum . ; calculate prefix sum . ; calculate suffix sum and compare it with prefix sum . update ans accordingly . ; 
def findMaxSum(arr, n):
    preSum = [0 for i in range(n)]
    suffSum = [0 for i in range(n)]
    ans = -10000000
    preSum[0] = arr[0]
    for i in range(1, n):
        preSum[i] = preSum[i - 1] + arr[i]
    suffSum[n - 1] = arr[n - 1]
    if (preSum[n - 1] == suffSum[n - 1]):
        ans = max(ans, preSum[n - 1])
    for i in range(n - 2, -1, -1):
        suffSum[i] = suffSum[i + 1] + arr[i]
        if (suffSum[i] == preSum[i]):
            ans = max(ans, preSum[i])
    return ans


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

# Expected output:
7
# maximum equlibrium sum in an array | python3 program to find maximum equilibrium sum . ; function to find maximum equilibrium sum . ; 

import sys


def findMaxSum(arr, n):
    ss = sum(arr)
    prefix_sum = 0
    res = -sys .maxsize
    for i in range(n):
        prefix_sum += arr[i]
        if prefix_sum == ss:
            res = max(res, prefix_sum)
        ss -= arr[i]
    return res


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

# Expected output:
7
# majority element | function to find majority element in an array ; sentinels ; update maxcount if count of current element is greater ; if maxcount is greater than n / 2 return the corresponding element ; 
def findMajority(arr, n):
    maxCount = 0
    index = -1
    for i in range(n):
        count = 0
        for j in range(n):
            if (arr[i] == arr[j]):
                count += 1
        if (count > maxCount):
            maxCount = count
            index = i
    if (maxCount > n // 2):
        print(arr[index])
    else:
        print("No Majority Element")


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

# Expected output:
1
# majority element | function to find the candidate for majority ; function to check if the candidate occurs more than n / 2 times ; function to print majority element ; find the candidate for majority ; print the candidate if it is majority ; 
def findCandidate(A):
    maj_index = 0
    count = 1
    for i in range(len(A)):
        if A[maj_index] == A[i]:
            count += 1
        else:
            count -= 1
        if count == 0:
            maj_index = i
            count = 1
    return A[maj_index]


def isMajority(A, cand):
    count = 0
    for i in range(len(A)):
        if A[i] == cand:
            count += 1
    if count > len(A) / 2:
        return True
    else:
        return False


def printMajority(A):
    cand = findCandidate(A)
    if isMajority(A, cand):
        print(cand)
    else:
        print("No Majority Element")


A = [1, 3, 3, 1, 2]
printMajority(A)

# Expected output:
No Majority Element
# majority element | python3 program for finding out majority element in an array ; 
def findMajority(arr, size):
    m = {}
    for i in range(size):
        if arr[i] in m:
            m[arr[i]] += 1
        else:
            m[arr[i]] = 1
    count = 0
    for key in m:
        if m[key] > size / 2:
            count = 1
            print("Majority found :-", key)
            break
    if (count == 0):
        print("No Majority element")


arr = [2, 2, 2, 2, 5, 5, 2, 3, 3]
n = len(arr)
findMajority(arr, n)

# Expected output:
Majority found :- 2