giulio98/xlcost-single-prompt huggingface dataset:
# count of cyclic permutations having xor with other binary string as 0 | implementation of z - algorithm for linear time pattern searching ; function to get the count of the cyclic permutations of b that given 0 when xored with a ; concatenate b with b ; new b now contains all the cyclic permutations of old b as it 's sub-strings ; concatenate pattern with text ; fill z array used in z algorithm ; pattern occurs at index i since z value of i equals pattern length ; 
def compute_z(s, z):
    l = 0
    r = 0
    n = len(s)
    for i in range(1, n, 1):
        if (i > r):
            l = i
            r = i
            while (r < n and s[r - l] == s[r]):
                r += 1
            z[i] = r - l
            r -= 1
        else:
            k = i - l
            if (z[k] < r - i + 1):
                z[i] = z[k]
            else:
                l = i
                while (r < n and s[r - l] == s[r]):
                    r += 1
                z[i] = r - l
                r -= 1


def countPermutation(a, b):
    b = b + b
    b = b[0:len(b) - 1]
    ans = 0
    s = a + "$" + b
    n = len(s)
    z = [0 for i in range(n)]
    compute_z(s, z)
    for i in range(1, n, 1):
        if (z[i] == len(a)):
            ans += 1
    return ans


if __name__ == '__main__':
    a = "101"
    b = "101"
    print(countPermutation(a, b))

# Expected output:
1
# lexicographically smallest k | function to find lexicographically smallest subsequence of size k ; length of string ; stores the minimum subsequence ; traverse the string s ; if the stack is empty ; iterate till the current character is less than the the character at the top of stack ; if stack size is < k ; push the current character into it ; stores the resultant string ; iterate until stack is empty ; reverse the string ; print the string ; 
def smallestSubsequence(S, K):
    N = len(S)
    answer = []
    for i in range(N):
        if (len(answer) == 0):
            answer .append(S[i])
        else:
            while (len(answer) > 0 and (
                    S[i] < answer[len(answer) - 1]) and (len(answer) - 1 + N - i >= K)):
                answer = answer[:-1]
            if (len(answer) == 0 or len(answer) < K):
                answer .append(S[i])
    ret = []
    while (len(answer) > 0):
        ret .append(answer[len(answer) - 1])
        answer = answer[:-1]
    ret = ret[::-1]
    ret = ''.join(ret)
    print(ret)


if __name__ == '__main__':
    S = "aabdaabc"
    K = 3
    smallestSubsequence(S, K)

# Expected output:
aaa
# check if string is right to left diagonal or not | python3 program to check if the given is right to left diagonal or not ; function to check if the given is right to left diagonal or not ; iterate over string ; if character is not same as the first character then return false ; 

from math import sqrt, floor, ceil


def is_rtol(s):
    tmp = floor(sqrt(len(s))) - 1
    first = s[tmp]
    for pos in range(tmp, len(s) - 1, tmp):
        if (s[pos] != first):
            return False
    return True


if __name__ == '__main__':
    str = "abcxabxcaxbcxabc"
    if (is_rtol(str)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# split a given string into substrings of length k with equal sum of ascii values | function for checking string ; check if the string can be split into substrings of k length only ; compute the sum of first substring of length k ; compute the sum of remaining substrings ; check if sum is equal to that of the first substring ; since all sums are not equal , return false ; all sums are equal , return true ; all substrings cannot be of size k ; 
def check(str, K):
    if (len(str) % K == 0):
        sum = 0
        for i in range(K):
            sum += ord(str[i])
        for j in range(K, len(str), K):
            s_comp = 0
            for p in range(j, j + K):
                s_comp += ord(str[p])
            if (s_comp != sum):
                return False
        return True
    return False


K = 3
str = "abdcbbdba"
if (check(str, K)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# maximize count of 0 s in left and 1 s in right substring by splitting given binary string | function to maximize the sum of the count of zeros and ones in the left and right substring ; count the total numbers of ones in str ; to store the count of zeros and ones while traversing string ; iterate the given and update the maximum sum ; update the maximum sum ; 
def maxSum(str):
    maximumSum = 0
    totalOnes = 0
    for i in str:
        if i == '1':
            totalOnes += 1
    zero = 0
    ones = 0
    i = 0
    while i < len(str):
        if (str[i] == '0'):
            zero += 1
        else:
            ones += 1
        maximumSum = max(maximumSum, zero + (totalOnes - ones))
        i += 1
    return maximumSum


if __name__ == '__main__':
    str = "011101"
    print(maxSum(str))

# Expected output:
5
# longest substring such that no three consecutive characters are same | function to return the length of the longest substring such that no three consecutive characters are same ; if the length of the given string is less than 3 ; initialize temporary and final ans to 2 as this is the minimum length of substring when length of the given string is greater than 2 ; traverse the string from the third character to the last ; if no three consecutive characters are same then increment temporary count ; else update the final ans and reset the temporary count ; 
def maxLenSubStr(s):
    if (len(s) < 3):
        return len(s)
    temp = 2
    ans = 2
    for i in range(2, len(s)):
        if (s[i] != s[i - 1] or s[i] != s[i - 2]):
            temp += 1
        else:
            ans = max(temp, ans)
            temp = 2
    ans = max(temp, ans)
    return ans


s = "baaabbabbb"
print(maxLenSubStr(s))

# Expected output:
7
# number of ways to remove a sub | function to return the number of ways of removing a sub - string from s such that all the remaining characters are same ; to store the count of prefix and suffix ; loop to count prefix ; loop to count suffix ; first and last characters of the string are same ; otherwise ; 
def no_of_ways(s):
    n = len(s)
    count_left = 0
    count_right = 0
    for i in range(0, n, 1):
        if (s[i] == s[0]):
            count_left += 1
        else:
            break
    i = n - 1
    while (i >= 0):
        if (s[i] == s[n - 1]):
            count_right += 1
        else:
            break
        i -= 1
    if (s[0] == s[n - 1]):
        return ((count_left + 1) * (count_right + 1))
    else:
        return (count_left + count_right + 1)


if __name__ == '__main__':
    s = "geeksforgeeks"
    print(no_of_ways(s))

# Expected output:
3
# find the direction from given string | function to find the final direction ; if count is positive that implies resultant is clockwise direction ; if count is negative that implies resultant is anti - clockwise direction ; 
def findDirection(s):
    count = 0
    d = ""
    for i in range(len(s)):
        if (s[i] == 'L'):
            count -= 1
        else:
            if (s[i] == 'R'):
                count += 1
    if (count > 0):
        if (count % 4 == 0):
            d = "N"
        elif (count % 4 == 10):
            d = "E"
        elif (count % 4 == 2):
            d = "S"
        elif (count % 4 == 3):
            d = "W"
    if (count < 0):
        count *= -1
        if (count % 4 == 0):
            d = "N"
        elif (count % 4 == 1):
            d = "W"
        elif (count % 4 == 2):
            d = "S"
        elif (count % 4 == 3):
            d = "E"
    return d


if __name__ == '__main__':
    s = "LLRLRRL"
    print(findDirection(s))
    s = "LL"
    print(findDirection(s))

# Expected output:
W
S
# check if lowercase and uppercase characters are in same order | function to check if both the case follow the same order ; traverse the string ; store both lowercase and uppercase in two different strings ; transfor lowerstr to uppercase ; 
def isCheck(str):
    length = len(str)
    lowerStr, upperStr = "", ""
    for i in range(length):
        if (ord(str[i]) >= 65 and ord(str[i]) <= 91):
            upperStr = upperStr + str[i]
        else:
            lowerStr = lowerStr + str[i]
    transformStr = lowerStr .upper()
    return transformStr == upperStr


if __name__ == "__main__":
    str = "geeGkEEsKS"
    if isCheck(str):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# print all paths of the binary tree with maximum element in each path greater than or equal to k | a binary tree node ; a recursive function to print the paths whose maximum element is greater than or equal to k . ; if the current node value is greater than or equal to k , then all the subtrees following that node will get printed , flag = 1 indicates to print the required path ; if the leaf node is encountered , then the path is printed if the size of the path vector is greater than 0 ; append the node to the path vector ; recur left and right subtrees ; backtracking to return the vector and print the path if the flag is 1 ; function to initialize the variables and call the utility function to print the paths with maximum values greater than or equal to k ; initialize flag ; ans is used to check empty condition ; call function that print path ; if the path doesn 't exist ; 

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


def findPathUtil(root: Node, k: int, path: list, flag: int):
    global ans
    if root is None:
        return
    if root .data >= k:
        flag = 1
    if root .left is None and root .right is None:
        if flag:
            ans = 1
            print("(", end="")
            for i in range(len(path)):
                print(path[i], end=", ")
            print(root .data, end="), ")
        return
    path .append(root .data)
    findPathUtil(root .left, k, path, flag)
    findPathUtil(root .right, k, path, flag)
    path .pop()


def findPath(root: Node, k: int):
    global ans
    flag = 0
    ans = 0
    v = []
    findPathUtil(root, k, v, flag)
    if ans == 0:
        print(-1)


if __name__ == "__main__":
    ans = 0
    k = 25
    root = Node(10)
    root .left = Node(5)
    root .right = Node(8)
    root .left .left = Node(29)
    root .left .right = Node(2)
    root .right .right = Node(98)
    root .right .left = Node(1)
    root .right .right .right = Node(50)
    root .left .left .left = Node(20)
    findPath(root, k)

# Expected output:
(10, 5, 29, 20), (10, 8, 98, 50),
# tridecagonal number | function to find n - th tridecagonal number ; formula to calculate nth tridecagonal number ; 
def Tridecagonal_num(n):
    return (11 * n * n - 9 * n) / 2


n = 3
print(int(Tridecagonal_num(n)))
n = 10
print(int(Tridecagonal_num(n)))

# Expected output:
36
505
# Number of N digit integers with weight W | Function to find total possible numbers with n digits and weight w ; When Weight of an integer is Positive ; Subtract the weight from 9 ; When weight of an integer is negative ; add the weight to 10 to make it positive ; number of digits in an integer and w as weight ; print the total possible numbers with n digits and weight w
def findNumbers(n, w):
    x = 0
    sum = 0
    if (w >= 0 and w <= 8):
        x = 9 - w
    elif (w >= -9 and w <= -1):
        x = 10 + w
    sum = pow(10, n - 2)
    sum = (x * sum)
    return sum


n = 3
w = 4
print(findNumbers(n, w))

# Expected output:
50
# maximum height of triangular arrangement of array values | python program to find the maximum height of pyramidal arrangement of array values ; just checking whether ith level is possible or not if possible then we must have atleast ( i * ( i + 1 ) ) / 2 elements in the array ; updating the result value each time ; otherwise we have exceeded n value ; 
def MaximumHeight(a, n):
    result = 1
    for i in range(1, n):
        y = (i * (i + 1)) / 2
        if (y < n):
            result = i
        else:
            break
    return result


arr = [40, 100, 20, 30]
n = len(arr)
print(MaximumHeight(arr, n))

# Expected output:
2
# k | python3 code to find k - th element in the odd - even sequence . ; insert all the odd numbers from 1 to n . ; insert all the even numbers from 1 to n . ; 
def findK(n, k):
    a = list()
    i = 1
    while i < n:
        a .append(i)
        i = i + 2
    i = 2
    while i < n:
        a .append(i)
        i = i + 2
    return (a[k - 1])


n = 10
k = 3
print(findK(n, k))

# Expected output:
5
# one line function for factorial of a number | python3 program to find factorial of given number ; single line to find factorial ; 
def factorial(n):
    return 1 if (n == 1 or n == 0)else n * factorial(n - 1)


num = 5
print("Factorial of", num, "is", factorial(num))

# Expected output:
Factorial of 5 is 120
# pell number | calculate nth pell number ; 
def pell(n):
    if (n <= 2):
        return n
    a = 1
    b = 2
    for i in range(3, n + 1):
        c = 2 * b + a
        a = b
        b = c
    return b


n = 4
print(pell(n))

# Expected output:
12
# an efficient way to check whether n | returns true if n - th fibonacci number is multiple of 10. ; 
def isMultipleOf10(n):
    return (n % 15 == 0)


n = 30
if (isMultipleOf10(n)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# find politeness of a number | a function to count all odd prime factors of a given number n ; eliminate all even prime factor of number of n ; n must be odd at this point , so iterate for only odd numbers till sqrt ( n ) ; if i divides n , then start counting of odd divisors ; if n odd prime still remains then count it ; 
def countOddPrimeFactors(n):
    result = 1
    while (n % 2 == 0):
        n /= 2
    i = 3
    while i * i <= n:
        divCount = 0
        while (n % i == 0):
            n /= i
            divCount = divCount + 1
        result = result * divCount + 1
        i = i + 2
    if (n > 2):
        result = result * 2
    return result


def politness(n):
    return countOddPrimeFactors(n) - 1


n = 90
print("Politness of ", n, " = ", politness(n))
n = 15
print("Politness of ", n, " = ", politness(n))

# Expected output:
Politness of  90  =  5
Politness of  15  =  3
# program for factorial of a number | function to find factorial of given number ; 
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)


num = 5
print("Factorial of", num, "is", factorial(num))

# Expected output:
Factorial of 5 is 120
# turn off the rightmost set bit | set 2 | unsets the rightmost set bit of n and returns the result ; 
def FlipBits(n):
    n -= (n & (-n))
    return n


if __name__ == '__main__':
    N = 12
    print("The number after unsetting the", end="")
    print(" rightmost set bit: ", FlipBits(N))

# Expected output:
The number after unsetting the rightmost set bit:  8
# maximum value of xor among all triplets of an array | function to count maximum xor value for a triplet ; set is used to avoid repetitions ; store all possible unique xor value of pairs ; store maximum value ; 
def Maximum_xor_Triplet(n, a):
    s = set()
    for i in range(0, n):
        for j in range(i, n):
            s .add(a[i] ^ a[j])
    ans = 0
    for i in s:
        for j in range(0, n):
            ans = max(ans, i ^ a[j])
    print(ans)


if __name__ == "__main__":
    a = [1, 3, 8, 15]
    n = len(a)
    Maximum_xor_Triplet(n, a)

# Expected output:
15
# find missing elements of a range | python library for binary search ; print all elements of range [ low , high ] that are not present in arr [ 0. . n - 1 ] ; do binary search for ' low ' in sorted array and find index of first element which either equal to or greater than low . ; start from the found index and linearly search every range element x after this index in arr [ ] ; if x doesn 't math with current element  print it ; if x matches , move to next element in arr [ ] ; move to next element in range [ low , high ] ; print range elements thar are greater than the last element of sorted array . ; 

from bisect import bisect_left


def printMissing(arr, n, low, high):
    arr .sort()
    ptr = bisect_left(arr, low)
    index = ptr
    i = index
    x = low
    while (i < n and x <= high):
        if (arr[i] != x):
            print(x, end=" ")
        else:
            i = i + 1
        x = x + 1
    while (x <= high):
        print(x, end=" ")
        x = x + 1


arr = [1, 3, 5, 4]
n = len(arr)
low = 1
high = 10
printMissing(arr, n, low, high)

# Expected output:
2 6 7 8 9 10
# find missing elements of a range | print all elements of range [ low , high ] that are not present in arr [ 0. . n - 1 ] ; create boolean list of size high - low + 1 , each index i representing wether ( i + low ) th element found or not . ; if ith element of arr is in range low to high then mark corresponding index as true in array ; traverse through the range and print all elements whose value is false ; 
def printMissing(arr, n, low, high):
    points_of_range = [False] * (high - low + 1)
    for i in range(n):
        if (low <= arr[i] and arr[i] <= high):
            points_of_range[arr[i] - low] = True
    for x in range(high - low + 1):
        if (points_of_range[x] == False):
            print(low + x, end=" ")


arr = [1, 3, 5, 4]
n = len(arr)
low, high = 1, 10
printMissing(arr, n, low, high)

# Expected output:
2 6 7 8 9 10
# find missing elements of a range | print all elements of range [ low , high ] that are not present in arr [ 0. . n - 1 ] ; insert all elements of arr [ ] in set ; traverse through the range and print all missing elements ; 
def printMissing(arr, n, low, high):
    s = set(arr)
    for x in range(low, high + 1):
        if x not in s:
            print(x, end=' ')


arr = [1, 3, 5, 4]
n = len(arr)
low, high = 1, 10
printMissing(arr, n, low, high)

# Expected output:
2 6 7 8 9 10
# k | returns k - th missing element . it returns - 1 if no k is more than number of missing elements . ; insert all elements of given sequence b [ ] . ; traverse through increasing sequence and keep track of count of missing numbers . ; 
def find(a, b, k, n1, n2):
    s = set()
    for i in range(n2):
        s .add(b[i])
    missing = 0
    for i in range(n1):
        if a[i]not in s:
            missing += 1
        if missing == k:
            return a[i]
    return -1


a = [0, 2, 4, 6, 8, 10, 12, 14, 15]
b = [4, 10, 6, 8, 12]
n1 = len(a)
n2 = len(b)
k = 3
print(find(a, b, k, n1, n2))

# Expected output:
14
# minimize steps to form string s from any random string of length k using a fixed length subsequences | ''function to find the minimum number of string required to generate the original string ; '' stores the frequency of each  character of string s ; '' stores the frequency of each  character of string s ; '' count unique characters in s ; '' if unique characters is greater  then n, then return -1 ; '' otherwise ; '' perform binary search ; '' find the value of mid ; '' iterate over the range  [0, 26] ; '' if the amount[i] is  greater than 0 ; '' update the ranges ; '' find the resultant string ; generate the subsequence ; ' ' ▁ if ▁ the ▁ length ▁ of ▁ resultant ▁ ▁ string ▁ is ▁ less ▁ than ▁ n ▁ than ▁ ▁ add ▁ a ▁ character ▁ ' a '  ; '' print the string ; ''
def findString(S, N):
    amounts = [0] * 26
    for i in range(len(S)):
        amounts[ord(S[i]) - 97] += 1
    count = 0
    for i in range(26):
        if amounts[i] > 0:
            count += 1
    if count > N:
        print("-1")
    else:
        ans = ""
        high = 100001
        low = 0
        while (high - low) > 1:
            total = 0
            mid = (high + low) // 2
            for i in range(26):
                if amounts[i] > 0:
                    total += (amounts[i] - 1) // mid + 1
            if total <= N:
                high = mid
            else:
                low = mid
        print(high, end=" ")
        total = 0
        for i in range(26):
            if amounts[i] > 0:
                total += (amounts[i] - 1) // high + 1
                for j in range((amounts[i] - 1) // high + 1):
                    ans += chr(i + 97)
        for i in range(total, N):
            ans += 'a'
        ans = ans[::-1]
        print(ans)


S = "toffee"
K = 4
findString(S, K)

# Expected output:
2 tofe
# find the first repeating element in an array of integers | this function prints the first repeating element in arr [ ] ; initialize index of first repeating element ; creates an empty hashset ; traverse the input array from right to left ; if element is already in hash set , update min ; else add element to hash set ; print the result ; 
def printFirstRepeating(arr, n):
    Min = -1
    myset = dict()
    for i in range(n - 1, -1, -1):
        if arr[i] in myset .keys():
            Min = i
        else:
            myset[arr[i]] = 1
    if (Min != -1):
        print("The first repeating element is", arr[Min])
    else:
        print("There are no repeating elements")


arr = [10, 5, 3, 4, 3, 5, 6]
n = len(arr)
printFirstRepeating(arr, n)

# Expected output:
The first repeating element is 5
# find the first repeating element in an array of integers | this function prints the first repeating element in arr [ ] ; this will set k = 1 , if any repeating element found ; max = maximum from ( all elements & n ) ; array a is for storing 1 st time occurence of element initialized by 0 ; store 1 in array b if element is duplicate initialized by 0 ; duplicate element found ; storing 1 st occurence of arr [ i ] ; trace array a & find repeating element with min index ; 
def printFirstRepeating(arr, n):
    k = 0
    max = n
    for i in range(n):
        if (max < arr[i]):
            max = arr[i]
    a = [0 for i in range(max + 1)]
    b = [0 for i in range(max + 1)]
    for i in range(n):
        if (a[arr[i]]):
            b[arr[i]] = 1
            k = 1
            continue
        else:
            a[arr[i]] = i
    if (k == 0):
        print("No repeating element found")
    else:
        min = max + 1
        for i in range(max + 1):
            if (a[i] and (min > (a[i])) and b[i]):
                min = a[i]
        print(arr[min])


arr = [10, 5, 3, 4, 3, 5, 6]
n = len(arr)
printFirstRepeating(arr, n)

# Expected output:
5
# k | returns k - th distinct element in arr . ; check if current element is present somewhere else . ; if element is unique ; 
def printKDistinct(arr, n, k):
    dist_count = 0
    for i in range(n):
        j = 0
        while j < n:
            if (i != j and arr[j] == arr[i]):
                break
            j += 1
        if (j == n):
            dist_count += 1
        if (dist_count == k):
            return arr[i]
    return -1


ar = [1, 2, 1, 3, 4, 2]
n = len(ar)
k = 2
print(printKDistinct(ar, n, k))

# Expected output:
4
# count subarrays having an equal count of 0 s and 1 s segregated | ''function to count subarrays having equal count of 0s and 1s with all 0s and all 1s grouped together ; '' stores the count ; '' initialize cur with first element ; '' if the next element is same  as the current element ; '' increment count ; '' update curr ; '' iterate over the array count ; '' consider the minimum ;  ; ''
def countSubarrays(A):
    res = 0
    curr, cnt = A[0], [1]
    for c in A[1:]:
        if c == curr:
            cnt[-1] += 1
        else:
            curr = c
        cnt .append(1)
    for i in range(1, len(cnt)):
        res += min(cnt[i - 1], cnt[i])
    print(res - 1)


A = [1, 1, 0, 0, 1, 0]
countSubarrays(A)

# Expected output:
4