giulio98/xlcost-single-prompt huggingface dataset:
# maximum number of set bits count in a k | function that find maximum number of set bit appears in a substring of size k . ; traverse string 1 to k ; increment count if character is set bit ; traverse string k + 1 to length of string ; remove the contribution of the ( i - k ) th character which is no longer in the window ; add the contribution of the current character ; update maxcount at for each window of size k ; return maxcount ; 
def maxSetBitCount(s, k):
    maxCount = 0
    n = len(s)
    count = 0
    for i in range(k):
        if (s[i] == '1'):
            count += 1
    maxCount = count
    for i in range(k, n):
        if (s[i - k] == '1'):
            count -= 1
        if (s[i] == '1'):
            count += 1
        maxCount = max(maxCount, count)
    return maxCount


if __name__ == '__main__':
    s = "100111010"
    k = 3
    print(maxSetBitCount(s, k))

# Expected output:
3
# minimum characters to be deleted from the beginning of two strings to make them equal | function that finds minimum character required to be deleted ; iterate in the strings ; check if the characters are not equal ; return the result ; 
def minDel(s1, s2):
    i = len(s1)
    j = len(s2)
    while (i > 0 and j > 0):
        if (s1[i - 1] != s2[j - 1]):
            break
        i -= 1
        j -= 1
    return i + j


if __name__ == '__main__':
    s1 = "geeksforgeeks"
    s2 = "peeks"
    print(minDel(s1, s2))

# Expected output:
10
# minimum characters to be deleted from the end to make given two strings equal | function that finds minimum character required to be deleted ; iterate in the strings ; check if the characters are not equal ; return the result ; 
def minDel(s1, s2):
    i = 0
    while (i < min(len(s1), len(s2))):
        if (s1[i] != s2[i]):
            break
        i += 1
    ans = ((len(s1) - i) + (len(s2) - i))
    return ans


if __name__ == '__main__':
    s1 = "geeks"
    s2 = "geeksfor"
    print(minDel(s1, s2))

# Expected output:
3
# check if given parentheses expression is balanced or not | function to check if parenthesis are balanced ; initialising variables ; traversing the expression ; it is a closing parenthesis ; this means there are more closing parenthesis than opening ; if count is not zero , it means there are more opening parenthesis ; 
def isBalanced(exp):
    flag = True
    count = 0
    for i in range(len(exp)):
        if (exp[i] == '('):
            count += 1
        else:
            count -= 1
        if (count < 0):
            flag = False
            break
    if (count != 0):
        flag = False
    return flag


if __name__ == '__main__':
    exp1 = "((()))()()"
    if (isBalanced(exp1)):
        print("Balanced")
    else:
        print("Not Balanced")
    exp2 = "())((())"
    if (isBalanced(exp2)):
        print("Balanced")
    else:
        print("Not Balanced")

# Expected output:
Balanced
Not Balanced
# check if a given string can be formed using characters of adjacent cells of a matrix | function to check if the word exists ; if index exceeds board range ; if the current cell does not contain the required character ; if the cell contains the required character and is the last character of the word required to be matched ; return true as word is found ; mark cell visited ; check adjacent cells for the next character ; restore cell value ; 
def checkWord(board, word,
              index, row, col):
    if (row < 0 or col < 0 or
        row >= len(board) or
            col >= len(board[0])):
        return False
    if (board[row][col] != word[index]):
        return False
    elif (index == len(word) - 1):
        return True

    temp = board[row][col]
    board[row][col] = '*'
    if (checkWord(board, word,
                  index + 1,
                  row + 1, col) or
        checkWord(board, word,
                  index + 1,
                  row - 1, col) or
        checkWord(board, word,
                  index + 1,
                  row, col + 1) or
        checkWord(board, word,
                  index + 1,
                  row, col - 1)):
        board[row][col] = temp
        return True
    board[row][col] = temp
    return False


if __name__ == "__main__":

    board = [['A', 'B', 'C', 'E'],
             ['S', 'F', 'C', 'S'],
             ['A', 'D', 'E', 'E']]
    word = "CFDASABCESEE"
    f = 0

    for i in range(len(board)):
        for j in range(len(board[0])):
            if (board[i][j] == word[0] and
                checkWord(board, word,
                          0, i, j)):
                print("True")
                f = 1
                break
        if f == 1:
            break

    if f == 0:
        print("False")

# Expected output:
True
# split the number n by maximizing the count of subparts divisible by k | function to count the subparts ; total substr till now ; if it can be divided , then this substring is one of the possible answer ; convert string to long long and check if its divisible with x ; consider there is no vertical cut between this index and the next one , hence take total carrying total substr a . ; if there is vertical cut between this index and next one , then we start again with substr as " " and add b for the count of substr upto now ; return max of both the cases ; 
def count(N, X, subStr, index, n):
    if (index == n):
        return 0
    a = subStr + N[index]
    b = 0
    if (int(a) % X == 0):
        b = 1
    m1 = count(N, X, a, index + 1, n)
    m2 = b + count(N, X, "", index + 1, n)
    return max(m1, m2)


N = "00001242"
K = 3
l = len(N)
print(count(N, K, "", 0, l))

# Expected output:
6
# check if a number ends with another number or not | function to check if b is a suffix of a or not ; convert numbers into strings ; find the lengths of strings s1 and s2 ; base case ; traverse the strings s1 & s2 ; if at any index characters are unequals then return false ; return true ; 
def checkSuffix(A, B):
    s1 = str(A)
    s2 = str(B)
    n1 = len(s1)
    n2 = len(s2)
    if (n1 < n2):
        return False
    for i in range(n2):
        if (s1[n1 - i - 1] != s2[n2 - i - 1]):
            return False
    return True


A = 12345
B = 45
result = checkSuffix(A, B)
if (result):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# check if a number ends with another number or not | function to check if b is a suffix of a or not ; convert numbers into strings ; check if s2 is a suffix of s1 or not ; if result is true print " yes " ; 
def checkSuffix(A, B):
    s1 = str(A)
    s2 = str(B)
    result = s1 .endswith(s2)
    if (result):
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    A = 12345
    B = 45
    checkSuffix(A, B)

# Expected output:
Yes
# binary string with given frequencies of sums of consecutive pairs of characters | a function that generates and returns the binary string ; p : frequency of consecutive characters with sum 0 q : frequency of consecutive characters with sum 1 r : frequency of consecutive characters with sum 2 ; if no consecutive character adds up to 1 ; not possible if both p and q are non - zero ; if p is not equal to 0 ; append 0 p + 1 times ; append 1 r + 1 times ; append "01" to satisfy q ; append "0" p times ; append "1" r times ; 
def build_binary_str(p, q, r):
    ans = ""
    if (q == 0):
        if (p != 0 and r != 0):
            return "-1"
        else:
            if (p):
                temp = ""
                for i in range(p + 1):
                    temp += '0'
                ans = temp
            else:
                temp = ""
                for i in range(r + 1):
                    temp += '1'
                ans = temp
    else:
        for i in range(1, q + 2):
            if (i % 2 == 0):
                ans += '0'
            else:
                ans += '1'
        temp = ""
        for i in range(p):
            temp += '0'
        st = ""
        st += ans[0]
        st += temp
        for i in range(1, len(ans)):
            st += ans[i]
        ans = st
        temp = ""
        for i in range(r):
            temp += '1'
        ans = temp + ans
    return ans


if __name__ == '__main__':
    p = 1
    q = 2
    r = 2
    print(build_binary_str(p, q, r))

# Expected output:
111001
# check if there exists a permutation of given string which doesn 't contain any monotonous substring | function to check a string doesn 't contains a monotonous substring ; loop to iterate over the string and check that it doesn 't contains  the monotonous substring ; function to check that there exist a arrangement of string such that it doesn 't contains monotonous substring ; loop to group the characters of the string into two buckets ; sorting the two buckets ; condition to check if the concatenation point doesn 't  contains the monotonous string ; 
def check(s):
    ok = True
    for i in range(0, len(s) - 1, 1):
        ok = (ok & (abs(ord(s[i]) - ord(s[i + 1])) != 1))
    return ok


def monotonousString(s):
    odd = ""
    even = ""
    for i in range(len(s)):
        if (ord(s[i]) % 2 == 0):
            odd += s[i]
        else:
            even += s[i]
    odd = list(odd)
    odd .sort(reverse=False)
    odd = str(odd)
    even = list(even)
    even .sort(reverse=False)
    even = str(even)
    if (check(odd + even)):
        return "Yes"
    elif (check(even + odd)):
        return "Yes"
    return "No"


if __name__ == '__main__':
    str1 = "abcd"
    ans = monotonousString(str1)
    print(ans)

# Expected output:
Yes
# length of the smallest substring which contains all vowels | function to return the index for respective vowels to increase their count ; returns - 1 for consonants ; function to find the minimum length ; store the starting index of the current substring ; store the frequencies of vowels ; if the current character is a vowel ; increase its count ; move start as much right as possible ; condition for valid substring ; 
def get_index(ch):
    if (ch == 'a'):
        return 0
    elif (ch == 'e'):
        return 1
    elif (ch == 'i'):
        return 2
    elif (ch == 'o'):
        return 3
    elif (ch == 'u'):
        return 4
    else:
        return -1


def findMinLength(s):
    n = len(s)
    ans = n + 1
    start = 0
    count = [0] * 5
    for x in range(n):
        idx = get_index(s[x])
        if (idx != -1):
            count[idx] += 1
        idx_start = get_index(s[start])
        while (idx_start == -1 or count[idx_start] > 1):
            if (idx_start != -1):
                count[idx_start] -= 1
            start += 1
            if (start < n):
                idx_start = get_index(s[start])
        if (count[0] > 0 and count[1] > 0 and count[2]
                > 0 and count[3] > 0 and count[4] > 0):
            ans = min(ans, x - start + 1)
    if (ans == n + 1):
        return -1
    return ans


if __name__ == "__main__":
    s = "aaeebbeaccaaoiuooooooooiuu"
    print(findMinLength(s))

# Expected output:
9
# number of strings which starts and ends with same character after rotations | function to find the count of string with equal end after rotations ; to store the final count ; traverse the string ; if current character is same as the previous character then increment the count ; return the final count ; 
def countStrings(s):
    cnt = 0
    for i in range(1, len(s) - 1):
        if (s[i] == s[i + 1]):
            cnt += 1
    return cnt


if __name__ == '__main__':
    str = "aacbb"
    print(countStrings(str))

# Expected output:
1
# check if frequency of each character is equal to its position in english alphabet | python3 program for the above approach ; initialise frequency array ; traverse the string ; update the frequency ; check for valid string ; if frequency is non - zero ; if freq is not equals to ( i + 1 ) , then return false ; return true ; 
def checkValidString(str):
    freq = [0 for i in range(26)]
    for i in range(len(str)):
        freq[ord(str[i]) - ord('a')] += 1
    for i in range(26):
        if (freq[i] != 0):
            if (freq[i] != i + 1):
                return False
    return True


str = "abbcccdddd"
if (checkValidString(str)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# print all the non | function to print all the non - repeating words from the two given sentences ; concatenate the two strings into one ; iterating over the whole concatenated string ; searching for the word in a . if while searching , we reach the end of the string , then the word is not present in the string ; initialise word for the next iteration ; 
def removeRepeating(s1, s2):
    s3 = s1 + " " + s2 + " "
    words = ""
    i = 0
    for x in s3:
        if (x == ' '):
            if (words not in s1 or words not in s2):
                print(words, end="")
            words = " "
        else:
            words = words + x


if __name__ == "__main__":
    s1 = "I have go a pen"
    s2 = "I want to go park"
    removeRepeating(s1, s2)

# Expected output:
 have a pen I want to park
# convert the number from international system to indian system | function to convert a number represented in international numeric system to indian numeric system . ; find the length of the input string ; removing all the separators ( , ) from the input string ; reverse the input string ; declaring the output string ; process the input string ; add a separator ( , ) after the third number ; then add a separator ( , ) after every second number ; reverse the output string ; return the output string back to the main function ; 
def convert(input):
    Len = len(input)
    i = 0
    while (i < Len):
        if (input[i] == ","):
            input = input[:i] + input[i + 1:]
            Len -= 1
            i -= 1
        elif (input[i] == " "):
            input = input[:i] + input[i + 1:]
            Len -= 1
            i -= 1
        else:
            i += 1
    input = input[::-1]
    output = ""
    for i in range(Len):
        if (i == 2):
            output += input[i]
            output += " ,"
        elif (i > 2 and i % 2 == 0 and i + 1 < Len):
            output += input[i]
            output += " ,"
        else:
            output += input[i]
    output = output[::-1]
    return output


input1 = "123, 456, 789"
input2 = "90, 050, 000, 000"
print(convert(input1))
print(convert(input2))

# Expected output:
12, 34, 56, 789
90, 05, 00, 00, 000
# construct the cypher string based on the given conditions | python3 program for the above approach ; function to check whether a number is prime or not ; function to check if a prime number can be expressed as sum of two prime numbers ; if the n && ( n - 2 ) is prime ; function to check semiprime ; loop from 2 to sqrt ( num ) ; increment the count of prime numbers ; if num is greater than 1 , then add 1 to it ; return '1' if count is 2 else return '0 ; function to make the cypher string ; resultant string ; make string for the number n ; check for semiprime ; traverse to make cypher string ; if index is odd add the current character ; else current character is changed ; check for sum of two primes ; traverse to make cypher string ; if index is odd then current character is changed ; else add the current character ; if the resultant string is " " then print - 1 ; else print the resultant string ; 

import math


def isPrime(n):
    if (n <= 1):
        return False
    sqt = (int)(math .sqrt(n))
    for i in range(2, sqt):
        if (n % i == 0):
            return False
    return True


def isPossibleSum(N):
    if (isPrime(N) and isPrime(N - 2)):
        return True
    else:
        return False


def checkSemiprime(num):
    cnt = 0
    i = 2
    while cnt < 2 and i * i <= num:
        while (num % i == 0):
            num //= i
            cnt += 1
        i += 1
    if (num > 1):
        cnt += 1

    return cnt == 2


def makeCypherString(N):
    semiPrime = ""
    sumOfPrime = ""
    st = str(N)
    if (checkSemiprime(N)):
        for i in range(len(st)):
            if (i & 1):
                semiPrime += st[i]
            else:
                semiPrime += chr(ord(st[i]) - ord('0') + 65)
    if (isPossibleSum(N)):
        for i in range(len(st)):
            if (i & 1):
                sumOfPrime += chr(ord(st[i]) - ord('0') + 65)
            else:
                sumOfPrime += st[i]
    if (semiPrime + sumOfPrime == ""):
        print("-1")
    else:
        print(semiPrime + sumOfPrime)


if __name__ == "__main__":
    N = 1011243
    makeCypherString(N)

# Expected output:
B0B1C4D
# maximum splits in binary string such that each substring is divisible by given odd number | function to calculate maximum splits possible ; 
def max_segments(st, K):
    n = len(st)
    s, sum, count = 0, 0, 0
    for i in range(n - 1, -1, -1):
        a = ord(st[i]) - 48
        sum += a * pow(2, s)
        s += 1
        if (sum != 0 and sum % K == 0):
            count += 1
            sum = 0
            s = 0
    if (sum != 0):
        print("-1")
    else:
        print(count)


if __name__ == "__main__":
    st = "10111001"
    K = 5
    max_segments(st, K)

# Expected output:
2
# make the string lexicographically smallest and non palindromic by replacing exactly one character | function to find the required string ; length of the string ; iterate till half of the string ; replacing a non ' a ' char with 'a ; check if there is no ' a ' in string we replace last char of string by 'b ; if the input is a single character ; 
def findStr(S):

    S = list(S)
    n = len(S)
    for i in range(0, n // 2):
        if S[i] != 'a':
            S[i] = 'a'
            return (''.join(S))
    S[n - 1] = 'b'
    if n < 2:
        return '-1'
    else:
        return (''.join(S))


if __name__ == '__main__':

    str1 = 'a'
    print(findStr(str1))

    str2 = 'abccba'
    print(findStr(str2))

# Expected output:
-1
aaccba
# find the k | function to find the kth string in lexicographical order which consists of n - 2 xs and 2 ys ; iterate for all possible positions of left most y ; if i is the left most position of y ; put y in their positions ; 
def kth_string(n, k):
    for i in range(n - 2, -1, -1):
        if k <= (n - i - 1):
            for j in range(n):
                if (j == i or j == n - k):
                    print('Y', end="")
                else:
                    print('X', end="")
            break
        k -= (n - i - 1)


n = 5
k = 7
kth_string(n, k)

# Expected output:
YXXXY
# transform string str1 into str2 by taking characters from string str3 | function to check whether str1 can be transformed to str2 ; to store the frequency of characters of string str3 ; declare two pointers & flag ; traverse both the string and check whether it can be transformed ; if both pointers point to same characters increment them ; if the letters don 't match check  if we can find it in string c ; if the letter is available in string str3 , decrement it 's  frequency & increment the ptr2 ; if letter isn 't present in str3[]  set the flag to false and break ; if the flag is true and both pointers points to their end of respective strings then it is possible to transformed str1 into str2 , otherwise not . ; 
def convertString(str1, str2, str3):
    freq = {}
    for i in range(len(str3)):
        if (freq .get(str3[i]) is None):
            freq[str3[i]] = 1
        else:
            freq .get(str3[i], 1)
    ptr1 = 0
    ptr2 = 0
    flag = True
    while (ptr1 < len(str1) and ptr2 < len(str2)):
        if (str1[ptr1] == str2[ptr2]):
            ptr1 += 1
            ptr2 += 1
        else:
            if (freq[str3[ptr2]] > 0):
                freq[str3[ptr2]] -= 1
                ptr2 += 1
            else:
                flag = False
                break
    if (flag and ptr1 == len(str1) and ptr2 == len(str2)):
        print("YES")
    else:
        print("NO")


if __name__ == '__main__':
    str1 = "abyzfe"
    str2 = "abcdeyzf"
    str3 = "popode"
    convertString(str1, str2, str3)

# Expected output:
NO
# decrypt the string according to given algorithm | python3 implementation of the approach ; function that returns ( num % 26 ) ; initialize result ; one by one process all digits of 'num ; function to return the decrypted string ; to store the final decrypted answer ; one by one check for each character if it is a numeric character ; modulo the number found in the string by 26 ; 

MOD = 26


def modulo_by_26(num):
    res = 0

    for i in range(len(num)):
        res = ((res * 10 + ord(num[i]) - ord('0')) % MOD)
    return res


def decrypt_message(s):
    decrypted_str = ""
    num_found_so_far = ""
    for i in range(len(s)):
        if (s[i] >= '0' and s[i] <= '9'):
            num_found_so_far += s[i]
        elif (len(num_found_so_far) > 0):
            decrypted_str += chr(ord('a') + (modulo_by_26(num_found_so_far)))
            num_found_so_far = ""
    if (len(num_found_so_far) > 0):
        decrypted_str += chr(ord('a') + (modulo_by_26(num_found_so_far)))
    return decrypted_str


if __name__ == "__main__":
    s = "32ytAAcV4ui30hf10hj18"
    print(decrypt_message(s))

# Expected output:
geeks
# maximum number of overlapping string | function to find the maximum overlapping strings ; get the current character ; condition to check if the current character is the first character of the string t then increment the overlapping count ; condition to check previous character is also occurred ; update count of previous and current character ; condition to check the current character is the last character of the string t ; condition to check the every subsequence is a valid string t ; 
def maxOverlap(S, T):
    str = T
    count = [0 for i in range(len(T))]
    overlap = 0
    max_overlap = 0
    for i in range(0, len(S)):
        index = str .find(S[i])
        if (index == 0):
            overlap += 1
            if (overlap >= 2):
                max_overlap = max(overlap, max_overlap)
            count[index] += 1
        else:
            if (count[index - 1] <= 0):
                return -1
            count[index] += 1
            count[index - 1] -= 1
        if (index == 4):
            overlap -= 1
    if (overlap == 0):
        return max_overlap
    else:
        return -1


S = "chcirphirp"
T = "chirp"
print(maxOverlap(S, T))

# Expected output:
2
# minimum number of operations required to make two strings equal | python3 implementation to find the minimum number of operations to make two strings equal ; function to find out parent of an alphabet ; function to merge two different alphabets ; merge a and b using rank compression ; function to find the minimum number of operations required ; initializing parent to i and rank ( size ) to 1 ; we will store our answerin this list ; traversing strings ; if they have different parents ; find their respective parents and merge them ; store this in our answer list ; number of operations ; 

MAX = 500001
parent = [0] * MAX
Rank = [0] * MAX


def find(x):
    if parent[x] == x:
        return x
    else:
        return find(parent[x])


def merge(r1, r2):
    if (r1 != r2):
        if (Rank[r1] > Rank[r2]):
            parent[r2] = r1
            Rank[r1] += Rank[r2]
        else:
            parent[r1] = r2
            Rank[r2] += Rank[r1]


def minimumOperations(s1, s2):
    for i in range(1, 26 + 1):
        parent[i] = i
        Rank[i] = 1
    ans = []
    for i in range(len(s1)):
        if (s1[i] != s2[i]):
            if (find(ord(s1[i]) - 96) != find(ord(s2[i]) - 96)):
                x = find(ord(s1[i]) - 96)
                y = find(ord(s2[i]) - 96)
                merge(x, y)
                ans .append([s1[i], s2[i]])
    print(len(ans))
    for i in ans:
        print(i[0], "->", i[1])


if __name__ == '__main__':
    s1 = "abb"
    s2 = "dad"
    minimumOperations(s1, s2)

# Expected output:
2
a -> d
b -> a