giulio98/xlcost-single-prompt huggingface dataset:
# sort array of strings after sorting each string after removing characters whose frequencies are not a powers of 2 | python3 program for the above approach ; function to check if n is power of 2 or not ; base case ; return true if n is power of 2 ; function to print array of strings in ascending order ; sort strings in ascending order ; print the array ; function to sort the strings after modifying each string according to the given conditions ; store the frequency of each characters of the string ; stores the required array of strings ; traverse the array of strings ; temporary string ; stores frequency of each alphabet of the string ; update frequency of s [ i ] [ j ] ; traverse the map freq ; check if the frequency of i . first is a power of 2 ; update string st ; clear the map ; null string ; sort the string in descending order ; update res ; print the array of strings ; 

from collections import defaultdict
import math


def isPowerOfTwo(n):
    if (n == 0):
        return False
    return (math .ceil(math .log2(n)) == math .floor(math .log2(n)))


def printArray(res):
    res .sort()
    for i in range(len(res)):
        print(res[i], end=" ")


def sortedStrings(S, N):
    freq = defaultdict(int)
    res = []
    for i in range(N):
        st = ""
        for j in range(len(S[i])):
            freq[S[i][j]] += 1
        for i in freq:
            if (isPowerOfTwo(freq[i])):
                for j in range(freq[i]):
                    st += i
        freq .clear()
        if (len(st) == 0):
            continue
        st = list(st)
        st .sort(reverse=True)
        st = ''.join(st)
        res .append(st)
    printArray(res)


if __name__ == "__main__":
    arr = ["aaacbb", "geeks", "aaa"]
    N = len(arr)
    sortedStrings(arr, N)

# Expected output:
cbb skgee
# modify string by replacing all occurrences of given characters by specified replacing characters | function to modify given string by replacing characters ; store the size of string and the number of pairs ; initialize 2 character arrays ; traverse the string s update arrays arr [ ] and brr [ ] ; traverse the array of pairs p ; a -> character to be replaced b -> replacing character ; iterate over the range [ 0 , 25 ] ; if it is equal to current character , then replace it in the array b ; print the array brr [ ] ; 
def replaceCharacters(s, p):
    n, k = len(s), len(p)
    arr = [0] * 26
    brr = [0] * 26
    for i in range(n):
        arr[ord(s[i]) - ord('a')] = s[i]
        brr[ord(s[i]) - ord('a')] = s[i]
    for j in range(k):
        a, b = p[j][0], p[j][1]
        for i in range(26):
            if (arr[i] == a):
                brr[i] = b
    for i in range(n):
        print(brr[ord(s[i]) - ord('a')], end="")


if __name__ == '__main__':
    S = "aabbgg"
    P = [['a', 'b'], ['b', 'g'], ['g', 'a']]
    replaceCharacters(S, P)

# Expected output:
bbggaa
# smallest semi | python3 program for the above approach ; function to find all the 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 smallest semi - prime number having a difference between any of its two divisors at least n ; stores the prime numbers ; fill the prime array ; initialize the first divisor ; find the value of the first prime number ; initialize the second divisor ; find the second prime number ; print the semi - prime number ; 

MAX = 100001


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


def smallestSemiPrime(n):
    prime = [True] * MAX
    SieveOfEratosthenes(prime)
    num1 = n + 1
    while (prime[num1] != True):
        num1 += 1
    num2 = num1 + n
    while (prime[num2] != True):
        num2 += 1
    print(num1 * num2)


if __name__ == "__main__":
    N = 2
    smallestSemiPrime(N)

# Expected output:
15
# check if a number can be represented as product of two positive perfect cubes | function to check if n can be represented as the product of two perfect cubes or not ; stores the perfect cubes ; traverse the map ; stores the first number ; stores the second number ; search the pair for the first number to obtain product n from the map ; if n cannot be represented as the product of the two positive perfect cubes ; 
def productOfTwoPerfectCubes(N):
    cubes = {}
    i = 1
    while i * i * i <= N:
        cubes[i * i * i] = i
        i += 1
    for itr in cubes:
        firstNumber = itr
        if (N % itr == 0):
            secondNumber = N // itr
            if (secondNumber in cubes):
                print("Yes")
                return
    print("No")


if __name__ == "__main__":
    N = 216
    productOfTwoPerfectCubes(N)

# Expected output:
Yes
# check if a number can be represented as product of two positive perfect cubes | function to check if the number n can be represented as the product of two perfect cubes or not ; if cube of cube_root is n ; otherwise , prno ; 
def productOfTwoPerfectCubes(N):
    cube_root = round((N)**(1 / 3))
    print(cube_root)
    if (cube_root * cube_root * cube_root == N):
        print("Yes")
        return
    else:
        print("No")
        return


if __name__ == '__main__':
    N = 216
    productOfTwoPerfectCubes(N)

# Expected output:
6
Yes
# size of smallest square that contains n non | function to check if side of square x can pack all the n rectangles or not ; find the number of rectangle it can pack ; if val is atleast n , then return true ; otherwise , return false ; function to find the size of the smallest square that can contain n rectangles of dimensions w * h ; stores the lower bound ; stores the upper bound ; iterate until i is less than j ; calculate the mid value ; if the current size of square cam contain n rectangles ; otherwise , update i ; return the minimum size of the square required ; 
def bound(w, h, N, x):
    val = (x // w) * (x // h)
    if (val >= N):
        return True
    else:
        return False


def FindSquare(N, W, H):
    i = 1
    j = W * H * N
    while (i < j):
        mid = i + (j - i) // 2
        if (bound(W, H, N, mid)):
            j = mid
        else:
            i = mid + 1
    return j


W = 2
H = 3
N = 10
print(FindSquare(N, W, H))

# Expected output:
9
# count integers up to n that are equal to at least 2 nd power of any integer exceeding 1 | python 3 program for the above approach ; function to count the integers up to n that can be represented as a ^ b , where a & b > 1 ; initialize a hashset ; iterating over the range [ 2 , sqrt ( n ) ] ; generate all possible power of x ; multiply x by i ; if the generated number lies in the range [ 1 , n ] then insert it in hashset ; print the total count ; 

from math import sqrt


def printNumberOfPairs(N):
    st = set()
    for i in range(2, int(sqrt(N)) + 1, 1):
        x = i
        while (x <= N):
            x *= i
            if (x <= N):
                st .add(x)
    print(len(st))


if __name__ == '__main__':
    N = 10000
    printNumberOfPairs(N)

# Expected output:
124
# maximize product of lengths of strings having no common characters | function to count the number of set bits in the integer n ; stores the count of set bits in n ; return the count ; function to find the maximum product of pair of strings having no common characters ; stores the integer equivalent of the strings ; traverse the array of strings ; traverse the current string ; store the current bit position in bits [ i ] ; store the required result ; traverse the array , bits [ ] to get all unique pairs ( i , j ) ; check whether the strings have no common characters ; update the overall maximum product ; print the maximum product ; 
def countSetBits(n):
    count = 0
    while (n > 0):
        count += n & 1
        n >>= 1
    return count


def maximumProduct(words):
    bits = [0 for i in range(len(words))]
    for i in range(len(words)):
        for j in range(len(words[i])):
            bits[i] = bits[i] | 1 << (ord(words[i][j]) - 97)
    result = 0
    for i in range(len(bits)):
        for j in range(i + 1, len(bits)):
            if ((bits[i] & bits[j]) == 0):
                L = countSetBits(bits[i])
                R = countSetBits(bits[j])
                result = max(L * R, result)
    print(result)


if __name__ == '__main__':
    arr = ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
    maximumProduct(arr)

# Expected output:
16
# modify a sentence by reversing order of occurrences of all palindrome words | function to check if a string s is a palindrome ; function to print the modified string after reversing teh order of occurrences of all palindromic words in the sentence ; stores the palindromic words ; stores the words in the list ; traversing the list ; if current word is a palindrome ; update newlist ; reverse the newlist ; traverse the list ; if current word is a palindrome ; update lis [ i ] ; increment j ; print the updated sentence ; 
def palindrome(string):
    if (string == string[::-1]):
        return True
    else:
        return False


def printReverse(sentence):
    newlist = []
    lis = list(sentence .split())
    for i in lis:
        if (palindrome(i)):
            newlist .append(i)
    newlist .reverse()
    j = 0
    for i in range(len(lis)):
        if (palindrome(lis[i])):
            lis[i] = newlist[j]
            j = j + 1
    for i in lis:
        print(i, end=" ")


sentence = "mom and dad went to eye hospital"
printReverse(sentence)

# Expected output:
eye and dad went to mom hospital
# convert an array into another by repeatedly removing the last element and placing it at any arbitrary index | function to count the minimum number of operations required to convert the array a [ ] into array b [ ] ; stores the index in the first permutation a [ ] which is same as the subsequence in b [ ] ; find the first i elements in a [ ] which is a subsequence in b [ ] ; if element a [ i ] is same as b [ j ] ; return the count of operations required ; 
def minCount(A, B, N):
    i = 0
    for j in range(N):
        if (A[i] == B[j]):
            i += 1
    return N - i


if __name__ == '__main__':
    A = [1, 2, 3, 4, 5]
    B = [1, 5, 2, 3, 4]
    N = len(A)
    print(minCount(A, B, N))

# Expected output:
1
# minimize maximum array element possible by at most k splits on the given array | function to check if all array elements can be reduced to at most mid by at most k splits ; stores the number of splits required ; traverse the array arr [ ] ; update count ; if possible , return true . otherwise return false ; function to find the minimum possible value of maximum array element that can be obtained by at most k splits ; set lower and upper limits ; perform binary search ; calculate mid ; check if all array elements can be reduced to at most mid value by at most k splits ; update the value of hi ; otherwise ; update the value of lo ; return the minimized maximum element in the array ; 
def possible(A, N, mid, K):
    count = 0
    for i in range(N):
        count += (A[i] - 1) // mid
    return count <= K


def minimumMaximum(A, N, K):
    lo = 1
    hi = max(A)
    while (lo < hi):
        mid = (lo + hi) // 2
        if (possible(A, N, mid, K)):
            hi = mid
        else:
            lo = mid + 1
    return hi


if __name__ == '__main__':
    arr = [2, 4, 8, 2]
    K = 4
    N = len(arr)
    print(minimumMaximum(arr, N, K))

# Expected output:
2
# maximum value of x such that difference between any array element and x does not exceed k | function to find maximum value of x such that | a [ i ] - x | a k ; stores the smallest array element ; store the possible value of x ; traverse the array a [ ] ; if required criteria is not satisfied ; update ans ; print the result ; 
def maximumNumber(arr, N, K):
    minimum = min(arr)
    ans = minimum + K
    for i in range(N):
        if (abs(arr[i] - ans) > K):
            ans = -1
            break
    print(ans)


if __name__ == '__main__':
    arr = [1, 2, 5]
    K = 2
    N = len(arr)
    maximumNumber(arr, N, K)

# Expected output:
3
# check if a number can be represented as a sum of a prime number and a perfect square | python3 program for the above approach ; function to check if a number is prime or not ; base cases ; check if n is divisible by 2 or 3 ; iterate over every 6 number from the range [ 5 , sqrt ( n ) ] ; if n is found to be non - prime ; otherwise , return true ; function to check if a number can be represented as the sum of a prime number and a perfect square or not ; stores all perfect squares less than n ; store the perfect square in the array ; iterate over all perfect squares ; store the difference of perfect square from n ; if difference is prime ; update flag ; break out of the loop ; if n is the sum of a prime number and a perfect square ; 

from math import sqrt


def isPrime(n):
    if (n <= 1):
        return False
    if (n <= 3):
        return True
    if (n % 2 == 0 or n % 3 == 0):
        return False
    for i in range(5, int(sqrt(n)) + 1, 6):
        if (n % i == 0 or n % (i + 2) == 0):
            return False
    return True


def sumOfPrimeSquare(n):
    i = 0
    squares = []
    while (i * i < n):
        squares .append(i * i)
        i += 1
    flag = False
    for i in range(len(squares)):
        difference = n - squares[i]
        if (isPrime(difference)):
            flag = True
            break
    if (flag):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    N = 27
    sumOfPrimeSquare(N)

# Expected output:
Yes
# check if a number can be represented as a sum of a prime number and a perfect square | python3 program for the above approach ; function to store all prime numbers less than or equal to n ; update prime [ 0 ] and prime [ 1 ] as false ; iterate over the range [ 2 , sqrt ( n ) ] ; if p is a prime ; update all multiples of p which are <= n as non - prime ; function to check whether a number can be represented as the sum of a prime number and a perfect square ; stores all the prime numbers less than or equal to n ; update the array prime [ ] ; iterate over the range [ 0 , n ] ; if current number is non - prime ; update difference ; if difference is a perfect square ; if true , update flag and break out of loop ; if n can be expressed as sum of prime number and perfect square ; 

import math


def SieveOfEratosthenes(prime, n):
    prime[0] = False
    prime[1] = False
    for p in range(2, int(n ** (1 / 2))):
        if (prime[p]):
            for i in range(p ** 2, n + 1, p):
                prime[i] = False


def sumOfPrimeSquare(n):
    flag = False
    prime = [True] * (n + 1)
    SieveOfEratosthenes(prime, n)
    for i in range(n + 1):
        if (not prime[i]):
            continue
        dif = n - i
        if (math .ceil(dif ** (1 / 2)) == math .floor(dif ** (1 / 2))):
            flag = True
            break
    if (flag):
        print("Yes")
    else:
        print("No")


if __name__ == "__main__":
    N = 27
    sumOfPrimeSquare(N)

# Expected output:
Yes
# check if any subarray of length m repeats at least k times consecutively or not | function to check if there exists any subarray of length m repeating at least k times consecutively ; iterate from i equal 0 to m ; iterate from j equals 1 to k ; if elements at pos + i and pos + i + j * m are not equal ; function to check if a subarray repeats at least k times consecutively or not ; iterate from ind equal 0 to m ; check if subarray arr [ i , i + m ] repeats atleast k times or not ; otherwise , return false ; 
def check(arr, M, K, ind):
    for i in range(M):
        for j in range(1, K, 1):
            if (arr[ind + i] != arr[ind + i + j * M]):
                return False
    return True


def SubarrayRepeatsKorMore(arr, N, M, K):
    for ind in range(N - M * K + 1):
        if (check(arr, M, K, ind)):
            return True
    return False


if __name__ == '__main__':
    arr = [2, 1, 2, 1, 1, 1, 3]
    M = 2
    K = 2
    N = len(arr)
    if (SubarrayRepeatsKorMore(arr, N, M, K)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# check if any subarray of length m repeats at least k times consecutively or not | function to check if any subarray of length m repeats at least k times consecutively or not ; stores the required count of repeated subarrays ; check if the next continuous subarray has equal elements ; check if k continuous subarray of length m are found or not ; if no subarrays are found ; 
def checkExists(arr, N, M, K):
    count = 0
    for i in range(N - M):
        if (arr[i] == arr[i + M]):
            count += 1
        else:
            count = 0
        if (count == M * (K - 1)):
            return True
    return False


if __name__ == '__main__':
    arr = [2, 1, 2, 1, 1, 1, 3]
    N = len(arr)
    M = 2
    K = 2
    if (checkExists(arr, N, M, K)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# number of common digits present in two given numbers | function to count number of digits that are common in both n and m ; stores the count of common digits ; stores the count of digits of n ; stores the count of digits of m ; iterate over the digits of n ; increment the count of last digit of n ; update n ; iterate over the digits of m ; increment the count of last digit of m ; update m ; iterate over the range [ 0 , 9 ] ; if freq1 [ i ] and freq2 [ i ] both exceeds 0 ; increment count by 1 ; return the count ; 
def CommonDigits(N, M):
    count = 0
    freq1 = [0] * 10
    freq2 = [0] * 10
    while (N > 0):
        freq1[N % 10] += 1
        N = N // 10
    while (M > 0):
        freq2[M % 10] += 1
        M = M // 10
    for i in range(10):
        if (freq1[i] > 0 and freq2[i] > 0):
            count += 1
    return count


if __name__ == '__main__':
    N = 748294
    M = 34298156
    print(CommonDigits(N, M))

# Expected output:
4
# smallest value of n such that the sum of all natural numbers from k to n is at least x | function to find the minimum possible value of n such that sum of natural numbers from k to n is at least x ; if k is greater than x ; stores value of minimum n ; stores the sum of values over the range [ k , ans ] ; iterate over the range [ k , n ] ; check if sum of first i natural numbers is >= x ; print the possible value of ans ; 
def minimumNumber(K, X):
    if (K > X):
        print("-1")
        return
    ans = 0
    sum = 0
    for i in range(K, X + 1):
        sum += i
        if (sum >= X):
            ans = i
            break
    print(ans)


K = 5
X = 13
minimumNumber(K, X)

# Expected output:
7
# smallest value of n such that the sum of all natural numbers from k to n is at least x | function to check if the sum of natural numbers from k to n is >= x ; function to find the minimum value of n such that the sum of natural numbers from k to n is at least x ; if k is greater than x ; perform the binary search ; if the sum of the natural numbers from k to mid is atleast x ; update res ; update high ; otherwise , update low ; print the value of res as the answer ; 
def isGreaterEqual(N, K, X):
    return (((N * (N + 1) // 2) - ((K - 1) * K // 2)) >= X)


def minimumNumber(K, X):
    if (K > X):
        print("-1")
        return
    low = K
    high = X
    res = -1
    while (low <= high):
        mid = low + ((high - low) // 2)
        if (isGreaterEqual(mid, K, X)):
            res = mid
            high = mid - 1
        else:
            low = mid + 1
    print(res)


K = 5
X = 13
minimumNumber(K, X)

# Expected output:
7
# count pairs with product of indices equal to the product of elements present at those indices | function to count the number of pairs having product of indices equal to the product of elements at that indices ; stores the count of valid pairs ; generate all possible pairs ; if the condition is satisfied ; increment the count ; return the total count ; 
def CountPairs(arr, n):
    count = 0
    for i in range(n - 1):
        for j in range(i + 1, n):
            if ((i * j) == (arr[i] * arr[j])):
                count += 1
    return count


if __name__ == "__main__":
    arr = [1, 0, 3, 2, 6]
    N = len(arr)
    print(CountPairs(arr, N))

# Expected output:
3
# maximize remainder of sum of a pair of array elements with different parity modulo k | python3 program for the above approach ; function to find the maximum remainder of sum of a pair of array elements modulo k ; stores all even numbers ; stores all odd numbers ; segregate remainders of even and odd numbers in respective sets ; stores the maximum remainder obtained ; find the complement of remainder of each even number in odd set ; find the complement of remainder x ; print the answer ; 

from bisect import bisect_left


def maxRemainder(A, N, K):
    even = {}
    odd = {}
    for i in range(N):
        num = A[i]
        if (num % 2 == 0):
            even[num % K] = 1
        else:
            odd[num % K] = 1
    max_rem = 0
    for x in even:
        y = K - 1 - x
        od = list(odd .keys())
        it = bisect_left(od, y)
        if (it != 0):
            max_rem = max(max_rem, x + od[it])
    print(max_rem)


if __name__ == '__main__':
    arr = [3, 2, 4, 11, 6, 7]
    N = len(arr)
    K = 7
    maxRemainder(arr, N, K)

# Expected output:
6
# length of the longest path ending at vertex v in a graph | python3 program for the above approach ; function to perform dfs traversal from source node to the deepest node and update maximum distance to the deepest node ; mark source as visited ; update the maximum distance ; traverse the adjacency list of the current source node ; recursively call for the child node ; backtracking step ; function to calculate maximum length of the path ending at vertex v from any source node ; stores the maximum length of the path ending at vertex v ; stores the size of the matrix ; stores the adjacency list of the given graph ; traverse the matrix to create adjacency list ; perform dfs traversal to update the maximum distance ; 

visited = [False for i in range(4)]


def dfs(src, Adj, level, distance):
    global visited
    visited[src] = True
    distance = max(distance, level)
    for child in Adj[src]:
        if (child != src and visited[child] == False):
            dfs(child, Adj, level + 1, distance)
    visited[src] = False


def maximumLength(mat, V):
    distance = 0
    N = len(mat)
    Adj = [[]for i in range(N)]
    for i in range(N):
        for j in range(N):
            if (mat[i][j] == 1):
                Adj[i].append(j)
    dfs(V, Adj, 0, distance)
    return distance + 2


if __name__ == '__main__':
    mat = [[0, 1, 0, 0], [1, 0, 1, 1], [0, 1, 0, 0], [0, 1, 0, 0]]
    V = 2
    print(maximumLength(mat, V))

# Expected output:
2
# minimum removals required such that given string consists only of a pair of alternating characters | function to find the maximum length of alternating occurrences of a pair of characters in a string s ; stores the next character for alternating sequence ; stores the length of alternating occurrences of a pair of characters ; traverse the given string ; if current character is same as the required character ; increase length by 1 ; reset required character ; return the length ; function to find minimum characters required to be deleted from s to obtain an alternating sequence ; stores maximum length of alternating sequence of two characters ; stores length of the string ; generate every pair of english alphabets ; function call to find length of alternating sequence for current pair of characters ; update len to store the maximum of len and newlen in len ; return n - len as the final result ; 
def findLength(s, i, j):
    required = i
    length = 0
    for curr in s:
        if (curr == required):
            length += 1
            if (required == i):
                required = j
            else:
                required = i
    return length


def minimumDeletions(S):
    len1 = 0
    n = len(S)
    for i in range(0, 26, 1):
        for j in range(i + 1, 26, 1):
            newLen = findLength(S, chr(i + 97), chr(j + 97))
            len1 = max(len1, newLen)
    return n - len1


if __name__ == '__main__':
    S = "adebbeeaebd"
    print(minimumDeletions(S))

# Expected output:
7