giulio98/xlcost-single-prompt huggingface dataset:
# count of sub | function to return the count of valid sub - strings ; variable ans to store all the possible substrings initialize its value as total number of substrings that can be formed from the given string ; stores recent index of the characters ; if character is a update a 's index  and the variable ans ; if character is b update b 's index  and the variable ans ; if character is c update c 's index  and the variable ans ; 
def CountSubString(Str, n):
    ans = (n * (n + 1)) // 2
    a_index = 0
    b_index = 0
    c_index = 0
    for i in range(n):
        if (Str[i] == 'a'):
            a_index = i + 1
            ans -= min(b_index, c_index)
        elif (Str[i] == 'b'):
            b_index = i + 1
            ans -= min(a_index, c_index)
        else:
            c_index = i + 1
            ans -= min(a_index, b_index)
    return ans


Str = "babac"
n = len(Str)
print(CountSubString(Str, n))

# Expected output:
12
# check if a binary string contains consecutive same or not | function that returns true is str is valid ; assuming the string is binary if any two consecutive characters are equal then the string is invalid ; if the string is alternating ; 
def isValid(string, length):
    for i in range(1, length):
        if string[i] == string[i - 1]:
            return False
    return True


if __name__ == "__main__":
    string = "0110"
    length = len(string)
    if isValid(string, length):
        print("Valid")
    else:
        print("Invalid")

# Expected output:
Invalid
# minimum k such that every substring of length atleast k contains a character c | this function checks if there exists some character which appears in all k length substrings ; iterate over all possible characters ; stores the last occurrence ; set answer as true ; no occurrence found of current character in first substring of length k ; check for every last substring of length k where last occurr - ence exists in substring ; if last occ is not present in substring ; current character is k amazing ; this function performs binary search over the answer to minimise it ; check if answer is found try to minimise it ; 
def check(s, K):
    for ch in range(0, 26):
        c = chr(97 + ch)
        last = -1
        found = True
        for i in range(0, K):
            if s[i] == c:
                last = i
        if last == -1:
            continue
        for i in range(K, len(s)):
            if s[i] == c:
                last = i
            if last <= (i - K):
                found = False
                break
        if found:
            return 1
    return 0


def binarySearch(s):
    low, high, ans = 1, len(s), None
    while low <= high:
        mid = (high + low) >> 1
        if check(s, mid):
            ans, high = mid, mid - 1
        else:
            low = mid + 1
    return ans


if __name__ == "__main__":
    s = "abcde"
    print(binarySearch(s))
    s = "aaaa"
    print(binarySearch(s))

# Expected output:
3
1
# check if number can be displayed using seven segment led | pre - computed values of segment used by digit 0 to 9. ; check if it is possible to display the number ; finding sum of the segments used by each digit of the number ; 

seg = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]


def LedRequired(s, led):
    count = 0
    for i in range(len(s)):
        count += seg[ord(s[i]) - 48]
    if (count <= led):
        return "YES"
    else:
        return "NO"


if __name__ == "__main__":
    S = "123456789"
    led = 20
    print(LedRequired(S, led))

# Expected output:
NO
# check whether two strings can be made equal by increasing prefixes | check whether the first string can be converted to the second string by increasing the ascii value of prefix string of first string ; length of two strings ; if lengths are not equal ; store the difference of ascii values ; difference of first element ; traverse through the string ; the ascii value of the second string should be greater than or equal to first string , if it is violated return false . ; store the difference of ascii values ; the difference of ascii values should be in descending order ; if the difference array is not in descending order ; if all the ascii values of characters of first string is less than or equal to the second string and the difference array is in descending order , return true ; 
def find(s1, s2):
    len__ = len(s1)
    len_1 = len(s2)
    if (len__ != len_1):
        return False
    d = [0 for i in range(len__)]
    d[0] = ord(s2[0]) - ord(s1[0])
    for i in range(1, len__, 1):
        if (s1[i] > s2[i]):
            return False
        else:
            d[i] = ord(s2[i]) - ord(s1[i])
    for i in range(len__ - 1):
        if (d[i] < d[i + 1]):
            return False
    return True


if __name__ == '__main__':
    s1 = "abcd"
    s2 = "bcdd"
    if (find(s1, s2)):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# n | function that returns the n - th character ; initially null string ; starting integer ; add integers in string ; one digit numbers added ; more than 1 digit number , generate equivalent number in a string s1 and concatenate s1 into s . ; add the number in string ; reverse the string ; attach the number ; if the length exceeds n ; 
def NthCharacter(n):
    s = ""
    c = 1
    while (True):
        if (c < 10):
            s += chr(48 + c)
        else:
            s1 = ""
            dup = c
            while (dup > 0):
                s1 += chr((dup % 10) + 48)
                dup //= 10
            s1 = "".join(reversed(s1))
            s += s1
        c += 1
        if (len(s) >= n):
            return s[n - 1]


if __name__ == "__main__":
    n = 11
    print(NthCharacter(n))

# Expected output:
0
# sub | function that counts all the sub - strings of length ' k ' which have all identical characters ; count of sub - strings , length , initial position of sliding window ; dictionary to store the frequency of the characters of sub - string ; increase the frequency of the character and length of the sub - string ; if the length of the sub - string is greater than k ; remove the character from the beginning of sub - string ; if the length of the sub string is equal to k and frequency of one of its characters is equal to the length of the sub - string i . e . all the characters are same increase the count ; display the number of valid sub - strings ; 
def solve(s, k):
    count, length, pos = 0, 0, 0
    m = dict .fromkeys(s, 0)
    for i in range(len(s)):
        m[s[i]] += 1
        length += 1
        if length > k:
            m[s[pos]] -= 1
            pos += 1
            length -= 1
        if length == k and m[s[i]] == length:
            count += 1
    print(count)


if __name__ == "__main__":
    s = "aaaabbbccdddd"
    k = 4
    solve(s, k)

# Expected output:
2
# minimum operation require to make first and last character same | python program to find minimum operation require to make first and last character same ; function to find minimum operation require to make first and last character same ; base conditions ; if answer found ; if string is already visited ; decrement ending index only ; increment starting index only ; increment starting index and decrement index ; store the minimum value ; 

import sys
MAX = sys .maxsize
m = {}
Min = sys .maxsize


def minOperation(s, i, j, count):
    global Min, MAX
    if ((i >= len(s) and j < 0) or (i == j)):
        return MAX
    if (s[i] == s[j] or count >= Min):
        return count
    Str = str(i) + "|" + str(j)
    if Str not in m:
        if (i >= len(s)):
            m[Str] = minOperation(s, i, j - 1, count + 1)
        elif (j < 0):
            m[Str] = minOperation(s, i + 1, j, count + 1)
        else:
            m[Str] = min(
                minOperation(
                    s,
                    i,
                    j - 1,
                    count + 1),
                minOperation(
                    s,
                    i + 1,
                    j,
                    count + 1))
    if (m[Str] < Min):
        Min = m[Str]
    return m[Str]


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

# Expected output:
4
# check if any permutation of a large number is divisible by 8 | function to check if any permutation of a large number is divisible by 8 ; less than three digit number can be checked directly . ; check for the reverse of a number ; stores the frequency of characters in the n . ; iterates for all three digit numbers divisible by 8 ; stores the frequency of all single digit in three - digit number ; check if the original number has the digit ; when all are checked its not possible ; 
def solve(n, l):
    if l < 3:
        if int(n) % 8 == 0:
            return True
        n = n[::-1]
        if int(n) % 8 == 0:
            return True
        return False
    hash = 10 * [0]
    for i in range(0, l):
        hash[int(n[i]) - 0] += 1
    for i in range(104, 1000, 8):
        dup = i
        freq = 10 * [0]
        freq[int(dup % 10)] += 1
        dup = dup / 10
        freq[int(dup % 10)] += 1
        dup = dup / 10
        freq[int(dup % 10)] += 1
        dup = i
        if (freq[int(dup % 10)] > hash[int(dup % 10)]):
            continue
        dup = dup / 10
        if (freq[int(dup % 10)] > hash[int(dup % 10)]):
            continue
        dup = dup / 10
        if (freq[int(dup % 10)] > hash[int(dup % 10)]):
            continue
        return True
    return False


if __name__ == "__main__":
    number = "31462708"
    l = len(number)
    if solve(number, l):
        print("Yes")
    else:
        print("No")

# Expected output:
Yes
# lexicographically smallest string formed by appending a character from the first k characters of a given string | function to find the new string thus formed by removing characters ; new string ; remove characters until the string is empty ; traverse to find the smallest character in the first k characters ; append the smallest character ; removing the lexicographically smallest character from the string ; 
def newString(s, k):
    X = ""
    while (len(s) > 0):
        temp = s[0]
        i = 1
        while (i < k and i < len(s)):
            if (s[i] < temp):
                temp = s[i]
            i += 1
        X = X + temp
        for i in range(k):
            if (s[i] == temp):
                s = s[0:i] + s[i + 1:]
                break
    return X


if __name__ == '__main__':
    s = "gaurang"
    k = 3
    print(newString(s, k))

# Expected output:
agangru
# palindrome by swapping only one character | python3 program palindrome by swapping only one character ; counts the number of differences which prevents the string from being palindrome . ; keeps a record of the characters that prevents the string from being palindrome . ; loops from the start of a string till the midpoint of the string ; difference is encountered preventing the string from being palindrome ; 3 rd differences encountered and its no longer possible to make is palindrome by one swap ; record the different character ; store the different characters ; its already palindrome ; only one difference is found ; if the middlechar matches either of the difference producing characters , return true ; two differences are found ; if the characters contained in the two sets are same , return true ; 
def isPalindromePossible(input: str) -> bool:
    length = len(input)
    diffCount = 0
    i = 0
    diff = [['0'] * 2] * 2
    while i < length // 2:
        if input[i] != input[length - i - 1]:
            if diffCount == 2:
                return False
            diff[diffCount][0] = input[i]
            diff[diffCount][1] = input[length - i - 1]
            diffCount += 1
        i += 1
    if diffCount == 0:
        return True
    elif diffCount == 1:
        midChar = input[i]
        if length % 2 != 0 and (
                diff[0][0] == midChar or diff[0][1] == midChar):
            return True
    elif diffCount == 2:
        if (diff[0][0] == diff[1][0] and diff[0][1] == diff[1][1]) or (
                diff[0][0] == diff[1][1] and diff[0][1] == diff[1][0]):
            return True
    return False


if __name__ == "__main__":
    print(isPalindromePossible("bbg"))
    print(isPalindromePossible("bdababd"))
    print(isPalindromePossible("gcagac"))

# Expected output:
True
True
False
# convert string into binary sequence | utility function ; convert each char to ascii value ; convert ascii value to binary ; 
def strToBinary(s):
    bin_conv = []
    for c in s:
        ascii_val = ord(c)
        binary_val = bin(ascii_val)
        bin_conv .append(binary_val[2:])
    return (' '.join(bin_conv))


if __name__ == '__main__':
    s = 'geeks'
print(strToBinary(s))

# Expected output:
1100111 1100101 1100101 1101011 1110011
# print distinct sorted permutations with duplicates allowed in input | python3 program to print all permutations of a string in sorted order . ; calculating factorial of a number ; method to find total number of permutations ; building map to store frequencies of all characters . ; traversing map and finding duplicate elements . ; start traversing from the end and find position ' i - 1' of the first character which is greater than its successor ; finding smallest character after ' i - 1' and greater than temp [ i - 1 ] ; swapping the above found characters . ; sort all digits from position next to ' i - 1' to end of the string ; print the string ; sorting string ; print first permutation ; finding the total permutations ; 

from collections import defaultdict


def factorial(n):
    f = 1
    for i in range(1, n + 1):
        f = f * i
    return f


def calculateTotal(temp, n):
    f = factorial(n)
    hm = defaultdict(int)
    for i in range(len(temp)):
        hm[temp[i]] += 1
    for e in hm:
        x = hm[e]
        if (x > 1):
            temp5 = factorial(x)
            f //= temp5
        return f


def nextPermutation(temp):
    for i in range(len(temp) - 1, 0, -1):
        if (temp[i] > temp[i - 1]):
            break
    min = i
    x = temp[i - 1]
    for j in range(i + 1, len(temp)):
        if ((temp[j] < temp[min]) and (temp[j] > x)):
            min = j
    temp[i - 1], temp[min] = (temp[min], temp[i - 1])
    temp[i:].sort()
    print(''.join(temp))


def printAllPermutations(s):
    temp = sorted(s)
    print(''.join(temp))
    total = calculateTotal(temp, len(temp))
    for i in range(1, total):
        nextPermutation(temp)


if __name__ == "__main__":
    s = "AAB"
    printAllPermutations(s)

# Expected output:
AAB
ABA
BAA
# convert a sentence into its equivalent mobile numeric keypad sequence | function which computes the sequence ; length of 
def printSequence(arr, input):
    n = len(input)
    output = ""
    for i in range(n):
        if (input[i] == ' '):
            output = output + "0"
        else:
            position = ord(input[i]) - ord('A')
            output = output + arr[position]
    return output


str = [
    "2",
    "22",
    "222",
    "3",
    "33",
    "333",
    "4",
    "44",
    "444",
    "5",
    "55",
    "555",
    "6",
    "66",
    "666",
    "7",
    "77",
    "777",
    "7777",
    "8",
    "88",
    "888",
    "9",
    "99",
    "999",
    "9999"]
input = "GEEKSFORGEEKS"
print(printSequence(str, input))

# Expected output:
4333355777733366677743333557777
# longest uncommon subsequence | function to calculate length of longest uncommon subsequence ; creating an unordered map to map strings to their frequency ; traversing all elements of vector strarr ; creating all possible subsequences , i . e 2 ^ n ; ( ( i >> j ) & 1 ) determines which character goes into t ; if common subsequence is found , increment its frequency ; traversing the map ; if frequency equals 1 ; 
def findLUSlength(a, b):
    map = dict()
    strArr = []
    strArr .append(a)
    strArr .append(b)
    for s in strArr:
        for i in range(1 << len(s)):
            t = ""
            for j in range(len(s)):
                if (((i >> j) & 1) != 0):
                    t += s[j]
            if (t in map .keys()):
                map[t] += 1
            else:
                map[t] = 1
    res = 0
    for a in map:
        if (map[a] == 1):
            res = max(res, len(a))
    return res


a = "abcdabcd"
b = "abcabc"
print(findLUSlength(a, b))

# Expected output:
8
# round the given number to nearest multiple of 10 | function to round the number to the nearest number having one 's digit 0 ; last character is 0 then return the original string ; if last character is 1 or 2 or 3 or 4 or 5 make it 0 ; process carry ; return final string ; 
def Round(s, n):
    s = list(s)
    c = s .copy()
    if (c[n - 1] == '0'):
        return ("".join(s))
    elif (c[n - 1] == '1' or c[n - 1] == '2' or c[n - 1] == '3' or c[n - 1] == '4' or c[n - 1] == '5'):
        c[n - 1] = '0'
        return ("".join(c))
    else:
        c[n - 1] = '0'
        for i in range(n - 2, -1, -1):
            if (c[i] == '9'):
                c[i] = '0'
            else:
                t = ord(c[i]) - ord('0') + 1
                c[i] = chr(48 + t)
                break
    s1 = "".join(c)
    if (s1[0] == '0'):
        s1 = "1" + s1
    return s1


s = "5748965412485599999874589965999"
n = len(s)
print(Round(s, n))

# Expected output:
5748965412485599999874589966000
# check whether given floating point number is even or odd | function to check even or odd . ; loop to traverse number from lsb ; we ignore trailing 0 s after dot ; if it is ' . ' we will check next digit and it means decimal part is traversed . ; if digit is divisible by 2 means even number . ; 
def isEven(s):
    l = len(s)
    dotSeen = False
    for i in range(l - 1, -1, -1):
        if (s[i] == '0' and dotSeen == False):
            continue
        if (s[i] == '.'):
            dotSeen = True
            continue
        if ((int)(s[i]) % 2 == 0):
            return True
        return False


s = "100.70"
if (isEven(s)):
    print("Even")
else:
    print("Odd")

# Expected output:
Odd
# minimum cost to construct a string | python 3 program to find minimum cost to construct a string ; initially all characters are un - seen ; marking seen characters ; count total seen character , and that is the cost ; 
def minCost(s):
    alphabets = [False for i in range(26)]
    for i in range(len(s)):
        alphabets[ord(s[i]) - 97] = True
    count = 0
    for i in range(26):
        if (alphabets[i]):
            count += 1
    return count


if __name__ == '__main__':
    s = "geeksforgeeks"
    print("Total cost to construct", s, "is", minCost(s))

# Expected output:
Total cost to construct geeksforgeeks is 7
# possibility of moving out of maze | function to check whether it will stay inside or come out ; marks all the positions that is visited ; initial starting point ; initial assumption is it comes out ; runs till it is inside or comes out ; if the movement is towards left then we move left . the start variable and mark that position as visited if not visited previously . else we break out ; it will be inside forever ; if the movement is towards right , then we move right . the start variable and mark that position as visited if not visited previously else we break out ; it will be inside forever ; 
def checkingPossibility(a, n, s):
    mark = [0] * n
    start = 0
    possible = 1
    while start >= 0 and start < n:
        if s[start] == "<":
            if mark[start] == 0:
                mark[start] = 1
                start -= a[start]
            else:
                possible = 0
                break
        else:
            if mark[start] == 0:
                mark[start] = 1
                start += a[start]
            else:
                possible = 0
                break
    if possible == 0:
        return False

    else:
        return True


n = 2
s = "><"
a = [1, 2]
if (checkingPossibility(a, n, s)):
    print("comes out")
else:
    print("it stays inside forever")

# Expected output:
comes out
# a | a iterative function that removes consecutive duplicates from string s ; we don 't need to do anything for  empty or single character string. ; j is used to store index is result string ( or index of current distinct character ) ; traversing string ; if current character s [ i ] is different from s [ j ] ; 
def removeDuplicates(S):
    n = len(S)
    if (n < 2):
        return
    j = 0
    for i in range(n):
        if (S[j] != S[i]):
            j += 1
            S[j] = S[i]
    j += 1
    S = S[:j]
    return S


if __name__ == '__main__':
    S1 = "geeksforgeeks"
    S1 = list(S1 .rstrip())
    S1 = removeDuplicates(S1)
    print(*S1, sep="")
    S2 = "aabcca"
    S2 = list(S2 .rstrip())
    S2 = removeDuplicates(S2)
    print(*S2, sep="")

# Expected output:
geksforgeks
abca
# Simplify the directory path ( Unix like ) | function to simplify a Unix - styled absolute path ; using vector in place of stack ; forming the current directory . ; if " . . " , we pop . ; do nothing ( added for better understanding . ) ; push the current directory into the vector . ; forming the ans ; vector is empty ; absolute path which we have to simplify .
def simplify(path):
    v = []
    n = len(path)
    ans = ""
    for i in range(n):
        Dir = ""
        while (i < n and path[i] != '/'):
            Dir += path[i]
            i += 1
        if (Dir == ".."):
            if (len(v) > 0):
                v .pop()
        elif (Dir == "." or Dir == ""):
            continue
        else:
            v .append(Dir)
    for i in v:
        ans += "/" + i
    if (ans == ""):
        return "/"
    return ans


Str = "/a/./b/../../c/"
res = simplify(Str)
print(res)

# Expected output:
/c
# evaluate a boolean expression represented as string | python3 program to evaluate value of an expression . ; evaluates boolean expression and returns the result ; traverse all operands by jumping a character after every iteration . ; if operator next to current operand is and . ; if operator next to current operand is or . ; if operator next to current operand is xor ( assuming a valid input ) ; 

import math as mt


def evaluateBoolExpr(s):
    n = len(s)
    for i in range(0, n - 2, 2):
        if (s[i + 1] == "A"):
            if (s[i + 2] == "0" or s[i] == "0"):
                s[i + 2] = "0"
            else:
                s[i + 2] = "1"
        elif (s[i + 1] == "B"):
            if (s[i + 2] == "1" or s[i] == "1"):
                s[i + 2] = "1"
            else:
                s[i + 2] = "0"
        else:
            if (s[i + 2] == s[i]):
                s[i + 2] = "0"
            else:
                s[i + 2] = "1"
    return ord(s[n - 1]) - ord("0")


s = "1C1B1B0A0"
string = [s[i]for i in range(len(s))]
print(evaluateBoolExpr(string))

# Expected output:
0
# efficiently find first repeated character in a string without using any additional data structure in one traversal | returns - 1 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 FirstRepeated(string):
    checker = 0
    pos = 0
    for i in string:
        val = ord(i) - ord('a')
        if ((checker & (1 << val)) > 0):
            return pos
        checker |= (1 << val)
        pos += 1
    return -1


string = "abcfdeacf"
i = FirstRepeated(string)
if i != -1:
    print("Char = ", string[i], " and Index = ", i)
else:
    print("No repeated Char")

# Expected output:
Char =  a  and Index =  6