giulio98/xlcost-single-prompt huggingface dataset:
# move spaces to front of string in single traversal | function to find spaces and move to beginning ; keep copying non - space characters ; move spaces to be beginning ; 
def moveSpaceInFront(s):
    i = len(s) - 1
    for j in range(i, -1, -1):
        if (s[j] != ' '):
            s = s[:i] + s[j] + s[i + 1:]
            i -= 1
    while (i >= 0):
        s = s[:i] + ' ' + s[i + 1:]
        i -= 1
    return s


s = "Hey there, it's GeeksforGeeks"
s = moveSpaceInFront(s)
print(s)

# Expected output:
   Heythere,it'sGeeksforGeeks
# minimum number of appends needed to make a string palindrome | checking if the string is palindrome or not ; single character is always palindrome ; pointing to first character ; pointing to last character ; recursive function to count number of appends ; removing first character of string by incrementing base address pointer . ; 
def isPalindrome(Str):
    Len = len(Str)
    if (Len == 1):
        return True
    ptr1 = 0
    ptr2 = Len - 1
    while (ptr2 > ptr1):
        if (Str[ptr1] != Str[ptr2]):
            return False
        ptr1 += 1
        ptr2 -= 1
    return True


def noOfAppends(s):
    if (isPalindrome(s)):
        return 0
    del s[0]
    return 1 + noOfAppends(s)


se = "abede"
s = [i for i in se]
print(noOfAppends(s))

# Expected output:
2
# find excel column number from column title | returns resul when we pass title . ; this process is similar to binary - to - decimal conversion ; 
def titleToNumber(s):
    result = 0
    for B in range(len(s)):
        result *= 26
        result += ord(s[B]) - ord('A') + 1
    return result


print(titleToNumber("CDA"))

# Expected output:
2133
# check whether k | php program to check if k - th bit of a given number is set or not using right shift operator . ; 
def isKthBitSet(n, k):
    if ((n >> (k - 1)) and 1):
        print("SET")
    else:
        print("NOT SET")


n, k = 5, 1
isKthBitSet(n, k)

# Expected output:
SET
# reverse string without using any temporary variable | function to reverse string and return reversed string ; iterate loop upto start not equal to end ; xor for swapping the variable ; 
def reversingString(str, start, end):
    while (start < end):
        str = (str[:start] + chr(ord(str[start])
               ^ ord(str[end])) + str[start + 1:])
        str = (str[:end] + chr(ord(str[start])
               ^ ord(str[end])) + str[end + 1:])
        str = (str[:start] + chr(ord(str[start])
               ^ ord(str[end])) + str[start + 1:])
        start += 1
        end -= 1
    return str


s = "GeeksforGeeks"
print(reversingString(s, 0, 12))

# Expected output:
skeeGrofskeeG
# check if a string follows a ^ nb ^ n pattern or not | python3 code to check a ^ nb ^ n pattern ; if length of str is odd return no ; check first half is ' a ' and other half is full of 'b ; 
def isanbn(str):
    n = len(str)
    if n & 1:
        return "No"

    for i in range(int(n / 2)):
        if str[i] != 'a' or str[n - i - 1] != 'b':
            return "No"
    return "Yes"


input_str = "ab"
print(isanbn(input_str))

# Expected output:
Yes
# number of substrings divisible by 6 in a string of integers | return the number of substring divisible by 6 and starting at index i in s [ ] and previous sum of digits modulo 3 is m . ; end of the string . ; if already calculated , return the stored value . ; converting into integer . ; increment result by 1 , if current digit is divisible by 2 and sum of digits is divisible by 3. and recur for next index with new modulo . ; returns substrings divisible by 6. ; for storing the value of all states . ; if string contain 0 , increment count by 1. ; else calculate using recursive function . pass previous sum modulo 3 as 0. ; 
def f(i, m, s, memoize):
    if (i == len(s)):
        return 0
    if (memoize[i][m] != -1):
        return memoize[i][m]
    x = ord(s[i]) - ord('0')
    ans = (((x + m) %
            3 == 0 and x %
            2 == 0) + f(i + 1, (m + x) %
                        3, s, memoize))
    memoize[i][m] = ans
    return memoize[i][m]


def countDivBy6(s):
    n = len(s)
    memoize = [[-1] * 3 for i in range(n + 1)]
    ans = 0
    for i in range(len(s)):
        if (s[i] == '0'):
            ans += 1
        else:
            ans += f(i, 0, s, memoize)
    return ans


if __name__ == '__main__':
    s = "4806"
    print(countDivBy6(s))

# Expected output:
5
# lexicographically first palindromic string | python3 program to find first palindromic permutation of given string ; function to count frequency of each char in the string . freq [ 0 ] for ' a ' , ... . , freq [ 25 ] for 'z ; cases to check whether a palindr0mic string can be formed or not ; count_odd to count no of chars with odd frequency ; for even length string no odd freq character ; for odd length string one odd freq character ; function to find odd freq char and reducing its freq by 1 returns " " if odd freq char is not present ; to find lexicographically first palindromic string . ; assigning odd freq character if present else empty string . ; traverse characters in increasing order ; divide all occurrences into two halves . note that odd character is removed by findoddandremoveitsfreq ( ) ; creating front string ; creating rear string ; final palindromic string which is lexicographically first ; 

MAX_CHAR = 26


def countFreq(str1, freq, len1):
    for i in range(len1):
        freq[ord(str1[i]) - ord('a')] += 1


def canMakePalindrome(freq, len1):
    count_odd = 0
    for i in range(MAX_CHAR):
        if (freq[i] % 2 != 0):
            count_odd += 1
    if (len1 % 2 == 0):
        if (count_odd > 0):
            return False
        else:
            return True
    if (count_odd != 1):
        return False
    return True


def findOddAndRemoveItsFreq(freq):
    odd_str = ""
    for i in range(MAX_CHAR):
        if (freq[i] % 2 != 0):
            freq[i] -= 1
            odd_str += chr(i + ord('a'))
            return odd_str
    return odd_str


def findPalindromicString(str1):
    len1 = len(str1)
    freq = [0] * MAX_CHAR
    countFreq(str1, freq, len1)
    if (canMakePalindrome(freq, len1) == False):
        return "No Palindromic String"
    odd_str = findOddAndRemoveItsFreq(freq)
    front_str = ""
    rear_str = " "
    for i in range(MAX_CHAR):
        temp = ""
        if (freq[i] != 0):
            ch = chr(i + ord('a'))
            for j in range(1, int(freq[i] / 2) + 1):
                temp += ch
            front_str += temp
            rear_str = temp + rear_str
    return (front_str + odd_str + rear_str)


str1 = "malayalam"
print(findPalindromicString(str1))

# Expected output:
aalmymlaa
# count substrings with same first and last characters | returns true if first and last characters of s are same . ; starting point of substring ; length of substring ; check if current substring has same starting and ending characters . ; 
def checkEquality(s):
    return (ord(s[0]) == ord(s[len(s) - 1]))


def countSubstringWithEqualEnds(s):
    result = 0
    n = len(s)
    for i in range(n):
        for j in range(1, n - i + 1):
            if (checkEquality(s[i:i + j])):
                result += 1
    return result


s = "abcab"
print(countSubstringWithEqualEnds(s))

# Expected output:
7
# count substrings with same first and last characters | space efficient python3 program to count all substrings with same first and last characters . ; iterating through all substrings in way so that we can find first and last character easily ; 
def countSubstringWithEqualEnds(s):
    result = 0
    n = len(s)
    for i in range(n):
        for j in range(i, n):
            if (s[i] == s[j]):
                result = result + 1
    return result


s = "abcab"
print(countSubstringWithEqualEnds(s))

# Expected output:
7
# find the missing number in a string of numbers with no separator | python3 program to find a missing number in a string of consecutive numbers without any separator . ; gets the integer at position i with length m , returns it or - 1 , if none ; find value at index i and length m . ; returns value of missing number ; try all lengths for first number ; get value of first number with current length ; to store missing number of current length ; to indicate whether the sequence failed anywhere for current length . ; find subsequent numbers with previous number as n ; if we haven 't yet found  the missing number for  current length. next  number is n+2. note  that we use log10 as  (n+2) may have more  length than n. ; if next value is ( n + 1 ) ; not found or no missing number ; 

import math
MAX_DIGITS = 6


def getValue(Str, i, m):
    if (i + m > len(Str)):
        return -1
    value = 0
    for j in range(m):
        c = (ord(Str[i + j]) - ord('0'))
        if (c < 0 or c > 9):
            return -1
        value = value * 10 + c
    return value


def findMissingNumber(Str):
    for m in range(1, MAX_DIGITS + 1):
        n = getValue(Str, 0, m)
        if (n == -1):
            break
        missingNo = -1
        fail = False
        i = m
        while (i != len(Str)):
            if ((missingNo == -1) and (getValue(Str, i,
                                                1 + int(math .log10(n + 2))) == n + 2)):
                missingNo = n + 1
                n += 2
            elif ((getValue(Str, i, 1 + int(math .log10(n + 1))) == n + 1)):
                n += 1
            else:
                fail = True
                break
            i += 1 + int(math .log10(n))
        if (not fail):
            return missingNo
    return -1


print(findMissingNumber("99101102"))

# Expected output:
100
# maximum consecutive repeating character in string | function to find out the maximum repeating character in given string ; find the maximum repeating character starting from str [ i ] ; update result if required ; 
def maxRepeating(str):
    l = len(str)
    count = 0
    res = str[0]
    for i in range(l):
        cur_count = 1
        for j in range(i + 1, l):
            if (str[i] != str[j]):
                break
            cur_count += 1
        if cur_count > count:
            count = cur_count
            res = str[i]
    return res


if __name__ == "__main__":
    str = "aaaabbaaccde"
    print(maxRepeating(str))

# Expected output:
a
# sum of two large numbers | function for finding sum of larger numbers ; before proceeding further , make sure length of str2 is larger . ; take an empty string for storing result ; calculate length of both string ; reverse both of strings ; do school mathematics , compute sum of current digits and carry ; calculate carry for next step ; add remaining digits of larger number ; add remaining carry ; reverse resultant string ; 
def findSum(str1, str2):
    if (len(str1) > len(str2)):
        t = str1
        str1 = str2
        str2 = t
    str = ""
    n1 = len(str1)
    n2 = len(str2)
    str1 = str1[::-1]
    str2 = str2[::-1]
    carry = 0
    for i in range(n1):
        sum = ((ord(str1[i]) - 48) + ((ord(str2[i]) - 48) + carry))
        str += chr(sum % 10 + 48)
        carry = int(sum / 10)
    for i in range(n1, n2):
        sum = ((ord(str2[i]) - 48) + carry)
        str += chr(sum % 10 + 48)
        carry = (int)(sum / 10)
    if (carry):
        str += chr(carry + 48)
    str = str[::-1]
    return str


str1 = "12"
str2 = "198111"
print(findSum(str1, str2))

# Expected output:
198123
# sum of two large numbers | function for finding sum of larger numbers ; before proceeding further , make sure length of str2 is larger . ; take an empty string for storing result ; calculate length of both string ; initially take carry zero ; traverse from end of both strings ; do school mathematics , compute sum of current digits and carry ; add remaining digits of str2 [ ] ; add remaining carry ; reverse resultant string ; 
def findSum(str1, str2):
    if len(str1) > len(str2):
        temp = str1
        str1 = str2
        str2 = temp
    str3 = ""
    n1 = len(str1)
    n2 = len(str2)
    diff = n2 - n1
    carry = 0
    for i in range(n1 - 1, -1, -1):
        sum = ((ord(str1[i]) - ord('0')) +
               int((ord(str2[i + diff]) - ord('0'))) + carry)
        str3 = str3 + str(sum % 10)
        carry = sum // 10
    for i in range(n2 - n1 - 1, -1, -1):
        sum = ((ord(str2[i]) - ord('0')) + carry)
        str3 = str3 + str(sum % 10)
        carry = sum // 10
    if (carry):
        str3 + str(carry + '0')
    str3 = str3[::-1]
    return str3


if __name__ == "__main__":
    str1 = "12"
    str2 = "198111"
    print(findSum(str1, str2))

# Expected output:
198123
# palindrome pair in an array of words ( or strings ) | utility function to check if a string is a palindrome ; compare each character from starting with its corresponding character from last ; function to check if a palindrome pair exists ; consider each pair one by one ; concatenate both strings ; check if the concatenated string is palindrome ; check for other combination of the two strings ; 
def isPalindrome(st):
    length = len(st)
    for i in range(length // 2):
        if (st[i] != st[length - i - 1]):
            return False
    return True


def checkPalindromePair(vect):
    for i in range(len(vect) - 1):
        for j in range(i + 1, len(vect)):
            check_str = vect[i] + vect[j]
            if (isPalindrome(check_str)):
                return True
            check_str = vect[j] + vect[i]
            if (isPalindrome(check_str)):
                return True
    return False


if __name__ == "__main__":
    vect = ["geekf", "geeks", "or", "keeg", "abc", "bc"]
    if checkPalindromePair(vect):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# print consecutive characters together in a line | python3 program to print consecutive characters together in a line . ; 
def _print(string):
    print(string[0], end="")
    for i in range(1, len(string)):
        if (ord(string[i]) == ord(string[i - 1]) +
                1 or ord(string[i]) == ord(string[i - 1]) - 1):
            print(string[i], end="")
        else:
            print()
            print(string[i], end="")


if __name__ == "__main__":
    string = "ABCXYZACCD"
    _print(string)

# Expected output:
ABC
XYZ
A
C
CD
# efficiently check if a string has all unique characters without using any additional data structure | returns true if all characters of str are unique . assumptions : ( 1 ) str contains only characters from ' a ' to ' z ' ( 2 ) integers are stored using 32 bits ; an integer to store presence / absence of 26 characters using its 32 bits ; if bit corresponding to current character is already set ; set bit in checker ; 
def areCharactersUnique(s):
    checker = 0
    for i in range(len(s)):
        val = ord(s[i]) - ord('a')
        if (checker & (1 << val)) > 0:
            return False
        checker |= (1 << val)
    return True


s = "aaabbccdaa"
if areCharactersUnique(s):
    print("Yes")
else:
    print("No")

# Expected output:
No
# count of words whose i | return the count of words . ; if word contain single letter , return 1. ; checking for first letter . ; traversing the string and multiplying for combinations . ; if all three letters are same . ; if two letter are distinct . ; if all three letter are distinct . ; checking for last letter . ; 
def countWords(str, l):
    count = 1
    if (l == 1):
        return count
    if (str[0] == str[1]):
        count *= 1
    else:
        count *= 2
    for j in range(1, l - 1):
        if (str[j] == str[j - 1] and str[j] == str[j + 1]):
            count *= 1
        elif (str[j] == str[j - 1] or str[j] == str[j + 1] or str[j - 1] == str[j + 1]):
            count *= 2
        else:
            count *= 3
    if (str[l - 1] == str[l - 2]):
        count *= 1
    else:
        count *= 2
    return count


if __name__ == "__main__":
    str = "abc"
    l = len(str)
    print(countWords(str, l))

# Expected output:
12
# maximum and minimum sums from two numbers with digit replacements | find new value of x after replacing digit " from " to " to " ; required digit found , replace it ; returns maximum and minimum possible sums of x1 and x2 if digit replacements are allowed . ; we always get minimum sum if we replace 6 with 5. ; we always get maximum sum if we replace 5 with 6. ; 
def replaceDig(x, from1, to):
    result = 0
    multiply = 1
    while (x > 0):
        reminder = x % 10
        if (reminder == from1):
            result = result + to * multiply
        else:
            result = result + reminder * multiply
        multiply *= 10
        x = int(x / 10)
    return result


def calculateMinMaxSum(x1, x2):
    minSum = replaceDig(x1, 6, 5) + replaceDig(x2, 6, 5)
    maxSum = replaceDig(x1, 5, 6) + replaceDig(x2, 5, 6)
    print("Minimum sum =", minSum)
    print("Maximum sum =", maxSum, end=" ")


if __name__ == '__main__':
    x1 = 5466
    x2 = 4555
    calculateMinMaxSum(x1, x2)

# Expected output:
Minimum sum = 10010
Maximum sum = 11132
# partition a number into two divisible parts | finds if it is possible to partition str into two parts such that first part is divisible by a and second part is divisible by b . ; create an array of size lenn + 1 and initialize it with 0. store remainders from left to right when divided by 'a ; compute remainders from right to left when divided by 'b ; find a pothat can partition a number ; if split is not possible at this point ; we can split at i if one of the following two is true . a ) all characters after str [ i ] are 0 b ) after str [ i ] is divisible by b , i . e . , str [ i + 1. . n - 1 ] is divisible by b . ; 
def findDivision(str, a, b):
    lenn = len(str)
    lr = [0] * (lenn + 1)
    lr[0] = (int(str[0])) % a
    for i in range(1, lenn):
        lr[i] = ((lr[i - 1] * 10) % a + int(str[i])) % a
    rl = [0] * (lenn + 1)
    rl[lenn - 1] = int(str[lenn - 1]) % b
    power10 = 10
    for i in range(lenn - 2, -1, -1):
        rl[i] = (rl[i + 1] + int(str[i]) * power10) % b
        power10 = (power10 * 10) % b
    for i in range(0, lenn - 1):
        if (lr[i] != 0):
            continue
        if (rl[i + 1] == 0):
            print("YES")
            for k in range(0, i + 1):
                print(str[k], end="")

            print(",", end=" ")

            for i in range(i + 1, lenn):
                print(str[k], end="")
                return

    print("NO")


str = "123"
a, b = 12, 3
findDivision(str, a, b)

# Expected output:
YES
12, 2
# efficient method for 2 's complement of a binary string | function to find two 's complement ; traverse the string to get first '1' from the last of string ; if there exists no '1' concatenate 1 at the starting of string ; continue traversal after the position of first '1 ; just flip the values ; return the modified string ; 
def findTwoscomplement(str):
    n = len(str)
    i = n - 1
    while (i >= 0):
        if (str[i] == '1'):
            break

        i -= 1
    if (i == -1):
        return '1'+str
    k = i - 1
    while (k >= 0):
        if (str[k] == '1'):
            str = list(str)
            str[k] = '0'
            str = ''.join(str)
        else:
            str = list(str)
            str[k] = '1'
            str = ''.join(str)

        k -= 1
    return str


if __name__ == '__main__':
    str = "00000101"
    print(findTwoscomplement(str))

# Expected output:
11111011
# check length of a string is equal to the number appended at its last | function to find if given number is equal to length or not ; traverse string from end and find the number stored at the end . x is used to store power of 10. ; check if number is equal to string length except that number 's digits ; 
def isequal(str):
    n = len(str)
    num = 0
    x = 1
    i = n - 1
    for i in range(n - 1, -1, -1):
        if ('0' <= str[i] and str[i] <= '9'):
            num = (ord(str[i]) - ord('0')) * x + num
            x = x * 10
            if (num >= n):
                return false
        else:
            break
    return num == i + 1


if __name__ == "__main__":
    str = "geeksforgeeks13"
    print("Yes")if isequal(str)else print("No")

# Expected output:
Yes
# check if two strings are k | python 3 program for the above approach ; function to check k anagram of two strings ; first condition : if both the strings have different length , then they cannot form anagram ; converting str1 to character array arr1 ; converting str2 to character array arr2 ; sort arr1 in increasing order ; sort arr2 in increasing order ; iterate till str1 . length ( ) ; condition if arr1 [ i ] is not equal to arr2 [ i ] then add it to list ; condition to check if strings for k - anagram or not ; 

import sys


def kAnagrams(str1, str2, k):
    flag = 0
    list1 = []
    if (len(str1) != len(str2)):
        sys .exit()
    arr1 = list(str1)
    arr2 = list(str2)
    arr1 .sort()
    arr2 .sort()
    for i in range(len(str1)):
        if (arr1[i] != arr2[i]):
            list1 .append(arr2[i])
    if (len(list1) <= k):
        flag = 1
    if (flag == 1):
        return True
    else:
        return False


if __name__ == "__main__":
    str1 = "fodr"
    str2 = "gork"
    k = 2
    kAnagrams(str1, str2, k)
    if (kAnagrams(str1, str2, k)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# minimum number of characters to be removed to make a binary string alternate | returns count of minimum characters to be removed to make s alternate . ; if two alternating characters of string are same ; result += 1 then need to delete a character ; 
def countToMake0lternate(s):

    result = 0

    for i in range(len(s) - 1):
        if (s[i] == s[i + 1]):
            result += 1

    return result


if __name__ == "__main__":
    print(countToMake0lternate("000111"))
    print(countToMake0lternate("11111"))
    print(countToMake0lternate("01010101"))

# Expected output:
4
4
0
# convert to a string that is repetition of a substring of k length | returns true if s can be converted to a with k repeated subs after replacing k characters . ; length of must be a multiple of k ; map to store s of length k and their counts ; if is already a repetition of k subs , return true . ; if number of distinct subs is not 2 , then not possible to replace a . ; one of the two distinct must appear exactly once . either the first entry appears once , or it appears n / k - 1 times to make other sub appear once . ; 
def check(S, k):
    n = len(S)
    if (n % k != 0):
        return False
    mp = {}
    for i in range(0, n, k):
        mp[S[i:k]] = mp .get(S[i:k], 0) + 1
    if (len(mp) == 1):
        return True
    if (len(mp) != 2):
        return False
    for i in mp:
        if i == (n // k - 1) or mp[i] == 1:
            return True
    return False


if check("abababcd", 2):
    print("Yes")
else:
    print("No")

# Expected output:
Yes
# group all occurrences of characters according to first appearance | since only lower case characters are there ; function to print the string ; initialize counts of all characters as 0 ; count occurrences of all characters in string ; starts traversing the string ; print the character till its count in hash array ; make this character 's count value as 0. ; 

MAX_CHAR = 26


def printGrouped(string):
    n = len(string)
    count = [0] * MAX_CHAR
    for i in range(n):
        count[ord(string[i]) - ord("a")] += 1
    for i in range(n):
        while count[ord(string[i]) - ord("a")]:
            print(string[i], end="")
            count[ord(string[i]) - ord("a")] -= 1
        count[ord(string[i]) - ord("a")] = 0


if __name__ == "__main__":
    string = "geeksforgeeks"
    printGrouped(string)

# Expected output:
ggeeeekkssfor