giulio98/xlcost-single-prompt huggingface dataset:
# remove a character from a string to make it a palindrome | utility method to check if substring from low to high is palindrome or not . ; this method returns - 1 if it is not possible to make string a palindrome . it returns - 2 if string is already a palindrome . otherwise it returns index of character whose removal can make the whole string palindrome . ; initialize low and right by both the ends of the string ; loop until low and high cross each other ; if both characters are equal then move both pointer towards end ; if removing str [ low ] makes the whole string palindrome . we basically check if substring str [ low + 1. . high ] is palindrome or not . ; if removing str [ high ] makes the whole string palindrome we basically check if substring str [ low + 1. . high ] is palindrome or not ; we reach here when complete string will be palindrome if complete string is palindrome then return mid character ; 
def isPalindrome(string: str, low: int, high: int) -> bool:
    while low < high:
        if string[low] != string[high]:
            return False
        low += 1
        high -= 1
    return True


def possiblepalinByRemovingOneChar(string: str) -> int:
    low = 0
    high = len(string) - 1
    while low < high:
        if string[low] == string[high]:
            low += 1
            high -= 1
        else:
            if isPalindrome(string, low + 1, high):
                return low
            if isPalindrome(string, low, high - 1):
                return high
            return -1
    return -2


if __name__ == "__main__":
    string = "abecbea"
    idx = possiblepalinByRemovingOneChar(string)
    if idx == -1:
        print("Not possible")
    elif idx == -2:
        print("Possible without removing any character")
    else:
        print("Possible by removing character at index", idx)

# Expected output:
Not possible
# generate all binary strings from given pattern | recursive function to generate all binary strings formed by replacing each wildcard character by 0 or 1 ; replace ' ? ' by '0' and recurse ; replace ' ? ' by '1' and recurse ; note : need to backtrack as string is passed by reference to the function ; 
def _print(string, index):
    if index == len(string):
        print(''.join(string))
        return
    if string[index] == "?":
        string[index] = '0'
        _print(string, index + 1)
        string[index] = '1'
        _print(string, index + 1)
        string[index] = '?'
    else:
        _print(string, index + 1)


if __name__ == "__main__":
    string = "1??0?101"
    string = list(string)
    _print(string, 0)

# Expected output:
10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101
# find the most frequent digit without using array / string | simple function to count occurrences of digit d in x ; count = 0 ; initialize count of digit d ; increment count if current digit is same as d ; returns the max occurring digit in x ; handle negative number ; traverse through all digits ; count occurrences of current digit ; update max_count and result if needed ; 
def countOccurrences(x, d):
    count = 0
    while (x):
        if (x % 10 == d):
            count += 1
        x = int(x / 10)
    return count


def maxOccurring(x):
    if (x < 0):
        x = -x
    result = 0
    max_count = 1
    for d in range(10):
        count = countOccurrences(x, d)
        if (count >= max_count):
            max_count = count
            result = d
    return result


x = 1223355
print("Max occurring digit is", maxOccurring(x))

# Expected output:
Max occurring digit is 5
# remove recurring digits in a given number | removes recurring digits in num [ ] ; index in modified string ; traverse digits of given number one by one ; copy the first occurrence of new digit ; remove repeating occurrences of digit ; 
def removeRecurringDigits(num):
    l = len(num)
    (i, j) = (0, 0)
    str = ''
    while i < l:
        str += num[i]
        j += 1
        while (i + 1 < l and num[i] == num[i + 1]):
            i += 1
        i += 1
    return str


if __name__ == '__main__':
    num = '1299888833'
    print('Modified number is {}'.format(removeRecurringDigits(num)))

# Expected output:
Modified number is 12983
# find the maximum subarray xor in a given array | a simple python program to find max subarray xor ; initialize result ; pick starting points of subarrays ; to store xor of current subarray ; pick ending points of subarrays starting with i ; 
def maxSubarrayXOR(arr, n):
    ans = -2147483648
    for i in range(n):
        curr_xor = 0
        for j in range(i, n):
            curr_xor = curr_xor ^ arr[j]
            ans = max(ans, curr_xor)
    return ans


arr = [8, 1, 2, 12]
n = len(arr)
print("Max subarray XOR is ", maxSubarrayXOR(arr, n))

# Expected output:
Max subarray XOR is  15
# recursive implementation of atoi ( ) | recursive function to compute atoi ( ) ; base case , we 've hit the end of the string,  we just return the last value ; if more than 1 digits , recur for ( n - 1 ) , multiplu result with 10 and add last digit ; 
def myAtoiRecursive(string, num):
    if len(string) == 1:
        return int(string) + (num * 10)
    num = int(string[0:1]) + (num * 10)
    return myAtoiRecursive(string[1:], num)


string = "112"
print(myAtoiRecursive(string, 0))

# Expected output:
112
# print string of odd length in ' x ' format | function to print the given string in respective pattern ; print characters at corresponding places satisfying the two conditions ; print blank space at rest of places ; 
def printPattern(Str, Len):
    for i in range(Len):
        for j in range(Len):
            if ((i == j) or (i + j == Len - 1)):
                print(Str[j], end="")
            else:
                print(" ", end="")
        print()


Str = "geeksforgeeks"
Len = len(Str)
printPattern(Str, Len)

# Expected output:
g           s
 e         k 
  e       e  
   k     e   
    s   g    
     f r     
      o      
     f r     
    s   g    
   k     e   
  e       e  
 e         k 
g           s
# find the longest substring with k unique characters in a given string | python program to find the longest substring with k unique characters in a given string ; this function calculates number of unique characters using a associative array count [ ] . returns true if no . of characters are less than required else returns false . ; return true if k is greater than or equal to val ; finds the maximum substring with exactly k unique characters ; associative array to store the count ; tranverse the string , fills the associative array count [ ] and count number of unique characters ; if there are not enough unique characters , show an error message . ; otherwise take a window with first element in it . start and end variables . ; also initialize values for result longest window ; initialize associative array count [ ] with zero ; put the first character ; start from the second character and add characters in window according to above explanation ; add the character ' s [ i ] ' to current window ; if there are more than k unique characters in current window , remove from left side ; update the max window size if required ; 

MAX_CHARS = 26


def isValid(count, k):
    val = 0
    for i in range(MAX_CHARS):
        if count[i] > 0:
            val += 1
    return (k >= val)


def kUniques(s, k):
    u = 0
    n = len(s)
    count = [0] * MAX_CHARS
    for i in range(n):
        if count[ord(s[i]) - ord('a')] == 0:
            u += 1
        count[ord(s[i]) - ord('a')] += 1
    if u < k:
        print("Not enough unique characters")
        return
    curr_start = 0
    curr_end = 0
    max_window_size = 1
    max_window_start = 0
    count = [0] * len(count)
    count[ord(s[0]) - ord('a')] += 1
    for i in range(1, n):
        count[ord(s[i]) - ord('a')] += 1
        curr_end += 1
        while not isValid(count, k):
            count[ord(s[curr_start]) - ord('a')] -= 1
            curr_start += 1
        if curr_end - curr_start + 1 > max_window_size:
            max_window_size = curr_end - curr_start + 1
            max_window_start = curr_start
    print("Max substring is : " +
          s[max_window_start:max_window_start +
            max_window_size] +
          " with length " +
          str(max_window_size))


s = "aabacbebebe"
k = 3
kUniques(s, k)

# Expected output:
Max substring is : cbebebe with length 7
# check if characters of a given string can be rearranged to form a palindrome | python3 implementation of above approach . ; bitvector to store the record of which character appear odd and even number of times ; 
def canFormPalindrome(s):
    bitvector = 0
    for str in s:
        bitvector ^= 1 << ord(str)
    return bitvector == 0 or bitvector & (bitvector - 1) == 0


if canFormPalindrome("geeksforgeeks"):
    print('Yes')
else:
    print('No')

# Expected output:
No
# print all pairs of anagrams in a given array of strings | python3 program to find best meeting point in 2d array ; function to check whether two strings are anagram of each other ; create two count arrays and initialize all values as 0 ; for each character in input strings , increment count in the corresponding count array ; if both strings are of different length . removing this condition will make the program fail for strings like " aaca " and " aca " ; see if there is any non - zero value in count array ; this function prints all anagram pairs in a given array of strings ; 

NO_OF_CHARS = 256


def areAnagram(str1: str, str2: str) -> bool:
    count = [0] * NO_OF_CHARS
    i = 0
    while i < len(str1) and i < len(str2):
        count[ord(str1[i])] += 1
        count[ord(str2[i])] -= 1
        i += 1
    if len(str1) != len(str2):
        return False
    for i in range(NO_OF_CHARS):
        if count[i]:
            return False
        return True


def findAllAnagrams(arr: list, n: int):
    for i in range(n):
        for j in range(i + 1, n):
            if areAnagram(arr[i], arr[j]):
                print(arr[i], "is anagram of", arr[j])


if __name__ == "__main__":
    arr = ["geeksquiz", "geeksforgeeks", "abcd", "forgeeksgeeks", "zuiqkeegs"]
    n = len(arr)
    findAllAnagrams(arr, n)

# Expected output:
geeksquiz is anagram of zuiqkeegs
geeksforgeeks is anagram of forgeeksgeeks
# program to print all palindromes in a given range | a function to check if n is palindrome ; find reverse of n ; if n and rev are same , then n is palindrome ; prints palindrome between min and max ; 
def isPalindrome(n: int) -> bool:
    rev = 0
    i = n
    while i > 0:
        rev = rev * 10 + i % 10
        i //= 10
    return (n == rev)


def countPal(minn: int, maxx: int) -> None:
    for i in range(minn, maxx + 1):
        if isPalindrome(i):
            print(i, end=" ")


if __name__ == "__main__":
    countPal(100, 2000)

# Expected output:
101 111 121 131 141 151 161 171 181 191 202 212 222 232 242 252 262 272 282 292 303 313 323 333 343 353 363 373 383 393 404 414 424 434 444 454 464 474 484 494 505 515 525 535 545 555 565 575 585 595 606 616 626 636 646 656 666 676 686 696 707 717 727 737 747 757 767 777 787 797 808 818 828 838 848 858 868 878 888 898 909 919 929 939 949 959 969 979 989 999 1001 1111 1221 1331 1441 1551 1661 1771 1881 1991
# length of the longest substring without repeating characters | python3 program to find the length of the longest substring without repeating characters ; result ; note : default values in visited are false ; if current character is visited break the loop ; else update the result if this window is larger , and mark current character as visited . ; remove the first character of previous window ; 
def longestUniqueSubsttr(str):
    n = len(str)
    res = 0
    for i in range(n):
        visited = [0] * 256
        for j in range(i, n):
            if (visited[ord(str[j])]):
                break
            else:
                res = max(res, j - i + 1)
                visited[ord(str[j])] = True
        visited[ord(str[i])] = False
    return res


str = "geeksforgeeks"
print("The input is ", str)
len = longestUniqueSubsttr(str)
print("The length of the longest " "non-repeating character substring is ", len)

# Expected output:
The input is  geeksforgeeks
The length of the longest non-repeating character substring is  7
# length of the longest substring without repeating characters | creating a set to store the last positions of occurrence ; starting the initial point of window to index 0 ; checking if we have already seen the element or not ; if we have seen the number , move the start pointer to position after the last occurrence ; updating the last seen value of the character ; 
def longestUniqueSubsttr(string):
    seen = {}
    maximum_length = 0
    start = 0
    for end in range(len(string)):
        if string[end] in seen:
            start = max(start, seen[string[end]] + 1)
        seen[string[end]] = end
        maximum_length = max(maximum_length, end - start + 1)
    return maximum_length


string = "geeksforgeeks"
print("The input string is", string)
length = longestUniqueSubsttr(string)
print("The length of the longest non-repeating character substring is", length)

# Expected output:
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
# find the smallest window in a string containing all characters of another string | python solution ; starting index of ans ; answer length of ans ; creating map ; references of window ; traversing the window ; calculating ; condition matching ; calculating answer . ; sliding i calculation for removing i ; 
def smallestWindow(s, p):
    n = len(s)
    if n < len(p):
        return -1
    mp = [0] * 256
    start = 0
    ans = n + 1
    cnt = 0
    for i in p:
        mp[ord(i)] += 1
        if mp[ord(i)] == 1:
            cnt += 1
    j = 0
    i = 0
    while (j < n):
        mp[ord(s[j])] -= 1
        if mp[ord(s[j])] == 0:
            cnt -= 1
            while cnt == 0:
                if ans > j - i + 1:
                    ans = j - i + 1
                    start = i
                mp[ord(s[i])] += 1
                if mp[ord(s[i])] > 0:
                    cnt += 1
                i += 1
        j += 1
    if ans > n:
        return "-1"
    return s[start:start + ans]


if __name__ == "__main__":
    s = "ADOBECODEBANC"
    p = "ABC"
    result = smallestWindow(s, p)
    print("-->Smallest window that contain all character :", result)

# Expected output:
-->Smallest window that contain all character : BANC
# run length encoding | python3 program to implement run length encoding ; count occurrences of current character ; print character and its count ; 
def printRLE(st):
    n = len(st)
    i = 0
    while i < n - 1:
        count = 1
        while (i < n - 1 and st[i] == st[i + 1]):
            count += 1
            i += 1
        i += 1
        print(st[i - 1] + str(count), end="")


if __name__ == "__main__":
    st = "wwwwaaadexxxxxxywww"
    printRLE(st)

# Expected output:
w4a3d1e1x6y1w3
# print list items containing all characters of a given word | python program to print the list items containing all characters of a given word ; prints list items having all characters of word ; set the values in map ; get the length of given word ; check each item of list if has all characters of words ; unset the bit so that strings like sss not printed ; set the values in map for next item ; 

NO_OF_CHARS = 256


def printList(list, word, list_size):
    map = [0] * NO_OF_CHARS
    for i in word:
        map[ord(i)] = 1
    word_size = len(word)
    for i in list:
        count = 0
        for j in i:
            if map[ord(j)]:
                count += 1
                map[ord(j)] = 0
        if count == word_size:
            print(i)
        for j in range(len(word)):
            map[ord(word[j])] = 1


string = "sun"
list = ["geeksforgeeks", "unsorted", "sunday", "just", "sss"]
printList(list, string, 5)

# Expected output:
unsorted
sunday
# given a string , find its first non | python program to print the first non - repeating character ; returns an array of size 256 containing count of characters in the passed char array ; the function returns index of first non - repeating character in a string . if all characters are repeating then returns - 1 ; 

NO_OF_CHARS = 256


def getCharCountArray(string):
    count = [0] * NO_OF_CHARS
    for i in string:
        count[ord(i)] += 1
    return count


def firstNonRepeating(string):
    count = getCharCountArray(string)
    index = -1
    k = 0
    for i in string:
        if count[ord(i)] == 1:
            index = k
            break
        k += 1
    return index


string = "geeksforgeeks"
index = firstNonRepeating(string)
if index == 1:
    print("Either all characters are repeating or string is empty")
else:
    print("First non-repeating character is " + string[index])

# Expected output:
First non-repeating character is f
# divide a string in n equal parts | function to print n equal parts of string ; check if string can be divided in n equal parts ; calculate the size of parts to find the division points ; 
def divideString(string, n):
    str_size = len(string)
    if str_size % n != 0:
        print("Invalid Input: String size is not divisible by n")
        return
    part_size = str_size/n
    k = 0
    for i in string:
        if k % part_size == 0:
            print()
        print(i, end='')
        k += 1


string = "a_simple_divide_string_quest"
divideString(string, 4)

# Expected output:

a_simpl
e_divid
e_strin
g_quest
# print all paths from a source point to all the 4 corners of a matrix | function to check if we reached on of the entry / exit ( corner ) point . ; function to check if the index is within the matrix boundary . ; recursive helper function ; if any corner is reached push the string t into ans and return ; for all the four directions ; the new ith index ; the new jth index ; the direction r / l / u / d ; if the new cell is within the matrix boundary and it is not previously visited in same path ; mark the new cell visited ; store the direction ; backtrack to explore other paths ; function to find all possible paths ; create a direction array for all the four directions ; stores the result ; 
def isCorner(i, j, M, N):
    if ((i == 0 and j == 0) or (i == 0 and j == N - 1)
            or (i == M - 1 and j == N - 1) or (i == M - 1 and j == 0)):
        return True
    return False


def isValid(i, j, M, N):
    if (i < 0 or i >= M or j < 0 or j >= N):
        return False
    return True


def solve(i, j, M, N, Dir, maze, t, ans):
    if (isCorner(i, j, M, N)):
        ans .append(t)
        return
    for k in range(4):
        x = i + Dir[k][0]
        y = j + Dir[k][1]
        c = Dir[k][2]
        if (isValid(x, y, M, N) and maze[x][y] == 1):
            maze[x][y] = 0
            t += c
            solve(x, y, M, N, Dir, maze, t, ans)
            t = t[:len(t) - 1]
            maze[x][y] = 1
    return


def possiblePaths(src, maze):
    Dir = [[-1, 0, 'U'], [0, 1, 'R'], [1, 0, 'D'], [0, -1, 'L']]
    temp = ""
    ans = []
    solve(src[0], src[1], len(maze), len(maze[0]), Dir, maze, temp, ans)
    return ans


maze = [
    [
        1, 0, 0, 1, 0, 0, 1, 1], [
            1, 1, 1, 0, 0, 0, 1, 0], [
                1, 0, 1, 1, 1, 1, 1, 0], [
                    0, 0, 0, 0, 1, 0, 0, 0], [
                        1, 0, 1, 0, 1, 0, 0, 1], [
                            0, 1, 1, 1, 1, 0, 0, 1], [
                                0, 1, 0, 0, 1, 1, 1, 1], [
                                    1, 1, 0, 0, 0, 0, 0, 1]]
src = [4, 2]
paths = possiblePaths(src, maze)
if (len(paths) == 0):
    print("No Possible Paths")
else:
    for i in paths:
        print(i)

# Expected output:
DRRUUURRUUR
DRRUUULLULLU
DRRDRRRD
DLDDL
# Count total ways to reach destination from source in an undirected Graph | Utility Function to count total ways ; Base condition When reach to the destination ; Make vertex visited ; Recursive function , for count ways ; Backtracking Make vertex unvisited ; Return total ways ; Function to count total ways to reach destination ; Loop to make all vertex unvisited , Initially ; Make source visited ; Print total ways
def countWays(mtrx, vrtx, i, dest, visited):
    if (i == dest):
        return 1
    total = 0
    for j in range(vrtx):
        if (mtrx[i][j] == 1 and not visited[j]):
            visited[j] = True
            total += countWays(mtrx, vrtx, j, dest, visited)
            visited[j] = False
    return total


def totalWays(mtrx, vrtx, src, dest):
    visited = [False] * vrtx
    for i in range(vrtx):
        visited[i] = False
    visited[src] = True
    return countWays(mtrx, vrtx, src, dest, visited)


vrtx = 11
mtrx = [
    [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
    [1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
    [0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0],
    [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0],
    [0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
]

src = 3
dest = 9
print(totalWays(mtrx, vrtx, src - 1, dest - 1))

# Expected output:
6
# print path from given source to destination in 2 | function to print the path ; base condition ; pop stores elements ; recursive call for printing stack in reverse order ; function to store the path into the stack , if path exist ; base condition ; push current elements ; condition to check whether reach to the destination or not ; increment ' x ' ordinate of source by ( 2 * x + y ) keeping ' y ' constant ; increment ' y ' ordinate of source by ( 2 * y + x ) keeping ' x ' constant ; pop current elements form stack ; if no path exists ; utility function to check whether path exist or not ; to store x co - ordinate ; to store y co - ordinate ; function to find the path ; print - 1 , if path doesn 't exist ; 
def printExistPath(sx, sy, last):
    if (len(sx) == 0 or len(sy) == 0):
        return
    x = sx[-1]
    y = sy[-1]
    sx .pop()
    sy .pop()
    printExistPath(sx, sy, last)
    if (len(sx) == last - 1):
        print("(" + str(x) + ", " + str(y) + ")", end='')
    else:
        print("(" + str(x) + ", " + str(y) + ") -> ", end='')


def storePath(srcX, srcY, destX, destY, sx, sy):
    if (srcX > destX or srcY > destY):
        return False
    sx .append(srcX)
    sy .append(srcY)
    if (srcX == destX and srcY == destY):
        printExistPath(sx, sy, len(sx))
        return True
    if (storePath((2 * srcX) + srcY, srcY, destX, destY, sx, sy)):
        return True
    if (storePath(srcX, (2 * srcY) + srcX, destX, destY, sx, sy)):
        return True
    sx .pop()
    sy .pop()
    return False


def isPathExist(srcX, srcY, destX, destY):
    sx = []
    sy = []
    return storePath(srcX, srcY, destX, destY, sx, sy)


def printPath(srcX, srcY, destX, destY):
    if (not isPathExist(srcX, srcY, destX, destY)):
        print("-1")


if __name__ == '__main__':
    srcX = 5
    srcY = 8
    destX = 83
    destY = 21
    printPath(srcX, srcY, destX, destY)

# Expected output:
(5, 8) -> (5, 21) -> (31, 21) -> (83, 21) ->