giulio98/xlcost-single-prompt huggingface dataset:
# minimum substring flips required to convert a binary string to another | function to count the minimum number of reversals required to make the given binary strings s1 and s2 same ; stores the minimum count of reversal of substrings required ; if the length of the strings are not the same then return - 1 ; iterate over each character ; if s1 [ i ] is not equal to s2 [ i ] ; iterate until s1 [ i ] != s2 [ i ] ; increment answer by 1 ; return the resultant count of reversal of subrequired ; 
def canMakeSame(s1, s2):
    ans = -1
    if (len(s1) != len(s2)):
        return -1
    N = len(s1)
    for i in range(0, N):
        if (s1[i] != s2[i]):
            while (i < len(s1) and s1[i] != s2[i]):
                i += 1
            ans += 1
    return ans


S1 = "100001"
S2 = "110111"
print(canMakeSame(S1, S2))

# Expected output:
2
# count points which are revisited while following the path specified by a given string | function to find the number of times already visited position is revisited after starting traversal from { x , y } ; stores the x and y temporarily ; stores the number of times an already visited position is revisited ; initialize hashset ; insert the starting coordinates ; traverse over the string ; update the coordinates according to the current directions ; if the new { x , y } has been visited before , then increment the count by 1 ; otherwise ; insert new { x , y } ; 
def count(S, X, Y):
    N = len(S)
    temp_x, temp_y = 0, 0
    count = 0
    s = {}
    s[(X, Y)] = 1
    for i in range(N):
        temp_x = X
        temp_y = Y
        if (S[i] == 'U'):
            X += 1
        elif (S[i] == 'D'):
            X -= 1
        elif (S[i] == 'R'):
            Y += 1
        else:
            Y -= 1
        if ((temp_x + X, temp_y + Y) in s):
            count += 1
        else:
            s[(temp_x + X, temp_y + Y)] = 1
    return count


if __name__ == '__main__':
    S = "RDDUDL"
    X, Y = 0, 0
    print(count(S, X, Y))

# Expected output:
2
# sum of frequencies of characters of a string present in another string | function to find sum of frequencies of characters of s1 present in s2 ; insert all characters of string s1 in the set ; traverse the string s2 ; check if x is present in bset or not ; increment count by 1 ; finally , print the count ; 
def countTotalFrequencies(S1, S2):
    bset = set(S1)
    count = 0
    for x in S2:
        if x in bset:
            count += 1
    print(count)


S1 = "geEksFOR"
S2 = "GeEksforgeEKS"
countTotalFrequencies(S1, S2)

# Expected output:
7
# make a given binary string non | function to return the length of smallest subsequence required to be removed to make the given string non - decreasing ; length of the string ; count of zeros and ones ; traverse the string ; count minimum removals to obtain strings of the form "00000 . . . . " or "11111 . . . " ; increment count ; remove 1 s and remaining 0 s ; 
def min_length(str):
    n = len(str)
    total_zeros = 0
    total_ones = 0
    for i in range(n):
        if (str[i] == '0'):
            total_zeros += 1
        else:
            total_ones += 1
    ans = min(total_zeros, total_ones)
    cur_zeros = 0
    cur_ones = 0
    for x in str:
        if (x == '0'):
            cur_zeros += 1
        else:
            cur_ones += 1
        ans = min(ans, cur_ones + (total_zeros - cur_zeros))
    print(ans)


if __name__ == '__main__':
    str = "10011"
    min_length(str)

# Expected output:
1
# print all words occurring in a sentence exactly k times | function to print all the words occurring k times in a string ; stores the words ; traverse the list ; check for count ; print the word ; remove from list ; 
def kFreqWords(S, K):
    l = list(S .split(" "))
    for i in l:
        if l .count(i) == K:
            print(i)
            l .remove(i)


if __name__ == "__main__":
    S = "banana is in yellow and sun flower is also in yellow"
    K = 2
    kFreqWords(S, K)

# Expected output:
is
yellow
in
# check if substrings from three given strings can be concatenated to form a palindrome | function to check if substrings from three given strings can be concatenated to form a palindrome ; mask for s1 and s2 ; set ( i - ' a ' ) th bit in maska ; set ( i - ' a ' ) th bit in maskc ; if the bitwise and is > 0 ; 
def make_palindrome(S1, S2, S3):
    maskA, maskC = 0, 0
    for i in S1:
        maskA |= (1 << (ord(i) - ord('a')))
    for i in S3:
        maskC |= (1 << (ord(i) - ord('a')))
    if ((maskA & maskC) > 0):
        return "YES"
    return "NO"


if __name__ == '__main__':
    S1, S2, S3 = "adcb", "bcdb", "abe"
    print(make_palindrome(S1, S2, S3))

# Expected output:
YES
# length of longest prefix anagram which are common in given two strings | python3 program for the above approach ; function to check if two arrays are identical or not ; iterate over the range [ 0 , size ] ; if frequency any character is not same in both the strings ; otherwise ; function to find the maximum length of the required string ; store the count of characters in str1 ; store the count of characters in str2 ; stores the maximum length ; minimum length of str1 and str2 ; increment the count of characters of str1 [ i ] in freq1 [ ] by one ; increment the count of characters of stord ( r2 [ i ] ) in freq2 [ ] by one ; checks if prefixes are anagram or not ; finally prthe ans ; 

SIZE = 26


def longHelper(freq1, freq2):
    for i in range(26):
        if (freq1[i] != freq2[i]):
            return False
    return True


def longCommomPrefixAnagram(s1, s2, n1, n2):
    freq1 = [0] * 26
    freq2 = [0] * 26
    ans = 0
    mini_len = min(n1, n2)
    for i in range(mini_len):
        freq1[ord(s1[i]) - ord('a')] += 1
        freq2[ord(s2[i]) - ord('a')] += 1
        if (longHelper(freq1, freq2)):
            ans = i + 1
    print(ans)


if __name__ == '__main__':
    str1 = "abaabcdezzwer"
    str2 = "caaabbttyh"
    N = len(str1)
    M = len(str2)
    longCommomPrefixAnagram(str1, str2, N, M)

# Expected output:
6
# lexicographic rank of a binary string | function to find the rank of a string ; store the length of the string ; stores its equivalent decimal value ; traverse the string ; store the number of strings of length less than n occurring before the given string ; store the decimal equivalent number of string bin ; store the rank in answer ; prthe answer ; 
def findRank(s):
    N = len(s)
    sb = ""
    for i in range(0, N):
        if (s[i] == '0'):
            sb += str('0')
        else:
            sb += str('1')
    bin = str(sb)
    X = pow(2, N)
    Y = int(bin)
    ans = X + Y - 1
    print(ans)


if __name__ == '__main__':
    S = "001"
    findRank(S)

# Expected output:
8
# find the gcd of an array made up of numeric strings | recursive function to return gcd of a and b ; base case ; length of a is greater ; calculate gcd ; store the gcd of the length of the strings ; 
def GCD(lena, lenb):
    if (lena == 0):
        return lenb
    if (lenb == 0):
        return lena
    if (lena == lenb):
        return lena
    if (lena > lenb):
        return GCD(lena - lenb, lenb)
    return GCD(lena, lenb - lena)


def StringGCD(a, b):
    gcd = GCD(len(a), len(b))
    if a[:gcd] == b[:gcd]:
        if a * (len(b) // gcd) == b * (len(a) // gcd):
            return a[:gcd]
    return -1


a = 'geeksgeeks'
b = 'geeks'
print(StringGCD(a, b))

# Expected output:
geeks
# minimize cost to rearrange substrings to convert a string to a balanced bracket sequence | function to count minimum number of operations to convert the string to a balanced bracket sequence ; initialize the integer array ; traverse the string ; decrement a [ i ] ; increment a [ i ] ; update the sum as current value of arr [ i ] ; if answer exists ; traverse from i ; find all substrings with 0 sum ; print the sum of sizes ; no answer exists ; 
def countMinMoves(str):
    n = len(str)
    a = [0 for i in range(n)]
    j, ans, sum = 0, 0, 0
    for i in range(n):
        if (str[i] == ')'):
            a[i] += sum - 1
        else:
            a[i] += sum + 1
        sum = a[i]
    if (sum == 0):
        i = 1
        while (i < n):
            j = i - 1
            while (i < n and a[i] != 0):
                i += 1
            if (i < n and a[i - 1] < 0):
                ans += i - j
                if (j == 0):
                    ans += 1
            i += 1
        print(ans)
    else:
        print("-1")


if __name__ == '__main__':
    str = ")(()"
    countMinMoves(str)

# Expected output:
2
# check if a given string can be converted to a balanced bracket sequence | function to check if the can be balanced by replacing the ' $ ' with opening or closing brackets ; if string can never be balanced ; declare 2 stacks to check if all ) can be balanced with ( or $ and vice - versa ; store the count the occurence of ( , ) and $ ; traverse the string ; increment closed bracket count by 1 ; if there are no opening bracket to match it then return false ; otherwise , pop the character from the stack ; if current character is an opening bracket or $ , push it to the stack ; increment symbol count by 1 ; increment open bracket count by 1 ; traverse the string from end and repeat the same process ; if there are no closing brackets to match it ; otherwise , pop character from stack ; store the extra ( or ) which are not balanced yet ; check if $ is available to balance the extra brackets ; count ramaining $ after balancing extra ( and ) ; check if each pair of $ is convertable in ( ) ; 
def canBeBalanced(sequence):
    if (len(sequence) % 2):
        return False
    stack_, stack2_ = [], []
    countOpen, countClosed = 0, 0
    countSymbol = 0
    for i in range(len(sequence)):
        if (sequence[i] == ')'):
            countClosed += 1
            if (len(stack_) == 0):
                return False
            else:
                del stack_[-1]
        else:
            if (sequence[i] == '$'):
                countSymbol += 1
            else:
                countOpen += 1
            stack_ .append(sequence[i])
    for i in range(len(sequence) - 1, -1, -1):
        if (sequence[i] == '('):
            if (len(stack2_) == 0):
                return False
            else:
                del stack2_[-1]
        else:
            stack2_ .append(sequence[i])
    extra = abs(countClosed - countOpen)
    if (countSymbol < extra):
        return False
    else:
        countSymbol -= extra
        if (countSymbol % 2 == 0):
            return True
    return False


if __name__ == '__main__':
    S = "()($"
    if (canBeBalanced(S)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# queries to calculate difference between the frequencies of the most and least occurring characters in specified substring | function to find difference between maximum and minimum frequency of a character in given range ; stores length of string ; stores count of queries ; iterate over the characters of the string ; stores l - value of a query ; stores r - value of a query ; store count of every character laying in range [ l , r ] ; update frequency of current character ; stores maximum frequency of characters in given range ; stores minimum frequency of characters in given range ; iterate over all possible characters of the given string ; update mx ; if ( j + ' a ' ) is present ; difference between max and min ; 
def maxDiffFreq(queries, S):
    N = len(S)
    Q = len(queries)
    for i in range(Q):
        l = queries[i][0] - 1
        r = queries[i][1] - 1
        freq = [0] * 26
        for j in range(l, r + 1):
            freq[ord(S[j]) - ord('a')] += 1
        mx = 0
        mn = 99999999
        for j in range(26):
            mx = max(mx, freq[j])
            if (freq[j]):
                mn = min(mn, freq[j])
        print(mx - mn)


if __name__ == "__main__":
    S = "abaabac"
    queries = [[2, 6], [1, 7]]
    maxDiffFreq(queries, S)

# Expected output:
1
3
# count strings from given array having all characters appearing in a given string | function to count the number of strings from an array having all characters appearing in the string s ; initialize a set to store all distinct characters of s ; traverse over s ; insert characters into the set ; stores the required count ; traverse the array ; traverse over arr [ i ] ; check if character in arr [ i ] [ j ] is present in the s or not ; increment the count if all the characters of arr [ i ] are present in the s ; finally , prthe count ; 
def countStrings(S, list):
    valid = {}
    for x in S:
        valid[x] = 1
    cnt = 0
    for i in range(len(list)):
        j = 0
        while j < len(list[i]):
            if (list[i][j] in valid):
                j += 1
                continue
            else:
                break
            j += 1
        if (j == len(list[i])):
            cnt += 1
    return cnt


if __name__ == '__main__':
    arr = ["ab", "aab", "abaaaa", "bbd"]
    S, l = "ab", []
    print(countStrings(S, arr))

# Expected output:
3
# minimize a string by removing all occurrences of another string | function to find the minimum length to which string str can be reduced to by removing all occurrences of string k ; initialize stack of characters ; push character into the stack ; if stack size >= k . size ( ) ; create empty string to store characters of stack ; traverse the string k in reverse ; if any of the characters differ , it means that k is not present in the stack ; push the elements back into the stack ; store the string ; remove top element ; size of stack gives the minimized length of str ; 
def minLength(Str, N, K, M):
    stackOfChar = []
    for i in range(N):
        stackOfChar .append(Str[i])
        if (len(stackOfChar) >= M):
            l = ""
            for j in range(M - 1, -1, -1):
                if (K[j] != stackOfChar[-1]):
                    f = 0
                    while (f != len(l)):
                        stackOfChar .append(l[f])
                        f += 1
                    break
                else:
                    l = stackOfChar[-1] + l
                    stackOfChar .pop()
    return len(stackOfChar)


S1 = "fffoxoxoxfxo"
S2 = "fox"
N = len(S1)
M = len(S2)
print(minLength(S1, N, S2, M))

# Expected output:
3
# largest palindrome not exceeding n which can be expressed as product of two 3 | function to find the largest palindrome not exceeding n which can be expressed as the product of two 3 - digit numbers ; stores all palindromes ; stores the product ; check if x is palindrome ; check n is less than n ; if true , append it in the list ; print the largest palindrome ; 
def palindrome_prod(N):
    palindrome_list = []
    for i in range(101, 1000):
        for j in range(121, 1000, (1 if i % 11 == 0 else 11)):
            n = i * j
            x = str(n)
            if x == x[::-1]:
                if n < N:
                    palindrome_list .append(i * j)
    print(max(palindrome_list))


N = 101110
palindrome_prod(N)

# Expected output:
101101
# check if given strings can be made same by swapping two characters of same or different strings | function to check if all strings can be made equal by swapping any pair of characters from the same or different strings ; stores length of string ; store frequency of each distinct character of the strings ; traverse the array ; iterate over the characters ; update frequency of arr [ i ] [ j ] ; traverse the array cntfreq [ ] ; if cntfreq [ i ] is divisible by n or not ; 
def isEqualStrings(arr, N):
    M = len(arr[0])
    cntFreq = [0] * 256
    for i in range(N):
        for j in range(M):
            cntFreq[ord(arr[i][j]) - ord('a')] += 1
    for i in range(256):
        if (cntFreq[i] % N != 0):
            return False
    return True


if __name__ == "__main__":
    arr = ["aab", "bbc", "cca"]
    N = len(arr)
    if isEqualStrings(arr, N):
        print("YES")
    else:
        print("NO")

# Expected output:
YES
# minimize a binary string by repeatedly removing even length substrings of same characters | recursive function to print stack elements from bottom to top without changing their order ; if stack is empty ; pop top element of the stack ; recursively call the function printstack ; print the stack element from the bottom ; push the same element onto the stack to preserve the order ; function to minimize binary string by removing substrings consisting of same character ; declare a stack of characters ; push the first character of the string into the stack ; traverse the string s ; if stack is empty ; push current character into the stack ; check if the current character is same as the top of the stack ; if true , pop the top of the stack ; otherwise , push the current element ; print stack from bottom to top ; 
def PrintStack(s):
    if (len(s) == 0):
        return
    x = s[-1]
    s .pop()
    PrintStack(s)
    print(x, end="")
    s .append(x)


def minString(s):
    Stack = []
    Stack .append(s[0])
    for i in range(1, len(s)):
        if (len(Stack) == 0):
            Stack .append(s[i])
        else:
            if (Stack[-1] == s[i]):
                Stack .pop()
            else:
                Stack .append(s[i])
    PrintStack(Stack)


if __name__ == "__main__":
    string = "101001"
    minString(string)

# Expected output:
10
# probability of collision between two trucks | function to calculate total number of accidents ; function to calculate count of all possible collision ; size of string ; stores the count of collisions ; total number of truck in lane b ; count total number of collisions while traversing the string a ; function to calculate the probability of collisions ; evaluate total outcome that is all the possible accident ; evaluate favourable outcome i . e . , count of collision of trucks ; print desired probability ; 
def count_of_accident(a, b):
    n = len(a)
    m = len(b)
    if (n > m):
        return (m * (m + 1)) / 2
    else:
        return ((n * (n + 1)) / 2 + (m - n) * n)


def count_of_collision(a, b):
    n = len(a)
    m = len(b)
    answer = 0
    count_of_truck_in_lane_b = 0
    for i in range(0, m):
        if (b[i] == 'T'):
            count_of_truck_in_lane_b += 1
    i = 0
    while (i < m and i < n):
        if (a[i] == 'T'):
            answer += count_of_truck_in_lane_b
        if (b[i] == 'T'):
            count_of_truck_in_lane_b -= 1
        i += 1
    return answer


def findProbability(a, b):
    total_outcome = count_of_accident(a, b)
    favourable_outcome = count_of_collision(a, b)
    print(favourable_outcome / total_outcome)


if __name__ == "__main__":
    S = "TCCBCTTB"
    T = "BTCCBBTT"
    findProbability(S, T)

# Expected output:
0.19444444444444445
# count alphanumeric palindromes of length n | function to calculate ( x ^ y ) mod p ; initialize result ; update x if it is more than or equal to p ; if y is odd , multiply x with result ; y must be even now ; return the final result ; 
def power(x, y, p):
    res = 1
    x = x % p
    if (x == 0):
        return 0
    while (y > 0):
        if ((y & 1) == 1):
            res = (res * x) % p
        y = y >> 1
        x = (x * x) % p
    return res


N = 3
if ((N == 1) or (N == 2)):
    print(62)
else:
    m = (10 ** 9) + 7
    if (N % 2 == 0):
        k = N // 2
        flag = True
    else:
        k = (N - 1) // 2
        flag = False
    if (flag):
        a = power(62, k, m)
        print(a)
    else:
        a = power(62, (k + 1), m)
        print(a)

# Expected output:
3844
# length of the longest substring with every character appearing even number of times | function to find length of the longest substring with each element occurring even number of times ; initialize unordered_map ; stores the length of the longest required substring ; traverse the string ; stores the value of the digit present at current index ; bitwise xor of the mask with 1 left - shifted by val ; check if the value of mask is already present in ind or not ; update the final answer ; otherwise ; return the answer ; 
def lenOfLongestReqSubstr(s, N):
    ind = {}
    mask = 0
    ind[0] = -1
    ans = 0
    for i in range(N):
        val = ord(s[i]) - ord('0')
        mask ^= (1 << val)
        if (mask in ind):
            ans = max(ans, i - ind[mask])
        else:
            ind[mask] = i
    return ans


if __name__ == "__main__":
    s = "223015150"
    N = len(s)
    print(lenOfLongestReqSubstr(s, N))

# Expected output:
6
# count distinct strings possible by replacing each character by its morse code | function to count unique array elements by replacing each character by its morse code ; stores morse code of all lowercase characters ; stores distinct elements of string by replacing each character by morse code ; stores length of arr array ; traverse the array ; stores the morse code of arr [ i ] ; stores length of current string ; update temp ; insert temp into st ; return count of elements in the set ; 
def uniqueMorseRep(arr):
    morseCode = [
        ".-",
        "-...",
        "-.-.",
        "-..",
        ".",
        "..-.",
        "--.",
        "....",
        "..",
        ".---",
        "-.-",
        ".-..",
        "--",
        "-.",
        "---",
        ".--.",
        "--.-",
        ".-.",
        "...",
        "-",
        "..-",
        "...-",
        ".--",
        "-..-",
        "-.--",
        "--.."]
    st = set()
    N = len(arr)
    for i in range(N):
        temp = ""
        M = len(arr[i])
        for j in range(M):
            temp += morseCode[ord(arr[i][j]) - ord('a')]
        st .add(temp)
    return len(st)


if __name__ == '__main__':
    arr = ["gig", "zeg", "gin", "msn"]
    print(uniqueMorseRep(arr), "")

# Expected output:
2
# maximum repeating character for every index in given string | function to print the maximum repeating character at each index of the string ; stores frequency of each distinct character ; stores frequency of maximum repeating character ; stores the character having maximum frequency ; traverse the string ; stores current character ; update the frequency of strr [ i ] ; if frequency of current character exceeds max ; update max ; update charmax ; print the required output ; 
def findFreq(strr, N):
    freq = [0] * 256
    max = 0
    charMax = '0'
    for i in range(N):
        ch = ord(strr[i])
        freq[ch] += 1
        if (freq[ch] >= max):
            max = freq[ch]
            charMax = ch
        print(chr(charMax), "->", max)


if __name__ == '__main__':
    strr = "abbc"
    N = len(strr)
    findFreq(strr, N)

# Expected output:
a -> 1
b -> 1
b -> 2
b -> 2
# minimize cost to convert given string to a palindrome | function to find the minimum cost to convert the into a palindrome ; length of the string ; if iointer is in the second half ; reverse the string ; find the farthest index needed to change on left side ; find the farthest index needed to change on right side ; changing the variable to make palindrome ; min distance to travel to make palindrome ; total cost ; return the minimum cost ; 
def findMinCost(strr, pos):
    n = len(strr)
    if (pos >= n / 2):
        strr = strr[::-1]
        pos = n - pos - 1
    left, right = pos, pos
    for i in range(pos, -1, -1):
        if (strr[i] != strr[n - i - 1]):
            left = i
    for i in range(pos, n // 2):
        if (strr[i] != strr[n - i - 1]):
            right = i
    ans = 0
    for i in range(left, right + 1):
        if (strr[i] != strr[n - i - 1]):
            ans += 1
    dis = (min((2 * (pos - left) + (right - pos)),
           (2 * (right - pos) + (pos - left))))
    ans = ans + dis
    return ans


if __name__ == '__main__':
    S = "bass"
    P = 3
    print(findMinCost(S, P))

# Expected output:
3