giulio98/xlcost-single-prompt huggingface dataset:
# balance a string after removing extra brackets | print balanced and remove extra brackets from string ; maintain a count for opening brackets traversing string ; check if opening bracket ; print str [ i ] and increment count by 1 ; check if closing bracket and count != 0 ; decrement count by 1 ; if str [ i ] not a closing brackets print it ; balanced brackets if opening brackets are more then closing brackets ; print remaining closing brackets ; 
def balancedString(str):
    count, i = 0, 0
    n = len(str)
    for i in range(n):
        if (str[i] == '('):
            print(str[i], end="")
            count += 1
        elif (str[i] == ')' and count != 0):
            print(str[i], end="")
            count -= 1
        elif (str[i] != ')'):
            print(str[i], end="")
    if (count != 0):
        for i in range(count):
            print(")", end="")


if __name__ == '__main__':
    str = "gau)ra)v(ku(mar(rajput))"
    balancedString(str)

# Expected output:
gaurav(ku(mar(rajput)))
# minimum operation require to make first and last character same | python3 program to minimum operation require to make first and last character same ; recursive function call ; decrement ending index only ; increment starting index only ; increment starting index and decrement index ; 

import sys
MAX = sys .maxsize


def minOperation(s, i, j, count):
    if ((i >= len(s) and j < 0) or (i == j)):
        return MAX
    if (s[i] == s[j]):
        return count
    if (i >= len(s)):
        return minOperation(s, i, j - 1, count + 1)
    elif (j < 0):
        return minOperation(s, i + 1, j, count + 1)
    else:
        return min(
            minOperation(
                s,
                i,
                j - 1,
                count + 1),
            minOperation(
                s,
                i + 1,
                j,
                count + 1))


if __name__ == '__main__':
    s = "bacdefghipalop"
    ans = minOperation(s, 0, len(s) - 1, 0)
    if (ans == MAX):
        print(-1)
    else:
        print(ans)

# Expected output:
4
# count strings with consonants and vowels at alternate position | function to find the count of strings ; variable to store the final result ; loop iterating through string ; if ' $ ' is present at the even position in the string ; ' sum ' is multiplied by 21 ; if ' $ ' is present at the odd position in the string ; ' sum ' is multiplied by 5 ; 
def countStrings(s):
    sum = 1
    for i in range(len(s)):
        if (i % 2 == 0 and s[i] == '$'):
            sum *= 21
        elif (s[i] == '$'):
            sum *= 5
    return sum


if __name__ == "__main__":
    str = "s$$e$"
    print(countStrings(str))

# Expected output:
2205
# remove duplicates from a string in o ( 1 ) extra space | function to remove duplicates ; keeps track of visited characters ; gets character value ; keeps track of length of resultant string ; check if xth bit of counter is unset ; mark current character as visited ; 
def removeDuplicatesFromString(str2):
    counter = 0
    i = 0
    size = len(str2)
    str1 = list(str2)
    x = 0
    length = 0
    while (i < size):
        x = ord(str1[i]) - 97
        if ((counter & (1 << x)) == 0):
            str1[length] = chr(97 + x)
            counter = counter | (1 << x)
            length += 1
        i += 1
    str2 = ''.join(str1)
    return str2[0:length]


str1 = "geeksforgeeks"
print(removeDuplicatesFromString(str1))

# Expected output:
geksfor
# remove duplicates from a string in o ( 1 ) extra space | method to remove duplicates ; table to keep track of visited characters ; to keep track of end index of resultant string ; 
def removeDuplicatesFromString(string):
    table = [0 for i in range(256)]
    endIndex = 0
    string = list(string)
    for i in range(len(string)):
        if (table[ord(string[i])] == 0):
            table[ord(string[i])] = -1
            string[endIndex] = string[i]
            endIndex += 1
    ans = ""
    for i in range(endIndex):
        ans += string[i]
    return ans


if __name__ == '__main__':
    temp = "geeksforgeeks"
    print(removeDuplicatesFromString(temp))

# Expected output:
geksfor
# check if the characters in a string form a palindrome in o ( 1 ) extra space | utility function to get the position of first character in the string ; get the position of first character in the string ; utility function to get the position of last character in the string ; get the position of last character in the string ; function to check if the characters in the given string forms a palindrome in o ( 1 ) extra space ; break , when all letters are checked ; if mismatch found , break the loop ; 
def firstPos(str, start, end):
    firstChar = -1
    for i in range(start, end + 1):
        if (str[i] >= 'a' and str[i] <= 'z'):
            firstChar = i
            break
    return firstChar


def lastPos(str, start, end):
    lastChar = -1
    for i in range(start, end - 1, -1):
        if (str[i] >= 'a' and str[i] <= 'z'):
            lastChar = i
            break
    return lastChar


def isPalindrome(str):
    firstChar = 0
    lastChar = len(str) - 1
    ch = True
    for i in range(len(str)):
        firstChar = firstPos(str, firstChar, lastChar)
        lastChar = lastPos(str, lastChar, firstChar)
        if (lastChar < 0 or firstChar < 0):
            break
        if (str[firstChar] == str[lastChar]):
            firstChar += 1
            lastChar -= 1
            continue
        ch = False
        break
    return (ch)


if __name__ == "__main__":
    str = "mTABSYMBOLa 343 la y a l am"
    if (isPalindrome(str)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# maximum length subsequence possible of the form r ^ n k ^ n | function to calculate the maximum length of substring of the form r ^ nk ^ n ; count no . of r 's before a k ; count no . of k 's after a k ; update maximum length ; 
def find(s):
    Max = j = countk = countr = 0
    table = [[0, 0]for i in range(len(s))]
    for i in range(0, len(s)):
        if s[i] == 'R':
            countr += 1
        else:
            table[j][0] = countr
            j += 1
    j -= 1
    for i in range(len(s) - 1, -1, -1):
        if s[i] == 'K':
            countk += 1
            table[j][1] = countk
            j -= 1
        if min(table[j + 1][0], table[j + 1][1]) > Max:
            Max = min(table[j + 1][0], table[j + 1][1])
    return Max


if __name__ == "__main__":
    s = "RKRRRKKRRKKKKRR"
    print(find(s))

# Expected output:
4
# check if two strings are permutation of each other | function to check whether two strings are permutation of each other ; get lengths of both strings ; if length of both strings is not same , then they cannot be permutation ; sort both strings ; compare sorted strings ; 
def arePermutation(str1, str2):
    n1 = len(str1)
    n2 = len(str2)
    if (n1 != n2):
        return False
    a = sorted(str1)
    str1 = " ".join(a)
    b = sorted(str2)
    str2 = " ".join(b)
    for i in range(0, n1, 1):
        if (str1[i] != str2[i]):
            return False
    return True


if __name__ == '__main__':
    str1 = "test"
    str2 = "ttew"
    if (arePermutation(str1, str2)):
        print("Yes")
    else:
        print("No")

# Expected output:
No
# maximum power of jump required to reach the end of string | function to calculate the maximum power of the jump ; initialize the count with 1 ; find the character at last index ; start traversing the string ; check if the current char is equal to the last character ; max_so_far stores maximum value of the power of the jump from starting to ith position ; reset the count to 1 ; else , increment the number of jumps / count ; return the maximum number of jumps ; 
def powerOfJump(s):
    count = 1
    max_so_far = 0
    ch = s[-1]
    for i in range(0, len(s)):
        if s[i] == ch:
            if count > max_so_far:
                max_so_far = count
            count = 1
        else:
            count += 1
    return max_so_far


if __name__ == "__main__":
    st = "1010101"
    print(powerOfJump(st))

# Expected output:
2
# longest substring with count of 1 s more than 0 s | function to find longest substring having count of 1 s more than count of 0 s . ; to store sum . ; to store first occurrence of each sum value . ; to store maximum length . ; to store current substring length . ; add 1 if current character is 1 else subtract 1. ; if sum is positive , then maximum length substring is bin1 [ 0. . i ] ; if sum is negative , then maximum length substring is bin1 [ j + 1. . i ] , where sum of substring bin1 [ 0. . j ] is sum - 1. ; make entry for this sum value in hash table if this value is not present . ; 
def findLongestSub(bin1):
    n = len(bin1)
    sum = 0
    prevSum = {i: 0 for i in range(n)}
    maxlen = 0
    for i in range(n):
        if (bin1[i] == '1'):
            sum += 1
        else:
            sum -= 1
        if (sum > 0):
            maxlen = i + 1
        elif (sum <= 0):
            if ((sum - 1) in prevSum):
                currlen = i - prevSum[sum - 1]
                maxlen = max(maxlen, currlen)
        if ((sum)not in prevSum):
            prevSum[sum] = i
    return maxlen


if __name__ == '__main__':
    bin1 = "1010"
    print(findLongestSub(bin1))

# Expected output:
3
# average of ascii values of characters of a given string | function to find average of ascii value of chars ; loop to sum the ascii value of chars ; returning average of chars ; 
def averageValue(s):
    sum_char = 0
    for i in range(len(s)):
        sum_char += ord(s[i])
    return sum_char // len(s)


if __name__ == "__main__":
    s = "GeeksforGeeks"
    print(averageValue(s))

# Expected output:
101
# check if two same sub | function to check if similar subsequences occur in a string or not ; iterate and count the frequency ; counting frequency of the letters ; check if frequency is more than once of any character ; 
def check(s, l):
    freq = [0 for i in range(26)]
    for i in range(l):
        freq[ord(s[i]) - ord('a')] += 1
    for i in range(26):
        if (freq[i] >= 2):
            return True
    return False


if __name__ == '__main__':
    s = "geeksforgeeks"
    l = len(s)
    if (check(s, l)):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# find the winner of a game where scores are given as a binary string | function for winner prediction ; increase count ; check losing condition ; check winning condition ; check tie on n - 1 point ; increase count ; check for 2 point lead ; condition of lost ; condition of win ; 
def predictWinner(score, n):
    count = [0 for i in range(2)]
    for i in range(0, len(score), 1):
        index = ord(score[i]) - ord('0')
        count[index] += 1
        if (count[0] == n and count[1] < n - 1):
            print("GEEKS lost", end=" ")
            return
        if (count[1] == n and count[0] < n - 1):
            print("GEEKS won", end=" ")
            return
        if (count[0] == n - 1 and count[1] == n - 1):
            count[0] = 0
            count[1] = 0
            break
    i += 1
    for i in range(i, len(score), 1):
        index = ord(score[i]) - ord('0')
        count[index] += 1
        if (abs(count[0] - count[1]) == 2):
            if (count[0] > count[1]):
                print("GEEKS lost", end=" ")
            else:
                print("GEEKS won", end=" ")
            return


if __name__ == '__main__':
    score = "1001010101111011101111"
    n = 15
    predictWinner(score, n)

# Expected output:
GEEKS won
# number of counterclockwise shifts to make a string palindrome | function to check if given string is palindrome or not . ; function to find counter clockwise shifts to make string palindrome . ; pointer to starting of current shifted string . ; pointer to ending of current shifted string . ; concatenate string with itself ; to store counterclockwise shifts ; move left and right pointers one step at a time . ; check if current shifted string is palindrome or not ; if string is not palindrome then increase count of number of shifts by 1. ; 
def isPalindrome(str, l, r):
    while (l < r):
        if (str[l] != str[r]):
            return False
        l += 1
        r -= 1
    return True


def CyclicShifts(str):
    n = len(str)
    left = 0
    right = n - 1
    str = str + str
    cnt = 0
    while (right < 2 * n - 1):
        if (isPalindrome(str, left, right)):
            break
        cnt += 1
        left += 1
        right += 1
    return cnt


if __name__ == "__main__":
    str = "bccbbaab"
    print(CyclicShifts(str))

# Expected output:
2
# find a string such that every character is lexicographically greater than its immediate next character | function that prints the required string ; find modulus with 26 ; print extra characters required ; print the given reverse string countofstr times ; 
def printString(n, str):
    str2 = ""
    extraChar = n % 26
    if (extraChar >= 1):
        for i in range(26 - (extraChar + 1), 26):
            str2 += str[i]
    countOfStr = n // 26
    for i in range(1, countOfStr + 1):
        for j in range(26):
            str2 += str[j]
    return str2


if __name__ == "__main__":
    n = 30
    str = "zyxwvutsrqponmlkjihgfedcba"
    print(printString(n, str))

# Expected output:
edcbazyxwvutsrqponmlkjihgfedcba
# longest common prefix matching | set | a utility function to find the common prefix between first and last strings ; compare str1 and str2 ; a function that returns the longest common prefix from the array of strings ; sorts the n set of strings ; prints the common prefix of the first and the last string of the set of strings ; 
def commonPrefixUtil(str1, str2):
    n1 = len(str1)
    n2 = len(str2)
    result = ""
    j = 0
    i = 0
    while (i <= n1 - 1 and j <= n2 - 1):
        if (str1[i] != str2[j]):
            break
        result += (str1[i])
        i += 1
        j += 1
    return (result)


def commonPrefix(arr, n):
    arr .sort(reverse=False)
    print(commonPrefixUtil(arr[0], arr[n - 1]))


if __name__ == '__main__':
    arr = ["geeksforgeeks", "geeks", "geek", "geezer"]
    n = len(arr)
    commonPrefix(arr, n)

# Expected output:
gee
# square of large number represented as string | multiplies str1 and str2 , and prints result . ; will keep the result number in vector in reverse order ; below two indexes are used to find positions in result . ; go from right to left in num1 ; to shift position to left after every multiplication of a digit in num2 ; go from right to left in num2 ; take current digit of second number ; multiply with current digit of first number and add result to previously stored result at current position . ; carry for next iteration ; store result ; store carry in next cell ; to shift position to left after every multiplication of a digit in num1 . ; ignore '0' s from the right ; if all were '0' s - means either both or one of num1 or num2 were '0 ; generate the result string ; 
def multiply(num1, num2):

    n1 = len(num1)
    n2 = len(num2)

    if (n1 == 0 or n2 == 0):
        return "0"
    result = [0] * (n1 + n2)
    i_n1 = 0
    i_n2 = 0
    for i in range(n1 - 1, -1, -1):
        carry = 0
        n_1 = ord(num1[i]) - ord('0')
        i_n2 = 0
        for j in range(n2 - 1, -1, -1):
            n_2 = ord(num2[j]) - ord('0')
            sum = n_1 * n_2 + result[i_n1 + i_n2] + carry
            carry = sum // 10
            result[i_n1 + i_n2] = sum % 10

            i_n2 += 1
        if (carry > 0):
            result[i_n1 + i_n2] += carry

        i_n1 += 1
    i = len(result) - 1

    while (i >= 0 and result[i] == 0):
        i -= 1
    if (i == -1):
        return "0"
    s = ""

    while (i >= 0):
        s += str(result[i])
        i -= 1

    return s


if __name__ == "__main__":

    str1 = "454545454545454545"

    print(multiply(str1, str1))

# Expected output:
206611570247933883884297520661157025
# perform n steps to convert every digit of a number in the format [ count ] [ digit ] | function to perform every step ; perform n steps ; traverse in the string ; for last digit ; recur for current string ; 
def countDigits(st, n):
    if (n > 0):
        cnt = 1
        i = 0
        st2 = ""
        i = 1
        while (i < len(st)):
            if (st[i] == st[i - 1]):
                cnt = cnt + 1
            else:
                st2 += chr(48 + cnt)
                st2 += st[i - 1]
                cnt = 1
            i = i + 1
        st2 += chr(48 + cnt)
        st2 += st[i - 1]
        countDigits(st2, n - 1)
        n = n - 1
    else:
        print(st)


num = "123"
n = 3
countDigits(num, n)

# Expected output:
1321123113
# sudo placement | special subsequences | python3 program to find all special subsequences of the given type ; function to generate the required subsequences ; if the index pointer has reached the end of input string ; skip empty ( " ▁ " ) subsequence ; exclude current character in output string ; include current character in output string ; remove the current included character and and include it in its uppercase form ; function to print the required subsequences ; output string to store every subsequence ; set of strings that will store all special subsequences in lexicographical sorted order ; sort the strings to print in sorted order ; 

from typing import List


def generateSubsequences(
        input: str,
        output: str,
        idx: int,
        ans: List[str]) -> None:
    if idx == len(input):
        if (len(output)):
            ans .append(output)
        return
    generateSubsequences(input, output, idx + 1, ans)
    output += input[idx]
    generateSubsequences(input, output, idx + 1, ans)
    output = output[:-1]
    upper = input[idx]
    upper = upper .upper()
    output += upper
    generateSubsequences(input, output, idx + 1, ans)


def printSubsequences(S: str) -> None:
    output = ""
    ans = []
    generateSubsequences(S, output, 0, ans)
    ans .sort()
    for string in ans:
        print(string, end=" ")


if __name__ == "__main__":
    S = "ab"
    printSubsequences(S)

# Expected output:
A AB Ab B a aB ab b
# check if the given string of words can be formed from words present in the dictionary | function to check if the word is in the dictionary or not ; map to store all words in dictionary with their count ; adding all words in map ; search in map for all words in the sentence ; all words of sentence are present ; 
def match_words(dictionary, sentence, n, m):
    mp = dict()
    for i in range(n):
        mp[dictionary[i]] = mp .get(dictionary[i], 0) + 1
    for i in range(m):
        if (mp[sentence[i]]):
            mp[sentence[i]] -= 1
        else:
            return False
    return True


dictionary = [
    "find",
    "a",
    "geeks",
    "all",
    "for",
    "on",
    "geeks",
    "answers",
    "inter"]
n = len(dictionary)
sentence = ["find", "all", "answers", "on", "geeks", "for", "geeks"]
m = len(sentence)
if (match_words(dictionary, sentence, n, m)):
    print("YES")
else:
    print("NO")

# Expected output:
YES
# print all 3 digit repeating numbers in a very large number | function to print 3 digit repeating numbers ; hashmap to store the frequency of a 3 digit number ; first three digit number ; if key already exists increase value by 1 ; output the three digit numbers with frequency > 1 ; 
def printNum(s):
    i, j, val = 0, 0, 0
    mp = {}
    val = ((ord(s[0]) - ord('0')) * 100 +
           (ord(s[1]) - ord('0')) * 10 + (ord(s[2]) - ord('0')))
    mp[val] = 1
    for i in range(3, len(s)):
        val = (val % 100) * 10 + ord(s[i]) - ord('0')
        if (val in mp):
            mp[val] = mp[val] + 1
        else:
            mp[val] = 1
    for m in mp:
        key = m
        value = mp[m]
        if (value > 1):
            print(key, " - ", value, " times")


if __name__ == "__main__":
    input = "123412345123456"
    printNum(input)

# Expected output:
123  -  3  times
234  -  3  times
345  -  2  times
# count occurrences of a substring recursively | recursive function to count the number of occurrences of " hi " in str . ; base case ; recursive case checking if the first substring matches ; otherwise , return the count from the remaining index ; 
def countSubstrig(str1, str2):
    n1 = len(str1)
    n2 = len(str2)
    if (n1 == 0 or n1 < n2):
        return 0
    if (str1[0:n2] == str2):
        return countSubstrig(str1[n2 - 1:], str2) + 1
    return countSubstrig(str1[n2 - 1:], str2)


if __name__ == '__main__':
    str1 = "geeksforgeeks"
    str2 = "geeks"
    print(countSubstrig(str1, str2))
    str1 = "hikakashi"
    str2 = "hi"
    print(countSubstrig(str1, str2))

# Expected output:
2
2
# add n binary strings | this function adds two binary strings and return result as a third string ; initialize result ; initialize digit sum ; traverse both strings starting from last characters ; compute sum of last digits and carry ; if current digit sum is 1 or 3 , add 1 to result ; compute carry ; move to next digits ; function to add n binary strings ; 
def addBinaryUtil(a, b):
    result = ""
    s = 0
    i = len(a) - 1
    j = len(b) - 1
    while (i >= 0 or j >= 0 or s == 1):
        s += (ord(a[i]) - ord('0'))if (i >= 0)else 0
        s += (ord(b[j]) - ord('0'))if (j >= 0)else 0
        result = chr(s % 2 + ord('0')) + result
        s //= 2
        i -= 1
        j -= 1
    return result


def addBinary(arr, n):
    result = ""
    for i in range(n):
        result = addBinaryUtil(result, arr[i])
    return result


arr = ["1", "10", "11"]
n = len(arr)
print(addBinary(arr, n))

# Expected output:
110
# reverse string according to the number of words | reverse the letters of the word ; temporary variable to store character ; swapping the first and last character ; this function forms the required string ; checking the number of words present in string to reverse ; reverse the letter of the words ; 
def reverse(string, start, end):
    temp = ''
    while start <= end:
        temp = string[start]
        string[start] = string[end]
        string[end] = temp
        start += 1
        end -= 1


def reverseletter(string, start, end):
    wstart, wend = start, start
    while wend < end:
        if string[wend] == " ":
            wend += 1
            continue
        while wend <= end and string[wend] != " ":
            wend += 1
        wend -= 1
        reverse(string, wstart, wend)
        wend += 1


if __name__ == "__main__":
    string = "Ashish Yadav Abhishek Rajput Sunil Pundir"
    string = list(string)
    reverseletter(string, 0, len(string) - 1)
    print(''.join(string))

# Expected output:
ridnuP tupjaR vadaY Ashish Abhishek Sunil
# minimum bit changes in binary circular array to reach a index | finding which path have minimum flip bit and the minimum flip bits ; concatenating given string to itself , to make it circular ; check x is greater than y . marking if output need to be opposite . ; iterate clockwise ; if current bit is not equal to next index bit . ; iterate anti - clockwise ; if current bit is not equal to next index bit . ; finding whether clockwise or anti - clockwise path take minimum flip . ; 
def minimumFlip(s, x, y):
    s = s + s
    isOpposite = False
    if (x > y):
        temp = y
        y = x
        x = temp
        isOpposite = True
    valClockwise = 0
    cur = s[x]
    for i in range(x, y + 1, 1):
        if (s[i] != cur):
            cur = s[i]
            valClockwise += 1
    valAnticlockwise = 0
    cur = s[y]
    x += len(s) - 1
    for i in range(y, x + 1, 1):
        if (s[i] != cur):
            cur = s[i]
            valAnticlockwise += 1
    if (valClockwise <= valAnticlockwise):
        if (isOpposite == False):
            print("Clockwise", valClockwise)
        else:
            print("Anti-clockwise", valAnticlockwise)
    else:
        if (isOpposite == False):
            print("Anti-clockwise", valAnticlockwise)
        else:
            print("Clockwise", valClockwise)


if __name__ == '__main__':
    x = 0
    y = 8
    s = "000110"
    minimumFlip(s, x, y)

# Expected output:
Clockwise 2