giulio98/xlcost-single-prompt huggingface dataset:
# find the player who rearranges the characters to get a palindrome string first | function that returns the winner of the game ; initialize the freq array to 0 ; iterate and count the frequencies of each character in the string ; count the odd occurring character ; if odd occurrence ; check condition for player - 1 winning the game ; 
def returnWinner(s, l):
    freq = [0 for i in range(26)]
    for i in range(0, l, 1):
        freq[ord(s[i]) - ord('a')] += 1
    cnt = 0
    for i in range(26):
        if (freq[i] % 2 != 0):
            cnt += 1
    if (cnt == 0 or cnt & 1 == 1):
        return 1
    else:
        return 2


if __name__ == '__main__':
    s = "abaaab"
    l = len(s)
    winner = returnWinner(s, l)
    print("Player-", winner)

# Expected output:
Player- 1
# maximum sum and product of the m consecutive digits in a number | python implementation of above approach ; function to find the maximum product ; 

import sys


def maxProductSum(string, m):
    n = len(string)
    maxProd, maxSum = (-(sys .maxsize) - 1, -(sys .maxsize) - 1)
    for i in range(n - m + 1):
        product, sum = 1, 0
        for j in range(i, m + i):
            product = product * (ord(string[j]) - ord('0'))
            sum = sum + (ord(string[j]) - ord('0'))
        maxProd = max(maxProd, product)
        maxSum = max(maxSum, sum)
    print("Maximum Product =", maxProd)
    print("Maximum sum =", maxSum)


if __name__ == "__main__":
    string = "3605356297"
    m = 3
    maxProductSum(string, m)

# Expected output:
Maximum Product = 126
Maximum sum = 18
# find time taken for signal to reach all positions in a string | python3 program to find time taken for signal to reach all positions in a string ; returns time needed for signal to traverse through complete string . ; for the calculation of last index ; for strings like oxoooo , xoxxoooo ; if coun is greater than max_length ; if ' x ' is present at the right side of max_length ; if ' x ' is present at left side of max_length ; we use ceiling function to handle odd number ' o ' s ; 

import sys
import math


def maxLength(s, n):
    right = 0
    left = 0
    coun = 0
    max_length = -(sys .maxsize - 1)
    s = s + '1'
    for i in range(0, n + 1):
        if s[i] == 'o':
            coun += 1
        else:
            if coun > max_length:
                right = 0
                left = 0
                if s[i] == 'x':
                    right = 1
                if i - coun > 0 and s[i - coun - 1] == 'x':
                    left = 1
                coun = math .ceil(float(coun / (right + left)))
                max_length = max(max_length, coun)
            coun = 0
    return max_length


if __name__ == '__main__':
    s = "oooxoooooooooxooo"
    n = len(s)
    print(maxLength(s, n))

# Expected output:
5
# lexicographically largest string formed from the characters in range l and r | function to return the lexicographically largest string ; hash array ; make 0 - based indexing ; iterate and count frequencies of character ; ans string ; iterate in frequency array ; add til all characters are added ; 
def printLargestString(s, l, r):
    freq = [0] * 26
    l -= 1
    r -= 1
    for i in range(min(l, r), max(l, r) + 1):
        freq[ord(s[i]) - ord('a')] += 1
    ans = ""
    for i in range(25, -1, -1):
        while (freq[i]):
            ans += chr(ord('a') + i)
            freq[i] -= 1
    return ans


if __name__ == "__main__":
    s = "striver"
    l = 3
    r = 5
    print(printLargestString(s, l, r))

# Expected output:
vri
# arrange a binary string to get maximum value within a range of indices | python implementation of the approach ; storing the count of 1 's in the string ; query of l and r ; applying range update technique . ; taking prefix sum to get the range update values ; final array which will store the arranged string ; if after maximizing the ranges any 1 is left then we maximize the string lexicographically . ; 
def arrange(s):
    cc = 0
    for i in range(len(s)):
        if (s[i] == "1"):
            cc += 1
    a = [0] * (len(s) + 1)
    qq = [(2, 3), (5, 5)]
    n = len(qq)
    for i in range(n):
        l, r = qq[i][0], qq[i][1]
        l -= 1
        r -= 1
        a[l] += 1
        a[r + 1] -= 1
    for i in range(1, len(a)):
        a[i] = a[i] + a[i - 1]
    zz = [0] * len(s)
    for i in range(len(a) - 1):
        if (a[i] > 0):
            if (cc > 0):
                zz[i] = 1
                cc -= 1
            else:
                break
        if (cc == 0):
            break
    if (cc > 0):
        for i in range(len(s)):
            if (zz[i] == 0):
                zz[i] = 1
                cc -= 1
            if (cc == 0):
                break
    print(*zz, sep="")


str = "11100"
arrange(str)

# Expected output:
01101
# check whether the vowels in a string are in alphabetical order or not | function that checks whether the vowel characters in a string are in alphabetical order or not ; ascii value 64 is less than all the alphabets so using it as a default value ; check if the vowels in the string are sorted or not ; if the vowel is smaller than the previous vowel ; store the vowel ; 
def areVowelsInOrder(s):
    n = len(s)
    c = chr(64)
    for i in range(0, n):
        if (s[i] == 'a' or s[i] == 'e' or s[i] ==
                'i' or s[i] == 'o' or s[i] == 'u'):
            if s[i] < c:
                return False
            else:
                c = s[i]
    return True


if __name__ == "__main__":
    s = "aabbbddeecc"
    if areVowelsInOrder(s):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# program to replace every space in a string with hyphen | python program for the above approach ; split by space and converting string to list and ; joining the list and storing in string ; returning thee string ; 
def printHyphen(string):
    lis = list(string .split(" "))
    string = '-'.join(lis)
    return string


string = "Text contains malayalam and level words"
print(printHyphen(string))

# Expected output:
Text-contains-malayalam-and-level-words
# rearrange the string to maximize the number of palindromic substrings | function to return the newstring ; length of string ; hashing array ; iterate and count ; resulting string ; form the resulting string ; number of times character appears ; append to resulting string ; 
def newString(s):
    l = len(s)
    freq = [0] * (26)
    for i in range(0, l):
        freq[ord(s[i]) - ord('a')] += 1
    ans = ""
    for i in range(0, 26):
        for j in range(0, freq[i]):
            ans += chr(97 + i)
    return ans


if __name__ == "__main__":
    s = "aabab"
    print(newString(s))

# Expected output:
aaabb
# program to find remainder when large number is divided by r | function to return remainder ; len is variable to store the length of number string . ; loop that find remainder ; return the remainder ; 
def Remainder(str, R):
    l = len(str)
    Rem = 0
    for i in range(l):
        Num = Rem * 10 + (ord(str[i]) - ord('0'))
        Rem = Num % R
    return Rem


if __name__ == "__main__":
    str = "13589234356546756"
    R = 13
    print(Remainder(str, R))

# Expected output:
11
# number of balanced bracket subsequence of length 2 and 4 | python 3 implementation of above approach ; taking the frequency suffix sum of the number of 2 's present  after every index ; storing the count of subsequence ; subsequence of length 2 ; subsequence of length 4 of type 1 1 2 2 ; subsequence of length 4 of type 1 2 1 2 ; 
def countWays(a, n):
    suff = [0] * n
    if (a[n - 1] == 2):
        suff[n - 1] = 1
    for i in range(n - 2, -1, -1):
        if (a[i] == 2):
            suff[i] = suff[i + 1] + 1
        else:
            suff[i] = suff[i + 1]
    ss = 0
    for i in range(n):
        if (a[i] == 1):
            ss += suff[i]
    for i in range(n):
        for j in range(i + 1, n):
            if (a[i] == 1 and a[j] == 1 and suff[j] >= 2):
                ss += (suff[j]) * (suff[j] - 1) // 2
    for i in range(n):
        for j in range(i + 1, n):
            if (a[i] == 1 and a[j] == 1 and (
                    suff[i] - suff[j]) >= 1 and suff[j] >= 1):
                ss += (suff[i] - suff[j]) * suff[j]
    print(ss)


if __name__ == "__main__":
    a = [1, 2, 1, 1, 2, 2]
    n = 6
    countWays(a, n)

# Expected output:
14
# count the number of carry operations required to add two numbers | function to count the number of carry operations ; initialize the value of carry to 0 ; counts the number of carry operations ; initialize len_a and len_b with the sizes of strings ; assigning the ascii value of the character ; add both numbers / digits ; if sum > 0 , increment count and set carry to 1 ; else , set carry to 0 ; 
def count_carry(a, b):
    carry = 0
    count = 0
    len_a = len(a)
    len_b = len(b)
    while (len_a != 0 or len_b != 0):
        x = 0
        y = 0
        if (len_a > 0):
            x = int(a[len_a - 1]) + int('0')
            len_a -= 1
        if (len_b > 0):
            y = int(b[len_b - 1]) + int('0')
            len_b -= 1
        sum = x + y + carry
        if (sum >= 10):
            carry = 1
            count += 1
        else:
            carry = 0
    return count


a = "9555"
b = "555"
count = count_carry(a, b)
if (count == 0):
    print("0")
elif (count == 1):
    print("1")
else:
    print(count)

# Expected output:
4
# check if a number is in given base or not | python3 program to check if given number is in given base or not . ; allowed bases are till 16 ( hexadecimal ) ; if base is below or equal to 10 , then all digits should be from 0 to 9. ; if base is below or equal to 16 , then all digits should be from 0 to 9 or from 'a ; 
def isInGivenBase(Str, base):
    if (base > 16):
        return False
    elif (base <= 10):
        for i in range(len(Str)):
            if (Str[i].isnumeric() and (ord(Str[i]) >= ord('0')
                                        and ord(Str[i]) < (ord('0') + base)) == False):
                return False

    else:
        for i in range(len(Str)):
            if (
                Str[i].isnumeric() and (
                    (ord(
                        Str[i]) >= ord('0') and ord(
                        Str[i]) < (
                    ord('0') +
                    base)) or (
                        ord(
                            Str[i]) >= ord('A') and ord(
                                Str[i]) < (
                                    ord('A') +
                                    base -
                            10))) == False):
                return False
    return True


Str = "AF87"
if (isInGivenBase(Str, 16)):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# find indices of all occurrence of one string in other | python program to find indices of all occurrences of one string in other . ; 
def printIndex(str, s):
    flag = False
    for i in range(len(str)):
        if (str[i:i + len(s)] == s):
            print(i, end=" ")
            flag = True
    if (flag == False):
        print("NONE")


str1 = "GeeksforGeeks"
str2 = "Geeks"
printIndex(str1, str2)

# Expected output:
0 8
# alternatively merge two strings in java | function for alternatively merging two strings ; to store the final string ; for every index in the strings ; first choose the ith character of the first string if it exists ; then choose the ith character of the second string if it exists ; 
def merge(s1, s2):
    result = ""
    i = 0
    while (i < len(s1)) or (i < len(s2)):
        if (i < len(s1)):
            result += s1[i]
        if (i < len(s2)):
            result += s2[i]
        i += 1
    return result


s1 = "geeks"
s2 = "forgeeks"
print(merge(s1, s2))

# Expected output:
gfeoerkgseeks
# maximum occurring character in an input string | set | function to find the maximum occurring character in an input string which is lexicographically first ; freq [ ] used as hash table ; to store maximum frequency ; length of str ; get frequency of each character of 'str ; for each character , where character is obtained by ( i + ' a ' ) check whether it is the maximum character so far and accodingly update 'result ; maximum occurring character ; 
def getMaxOccurringChar(str):

    freq = [0 for i in range(100)]

    max = -1

    len__ = len(str)

    for i in range(0, len__, 1):
        freq[ord(str[i]) - ord('a')] += 1

    for i in range(26):
        if (max < freq[i]):
            max = freq[i]
            result = chr(ord('a') + i)

    return result


if __name__ == '__main__':
    str = "sample program"
    print("Maximum occurring character =",
          getMaxOccurringChar(str))

# Expected output:
Maximum occurring character = a
# given two numbers as strings , find if one is a power of other | python3 program to check if one number is a power of other ; multiply the numbers . it multiplies each digit of second string to each digit of first and stores the result . ; if the digit exceeds 9 , add the cumulative carry to previous digit . ; if all zeroes , return "0" . ; remove starting zeroes . ; removes extra zeroes from front of a string . ; make sure there are no leading zeroes in the string . ; making sure that s1 is smaller . if it is greater , we recur we reversed parameters . ; 
def isGreaterThanEqualTo(s1, s2):
    if len(s1) > len(s2):
        return True
    return s1 == s2


def multiply(s1, s2):
    n, m = len(s1), len(s2)
    result = [0] * (n + m)
    for i in range(n - 1, -1, -1):
        for j in range(m - 1, -1, -1):
            result[i + j + 1] += (int(s1[i]) * int(s2[j]))
    size = len(result)
    for i in range(size - 1, 0, -1):
        if result[i] >= 10:
            result[i - 1] += result[i] // 10
            result[i] = result[i] % 10
    i = 0
    while i < size and result[i] == 0:
        i += 1
    if i == size:
        return "0"
    temp = ""
    while i < size:
        temp += str(result[i])
        i += 1
    return temp


def removeLeadingZeores(s):
    n, i = len(s), 0
    while i < n and s[i] == '0':
        i += 1
    if i == n:
        return "0"
    temp = ""
    while i < n:
        temp += s[i]
        i += 1
    return temp


def isPower(s1, s2):
    s1 = removeLeadingZeores(s1)
    s2 = removeLeadingZeores(s2)
    if s1 == "0" or s2 == "0":
        return False
    if s1 == "1" and s2 == "1":
        return True
    if s1 == "1" and s2 == "1":
        return True
    if len(s1) > len(s2):
        return isPower(s2, s1)
    temp = s1
    while not isGreaterThanEqualTo(s1, s2):
        s1 = multiply(s1, temp)
    return s1 == s2


if __name__ == "__main__":
    s1, s2 = "374747", "52627712618930723"
    if isPower(s1, s2):
        print("YES")
    else:
        print("NO")
    s1, s2 = "4099", "2"
    if isPower(s1, s2):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
NO
# check for balanced parentheses in an expression | o ( 1 ) space | function1 to match closing bracket ; function1 to match opening bracket ; function to check balanced parentheses ; helper variables ; handling case of opening parentheses ; handling case of closing parentheses ; if corresponding matching opening parentheses doesn 't lie in given  interval return 0 ; else continue ; if corresponding closing parentheses doesn 't lie in given interval, return 0 ; if found , now check for each opening and closing parentheses in this interval ; 
def matchClosing(X, start, end, open, close):
    c = 1
    i = start + 1
    while (i <= end):
        if (X[i] == open):
            c += 1
        elif (X[i] == close):
            c -= 1
        if (c == 0):
            return i
        i += 1
    return i


def matchingOpening(X, start, end, open, close):
    c = -1
    i = end - 1
    while (i >= start):
        if (X[i] == open):
            c += 1
        elif (X[i] == close):
            c -= 1
        if (c == 0):
            return i
        i -= 1
    return -1


def isBalanced(X, n):
    for i in range(n):
        if (X[i] == '('):
            j = matchClosing(X, i, n - 1, '(', ')')
        elif (X[i] == '{'):
            j = matchClosing(X, i, n - 1, '{', '}')
        elif (X[i] == '['):
            j = matchClosing(X, i, n - 1, '[', ']')
        else:
            if (X[i] == ')'):
                j = matchingOpening(X, 0, i, '(', ')')
            elif (X[i] == '}'):
                j = matchingOpening(X, 0, i, '{', '}')
            elif (X[i] == ']'):
                j = matchingOpening(X, 0, i, '[', ']')
            if (j < 0 or j >= i):
                return False
            continue
        if (j >= n or j < 0):
            return False
        start = i
        end = j
        for k in range(start + 1, end):
            if (X[k] == '('):
                x = matchClosing(X, k, end, '(', ')')
                if (not (k < x and x < end)):
                    return False
            elif (X[k] == ')'):
                x = matchingOpening(X, start, k, '(', ')')
                if (not (start < x and x < k)):
                    return False
            if (X[k] == '{'):
                x = matchClosing(X, k, end, '{', '}')
                if (not (k < x and x < end)):
                    return False
            elif (X[k] == '}'):
                x = matchingOpening(X, start, k, '{', '}')
                if (not (start < x and x < k)):
                    return False
            if (X[k] == '['):
                x = matchClosing(X, k, end, '[', ']')
                if (not (k < x and x < end)):
                    return False
            elif (X[k] == ']'):
                x = matchingOpening(X, start, k, '[', ']')
                if (not (start < x and x < k)):
                    return False
    return True


if __name__ == "__main__":
    X = "[()]()"
    n = 6
    if (isBalanced(X, n)):
        print("Yes")
    else:
        print("No")
    Y = "[[()]])"
    n = 7
    if (isBalanced(Y, n)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
No
# sorting array with conditional swapping | function to check if it is possible to sort the array ; calculating max_element at each iteration . ; if we can not swap the i - th element . ; if it is impossible to swap the max_element then we can not sort the array . ; otherwise , we can sort the array . ; 
def possibleToSort(arr, n, str):
    max_element = -1
    for i in range(len(str)):
        max_element = max(max_element, arr[i])
        if (str[i] == '0'):
            if (max_element > i + 1):
                return "No"
    return "Yes"


if __name__ == "__main__":
    arr = [1, 2, 5, 3, 4, 6]
    n = len(arr)
    str = "01110"
    print(possibleToSort(arr, n, str))

# Expected output:
Yes
# prime string | function that checks if sum is prime or not ; corner cases ; this is checked so that we can skip middle five numbers in below loop ; 
def isPrimeString(str1):
    len1 = len(str1)
    n = 0
    for i in range(len1):
        n += ord(str1[i])
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    while (i * i <= n):
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True


str1 = "geekRam"
if (isPrimeString(str1)):
    print("Yes")
else:
    print("No")

# Expected output:
No
# ways to split string such that each partition starts with distinct character | returns the number of we can split the string ; finding the frequency of each character . ; making frequency of first character of string equal to 1. ; finding the product of frequency of occurrence of each character . ; 
def countWays(s):
    count = [0] * 26
    for x in s:
        count[ord(x) - ord('a')] = (count[ord(x) - ord('a')]) + 1
    count[ord(s[0]) - ord('a')] = 1
    ans = 1
    for i in range(26):
        if (count[i] != 0):
            ans *= count[i]
    return ans


if __name__ == '__main__':
    s = "acbbcc"
    print(countWays(s))

# Expected output:
6
# lexicographically next greater string using same character set | function to print output ; to store unique characters of the string ; to check uniqueness ; if mp [ s [ i ] ] = 0 then it is first time ; sort the unique characters ; simply add n - k smallest characters ; searching the first character left of index k and not equal to greatest character of the string ; finding the just next greater character than s [ i ] ; suffix with smallest character ; if we reach here then all indices to the left of k had the greatest character ; 
def lexoString(s, k):
    n = len(s)
    v = []
    mp = {s[i]: 0 for i in range(len(s))}
    for i in range(len(s)):
        if (mp[s[i]] == 0):
            mp[s[i]] = 1
            v .append(s[i])
    v .sort(reverse=False)
    if (k > n):
        print(s, end="")
        for i in range(n, k, 1):
            print(v[0], end="")
        return
    i = k - 1
    while (i >= 0):
        if (s[i] != v[len(v) - 1]):
            for j in range(0, i, 1):
                print(s[j], end=" ")
            for j in range(0, len(v), 1):
                if (v[j] > s[i]):
                    print(v[j], end=" ")
                    break
            for j in range(i + 1, k, 1):
                print(v[0], end=" ")
            re1turn
        i -= 1
    print(
        "No lexicographically greater",
        "string of length",
        k,
        "possible here.")


if __name__ == '__main__':
    s = "gi"
    k = 3
    lexoString(s, k)

# Expected output:
gig
# number of palindromic permutations | set 1 | python3 program to find number of palindromic permutations of a given string ; returns factorial of n ; returns count of palindromic permutations of str . ; count frequencies of all characters ; since half of the characters decide count of palindromic permutations , we take ( n / 2 ) ! ; to make sure that there is at most one odd occurring char ; traverse through all counts ; to make sure that the string can permute to form a palindrome ; if there are more than one odd occurring chars ; divide all permutations with repeated characters ; 

MAX = 256


def fact(n):
    res = 1
    for i in range(2, n + 1):
        res = res * i
    return res


def countPalinPermutations(str):
    global MAX
    n = len(str)
    freq = [0] * MAX
    for i in range(0, n):
        freq[ord(str[i])] = freq[ord(str[i])] + 1
    res = fact(int(n / 2))
    oddFreq = False
    for i in range(0, MAX):
        half = int(freq[i] / 2)
        if (freq[i] % 2 != 0):
            if (oddFreq):
                return 0
            oddFreq = True
        res = int(res / fact(half))
    return res


str = "gffg"
print(countPalinPermutations(str))

# Expected output:
2
# rearrange characters to form palindrome if possible | python3 program to rearrange a string to make palindrome . ; store counts of characters ; find the number of odd elements . takes o ( n ) ; odd_cnt = 1 only if the length of str is odd ; generate first halh of palindrome ; build a string of floor ( count / 2 ) occurrences of current character ; attach the built string to end of and begin of second half ; insert odd character if there is any ; 

from collections import defaultdict


def getPalindrome(st):
    hmap = defaultdict(int)
    for i in range(len(st)):
        hmap[st[i]] += 1
    oddCount = 0
    for x in hmap:
        if (hmap[x] % 2 != 0):
            oddCount += 1
            oddChar = x
    if (oddCount > 1 or oddCount == 1 and len(st) % 2 == 0):
        return "NO PALINDROME"
    firstHalf = ""
    secondHalf = ""
    for x in sorted(hmap .keys()):
        s = (hmap[x] // 2) * x
        firstHalf = firstHalf + s
        secondHalf = s + secondHalf
    if (oddCount == 1):
        return (firstHalf + oddChar + secondHalf)
    else:
        return (firstHalf + secondHalf)


if __name__ == "__main__":
    s = "mdaam"
    print(getPalindrome(s))

# Expected output:
amdma