giulio98/xlcost-single-prompt huggingface dataset:
# distinct adjacent elements in an array | python program to check if we can make neighbors distinct . ; dict used to count the frequency of each element occurring in the array ; in this loop we count the frequency of element through map m ; mx store the frequency of element which occurs most in array . ; in this loop we calculate the maximum frequency and store it in variable mx . ; by swapping we can adjust array only when the frequency of the element which occurs most is less than or equal to ( n + 1 ) / 2 . ; 
def distantAdjacentElement(a, n):
    m = dict()
    for i in range(n):
        if a[i] in m:
            m[a[i]] += 1
        else:
            m[a[i]] = 1
    mx = 0
    for i in range(n):
        if mx < m[a[i]]:
            mx = m[a[i]]
    if mx > (n + 1) // 2:
        print("NO")
    else:
        print("YES")


if __name__ == "__main__":
    a = [7, 7, 7, 7]
    n = len(a)
    distantAdjacentElement(a, n)

# Expected output:
NO
# given an array arr [ ] , find the maximum j | for a given array arr [ ] , returns the maximum j a i such that arr [ j ] > arr [ i ] ; 
def maxIndexDiff(arr, n):
    maxDiff = -1
    for i in range(0, n):
        j = n - 1
        while (j > i):
            if arr[j] > arr[i] and maxDiff < (j - i):
                maxDiff = j - i
            j -= 1
    return maxDiff


arr = [9, 2, 3, 4, 5, 6, 7, 8, 18, 0]
n = len(arr)
maxDiff = maxIndexDiff(arr, n)
print(maxDiff)

# Expected output:
8
# print sorted distinct elements of array | python3 program to print sorted distinct elements . ; create a set using array elements ; print contents of the set . ; 
def printRepeating(arr, size):
    s = set()
    for i in range(size):
        if arr[i]not in s:
            s .add(arr[i])
    for i in s:
        print(i, end=" ")


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

# Expected output:
1 2 3
# minimum swaps to make two arrays identical | function returns the minimum number of swaps required to sort the array this method is taken from below post https : www . geeksforgeeks . org / minimum - number - swaps - required - sort - array / ; create an array of pairs where first element is array element and second element is position of first element ; sort the array by array element values to get right position of every element as second element of pair . ; to keep track of visited elements . initialize all elements as not visited or false . ; initialize result ; traverse array elements ; already swapped and corrected or already present at correct pos ; find out the number of node in this cycle and add in ans ; move to next node ; update answer by adding current cycle . ; return result ; method returns minimum number of swap to mak array b same as array a ; map to store position of elements in array b we basically store element to index mapping . ; now we 're storing position  of array a elements  in array b. ; returing minimum swap for sorting in modified array b as final answer ; 
def minSwapsToSort(arr, n):
    arrPos = [[0 for x in range(2)]for y in range(n)]
    for i in range(n):
        arrPos[i][0] = arr[i]
        arrPos[i][1] = i
    arrPos .sort()
    vis = [False] * (n)
    ans = 0
    for i in range(n):
        if (vis[i] or arrPos[i][1] == i):
            continue
        cycle_size = 0
        j = i
        while (not vis[j]):
            vis[j] = 1
            j = arrPos[j][1]
            cycle_size += 1
        ans += (cycle_size - 1)
    return ans


def minSwapToMakeArraySame(a, b, n):
    mp = {}
    for i in range(n):
        mp[b[i]] = i
    for i in range(n):
        b[i] = mp[a[i]]
    return minSwapsToSort(b, n)


if __name__ == "__main__":
    a = [3, 6, 4, 8]
    b = [4, 6, 8, 3]
    n = len(a)
    print(minSwapToMakeArraySame(a, b, n))

# Expected output:
2
# k | function to find k - th missing element ; interating over the array ; check if i - th and ( i + 1 ) - th element are not consecutive ; save their difference ; check for difference and 
def missingK(a, k, n):
    difference = 0
    ans = 0
    count = k
    flag = 0
    for i in range(0, n - 1):
        difference = 0
        if ((a[i] + 1) != a[i + 1]):
            difference += (a[i + 1] - a[i]) - 1
            if (difference >= count):
                ans = a[i] + count
                flag = 1
                break
            else:
                count -= difference
    if (flag):
        return ans
    else:
        return -1


a = [1, 5, 11, 19]
k = 11
n = len(a)
missing = missingK(a, k, n)
print(missing)

# Expected output:
14
# k | function to find kth missing number ; if the total missing number count is equal to k we can iterate backwards for the first missing number and that will be the answer . ; to further optimize we check if the previous element ' s ▁ ▁ missing ▁ number ▁ count ▁ is ▁ equal ▁ ▁ to ▁ k . ▁ eg : ▁ arr ▁ = ▁ [ 4,5,6,7,8 ] ▁ ▁ if ▁ you ▁ observe ▁ in ▁ the ▁ example ▁ array , ▁ ▁ the ▁ total ▁ count ▁ of ▁ missing ▁ numbers ▁ for ▁ all ▁ ▁ the ▁ indices ▁ are ▁ same , ▁ and ▁ we ▁ are ▁ ▁ aiming ▁ to ▁ narrow ▁ down ▁ the ▁ ▁ search ▁ window ▁ and ▁ achieve ▁ o ( logn ) ▁ ▁ time ▁ complexity ▁ which ▁ ▁ otherwise ▁ would ' ve been o ( n ) . ; else we return arr [ mid ] - 1. ; here we appropriately narrow down the search window . ; in case the upper limit is - ve it means the missing number set is 1 , 2 , . . , k and hence we directly return k . ; else we find the residual count of numbers which we 'd then add to  arr[u] and get the missing kth number. ; return arr [ u ] + k ; 
def missingK(arr, k):
    n = len(arr)
    l = 0
    u = n - 1
    mid = 0
    while (l <= u):
        mid = (l + u)//2
        numbers_less_than_mid = arr[mid] - (mid + 1)
        if (numbers_less_than_mid == k):
            if (mid > 0 and (arr[mid - 1] - (mid)) == k):
                u = mid - 1
                continue
            return arr[mid]-1
        if (numbers_less_than_mid < k):
            l = mid + 1
        elif (k < numbers_less_than_mid):
            u = mid - 1
    if (u < 0):
        return k
    less = arr[u] - (u + 1)
    k -= less
    return arr[u] + k


if __name__ == '__main__':
    arr = [2, 3, 4, 7, 11]
    k = 5
    print("Missing kth number = " + str(missingK(arr, k)))

# Expected output:
Missing kth number = 9
# rotate all matrix elements except the diagonal k times by 90 degrees in clockwise direction | function to print the matrix ; iterate over the rows ; iterate over the columns ; print the value ; function to perform the swapping of matrix elements in clockwise manner ; stores the last row ; stores the last column ; perform the swaps ; function to rotate non - diagonal elements of the matrix k times in clockwise direction ; update k to k % 4 ; iterate until k is positive ; iterate each up to n / 2 - th row ; iterate each column from i to n - i - 1 ; check if the element at i , j is not a diagonal element ; perform the swapping ; print the matrix ; 
def printMat(mat):
    for i in range(len(mat)):
        for j in range(len(mat[0])):
            print(mat[i][j], end=" ")
        print()


def performSwap(mat, i, j):
    N = len(mat)
    ei = N - 1 - i
    ej = N - 1 - j
    temp = mat[i][j]
    mat[i][j] = mat[ej][i]
    mat[ej][i] = mat[ei][ej]
    mat[ei][ej] = mat[j][ei]
    mat[j][ei] = temp


def rotate(mat, N, K):
    K = K % 4
    while (K > 0):
        for i in range(int(N / 2)):
            for j in range(i, N - i - 1):
                if (i != j and (i + j) != N - 1):
                    performSwap(mat, i, j)
        K -= 1
    printMat(mat)


K = 5
mat = [[1, 2, 3, 4], [6, 7, 8, 9], [11, 12, 13, 14], [16, 17, 18, 19]]
N = len(mat)
rotate(mat, N, K)

# Expected output:
1 11 6 4 
17 7 8 2 
18 12 13 3 
16 14 9 19
# minimum rotations required to get the same string | returns count of rotations to get the same string back . ; tmp is the concatenated string . ; substring from i index of original string size . ; if substring matches with original string then we will come out of the loop . ; 
def findRotations(str):
    tmp = str + str
    n = len(str)
    for i in range(1, n + 1):
        substring = tmp[i:i + n]
        if (str == substring):
            return i
    return n


if __name__ == '__main__':
    str = "abc"
    print(findRotations(str))

# Expected output:
3
# count of integral coordinates that lies inside a square | function to calculate the integral points inside a square ; 
def countIntgralPoints(x1, y1, x2, y2):
    print((y2 - y1 - 1) * (x2 - x1 - 1))


if __name__ == '__main__':
    x1 = 1
    y1 = 1
    x2 = 4
    y2 = 4
    countIntgralPoints(x1, y1, x2, y2)

# Expected output:
4
# find next number having distinct digits from the given number n | function to find the next distinct digits number ; loop to find the distinct digits using hash array and the number of digits ; loop to find the most significant distinct digit of the next number ; condition to check if the number is possible with the same number of digits count ; condition to check if the desired most siginificant distinct digit is found ; loop to find the minimum next digit which is not present in the number ; computation of the number ; condition to check if the number is greater than the given number ; 
def findNextNumber(n):
    h = [0 for i in range(10)]
    i = 0
    msb = n
    rem = 0
    next_num = -1
    count = 0
    while (msb > 9):
        rem = msb % 10
        h[rem] = 1
        msb //= 10
        count += 1
    h[msb] = 1
    count += 1
    for i in range(msb + 1, 10, 1):
        if (h[i] == 0):
            next_num = i
            break
    if (next_num == -1):
        for i in range(1, msb, 1):
            if (h[i] == 0):
                next_num = i
                count += 1
                break
    if (next_num > 0):
        for i in range(0, 10, 1):
            if (h[i] == 0):
                msb = i
                break
        for i in range(1, count, 1):
            next_num = ((next_num * 10) + msb)
        if (next_num > n):
            print(next_num)
        else:
            print("Not Possible")
    else:
        print("Not Possible")


if __name__ == '__main__':
    n = 2019
    findNextNumber(n)

# Expected output:
3333
# find a triplet ( a , b , c ) such that 3 * a + 5 * b + 7 * c is equal to n | function to find a triplet ( a , b , c ) such that 3 * a + 5 * b + 7 * c is n ; iterate over the range [ 0 , n7 ] ; iterate over the range [ 0 , n5 ] ; find the value of a ; if a is greater than or equal to 0 and divisible by 3 ; otherwise , print - 1 ; 
def CalculateValues(N):
    for C in range(0, N // 7 + 1):
        for B in range(0, N // 5 + 1):
            A = N - 7 * C - 5 * B
            if (A >= 0 and A % 3 == 0):
                print("A =", A / 3, ", B =", B, ", \\ C =", C, sep=" ")
                return
    print(-1)
    return


if __name__ == '__main__':
    N = 19
    CalculateValues(19)

# Expected output:
A = 3.0 , B = 2 , \ C = 0
# minimize total time taken by two persons to visit n cities such that none of them meet | function to find the minimum time to visit all the cities such that both the person never meets ; initialize sum as 0 ; find the maximum element ; traverse the array ; increment sum by arr [ i ] ; prmaximum of 2 * t and sum ; 
def minimumTime(arr, n):
    sum = 0
    T = max(arr)
    for i in range(n):
        sum += arr[i]
    print(max(2 * T, sum))


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

# Expected output:
16
# lexicographically largest string possible by reversing substrings having even number of 1 s | function to find the lexicographically maximum string by reversing substrings having even numbers of 1 s ; store size of string ; traverse the string ; count the number of 1 s ; stores the starting index ; stores the end index ; increment count , when 1 is encountered ; traverse the remaining string ; temp is for reverse the string from starting and end index ; printing the string ; 
def lexicographicallyMax(s):
    n = len(s)
    for i in range(n):
        count = 0
        beg = i
        end = i
        if (s[i] == '1'):
            count += 1
        for j in range(i + 1, n):
            if (s[j] == '1'):
                count += 1
            if (count % 2 == 0 and count != 0):
                end = j
                break
        temp = s[beg:end + 1]
        temp = temp[::-1]
        s = s[0:beg] + temp + s[end + 1:]
    print(s)


S = "0101"
lexicographicallyMax(S)

# Expected output:
1010
# count maximum possible pairs from an array having sum k | function to count the maximum number of pairs from given array with sum k ; sort array in increasing order ; stores the final result ; initialize the left and right pointers ; traverse array until start < end ; decrement right by 1 ; increment left by 1 ; increment result and left pointer by 1 and decrement right pointer by 1 ; print the result ; 
def maxPairs(nums, k):
    nums = sorted(nums)
    result = 0
    start, end = 0, len(nums) - 1
    while (start < end):
        if (nums[start] + nums[end] > k):
            end -= 1
        elif (nums[start] + nums[end] < k):
            start += 1
        else:
            start += 1
            end -= 1
            result += 1
    print(result)


if __name__ == '__main__':
    arr = [1, 2, 3, 4]
    K = 5
    maxPairs(arr, K)

# Expected output:
2
# count maximum possible pairs from an array having sum k | function to find the maximum number of pairs with a sum k such that same element can 't be used twice ; initialize a hashm ; store the final result ; iterate over the array nums [ ] ; decrement its frequency in m and increment the result by 1 ; increment its frequency by 1 if it is already present in m . otherwise , set its frequency to 1 ; print the result ; 
def maxPairs(nums, k):
    m = {}
    result = 0
    for i in nums:
        if ((i in m) and m[i] > 0):
            m[i] = m[i] - 1
            result += 1
        else:
            if k - i in m:
                m[k - i] += 1
            else:
                m[k - i] = 1
    print(result)


arr = [1, 2, 3, 4]
K = 5
maxPairs(arr, K)

# Expected output:
2
# print indices of array elements whose removal makes the sum of odd and even | function to find indices of array elements whose removal makes the sum of odd and even indexed array elements equal ; stores size of array ; store prefix sum of odd index array elements ; store prefix sum of even index array elements ; update even [ 0 ] ; traverse the given array ; update odd [ i ] ; update even [ i ] ; if the current index is an even number ; update even [ i ] ; if the current index is an odd number ; update odd [ i ] ; check if at least one index found or not that satisfies the condition ; store odd indices sum by removing 0 - th index ; store even indices sum by removing 0 - th index ; if p and q are equal ; traverse the array arr ; if i is an even number ; update p by removing the i - th element ; update q by removing the i - th element ; update q by removing the i - th element ; update p by removing the i - th element ; if odd index values sum is equal to even index values sum ; set the find variable ; print the current index ; if no index found ; print not possible ; 
def removeIndicesToMakeSumEqual(arr):
    N = len(arr)
    odd = [0] * N
    even = [0] * N
    even[0] = arr[0]
    for i in range(1, N):
        odd[i] = odd[i - 1]
        even[i] = even[i - 1]
        if (i % 2 == 0):
            even[i] += arr[i]
        else:
            odd[i] += arr[i]
    find = False
    p = odd[N - 1]
    q = even[N - 1] - arr[0]
    if (p == q):
        print("0 ")
        find = True
    for i in range(1, N):
        if (i % 2 == 0):
            p = even[N - 1] - even[i - 1] - arr[i] + odd[i - 1]
            q = odd[N - 1] - odd[i - 1] + even[i - 1]
        else:
            q = odd[N - 1] - odd[i - 1] - arr[i] + even[i - 1]
            p = even[N - 1] - even[i - 1] + odd[i - 1]
        if (p == q):
            find = True
            print(i, end="")
    if (find == False):
        print(-1)


if __name__ == '__main__':
    arr = [4, 1, 6, 2]
    removeIndicesToMakeSumEqual(arr)

# Expected output:
1
# minimum removals required to make a given array bitonic | function to coutnt minimum array elements required to be removed to make an array bitonic ; left [ i ] : stores the length of lis up to i - th index ; right [ i ] : stores the length of decreasing subsequence over the range [ i , n ] ; calculate the length of lis up to i - th index ; traverse the array upto i - th index ; if arr [ j ] is less than arr [ i ] ; update left [ i ] ; calculate the length of decreasing subsequence over the range [ i , n ] ; traverse right [ ] array ; if arr [ i ] is greater than arr [ j ] ; update right [ i ] ; stores length of the longest bitonic array ; traverse left [ ] and right [ ] array ; update maxlen ; function to prminimum removals required to make given array bitonic ; 
def min_element_removal(arr, N):
    left = [1] * N
    right = [1] * (N)
    for i in range(1, N):
        for j in range(i):
            if (arr[j] < arr[i]):
                left[i] = max(left[i], left[j] + 1)
    for i in range(N - 2, -1, -1):
        for j in range(N - 1, i, -1):
            if (arr[i] > arr[j]):
                right[i] = max(right[i], right[j] + 1)
    maxLen = 0
    for i in range(1, N - 1):
        maxLen = max(maxLen, left[i] + right[i] - 1)
    print((N - maxLen))


def makeBitonic(arr, N):
    if (N == 1):
        print("0")
        return
    if (N == 2):
        if (arr[0] != arr[1]):
            print("0")
        else:
            print("1")
        return
    min_element_removal(arr, N)


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

# Expected output:
3
# count subarrays having an equal count of 0 s and 1 s segregated | function to count subarrays having equal count of 0 s and 1 s with all 0 s and all 1 s grouped together ; stores the count of subarrays ; if current element is different from the next array element ; increment count ; count the frequency of 1 s and 0 s ; increment count ; print the final count ; 
def countSubarrays(A, N):
    ans = 0
    for i in range(N - 1):
        if (A[i] != A[i + 1]):
            ans += 1
            j = i - 1
            k = i + 2
            while (j >= 0 and k < N and A[j] == A[i] and A[k] == A[i + 1]):
                ans += 1
                j -= 1
                k += 1
    print(ans)


if __name__ == "__main__":
    A = [1, 1, 0, 0, 1, 0]
    N = len(A)
    countSubarrays(A, N)

# Expected output:
4
# count quadruples of given type from given array | python3 program of the above approach ; lcount [ i ] [ j ] : stores the count of i on left of index j ; rcount [ i ] [ j ] : stores the count of i on right of index j ; function to count unique elements on left and right of any index ; find the maximum array element ; calculate prefix sum of counts of each value ; calculate suffix sum of counts of each value ; function to count quadruples of the required type ; 

maxN = 2002
lcount = [[0 for i in range(maxN)]for j in range(maxN)]
rcount = [[0 for i in range(maxN)]for j in range(maxN)]


def fill_counts(a, n):
    maxA = a[0]
    for i in range(n):
        if (a[i] > maxA):
            maxA = a[i]
    for i in range(n):
        lcount[a[i]][i] = 1
        rcount[a[i]][i] = 1
    for i in range(maxA + 1):
        for j in range(n):
            lcount[i][j] = (lcount[i][j - 1] + lcount[i][j])
        for j in range(n - 2, -1, -1):
            rcount[i][j] = (rcount[i][j + 1] + rcount[i][j])


def countSubsequence(a, n):
    fill_counts(a, n)
    answer = 0
    for i in range(1, n):
        for j in range(i + 1, n - 1):
            answer += (lcount[a[j]][i - 1] * rcount[a[i]][j + 1])
    return answer


a = [1, 2, 3, 2, 1, 3, 2]
print(countSubsequence(a, 7))

# Expected output:
5
# reduce string by removing outermost parenthesis from each primitive substring | function to remove the outermost parentheses of every primitive substring from the given string ; stores the resultant string ; stores the count of opened parentheses ; traverse the string ; if opening parenthesis is encountered and their count exceeds 0 ; include the character ; if closing parenthesis is encountered and their count is less than count of opening parentheses ; include the character ; return the resultant string ; 
def removeOuterParentheses(S):
    res = ""
    count = 0
    for c in S:
        if (c == '(' and count > 0):
            res += c
        if (c == '('):
            count += 1
        if (c == ')' and count > 1):
            res += c
        if (c == ')'):
            count -= 1
    return res


if __name__ == '__main__':
    S = "(()())(())()"
    print(removeOuterParentheses(S))

# Expected output:
()()()
# length of longest subarray with increasing contiguous elements | function to find the longest subarray with increasing contiguous elements ; stores the length of required longest subarray ; stores the length of length of longest such subarray from ith index ; if consecutive elements are increasing and differ by 1 ; otherwise ; update the longest subarray obtained so far ; return the length obtained ; 
def maxiConsecutiveSubarray(arr, N):
    maxi = 0
    for i in range(N - 1):
        cnt = 1
        for j in range(i, N - 1):
            if (arr[j + 1] == arr[j] + 1):
                cnt += 1
            else:
                break
        maxi = max(maxi, cnt)
        i = j
    return maxi


if __name__ == '__main__':
    N = 11
    arr = [1, 3, 4, 2, 3, 4, 2, 3, 5, 6, 7]
    print(maxiConsecutiveSubarray(arr, N))

# Expected output:
3
# length of longest subsequence having sum of digits of each element as a composite number | python3 implementation of the above approach ; function to generate prime numbers using sieve of eratosthenes ; set 0 and 1 as non - prime ; if p is a prime ; set all multiples of p as non - prime ; function to find the digit sum of a given number ; stores the sum of digits ; extract digits and add to the sum ; return the sum of the digits ; function to find the longest subsequence with sum of digits of each element equal to a composite number ; calculate sum of digits of current array element ; if sum of digits equal to 1 ; if sum of digits is a prime ; 

N = 100005


def SieveOfEratosthenes(prime, p_size):
    prime[0] = False
    prime[1] = False
    p = 2
    while p * p <= p_size:
        if (prime[p]):
            for i in range(p * 2, p_size + 1, p):
                prime[i] = False
        p += 1


def digitSum(number):
    sum = 0
    while (number > 0):
        sum += (number % 10)
        number //= 10
    return sum


def longestCompositeDigitSumSubsequence(arr, n):
    count = 0
    prime = [True] * (N + 1)
    SieveOfEratosthenes(prime, N)
    for i in range(n):
        res = digitSum(arr[i])
        if (res == 1):
            continue
        if (not prime[res]):
            count += 1
    print(count)


if __name__ == "__main__":
    arr = [13, 55, 7, 3, 5, 1, 10, 21, 233, 144, 89]
    n = len(arr)
    longestCompositeDigitSumSubsequence(arr, n)

# Expected output:
4