giulio98/xlcost-single-prompt huggingface dataset:
# smallest subarray with sum k from an array | python3 program to implement the above approach ; function to find the length of the smallest subarray with sum k ; stores the frequency of prefix sums in the array ; initialize ln ; if sum of array till i - th index is less than k ; no possible subarray exists till i - th index ; find the exceeded value ; if exceeded value is zero ; 

from collections import defaultdict
import sys


def subArraylen(arr, n, K):
    mp = defaultdict(lambda: 0)
    mp[arr[0]] = 0
    for i in range(1, n):
        arr[i] = arr[i] + arr[i - 1]
        mp[arr[i]] = i
    ln = sys .maxsize
    for i in range(n):
        if (arr[i] < K):
            continue
        else:
            x = K - arr[i]
            if (x == 0):
                ln = min(ln, i)
            if (x in mp .keys()):
                continue
            else:
                ln = min(ln, i - mp[x])
    return ln


arr = [1, 2, 4, 3, 2, 4, 1]
n = len(arr)
K = 7
ln = subArraylen(arr, n, K)
if (ln == sys .maxsize):
    print("-1")
else:
    print(ln)

# Expected output:
2
# nth term of a fibonacci series of primes formed by concatenating pairs of primes in a given range | stores at each index if it 's a prime or not ; sieve of eratosthenes to generate all possible primes ; if p is a prime ; set all multiples of p as non - prime ; function to generate the required fibonacci series ; stores all primes between n1 and n2 ; generate all primes between n1 and n2 ; stores all concatenations of each pair of primes ; generate all concatenations of each pair of primes ; stores the primes out of the numbers generated above ; store the unique primes ; find the minimum ; find the minimum ; find n ; print the n - th term of the fibonacci series ; 

prime = [True for i in range(100001)]


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


def fibonacciOfPrime(n1, n2):
    SieveOfEratosthenes()
    initial = []
    for i in range(n1, n2):
        if prime[i]:
            initial .append(i)
    now = []
    for a in initial:
        for b in initial:
            if a != b:
                c = str(a) + str(b)
                now .append(int(c))
    current = []
    for x in now:
        if prime[x]:
            current .append(x)
    current = set(current)
    first = min(current)
    second = max(current)
    count = len(current) - 1
    curr = 1
    while curr < count:
        c = first + second
        first = second
        second = c
        curr += 1
    print(c)


if __name__ == "__main__":
    x = 2
    y = 40
    fibonacciOfPrime(x, y)

# Expected output:
13158006689
# count of array elements greater than all elements on its left and next k elements on its right | python3 program to implement the above approach ; function to print the count of array elements greater than all elements on its left and next k elements on its right ; iterate over the array ; if the stack is not empty and the element at the top of the stack is smaller than arr [ i ] ; store the index of next greater element ; pop the top element ; insert the current index ; stores the count ; 

import sys


def countElements(arr, n, k):
    s = []
    next_greater = [n] * (n + 1)
    for i in range(n):
        if (len(s) == 0):
            s .append(i)
            continue
        while (len(s) != 0 and arr[s[-1]] < arr[i]):
            next_greater[s[-1]] = i
            s .pop(-1)
        s .append(i)
    count = 0
    maxi = -sys .maxsize - 1
    for i in range(n):
        if (next_greater[i] - i > k and maxi < arr[i]):
            maxi = max(maxi, arr[i])
            count += 1
    return count


if __name__ == '__main__':
    arr = [4, 2, 3, 6, 4, 3, 2]
    K = 2
    n = len(arr)
    print(countElements(arr, n, K))

# Expected output:
2
# maximize length of subarray of 1 's after removal of a pair of consecutive array elements | python program to find the maximum count of 1 s ; if arr [ i - 2 ] = = 1 then we increment the count of occurences of 1 's ; else we initialise the count with 0 ; if arr [ i + 2 ] = = 1 then we increment the count of occurences of 1 's ; else we initialise the count with 0 ; we get the maximum count by skipping the current and the next element . ; 
def maxLengthOf1s(arr, n):
    prefix = [0 for i in range(n)]
    for i in range(2, n):
        if (arr[i - 2] == 1):
            prefix[i] = prefix[i - 1] + 1
        else:
            prefix[i] = 0
    suffix = [0 for i in range(n)]
    for i in range(n - 3, -1, -1):
        if (arr[i + 2] == 1):
            suffix[i] = suffix[i + 1] + 1
        else:
            suffix[i] = 0
    ans = 0
    for i in range(n - 1):
        ans = max(ans, prefix[i + 1] + suffix[i])
    print(ans)


n = 6
arr = [1, 1, 1, 0, 1, 1]
maxLengthOf1s(arr, n)

# Expected output:
4
# minimum number of operations required to obtain a given binary string | function to find the minimum number of operations required to obtain the string s ; iterate the string s ; if first occurrence of 1 is found ; mark the index ; base case : if no 1 occurred ; no operations required ; stores the character for which last operation was performed ; stores minimum number of operations ; iterate from pos to n ; check if s [ i ] is 0 ; check if last operation was performed because of 1 ; set last to 0 ; check if last operation was performed because of 0 ; set last to 1 ; return the answer ; 
def minOperations(s):
    n = len(s)
    pos = -1
    for i in range(len(s)):
        if (s[i] == '1'):
            pos = i
            break
    if (pos == -1):
        return 0
    last = 1
    ans = 1
    for i in range(pos + 1, n):
        if (s[i] == '0'):
            if (last == 1):
                ans += 1
                last = 0
        else:
            if (last == 0):
                ans += 1
                last = 1
    return ans


if __name__ == "__main__":
    s = "10111"
    print(minOperations(s))

# Expected output:
3
# count the number of clumps in the given array | function to count the number of clumps in the given array arr [ ] ; initialise count of clumps as 0 ; traverse the arr [ ] ; whenever a sequence of same value is encountered ; return the count of clumps ; 
def countClumps(arr, N):
    clumps = 0
    i = 0
    while (i < N - 1):
        flag = 0
        while (i + 1 < N and arr[i] == arr[i + 1]):
            flag = 1
            i += 1
        if (flag):
            clumps += 1
        i += 1
    return clumps


arr = [13, 15, 66, 66, 66, 37, 37, 8, 8, 11, 11]
N = len(arr)
print(countClumps(arr, N))

# Expected output:
4
# find if string is k | find if string is k - palindrome or not using all characters exactly once python 3 program to find if string is k - palindrome or not using all characters exactly once ; when size of string is less than k ; when size of string is equal to k ; when size of string is greater than k to store the frequencies of the characters ; to store the count of characters whose number of occurrences is odd . ; iterating over the map ; 
def iskPalindromesPossible(s, k):
    if (len(s) < k):
        print("Not Possible")
        return
    if (len(s) == k):
        print("Possible")
        return
    freq = dict .fromkeys(s, 0)
    for i in range(len(s)):
        freq[s[i]] += 1
    count = 0
    for value in freq .values():
        if (value % 2 == 1):
            count += 1
    if (count > k):
        print("No")
    else:
        print("Yes")


if __name__ == '__main__':
    str1 = "poor"
    K = 3
    iskPalindromesPossible(str1, K)
    str = "geeksforgeeks"
    K = 10
    iskPalindromesPossible(str, K)

# Expected output:
Yes
Yes
# check if an array is sorted and rotated using binary search | function to return the index of the pivot ; base cases ; check if element at ( mid - 1 ) is pivot consider the cases like { 4 , 5 , 1 , 2 , 3 } ; decide whether we need to go to the left half or the right half ; function to check if a given array is sorted rotated or not ; to check if the elements to the left of the pivot are in descending or not ; to check if the elements to the right of the pivot are in ascending or not ; if any of the above if or else is true then the array is sorted rotated ; else the array is not sorted rotated ; 
def findPivot(arr, low, high):
    if (high < low):
        return -1
    if (high == low):
        return low
    mid = (low + high) // 2
    if (mid < high and arr[mid + 1] < arr[mid]):
        return mid
    if (mid > low and arr[mid] < arr[mid - 1]):
        return mid - 1
    if (arr[low] > arr[mid]):
        return findPivot(arr, low, mid - 1)
    else:
        return findPivot(arr, mid + 1, high)


def isRotated(arr, n):
    l = 0
    r = n - 1
    pivot = -1
    if (arr[l] > arr[r]):
        pivot = findPivot(arr, l, r)
        temp = pivot
        if (l < pivot):
            while (pivot > l):
                if (arr[pivot] < arr[pivot - 1]):
                    return False
                pivot -= 1
        else:
            pivot = temp
            pivot += 1
            while (pivot < r):
                if (arr[pivot] > arr[pivot + 1]):
                    return False
                pivot + +1
        return True
    else:
        return False


if __name__ == "__main__":
    arr = [3, 4, 5, 1, 2]
    if (isRotated(arr, 5)):
        print("True")
    else:
        print("False")

# Expected output:
True
# find the deepest node in a binary tree | a python3 program to find value of the deepest node in a given binary tree by method 3 ; a tree node with constructor ; constructor ; funtion to return the deepest node ; creating a queue ; iterates untill queue become empty ; 

from collections import deque


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


def deepestNode(root):
    node = None
    if root is None:
        return 0
    q = deque()
    q .append(root)
    while len(q) != 0:
        node = q .popleft()
        if node .left is not None:
            q .append(node .left)
        if node .right is not None:
            q .append(node .right)
    return node .data


if __name__ == '__main__':
    root = new_Node(1)
    root .left = new_Node(2)
    root .right = new_Node(3)
    root .left .left = new_Node(4)
    root .right .left = new_Node(5)
    root .right .right = new_Node(6)
    root .right .left .right = new_Node(7)
    root .right .right .right = new_Node(8)
    root .right .left .right .left = new_Node(9)
    levels = deepestNode(root)
    print(levels)

# Expected output:
9
# find a distinct pair ( x , y ) in given range such that x divides y | function to return the possible pair ; ans1 , ans2 store value of x and y respectively ; 
def findpair(l, r):
    ans1 = l
    ans2 = 2 * l
    print(ans1, ", ", ans2)


if __name__ == '__main__':
    l, r = 1, 10
    findpair(l, r)

# Expected output:
1 ,  2
# Jump in rank of a student after updating marks | Function to print the name of student who stood first after updation in rank ; Array of students ; Store the name of the student ; Update the marks of the student ; Store the current rank of the student ; Print the name and jump in rank ; Names of the students ; Marks of the students ; Updates that are to be done ; Number of students
def nameRank(names, marks, updates, n):
    x = [[0 for j in range(3)]for i in range(n)]
    for i in range(n):
        x[i][0] = names[i]
        x[i][1] = marks[i] + updates[i]
        x[i][2] = i + 1
    highest = x[0]
    for j in range(1, n):
        if (x[j][1] >= highest[1]):
            highest = x[j]
    print("Name: ", highest[0], ", Jump: ", abs(highest[2] - 1), sep="")


names = ["sam", "ram", "geek"]
marks = [80, 79, 75]
updates = [0, 5, -9]
n = len(marks)
nameRank(names, marks, updates, n)

# Expected output:
Name: ram, Jump: 1
# integers from the range that are composed of a single distinct digit | function to return the count of digits of a number ; function to return a number that contains only digit ' d ' repeated exactly count times ; function to return the count of integers that are composed of a single distinct digit only ; count of digits in l and r ; first digits of l and r ; if l has lesser number of digits than r ; if the number that starts with firstdigitl and has number of digits = countdigitsl is within the range include the number ; exclude the number ; if the number that starts with firstdigitr and has number of digits = countdigitsr is within the range include the number ; exclude the number ; if both l and r have equal number of digits ; include the number greater than l upto the maximum number whose digit = coutdigitsl ; exclude the numbers which are greater than r ; return the count ; 
def countDigits(n):
    count = 0
    while (n > 0):
        count += 1
        n //= 10
    return count


def getDistinct(d, count):
    num = 0
    count = pow(10, count - 1)
    while (count > 0):
        num += (count * d)
        count //= 10
    return num


def findCount(L, R):
    count = 0
    countDigitsL = countDigits(L)
    countDigitsR = countDigits(R)
    firstDigitL = (L // pow(10, countDigitsL - 1))
    firstDigitR = (R // pow(10, countDigitsR - 1))
    if (countDigitsL < countDigitsR):
        count += (9 * (countDigitsR - countDigitsL - 1))
        if (getDistinct(firstDigitL, countDigitsL) >= L):
            count += (9 - firstDigitL + 1)
        else:
            count += (9 - firstDigitL)
        if (getDistinct(firstDigitR, countDigitsR) <= R):
            count += firstDigitR
        else:
            count += (firstDigitR - 1)
    else:
        if (getDistinct(firstDigitL, countDigitsL) >= L):
            count += (9 - firstDigitL + 1)
        else:
            count += (9 - firstDigitL)
        if (getDistinct(firstDigitR, countDigitsR) <= R):
            count -= (9 - firstDigitR)
        else:
            count -= (9 - firstDigitR + 1)
    return count


L = 10
R = 50
print(findCount(L, R))

# Expected output:
4
# check if a pair with given absolute difference exists in a matrix | python 3 program to check for pairs with given difference exits in the matrix or not ; function to check if a pair with given difference exist in the matrix ; store elements in a hash ; loop to iterate over the elements of the matrix ; input matrix ; 

N = 4
M = 4


def isPairWithDiff(mat, k):
    s = set()
    for i in range(N):
        for j in range(M):
            if mat[i][j] > k:
                m = mat[i][j] - k
                if m in s:
                    return True
            else:
                m = k - mat[i][j]
                if m in s:
                    return True
            s .add(mat[i][j])
    return False


n, m = 4, 4
mat = [[5, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 100]]
k = 85
if isPairWithDiff(mat, k):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# next smaller element | prints element and nse pair for all elements of arr [ ] of size n ; push the first element to stack ; iterate for rest of the elements ; if stack is not empty , then pop an element from stack . if the popped element is greater than next , then a ) print the pair b ) keep popping while elements are greater and stack is not empty ; push next to stack so that we can find next smaller for it ; after iterating over the loop , the remaining elements in stack do not have the next smaller element , so print - 1 for them ; 
def printNSE(arr, n):
    s = []
    mp = {}
    s .append(arr[0])
    for i in range(1, n):
        if (len(s) == 0):
            s .append(arr[i])
            continue
        while (len(s) != 0 and s[-1] > arr[i]):
            mp[s[-1]] = arr[i]
            s .pop()
        s .append(arr[i])
    while (len(s) != 0):
        mp[s[-1]] = -1
        s .pop()
    for i in range(n):
        print(arr[i], "--->", mp[arr[i]])


arr = [11, 13, 21, 3]
n = len(arr)
printNSE(arr, n)

# Expected output:
11 ---> 3
13 ---> 3
21 ---> 3
3 ---> -1
# deepest left leaf node in a binary tree | iterative approach | helper function that allocates a new node with the given data and none left and right poers . ; constructor to create a new node ; utility function to return deepest left leaf node ; create a queue for level order traversal ; traverse until the queue is empty ; since we go level by level , the last stored right leaf node is deepest one ; 

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


def getDeepestLeftLeafNode(root):
    if (not root):
        return None
    q = []
    q .append(root)
    result = None
    while (len(q)):
        temp = q[0]
        q .pop(0)
        if (temp .left):
            q .append(temp .left)
            if (not temp .left .left and not temp .left .right):
                result = temp .left
        if (temp .right):
            q .append(temp .right)
    return result


if __name__ == '__main__':
    root = newnode(1)
    root .left = newnode(2)
    root .right = newnode(3)
    root .left .Left = newnode(4)
    root .right .left = newnode(5)
    root .right .right = newnode(6)
    root .right .left .right = newnode(7)
    root .right .right .right = newnode(8)
    root .right .left .right .left = newnode(9)
    root .right .right .right .right = newnode(10)
    result = getDeepestLeftLeafNode(root)
    if result:
        print("Deepest Left Leaf Node ::", result .data)
    else:
        print("No result, Left leaf not found")

# Expected output:
Deepest Left Leaf Node :: 9
# maximum elements that can be made equal with k updates | function to calculate the maximum number of equal elements possible with atmost k increment of values . here we have done sliding window to determine that whether there are x number of elements present which on increment will become equal . the loop here will run in fashion like 0. . . x - 1 , 1. . . x , 2. . . x + 1 , ... . , n - x - 1. . . n - 1 ; it can be explained with the reasoning that if for some x number of elements we can update the values then the increment to the segment ( i to j having length -> x ) so that all will be equal is ( x * maxx [ j ] ) this is the total sum of segment and ( pre [ j ] - pre [ i ] ) is present sum so difference of them should be less than k if yes , then that segment length ( x ) can be possible return true ; sort the array in ascending order ; initializing the prefix array and maximum array ; calculating prefix sum of the array ; calculating max value upto that position in the array ; binary search applied for computation here ; printing result ; 
def ElementsCalculationFunc(pre, maxx, x, k, n):
    i = 0
    j = x
    while j <= n:
        if (x * maxx[j] - (pre[j] - pre[i]) <= k):
            return True
        i += 1
        j += 1
    return False


def MaxNumberOfElements(a, n, k):
    a .sort()
    pre = [0] * (n + 1)
    maxx = [0] * (n + 1)
    for i in range(n + 1):
        pre[i] = 0
        maxx[i] = 0
    for i in range(1, n + 1):
        pre[i] = pre[i - 1] + a[i - 1]
        maxx[i] = max(maxx[i - 1], a[i - 1])
    l = 1
    r = n
    while (l < r):
        mid = (l + r) // 2
        if (ElementsCalculationFunc(pre, maxx, mid - 1, k, n)):
            ans = mid
            l = mid + 1
        else:
            r = mid - 1
    print(ans)


if __name__ == "__main__":
    arr = [2, 4, 9]
    n = len(arr)
    k = 3
    MaxNumberOfElements(arr, n, k)

# Expected output:
2
# count palindromic characteristics of a string | python program which counts different palindromic characteristics of a string . ; function which checks whether a substr [ i . . j ] of a given is a palindrome or not . ; p [ i , j ] = true if substr [ i . . j ] is palindrome , else false ; palindrome of single length ; palindrome of length 2 ; palindromes of length more then 2. this loop is similar to matrix chain multiplication . we start with a gap of length 2 and fill p table in a way that gap between starting and ending indexes increases one by one by outer loop . ; pick starting point for current gap ; set ending point ; if current string is palindrome ; function which recursively counts if a str [ i . . j ] is a k - palindromic or not . ; terminating condition for a which is a k - palindrome . ; terminating condition for a which is not a k - palindrome . ; increases the counter for the if it is a k - palindrome . ; mid is middle pointer of the str [ i ... j ] . ; if length of which is ( j - i + 1 ) is odd than we have to subtract one from mid else if even then no change . ; if the is k - palindrome then we check if it is a ( k + 1 ) - palindrome or not by just sending any of one half of the to the count_k_palindrome def . ; finding all palindromic substrings of given string ; counting k - palindromes for each and every sub of given string . . ; output the number of k - palindromic substrings of a given string . ; 

MAX_STR_LEN = 1000
P = [[0 for x in range(MAX_STR_LEN)]for y in range(MAX_STR_LEN)]
for i in range(0, MAX_STR_LEN):
    for j in range(0, MAX_STR_LEN):
        P[i][j] = False
Kpal = [0] * MAX_STR_LEN


def checkSubStrPal(str, n):
    global P, Kpal, MAX_STR_LEN
    for i in range(0, MAX_STR_LEN):
        for j in range(0, MAX_STR_LEN):
            P[i][j] = False
        Kpal[i] = 0
    for i in range(0, n):
        P[i][i] = True
    for i in range(0, n - 1):
        if (str[i] == str[i + 1]):
            P[i][i + 1] = True
    for gap in range(2, n):
        for i in range(0, n - gap):
            j = gap + i
            if (str[i] == str[j] and P[i + 1][j - 1]):
                P[i][j] = True


def countKPalindromes(i, j, k):
    global Kpal, P
    if (i == j):
        Kpal[k] = Kpal[k] + 1
        return
    if (P[i][j] == False):
        return
    Kpal[k] = Kpal[k] + 1
    mid = int((i + j) / 2)
    if ((j - i + 1) % 2 == 1):
        mid = mid - 1
    countKPalindromes(i, mid, k + 1)


def printKPalindromes(s):
    global P, Kpal, MAX_STR_LEN
    n = len(s)
    checkSubStrPal(s, n)
    for i in range(0, n):
        for j in range(0, n - i):
            countKPalindromes(j, j + i, 1)
    for i in range(1, n + 1):
        print(Kpal[i], end=" ")
    print()


s = "abacaba"
printKPalindromes(s)

# Expected output:
12 4 1 0 0 0 0
# print number in ascending order which contains 1 , 2 and 3 in their digits . | convert all numbers to strings ; check if each number in the list has 1 , 2 and 3 ; sort all the numbers ; 
def printNumbers(numbers):
    numbers = map(str, numbers)
    result = []
    for num in numbers:
        if ('1' in num and '2' in num and '3' in num):
            result .append(num)
    if not result:
        result = ['-1']
    return sorted(result)


numbers = [123, 1232, 456, 234, 32145]
result = printNumbers(numbers)
print(', '.join(num for num in result))

# Expected output:
123, 1232, 32145
# grouping countries | python3 program to count no of distinct countries from a given group of people ; answer is valid if adjacent sitting num people give same answer ; someone gives different answer ; check next person ; one valid country group has been found ; 
def countCountries(ans, N):
    total_countries = 0
    i = 0
    invalid = 0
    while (i < N):
        curr_size = ans[i]
        num = ans[i]
        while (num > 0):
            if (ans[i] != curr_size):
                print("Invalid Answer")
                return
            else:
                num = num - 1
            i = i + 1
        total_countries = total_countries + 1
    print("There are ", total_countries, " distinct companies in the group.")


ans = [1, 1, 2, 2, 4, 4, 4, 4]
n = len(ans)
countCountries(ans, n)

# Expected output:
There are  4  distinct companies in the group.