giulio98/xlcost-single-prompt huggingface dataset:
# make all array elements equal to 0 by replacing minimum subsequences consisting of equal elements | function to find minimum count of operations required to convert all array elements to zero by replacing subsequence of equal elements to 0 ; store distinct elements present in the array ; traverse the array ; if arr [ i ] is already present in the set or arr [ i ] is equal to 0 ; otherwise , increment ans by 1 and insert current element ; given array ; size of the 
def minOpsToTurnArrToZero(arr, N):
    st = dict()
    for i in range(N):
        if (i in st .keys() or arr[i] == 0):
            continue
        else:
            st[arr[i]] = 1
    print(len(st))


arr = [3, 7, 3]
N = len(arr)
minOpsToTurnArrToZero(arr, N)

# Expected output:
2
# split an array into equal length subsequences consisting of equal elements only | python3 program for the above approach ; function to find the gcd of two numbers a and b ; function to check if it is possible to split the array into equal length subsequences such that all elements in the subsequence are equal ; store frequencies of array elements ; traverse the array ; update frequency of arr [ i ] ; store the gcd of frequencies of all array elements ; traverse the map ; update gcd ; if the gcd is greater than 1 , print yes otherwise print no ; 

from collections import defaultdict


def gcd(a, b):
    if (b == 0):
        return a
    return gcd(b, a % b)


def splitArray(arr, N):
    mp = defaultdict(int)
    for i in range(N):
        mp[arr[i]] += 1
    G = 0
    for i in mp:
        G = gcd(G, mp[i])
    if (G > 1):
        print("YES")
    else:
        print("NO")


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

# Expected output:
YES
# minimize count of given operations required to be performed to make all array elements equal to 1 | python 3 program to implement the above approach ; function to check if all array elements are equal or not ; traverse the array ; if all array elements are not equal ; function to find minimum count of operation to make all the array elements equal to 1 ; stores largest element of the array ; check if a number is a power of 2 or not ; if max is a power of 2 and all array elements are equal ; 

import math


def CheckAllEqual(arr, N):
    for i in range(1, N):
        if (arr[0] != arr[i]):
            return False
    return True


def minCntOperations(arr, N):
    Max = max(arr)
    isPower2 = not (Max and (Max & (Max - 1)))
    if (isPower2 and CheckAllEqual(arr, N)):
        return log2(Max)
    else:
        return math .ceil(math .log2(Max)) + 1


if __name__ == "__main__":
    arr = [2, 4]
    N = len(arr)
    print(minCntOperations(arr, N))

# Expected output:
3
# largest number not exceeding n that does not contain any of the digits of s | function to obtain the largest number not exceeding num which does not contain any digits present in s ; stores digits of s ; traverse the string s ; set occurrence as true ; traverse the string n ; all digits of num are not present in string s ; largest digit not present in the string s ; set all digits from positions in + 1 to n - 1 as largestdig ; counting leading zeroes ; removing leading zeroes ; if the string becomes null ; return the largest number ; 
def greatestReducedNumber(num, s):
    vis_s = [False] * 10
    for i in range(len(s)):
        vis_s[(ord)(s[i]) - 48] = True
    n = len(num)
    In = -1
    for i in range(n):
        if (vis_s[ord(num[i]) - ord('0')]):
            In = i
            break
    if (In == -1):
        return num
    for dig in range(ord(num[In]), ord('0') - 1, -1):
        if (vis_s[dig - ord('0')] == False):
            num = num[0: In] + chr(dig) + num[In + 1: n - In - 1]
            break
    LargestDig = '0'
    for dig in range(ord('9'), ord('0') - 1, -1):
        if (vis_s[dig - ord('0')] == False):
            LargestDig = dig
            break
    for i in range(In + 1, n):
        num = num[0: i] + chr(LargestDig)
    Count = 0
    for i in range(n):
        if (num[i] == '0'):
            Count += 1
        else:
            break
    num = num[Count: n]
    if (int(len(num)) == 0):
        return "0"
    return num


N = "12345"
S = "23"
print(greatestReducedNumber(N, S))

# Expected output:
11999
# generate an array of minimum sum whose xor of same | function to generate an array whose xor with same - indexed elements of the given array is always a prime ; traverse the array ; if current array element is 2 ; print its xor with 3 ; otherwise ; print its xor with 2 ; 
def minXOR(Arr, N):
    for i in range(N):
        if (Arr[i] == 2):
            print(Arr[i] ^ 3, end=" ")
        else:
            print(Arr[i] ^ 2, end=" ")


if __name__ == '__main__':
    Arr = [5, 4, 7, 6]
    N = len(Arr)
    minXOR(Arr, N)

# Expected output:
7 6 5 4
# find the largest element in an array generated using the given conditions | function to generate the required array ; stores the array ; base case ; iterate over the indices ; if current index is even ; otherwise ; function to find and return the maximum array element ; if n is 0 ; if n is 1 ; generates the required array ; return maximum element of arr ; 
def findArray(n):
    Arr = [0] * (n + 1)
    Arr[1] = 1
    for i in range(2, n + 1):
        if (i % 2 == 0):
            Arr[i] = Arr[i // 2]
        else:
            Arr[i] = (Arr[(i - 1) // 2] + Arr[(i - 1) // 2 + 1])
    return Arr


def maxElement(n):
    if (n == 0):
        return 0
    if (n == 1):
        return 1
    Arr = findArray(n)
    return max(Arr)


if __name__ == "__main__":
    N = 7
    print(maxElement(N))

# Expected output:
3
# construct a graph using n vertices whose shortest distance between k pair of vertices is 2 | function to construct the simple and connected graph such that the distance between exactly k pairs of vertices is 2 ; stores maximum possible count of edges in a graph ; base case ; stores edges of a graph ; connect all vertices of pairs ( i , j ) ; print first ( ( n - 1 ) + max - k ) elements of edges [ ] ; 
def constGraphWithCon(N, K):
    Max = ((N - 1) * (N - 2)) // 2
    if (K > Max):
        print(-1)
        return
    ans = []
    for i in range(1, N):
        for j in range(i + 1, N + 1):
            ans .append([i, j])
    for i in range(0, (N - 1) + Max - K):
        print(ans[i][0], ans[i][1], sep=" ")


if __name__ == '__main__':
    N = 5
    K = 3
    constGraphWithCon(N, K)

# Expected output:
1 2
1 3
1 4
1 5
2 3
2 4
2 5
# minimum steps required to visit all corners of an n * m grid | python3 program to implement the above approach ; function to find the minimum count of steps required to visit all the corners of the grid ; stores corner of the grid ; stores minimum count of steps required to visit the first corner of the grid ; checking for leftmost upper corner ; checking for leftmost down corner ; checking for rightmost upper corner ; checking for rightmost down corner ; stores minimum count of steps required to visit remaining three corners of the grid ; 

import sys
INT_MAX = sys .maxsize


def min_steps_required(n, m, r, c):
    i = 0
    j = 0
    corner_steps_req = INT_MAX
    i = 1
    j = 1
    corner_steps_req = min(corner_steps_req, abs(r - i) + abs(j - c))
    i = n
    j = 1
    corner_steps_req = min(corner_steps_req, abs(r - i) + abs(j - c))
    i = 1
    j = m
    corner_steps_req = min(corner_steps_req, abs(r - i) + abs(j - c))
    i = n
    j = m
    corner_steps_req = min(corner_steps_req, abs(r - i) + abs(j - c))
    minimum_steps = min(2 * (n - 1) + m - 1, 2 * (m - 1) + n - 1)
    return minimum_steps + corner_steps_req


if __name__ == "__main__":
    n = 3
    m = 2
    r = 1
    c = 1
    print(min_steps_required(n, m, r, c))

# Expected output:
4
# minimum replacements required to have at most k distinct elements in the array | function to find minimum count of array elements required to be replaced such that count of distinct elements is at most k ; store the frequency of each distinct element of the array ; traverse the array ; update frequency of arr [ i ] ; store frequency of each distinct element of the array ; traverse the map ; stores key of the map ; insert mp [ i ] into freq [ ] ; sort freq [ ] in descending order ; stores size of freq [ ] ; if len is less than or equal to k ; stores minimum count of array elements required to be replaced such that count of distinct elements is at most k ; iterate over the range [ k , len ] ; update cntmin ; 
def min_elements(arr, N, K):
    mp = {}
    for i in range(N):
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    Freq = []
    for it in mp:
        i = it
        Freq .append(mp[i])
    Freq .sort()
    Freq .reverse()
    Len = len(Freq)
    if (Len <= K):
        return 0
    cntMin = 0
    for i in range(K, Len):
        cntMin += Freq[i]
    return cntMin


arr = [5, 1, 3, 2, 4, 1, 1, 2, 3, 4]
N = len(arr)
K = 3
print(min_elements(arr, N, K))

# Expected output:
3
# check if sum of the given array can be reduced to 0 by reducing array elements by k | function to check if the sum can be made 0 or not ; stores sum of array elements ; traverse the array ; 
def sumzero(arr, N, K):
    sum = 0
    for i in range(N):
        sum += arr[i]
    if (sum == 0):
        print("Yes")
    elif (sum > 0):
        if (sum % K == 0):
            print("Yes")
        else:
            print("No")
    else:
        print("No")


if __name__ == "__main__":
    arr1 = [1, -6, 2, 2]
    K = 1
    N = len(arr1)
    sumzero(arr1, N, K)

# Expected output:
No
# counts 1 s that can be obtained in an array by performing given operations | function to count total number of 1 s in array by performing given operations ; stores count of 1 s in the array by performing the operations ; iterate over the range [ 1 , n ] ; flip all array elements whose index is multiple of i ; update arr [ i ] ; traverse the array ; if current element is 1 ; update cntones ; 
def cntOnesArrWithGivenOp(arr, N):
    cntOnes = 0
    for i in range(1, N + 1):
        for j in range(i - 1, N, i):
            arr[j] = 1 if arr[j] == 0 else 0
    for i in range(N):
        if (arr[i] == 1):
            cntOnes += 1
    return cntOnes


if __name__ == '__main__':
    arr = [0, 0, 0, 0, 0]
    N = len(arr)
    print(cntOnesArrWithGivenOp(arr, N))

# Expected output:
2
# counts 1 s that can be obtained in an array by performing given operations | function to count total number of 1 s in array by performing the given operations ; stores count of 1 s in the array by performing the operations ; update cntones ; 
def cntOnesArrWithGivenOp(arr, N):
    cntOnes = 0
    cntOnes = int(N ** (1 / 2))
    return cntOnes


if __name__ == "__main__":
    arr = [0, 0, 0, 0, 0]
    N = len(arr)
    print(cntOnesArrWithGivenOp(arr, N))

# Expected output:
2
# count knights that can attack a given pawn in an n * n board | function to count the knights that are attacking the pawn in an m * m board ; stores count of knights that are attacking the pawn ; traverse the knights array ; stores absolute difference of x co - ordinate of i - th knight and pawn ; stores absolute difference of y co - ordinate of i - th knight and pawn ; if x is 1 and y is 2 or x is 2 and y is 1 ; update cntknights ; 
def cntKnightsAttackPawn(knights, pawn, M):
    cntKnights = 0
    for i in range(M):
        X = abs(knights[i][0] - pawn[0])
        Y = abs(knights[i][1] - pawn[1])
        if ((X == 1 and Y == 2) or (X == 2 and Y == 1)):
            cntKnights += 1
    return cntKnights


if __name__ == '__main__':
    knights = [[0, 4], [4, 5], [1, 4], [3, 1]]
    pawn = [2, 3]
    M = len(knights)
    print(cntKnightsAttackPawn(knights, pawn, M))

# Expected output:
2
# find the winner of game of removing array elements having gcd equal to 1 | function to find the winner of the game by removing array elements whose gcd is 1 ; mp [ i ] : stores count of array elements whose prime factor is i ; traverse the array ; calculate the prime factors of arr [ i ] ; if arr [ i ] is divisible by j ; update mp [ j ] ; update arr [ i ] ; if arr [ i ] exceeds 1 ; stores maximum value present in the map ; traverse the map ; update maxcnt ; if n is an even number ; if maxcnt is greater than or equal to n - 1 ; player 1 wins ; player 2 wins ; if maxcnt equal to n ; player 1 wins ; player 2 wins ; 
def findWinnerGameRemoveGCD(arr, n):
    mp = dict .fromkeys(arr, 0)
    for i in range(n):
        for j in range(2, int(arr[i] * (1 / 2)) + 1):
            if (arr[i] % j == 0):
                mp[j] += 1
                while (arr[i] % j == 0):
                    arr[i] = arr[i] // j
        if (arr[i] > 1):
            mp[arr[i]] += 1
    maxCnt = 0
    for i in mp:
        maxCnt = max(maxCnt, mp[i])
    if (n % 2 == 0):
        if (maxCnt >= n - 1):
            print("Player 1", end="")
        else:
            print("Player 2", end="")
    else:
        if (maxCnt == n):
            print("Player 1", end="")
        else:
            print("Player 2", end="")


if __name__ == "__main__":
    arr = [2, 4, 8]
    N = len(arr)
    findWinnerGameRemoveGCD(arr, N)

# Expected output:
Player 1
# maximum possible sum of k even multiples of 5 in a given range | function to find the maximum sum of k even multiples of 5 in the range [ l , r ] ; store the total number of even multiples of 5 in the range [ l , r ] ; check if k > n ; if true , print - 1 and return ; otherwise , divide r by 10 ; store the sum using the formula ; print the sum ; 
def maxksum(L, R, K):
    N = (R // 10 - L // 10) + 1
    if (K > N):
        print(-1)
        return
    R = R // 10
    X = R - K
    sum = 10 * ((R * (R + 1)) // 2 - (X * (X + 1)) // 2)
    print(sum)


if __name__ == "__main__":
    L = 16
    R = 60
    K = 4
    maxksum(L, R, K)

# Expected output:
180
# minimum swaps of same | function to count the minimum swaps of same - indexed elements from arrays arr1 and arr2 required to make the sum of both the arrays even ; store the sum of elements of the array arr1 and arr2 respectively ; store the array sum of both the arrays ; if both sumarr1 and sumarr2 are even , pr0 and return ; if both sumarr1 and sumarr2 are odd and check for a pair with sum odd sum ; stores if a pair with odd sum exists or not ; traverse the array ; if a pair exists with odd sum , set flag = 1 ; print the answer and return ; for all other cases , pr - 1 ; 
def minimumSwaps(arr1, arr2, n):
    sumArr1 = 0
    sumArr2 = 0
    for i in range(n):
        sumArr1 += arr1[i]
        sumArr2 += arr2[i]
    if (sumArr1 % 2 == 0 and sumArr2 % 2 == 0):
        print(0)
        return
    if (sumArr1 % 2 != 0 and sumArr2 % 2 != 0):
        flag = -1
        for i in range(n):
            if ((arr1[i] + arr2[i]) % 2 == 1):
                flag = 1
                break
        print(flag)
        return
    print(-1)


if __name__ == '__main__':
    arr1 = [11, 14, 20, 2]
    arr2 = [5, 9, 6, 3]
    N = len(arr1)
    minimumSwaps(arr1, arr2, N)

# Expected output:
1
# count of seats booked on each of the given n flights | function to find the total of the seats booked in each of the flights ; stores the resultant sequence ; traverse the array ; store the first booked flight ; store the last booked flight ; store the total number of seats booked in flights [ l , r ] ; add k to the flight l ; subtract k from flight number r + 1 ; find the prefix sum of the array ; print total number of seats booked in each flight ; 
def corpFlightBookings(Bookings, N):
    res = [0] * N
    for i in range(len(Bookings)):
        l = Bookings[i][0]
        r = Bookings[i][1]
        K = Bookings[i][2]
        res[l - 1] = res[l - 1] + K
        if (r <= len(res) - 1):
            res[r] = (-K) + res[r]
    for i in range(1, len(res)):
        res[i] = res[i] + res[i - 1]
    for i in range(len(res)):
        print(res[i], end=" ")


if __name__ == '__main__':
    bookings = [[1, 3, 100], [2, 6, 100], [3, 4, 100]]
    N = 6
    corpFlightBookings(bookings, N)

# Expected output:
100 200 300 200 100 100
# bitwise xor of all odd numbers from a given range | function to calculate bitwise xor of odd numbers in the range [ 1 , n ] ; n & 3 is equivalent to n % 4 ; if n is multiple of 4 ; if n % 4 gives remainder 1 ; if n % 4 gives remainder 2 ; if n % 4 gives remainder 3 ; function to find the xor of odd numbers less than or equal to n ; if number is even ; prthe answer ; if number is odd ; prthe answer ; 
def findXOR(n):
    if (n % 4 == 0):
        return n
    elif (n % 4 == 1):
        return 1
    elif (n % 4 == 2):
        return n + 1
    elif (n % 4 == 3):
        return 0


def findOddXOR(n):
    if (n % 2 == 0):
        print(((findXOR(n)) ^ (2 * findXOR(n // 2))))
    else:
        print(((findXOR(n)) ^ (2 * findXOR((n - 1) // 2))))


if __name__ == '__main__':
    N = 11
    findOddXOR(N)

# Expected output:
2
# smallest number greater than or equal to n which is divisible by its non | function to find the smallest number greater than or equal to n such that it is divisible by its non - zero digits ; iterate in range [ n , n + 2520 ] ; to check if the current number satisfies the given condition ; store the number in a temporary variable ; loop until temp > 0 ; check only for non zero digits ; extract the current digit ; if number is divisible by current digit or not ; otherwise , set possible to 0 ; break out of the loop ; divide by 10 ; 
def findSmallestNumber(n):
    for i in range(n, n + 2521):
        possible = 1
        temp = i
        while (temp):
            if (temp % 10 != 0):
                digit = temp % 10
                if (i % digit != 0):
                    possible = 0
                    break
            temp //= 10
        if (possible == 1):
            print(i, end="")
            return


if __name__ == "__main__":
    N = 31
    findSmallestNumber(N)

# Expected output:
33
# print path from a node to root of given complete binary tree | function to print the path from node to root ; iterate until root is reached ; print the value of the current node ; move to parent of the current node ; 
def path_to_root(node):
    while (node >= 1):
        print(node, end=" ")
        node //= 2


if __name__ == '__main__':
    N = 7
    path_to_root(N)

# Expected output:
7 3 1
# smallest number whose sum of digits is n and every digit occurring at most k times | function to find the smallest number whose sum of digits is n and each digit occurring at most k times ; maximum sum possible using each digit at most k times ; append smallest number into the resultant string ; iterate over the range [ 9 , 1 ] ; if the count of the digit is k , then update count and check for the next digit ; if n is greater than current digit ; subtract i from n ; insert i as a digit ; insert remaining n as a digit ; increment count ; reverse the string ; print the answer ; 
def findSmallestNumberPossible(N, K):
    if (N > 45 * K):
        print("-1", endl="")
        return
    res = ""
    count = 0
    i = 9
    while i >= 1:
        if (count == K):
            i -= 1
            count = 0
        if (N > i):
            N -= i
            res += chr(48 + i)
        else:
            res += chr(N + 48)
            N = 0
            break
        count += 1
    res = res[::-1]
    print(res, end="")


if __name__ == "__main__":
    N = 25
    K = 3
    findSmallestNumberPossible(N, K)

# Expected output:
799
# minimum sum of values subtracted from array elements to make all array elements equal | function to find the sum of values removed to make all array elements equal ; stores the minimum of the array ; stores required sum ; traverse the array ; add the value subtracted from the current element ; return the total sum ; 
def minValue(arr, n):
    minimum = min(arr)
    sum = 0
    for i in range(n):
        sum = sum + (arr[i] - minimum)
    return sum


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

# Expected output:
3
# smallest positive number made up of non | function to find smallest positive number made up of non - repeating digits whose sum of its digits is equal to n ; no such number exists ; stores the required answer ; store the digit at unit 's place ; iterate until n > digit ; push digit at the start of res ; decrement n by digit ; decrement digit by 1 ; push the remaining number as the starting digit ; print the required number ; 
def result(n):
    if (n > 45):
        print(-1, end="")
        return
    res = ""
    digit = 9
    while (n > digit):
        res = str(digit) + res
        n -= digit
        digit -= 1
    if (n > 0):
        res = str(n) + res
    print(res)


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

# Expected output:
289
# count pair of integers having even sum | python3 program for the above approach ; function to count even pairs ; stores count of pairs having even sum ; stores count of even numbers up to n ; stores count of odd numbers up to n ; stores count of even numbers up to m ; stores count of odd numbers up to m ; return the count ; 

import math


def countEvenPairs(N, M):
    count = 0
    nEven = int(math .floor(N / 2))
    nOdd = int(math .ceil(N / 2))
    mEven = int(math .floor(M / 2))
    mOdd = int(math .ceil(M / 2))
    count = nEven * mEven + nOdd * mOdd
    return count


if __name__ == '__main__':
    N = 4
    M = 6
    print(countEvenPairs(N, M))

# Expected output:
12
# generate an n | function to generate a string of length n having longest palindromic substring of length k ; fill first k characters with 'a ; stores a non - palindromic sequence to be repeated for n - k slots ; prn - k remaining characters ; 
def string_palindrome(N, K):
    for i in range(K):
        print("a", end="")
    s = "bcd"
    for i in range(N - K):
        print(s[i % 3], end="")


if __name__ == '__main__':
    N, K = 5, 3
    string_palindrome(N, K)

# Expected output:
aaabc
# last remaining character after repeated removal of the first character and flipping of characters of a binary string | function to find the last removed character from the string ; stores length of the string ; base case : ; if the second last character is '0 ; if the second last character is '1 ; 
def lastRemovedCharacter(str):
    n = len(str)
    if (n == 1):
        return ord(str[0])
    if (str[n - 2] == '0'):
        return (ord('1') -
                ord(str[n - 1]) +
                ord('0'))
    else:
        return ord(str[n - 1])


if __name__ == '__main__':

    str = "10010"

    print(chr(lastRemovedCharacter(str)))

# Expected output:
0
# find the triplet from given bitwise xor and bitwise and values of all its pairs | function to find the triplet with given bitwise xor and bitwise and values of all possible pairs of the triplet ; stores values of a triplet ; stores a + b ; stores a + c ; stores b + c ; calculate asumb ; calculate asumc ; calculate bsumc ; calculate a ; calculate b ; calculate c ; pra ; prb ; prc ; 
def findNumbers(aXORb, aANDb, aXORc, aANDc, bXORc, bANDc):
    a, b, c = 0, 0, 0
    aSUMb = 0
    aSUMc = 0
    bSUMc = 0
    aSUMb = aXORb + aANDb * 2
    aSUMc = aXORc + aANDc * 2
    bSUMc = bXORc + bANDc * 2
    a = (aSUMb - bSUMc + aSUMc) // 2
    b = aSUMb - a
    c = aSUMc - a
    print("a = ", a, end="")
    print(", b = ", b, end="")
    print(", c = ", c, end="")


if __name__ == '__main__':
    aXORb = 30
    aANDb = 0
    aXORc = 20
    aANDc = 10
    bXORc = 10
    bANDc = 20
    findNumbers(aXORb, aANDb, aXORc, aANDc, bXORc, bANDc)

# Expected output:
a =  10, b =  20, c =  30